Merge remote-tracking branch 'origin/main' into lesj/qwen4exp-bugfixes
Both sides edited the same import block in the Qwen4Exp NVIDIA and AMD
models and nothing else collided. This branch adds
`from ..common.mtp import make_mtp_hidden_buffer`, the helper the MTP
buffer extraction calls; upstream ec4a3a5370 widened the `..config`
import to `ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig` for the
layer-type constants it introduced. The two changes are independent, so
the resolution keeps both lines. Every symbol still has a use outside the
import in both files.
Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
@@ -71,10 +71,7 @@ from vllm.model_executor.models.utils import (
|
||||
make_layers,
|
||||
maybe_prefix,
|
||||
)
|
||||
from vllm.models.deepseek_v4.amd.rocm import (
|
||||
DeepseekV4ROCMAiterMLAAttention,
|
||||
weight_already_preshuffled,
|
||||
)
|
||||
from vllm.models.deepseek_v4.amd.rocm import DeepseekV4ROCMAiterMLAAttention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
from vllm.sequence import IntermediateTensors
|
||||
@@ -152,13 +149,11 @@ class DeepseekV4MLP(nn.Module):
|
||||
return
|
||||
if ws.dtype == torch.float8_e8m0fnu:
|
||||
ws = _upcast_e8m0_to_fp32(ws).contiguous()
|
||||
# Skip if the linear's kernel already shuffled it.
|
||||
if not weight_already_preshuffled(self.gate_up_proj):
|
||||
replace_parameter(
|
||||
self.gate_up_proj,
|
||||
"weight",
|
||||
rocm_aiter_ops.shuffle_weight(w.data, layout=(16, 16)),
|
||||
)
|
||||
replace_parameter(
|
||||
self.gate_up_proj,
|
||||
"weight",
|
||||
rocm_aiter_ops.shuffle_weight(w.data, layout=(16, 16)),
|
||||
)
|
||||
self._gateup_scale = ws
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
@@ -496,8 +496,7 @@ class DeepSeekV4MTP(nn.Module):
|
||||
return loaded_params
|
||||
|
||||
def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
|
||||
"""
|
||||
Rewrite the weight name to match the format of the original model.
|
||||
"""Rewrite the weight name to match the format of the original model.
|
||||
Add .mtp_block for modules in transformer layer block for spec layer
|
||||
and rename shared layer weights to be top level.
|
||||
"""
|
||||
|
||||
@@ -62,21 +62,6 @@ def _build_indptr_from_lengths(lengths: torch.Tensor) -> torch.Tensor:
|
||||
return indptr
|
||||
|
||||
|
||||
def weight_already_preshuffled(linear: torch.nn.Module) -> bool:
|
||||
"""True when the linear's kernel already B-preshuffled ``weight``.
|
||||
|
||||
The hand-shuffles below (fused_wqa_wkv, wo_b, gate_up_proj) must be skipped
|
||||
for those, since shuffle_weight is a permutation rather than an involution.
|
||||
"""
|
||||
return any(
|
||||
getattr(getattr(method, "fp8_linear", None), "preshuffles_weight", False)
|
||||
for method in (
|
||||
getattr(linear, "quant_method", None),
|
||||
getattr(linear, "scheme", None),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def apply_pre_quantized_block_scaled_mm(
|
||||
linear: torch.nn.Module,
|
||||
x_fp8: torch.Tensor,
|
||||
@@ -792,13 +777,12 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
return None
|
||||
if ws.dtype == torch.float8_e8m0fnu:
|
||||
ws = _upcast_e8m0_to_fp32(ws).contiguous()
|
||||
# Skip if the linear's kernel already shuffled it.
|
||||
if not weight_already_preshuffled(linear):
|
||||
replace_parameter(
|
||||
linear,
|
||||
"weight",
|
||||
rocm_aiter_ops.shuffle_weight(w.data, layout=(16, 16)),
|
||||
)
|
||||
# Shuffle the weight in place (single weight, no unshuffled copy).
|
||||
replace_parameter(
|
||||
linear,
|
||||
"weight",
|
||||
rocm_aiter_ops.shuffle_weight(w.data, layout=(16, 16)),
|
||||
)
|
||||
return ws
|
||||
|
||||
self._wqa_wkv_scale = _prep(self.fused_wqa_wkv)
|
||||
@@ -896,26 +880,16 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
return qr_kv, kv_score, indexer_kv_score, indexer_weights
|
||||
|
||||
@functools.cached_property
|
||||
def _wq_b_act_scale_transpose(self) -> bool | None:
|
||||
"""Activation-scale byte order every wq_b consumer agrees on, else None.
|
||||
|
||||
None means "do not take the fused norm+quant path". Otherwise the value
|
||||
is the ``transpose_scale`` the producer must pass so that the scale it
|
||||
writes matches what the selected GEMM reads.
|
||||
def _wq_b_uses_aiter_block_scaled(self) -> bool:
|
||||
"""True when both wq_b GEMMs run the aiter block-scaled fp8 kernel.
|
||||
|
||||
Cached: the linear kernels and the aiter env gates are fixed once
|
||||
the model is built, so this is evaluated at the first forward
|
||||
only.
|
||||
|
||||
Two conditions, both necessary:
|
||||
|
||||
* The fused norm+quant path is only valid if the quant and GEMM it
|
||||
replaces are exactly the aiter ones; otherwise fall back to the
|
||||
shared path.
|
||||
* One qr_scale feeds both self.wq_b and self.indexer.wq_b, which have
|
||||
different (N, K) and so can resolve to kernels wanting opposite byte
|
||||
orders. A single producer cannot serve both, so refuse the fast path
|
||||
when they disagree rather than guessing.
|
||||
The fused norm+quant path is only valid if the quant and GEMM it
|
||||
replaces are exactly the aiter ones; otherwise fall back to the
|
||||
shared path.
|
||||
"""
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.model_executor.kernels.linear.scaled_mm import (
|
||||
@@ -923,31 +897,16 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
)
|
||||
|
||||
if not rocm_aiter_ops.is_linear_fp8_enabled():
|
||||
return None
|
||||
return False
|
||||
|
||||
linears = [self.wq_b]
|
||||
if self.indexer is not None:
|
||||
linears.append(self.indexer.wq_b)
|
||||
layouts: set[bool] = set()
|
||||
for linear in linears:
|
||||
kernel = getattr(getattr(linear, "quant_method", None), "fp8_linear", None)
|
||||
if not isinstance(kernel, Fp8BlockScaledMMLinearKernel):
|
||||
return None
|
||||
layouts.add(bool(getattr(kernel, "wants_transposed_act_scale", False)))
|
||||
if len(layouts) != 1:
|
||||
logger.warning_once(
|
||||
"DeepSeek-V4 wq_b consumers disagree on activation-scale layout; "
|
||||
"disabling the fused q/kv norm+quant path.",
|
||||
scope="global",
|
||||
)
|
||||
return None
|
||||
transpose_scale = layouts.pop()
|
||||
logger.debug_once(
|
||||
"DeepSeek-V4 wq_b: emitting %s-major activation scales",
|
||||
"column" if transpose_scale else "row",
|
||||
scope="global",
|
||||
)
|
||||
return transpose_scale
|
||||
return False
|
||||
return True
|
||||
|
||||
def _split_qkv_and_norm(
|
||||
self, qr_kv: torch.Tensor
|
||||
@@ -964,12 +923,11 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
when the aiter linear path is not active.
|
||||
"""
|
||||
qr, kv = qr_kv.split([self.q_lora_rank, self.head_dim], dim=-1)
|
||||
transpose_scale = self._wq_b_act_scale_transpose
|
||||
if not (
|
||||
qr.dim() == 2
|
||||
and qr.shape[0] > 0
|
||||
and self.q_lora_rank % 128 == 0
|
||||
and transpose_scale is not None
|
||||
and self._wq_b_uses_aiter_block_scaled
|
||||
):
|
||||
return super()._split_qkv_and_norm(qr_kv)
|
||||
|
||||
@@ -983,8 +941,7 @@ class DeepseekV4ROCMAiterMLAAttention(DeepseekV4Attention):
|
||||
kv_weight=self.kv_norm.weight.data,
|
||||
kv_epsilon=self.eps,
|
||||
group_size=128,
|
||||
# Emit the byte order the wq_b GEMMs read.
|
||||
transpose_scale=transpose_scale,
|
||||
transpose_scale=False,
|
||||
)
|
||||
|
||||
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
DeepseekV4 MLA Attention Layer
|
||||
"""
|
||||
"""DeepseekV4 MLA Attention Layer."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Triton kernels for DeepseekV4 paged K-cache management and sparse-attention index
|
||||
"""Triton kernels for DeepseekV4 paged K-cache management and sparse-attention index
|
||||
preparation.
|
||||
|
||||
- quantize_and_insert_k_cache: quantize bf16 K to UE8M0 FP8 and insert into
|
||||
@@ -61,8 +60,7 @@ def quantize_and_insert_k_kernel(
|
||||
n_quant_blocks: tl.constexpr, # 8 (7 real + 1 padding)
|
||||
use_fnuz: tl.constexpr = False,
|
||||
):
|
||||
"""
|
||||
Quantize K tensor and insert into paged K cache.
|
||||
"""Quantize K tensor and insert into paged K cache.
|
||||
|
||||
K Cache block layout (block_size=64 tokens):
|
||||
- [0, 64*576): Token data, each token has 448 fp8 + 128 bf16
|
||||
@@ -174,8 +172,7 @@ def quantize_and_insert_k_cache(
|
||||
is_ue8m0: bool = True,
|
||||
use_fnuz: bool = False,
|
||||
):
|
||||
"""
|
||||
Quantize K tensor and insert into paged K cache.
|
||||
"""Quantize K tensor and insert into paged K cache.
|
||||
|
||||
K Cache block layout (block_size=64 tokens):
|
||||
- First 64 * 576 = 36864 bytes: Token data
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Fused compressor + FP8/MXFP4 UE8M0 quantization + KV cache insert kernels.
|
||||
"""Fused compressor + FP8/MXFP4 UE8M0 quantization + KV cache insert kernels.
|
||||
|
||||
Three specialized kernels:
|
||||
- _fused_kv_compress_norm_rope_insert_sparse_attn:
|
||||
@@ -390,7 +389,7 @@ def _compress_gather_split_sparse_attn(
|
||||
NUM_SPLITS: tl.constexpr,
|
||||
HEAD_TILE: tl.constexpr, # HEAD_SIZE // NUM_SPLITS
|
||||
):
|
||||
"""Stage 1: per-(token, head-split) compress gather, write to fp32 scratch
|
||||
"""Stage 1: per-(token, head-split) compress gather, write to fp32 scratch.
|
||||
|
||||
No-overlap gather (cr>=128) on rows [0, COMPRESS_RATIO)
|
||||
"""
|
||||
@@ -639,7 +638,7 @@ def compress_norm_rope_store_two_stage_triton(
|
||||
num_decode_tokens: int,
|
||||
compress_scratch: torch.Tensor,
|
||||
) -> None:
|
||||
"""Two-stage split compressor dispatch for head=512 cr>=128 (no-overlap)
|
||||
"""Two-stage split compressor dispatch for head=512 cr>=128 (no-overlap).
|
||||
|
||||
Run the occupancy-fanned two-stage split for prefill [num_decodee_tokens:]
|
||||
to fill the CUs, and use the original single-pass launcher
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Fused inverse RoPE + block-scaled FP8 quantization kernel for DeepseekV4 attention.
|
||||
"""Fused inverse RoPE + block-scaled FP8 quantization kernel for DeepseekV4 attention.
|
||||
|
||||
Output scale format is pre-transformed (MN-major TMA-aligned; FP32 on SM90,
|
||||
INT32-packed UE8M0 on SM100) so fp8_einsum skips transform_sf_into_required_layout.
|
||||
@@ -380,6 +379,7 @@ def fused_inv_rope_fp8_quant(
|
||||
Returns:
|
||||
Rotated output in [T, G, D] and its FP8 scales. The scale tensor is
|
||||
empty when quantization is disabled.
|
||||
|
||||
"""
|
||||
from vllm.utils.deep_gemm import get_tma_aligned_size
|
||||
|
||||
|
||||
@@ -263,6 +263,7 @@ def run_dp_sharded_vision_tower(
|
||||
|
||||
Returns:
|
||||
One ``(n_aligner_rows, hidden_size)`` embedding tensor per image.
|
||||
|
||||
"""
|
||||
tp_size = get_tensor_model_parallel_world_size()
|
||||
tp_rank = get_tensor_model_parallel_rank()
|
||||
|
||||
@@ -23,6 +23,7 @@ def map_local_to_global_slots_cpu(
|
||||
|
||||
Returns:
|
||||
[N, K] int64 global slot ids, -1 where ``local_indices`` was invalid.
|
||||
|
||||
"""
|
||||
valid = local_indices >= 0
|
||||
safe_local = local_indices.clamp(min=0).to(torch.int64)
|
||||
|
||||
@@ -204,7 +204,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
self.top_k = top_k
|
||||
self.hidden_size = hidden_size
|
||||
self.intermediate_size = intermediate_size
|
||||
self.unpadded_intermediate_size = intermediate_size
|
||||
self.num_shared_experts = num_shared_experts
|
||||
self.max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
|
||||
@@ -387,17 +386,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
# the generic linear post-load hook replaces the raw checkpoint scales
|
||||
# with its 128x128 DeepGEMM layout.
|
||||
checkpoint_scale_dtypes = (torch.float8_e8m0fnu, torch.uint8)
|
||||
unpadded_size = self.unpadded_intermediate_size * self.num_shared_experts
|
||||
padding = self.intermediate_size * self.num_shared_experts - unpadded_size
|
||||
pad_weights = (
|
||||
padding > 0
|
||||
and gate_up_weight.dtype == torch.float8_e4m3fn
|
||||
and down_weight.dtype == torch.float8_e4m3fn
|
||||
and gate_up_weight.shape == (2 * unpadded_size, self.hidden_size)
|
||||
and down_weight.shape == (self.hidden_size, unpadded_size)
|
||||
and gate_up_scale.dtype in checkpoint_scale_dtypes
|
||||
and down_scale.dtype in checkpoint_scale_dtypes
|
||||
)
|
||||
if (
|
||||
gate_up_scale.dtype in checkpoint_scale_dtypes
|
||||
and down_scale.dtype in checkpoint_scale_dtypes
|
||||
@@ -408,7 +396,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
gate_up_scale,
|
||||
gate_up_weight.shape[0],
|
||||
gate_up_weight.shape[1],
|
||||
padding=(padding, 0) if pad_weights else (0, 0),
|
||||
)
|
||||
down_scale = self._prepare_shared_expert_scale(
|
||||
deep_gemm,
|
||||
@@ -416,27 +403,12 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
down_scale,
|
||||
down_weight.shape[0],
|
||||
down_weight.shape[1],
|
||||
padding=(0, padding) if pad_weights else (0, 0),
|
||||
)
|
||||
|
||||
if gate_up_scale is None or down_scale is None:
|
||||
self.num_shared_experts = 0
|
||||
return
|
||||
|
||||
if pad_weights:
|
||||
# Pad gate/up separately so the SwiGLU split stays at the midpoint.
|
||||
gate_up_weight = (
|
||||
torch.nn.functional.pad(
|
||||
gate_up_weight.view(torch.uint8).unflatten(0, (2, unpadded_size)),
|
||||
(0, 0, 0, padding),
|
||||
)
|
||||
.flatten(0, 1)
|
||||
.view(gate_up_weight.dtype)
|
||||
)
|
||||
down_weight = torch.nn.functional.pad(
|
||||
down_weight.view(torch.uint8), (0, padding)
|
||||
).view(down_weight.dtype)
|
||||
|
||||
shared_intermediate_size = self.intermediate_size * self.num_shared_experts
|
||||
expected_gate_up_shape = (
|
||||
2 * shared_intermediate_size,
|
||||
@@ -477,11 +449,11 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
# released instead of adding roughly 0.7 GiB per rank on DSV4-Flash.
|
||||
# The generic linear post-load hook may still repack the serial scales,
|
||||
# but this shared MLP is never called after native fusion is enabled.
|
||||
# Padded weights need separate storage: the generic linear post-load
|
||||
# hooks still expect the original checkpoint weight/scale shapes.
|
||||
if not pad_weights:
|
||||
gate_up.weight.data = transformed_l1[0]
|
||||
self._transformed_shared_l1_weights = transformed_l1
|
||||
gate_up.weight.data = transformed_l1[0]
|
||||
self._transformed_shared_l1_weights = (
|
||||
gate_up.weight.data,
|
||||
transformed_l1[1],
|
||||
)
|
||||
self._transformed_shared_l2_weights = transformed_l2
|
||||
|
||||
def _prepare_shared_expert_scale(
|
||||
@@ -491,8 +463,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
scale: torch.Tensor,
|
||||
mn: int,
|
||||
k: int,
|
||||
*,
|
||||
padding: tuple[int, int] = (0, 0),
|
||||
) -> torch.Tensor | None:
|
||||
block_size = getattr(linear, "weight_block_size", None)
|
||||
if block_size is None or len(block_size) != 2:
|
||||
@@ -527,19 +497,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
.repeat_interleave(block_k // 32, dim=1)[:mn, : k // 32]
|
||||
.contiguous()
|
||||
)
|
||||
pad_m, pad_k = padding
|
||||
if pad_m:
|
||||
scale_1x32 = torch.nn.functional.pad(
|
||||
scale_1x32.unflatten(0, (2, mn // 2)),
|
||||
(0, 0, 0, pad_m),
|
||||
value=1.0,
|
||||
).flatten(0, 1)
|
||||
mn += 2 * pad_m
|
||||
if pad_k:
|
||||
scale_1x32 = torch.nn.functional.pad(
|
||||
scale_1x32, (0, pad_k // 32), value=1.0
|
||||
)
|
||||
k += pad_k
|
||||
# The grouped API is used with a singleton dimension to request the
|
||||
# MN-major, TMA-aligned packed-UE8M0 strides, then squeezed back to the
|
||||
# 2D layout required for a shared expert.
|
||||
@@ -558,23 +515,6 @@ class DeepseekV4MegaMoEExperts(nn.Module):
|
||||
|
||||
if self._transformed_l1_weights is None:
|
||||
self._check_runtime_supported()
|
||||
# MegaMoE's 1x32 activation scales need 16-byte TMA rows, so
|
||||
# pad each gate/up half and the down projection to a multiple of 512.
|
||||
padded_size = (self.intermediate_size + 511) // 512 * 512
|
||||
padding = padded_size - self.intermediate_size
|
||||
if padding:
|
||||
for param in (self.w13_weight, self.w13_weight_scale):
|
||||
gate_up = param.data.unflatten(1, (2, self.intermediate_size))
|
||||
param.data = torch.nn.functional.pad(
|
||||
gate_up, (0, 0, 0, padding)
|
||||
).flatten(1, 2)
|
||||
self.w2_weight.data = torch.nn.functional.pad(
|
||||
self.w2_weight.data, (0, padding // 2)
|
||||
)
|
||||
self.w2_weight_scale.data = torch.nn.functional.pad(
|
||||
self.w2_weight_scale.data, (0, padding // 32)
|
||||
)
|
||||
self.intermediate_size = padded_size
|
||||
w13_scale = deep_gemm.transform_sf_into_required_layout(
|
||||
self._ue8m0_uint8_to_float(self.w13_weight_scale.data).contiguous(),
|
||||
2 * self.intermediate_size,
|
||||
|
||||
@@ -518,8 +518,7 @@ class DeepSeekV4MTP(nn.Module):
|
||||
self.finalize_mega_moe_weights()
|
||||
|
||||
def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
|
||||
"""
|
||||
Rewrite the weight name to match the format of the original model.
|
||||
"""Rewrite the weight name to match the format of the original model.
|
||||
Add .mtp_block for modules in transformer layer block for spec layer
|
||||
and rename shared layer weights to be top level.
|
||||
"""
|
||||
|
||||
@@ -493,8 +493,7 @@ class DeepSeekV4MTP(nn.Module):
|
||||
layer.mtp_block.ffn.finalize_mega_moe_weights()
|
||||
|
||||
def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
|
||||
"""
|
||||
Rewrite the weight name to match the format of the original model.
|
||||
"""Rewrite the weight name to match the format of the original model.
|
||||
Add .mtp_block for modules in transformer layer block for spec layer
|
||||
and rename shared layer weights to be top level.
|
||||
"""
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
DeepseekV4 MLA Attention Layer
|
||||
"""
|
||||
"""DeepseekV4 MLA Attention Layer"""
|
||||
|
||||
import math
|
||||
from abc import ABC, abstractmethod
|
||||
@@ -290,13 +288,6 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
|
||||
self.n_groups = config.o_groups
|
||||
self.n_local_groups = self.n_groups // tp_size
|
||||
self.window_size = config.sliding_window
|
||||
# Vision variant: image spans are visible bidirectionally, widening
|
||||
# prefill SWA index rows by up to max_image_tokens columns.
|
||||
self.max_image_tokens = (
|
||||
getattr(config, "vision_max_n_token", 0)
|
||||
if getattr(config, "vision_n_layers", 0) > 0
|
||||
else 0
|
||||
)
|
||||
# ---- v4.1 sparse-attention topology ----
|
||||
# compress_ratios has one entry per layer (MTP layers included):
|
||||
# 0 = pure sliding window, 1 = full-length compressed cache,
|
||||
@@ -578,7 +569,6 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
|
||||
_COMPUTE_SWA_INDICES_AND_LENS_KERNEL.register_warmup(
|
||||
window_size=self.window_size,
|
||||
block_size=self.swa_cache_layer.block_size,
|
||||
max_image_tokens=self.max_image_tokens,
|
||||
)
|
||||
|
||||
if self.compress_ratio > 1:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""
|
||||
Triton kernels for DeepseekV4 paged K-cache management and sparse-attention index
|
||||
"""Triton kernels for DeepseekV4 paged K-cache management and sparse-attention index
|
||||
preparation.
|
||||
|
||||
- quantize_and_insert_k_cache: quantize bf16 K to UE8M0 FP8 and insert into
|
||||
@@ -76,8 +75,7 @@ def quantize_and_insert_k_kernel(
|
||||
n_quant_blocks: tl.constexpr, # 8 (7 real + 1 padding)
|
||||
use_fnuz: tl.constexpr = False,
|
||||
):
|
||||
"""
|
||||
Quantize K tensor and insert into paged K cache.
|
||||
"""Quantize K tensor and insert into paged K cache.
|
||||
|
||||
K Cache block layout (block_size=64 tokens):
|
||||
- [0, 64*576): Token data, each token has 448 fp8 + 128 bf16
|
||||
@@ -251,8 +249,7 @@ def quantize_and_insert_k_cache(
|
||||
use_fnuz: bool = False,
|
||||
bytes_per_token: int = V4_BYTES_PER_TOKEN,
|
||||
):
|
||||
"""
|
||||
Quantize K tensor and insert into paged K cache.
|
||||
"""Quantize K tensor and insert into paged K cache.
|
||||
|
||||
``bytes_per_token`` picks the record (see the module header): the V4 one,
|
||||
or V4.1's all-dims MXFP8 one.
|
||||
@@ -818,16 +815,12 @@ def combine_topk_swa_indices(
|
||||
M: int,
|
||||
N: int,
|
||||
out: tuple[torch.Tensor, torch.Tensor] | None = None,
|
||||
left_visible: torch.Tensor | None = None,
|
||||
right_visible: torch.Tensor | None = None,
|
||||
max_image_tokens: int = 0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
num_tokens = topk_indices.shape[0]
|
||||
# max_image_tokens widens the SWA column region for in-image
|
||||
# bidirectional visibility; the width is fixed per model so the
|
||||
# caller-provided workspace stays valid on image-free batches.
|
||||
# The width is fixed per model so the caller-provided workspace stays
|
||||
# valid on every batch.
|
||||
combined_topk = (
|
||||
(topk + window_size + max_image_tokens + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1)
|
||||
(topk + window_size + _SPARSE_PREFILL_TOPK_ALIGNMENT - 1)
|
||||
// _SPARSE_PREFILL_TOPK_ALIGNMENT
|
||||
* _SPARSE_PREFILL_TOPK_ALIGNMENT
|
||||
)
|
||||
@@ -856,9 +849,6 @@ def combine_topk_swa_indices(
|
||||
TOP_K=topk,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
WINDOW_SIZE=window_size,
|
||||
left_visible=left_visible,
|
||||
right_visible=right_visible,
|
||||
max_image_tokens=max_image_tokens,
|
||||
)
|
||||
return combined_indices, combined_lens
|
||||
|
||||
@@ -927,7 +917,6 @@ class CombineTopkSwaIndicesKernel(
|
||||
TOP_K: int
|
||||
COMPRESS_RATIO: int
|
||||
WINDOW_SIZE: int
|
||||
IMAGE_WIDTH: int
|
||||
PADDED_TOP_K: int
|
||||
input_variant: TritonPointerInputVariant
|
||||
|
||||
@@ -949,14 +938,11 @@ class CombineTopkSwaIndicesKernel(
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
gather_lens_ptr,
|
||||
left_visible_ptr,
|
||||
right_visible_ptr,
|
||||
M,
|
||||
N,
|
||||
TOP_K: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
WINDOW_SIZE: tl.constexpr,
|
||||
IMAGE_WIDTH: tl.constexpr,
|
||||
PADDED_TOP_K: tl.constexpr,
|
||||
):
|
||||
batch_idx = tl.program_id(0)
|
||||
@@ -991,19 +977,8 @@ class CombineTopkSwaIndicesKernel(
|
||||
# (integer div by constexpr 0 is UB and yields garbage, which
|
||||
# turns the store index below negative).
|
||||
topk_len = 0
|
||||
if IMAGE_WIDTH > 0:
|
||||
# In-image bidirectional visibility: the window starts up to
|
||||
# max(left - (window - 1), 0) positions earlier and extends
|
||||
# `right` positions past the query token (both 0 outside
|
||||
# image spans, reducing to the plain causal window).
|
||||
left = tl.load(left_visible_ptr + token_idx)
|
||||
right = tl.load(right_visible_ptr + token_idx)
|
||||
else:
|
||||
left = 0
|
||||
right = 0
|
||||
left_add = tl.maximum(left - (WINDOW_SIZE - 1), 0)
|
||||
swa_start = tl.maximum(pos - (WINDOW_SIZE - 1) - left_add, 0)
|
||||
swa_len = pos + right - swa_start + 1
|
||||
swa_start = tl.maximum(pos - (WINDOW_SIZE - 1), 0)
|
||||
swa_len = pos - swa_start + 1
|
||||
|
||||
offset = tl.arange(0, PADDED_TOP_K)
|
||||
mask = offset < topk_len
|
||||
@@ -1017,18 +992,17 @@ class CombineTopkSwaIndicesKernel(
|
||||
mask=mask,
|
||||
)
|
||||
# Index into gathered buffer: N + (position - gather_start)
|
||||
# For positions [swa_start, pos + right], the buffer indices are:
|
||||
# [N + swa_start - gather_start, N + pos + right - gather_start]
|
||||
for i in range(0, WINDOW_SIZE + IMAGE_WIDTH, WINDOW_SIZE):
|
||||
swa_offset = i + tl.arange(0, WINDOW_SIZE)
|
||||
tl.store(
|
||||
combined_indices_ptr
|
||||
+ token_idx * combined_indices_stride
|
||||
+ topk_len
|
||||
+ swa_offset,
|
||||
M * batch_idx + N + swa_start + swa_offset - gather_start,
|
||||
mask=swa_offset < swa_len,
|
||||
)
|
||||
# For positions [swa_start, pos], the buffer indices are:
|
||||
# [N + swa_start - gather_start, N + pos - gather_start]
|
||||
swa_offset = tl.arange(0, WINDOW_SIZE)
|
||||
tl.store(
|
||||
combined_indices_ptr
|
||||
+ token_idx * combined_indices_stride
|
||||
+ topk_len
|
||||
+ swa_offset,
|
||||
M * batch_idx + N + swa_start + swa_offset - gather_start,
|
||||
mask=swa_offset < swa_len,
|
||||
)
|
||||
|
||||
combined_len = topk_len + swa_len
|
||||
tl.store(combined_lens_ptr + token_idx, combined_len)
|
||||
@@ -1044,7 +1018,6 @@ class CombineTopkSwaIndicesKernel(
|
||||
topk: int,
|
||||
compress_ratio: int,
|
||||
WINDOW_SIZE: int,
|
||||
image_width: int = 0,
|
||||
) -> CompileKey:
|
||||
padded_topk = next_power_of_2(topk_width)
|
||||
input_variant = TritonPointerInputVariant.from_alignment(
|
||||
@@ -1057,7 +1030,6 @@ class CombineTopkSwaIndicesKernel(
|
||||
TOP_K=topk,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
WINDOW_SIZE=WINDOW_SIZE,
|
||||
IMAGE_WIDTH=image_width,
|
||||
PADDED_TOP_K=padded_topk,
|
||||
input_variant=input_variant,
|
||||
)
|
||||
@@ -1067,19 +1039,10 @@ class CombineTopkSwaIndicesKernel(
|
||||
return []
|
||||
|
||||
window_size = _hf_config_int(vllm_config, "sliding_window", 128)
|
||||
image_width = (
|
||||
_hf_config_int(vllm_config, "vision_max_n_token", 0)
|
||||
if _hf_config_int(vllm_config, "vision_n_layers", 0) > 0
|
||||
else 0
|
||||
)
|
||||
# Warm both the plain-window variant (batches without image spans)
|
||||
# and the in-image bidirectional variant.
|
||||
image_widths = [0, image_width] if image_width > 0 else [0]
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
_combine_topk_swa_warmup_inputs(vllm_config),
|
||||
_COMBINE_TOPK_SWA_POINTER_INPUTS,
|
||||
WINDOW_SIZE=window_size,
|
||||
image_width=image_widths,
|
||||
)
|
||||
|
||||
def compile(self, compile_key: CompileKey) -> None:
|
||||
@@ -1096,14 +1059,11 @@ class CombineTopkSwaIndicesKernel(
|
||||
input_variant.pointer("query_start_loc", torch.int32),
|
||||
input_variant.pointer("seq_lens", torch.int32),
|
||||
input_variant.pointer("gather_lens", torch.int32),
|
||||
int32_ptr,
|
||||
int32_ptr,
|
||||
1, # do not specialize M
|
||||
1, # do not specialize N
|
||||
TOP_K=compile_key.TOP_K,
|
||||
COMPRESS_RATIO=compile_key.COMPRESS_RATIO,
|
||||
WINDOW_SIZE=compile_key.WINDOW_SIZE,
|
||||
IMAGE_WIDTH=compile_key.IMAGE_WIDTH,
|
||||
PADDED_TOP_K=compile_key.PADDED_TOP_K,
|
||||
grid=(1, _COMBINE_TOPK_SWA_NUM_WORKERS),
|
||||
)
|
||||
@@ -1122,13 +1082,8 @@ class CombineTopkSwaIndicesKernel(
|
||||
TOP_K: int,
|
||||
COMPRESS_RATIO: int,
|
||||
WINDOW_SIZE: int,
|
||||
left_visible: torch.Tensor | None = None,
|
||||
right_visible: torch.Tensor | None = None,
|
||||
max_image_tokens: int = 0,
|
||||
) -> None:
|
||||
num_reqs = seq_lens.shape[0]
|
||||
has_image = left_visible is not None
|
||||
image_width = max_image_tokens if has_image else 0
|
||||
self.kernel[(num_reqs, _COMBINE_TOPK_SWA_NUM_WORKERS)](
|
||||
combined_indices,
|
||||
combined_indices.stride(0),
|
||||
@@ -1138,14 +1093,11 @@ class CombineTopkSwaIndicesKernel(
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
gather_lens,
|
||||
left_visible if has_image else topk_indices,
|
||||
right_visible if has_image else topk_indices,
|
||||
M,
|
||||
N,
|
||||
TOP_K=TOP_K,
|
||||
COMPRESS_RATIO=COMPRESS_RATIO,
|
||||
WINDOW_SIZE=WINDOW_SIZE,
|
||||
IMAGE_WIDTH=image_width,
|
||||
PADDED_TOP_K=next_power_of_2(topk_indices.shape[-1]),
|
||||
)
|
||||
|
||||
@@ -1172,9 +1124,6 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
decode_is_valid_token: torch.Tensor | None = None,
|
||||
swa_block_span: int | None = None,
|
||||
compressed_block_span: int | None = None,
|
||||
prefill_left_visible: torch.Tensor | None = None,
|
||||
prefill_right_visible: torch.Tensor | None = None,
|
||||
max_image_tokens: int = 0,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Build the FlashInfer DSV4 sparse-index matrix for decode-first batches.
|
||||
|
||||
@@ -1184,21 +1133,11 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
per token). Decode tokens read precomputed SWA/compressed indices; prefill
|
||||
tokens derive their SWA window from the position and translate local
|
||||
compressed indices to global slots via the block tables.
|
||||
|
||||
When ``prefill_left_visible``/``prefill_right_visible`` are given (vision
|
||||
variant), the SWA column region widens by ``max_image_tokens`` and prefill
|
||||
tokens inside an image span get a bidirectionally widened window; decode
|
||||
rows are padded with -1 across the extra columns.
|
||||
"""
|
||||
assert decode_swa_indices.dtype == torch.int32
|
||||
assert decode_swa_indices.dim() == 2
|
||||
swa_index_width = decode_swa_indices.shape[-1]
|
||||
assert swa_index_width >= window_size
|
||||
has_image = prefill_left_visible is not None
|
||||
image_width = max_image_tokens if has_image else 0
|
||||
swa_total_width = swa_index_width + image_width
|
||||
if has_image:
|
||||
assert prefill_right_visible is not None
|
||||
swa_total_width = decode_swa_indices.shape[-1]
|
||||
assert swa_total_width >= window_size
|
||||
if decode_compressed_topk_lens is not None:
|
||||
assert decode_compressed_topk_lens.dtype == torch.int32
|
||||
assert prefill_topk_indices.dtype == torch.int32
|
||||
@@ -1257,7 +1196,7 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
if num_tokens == 0:
|
||||
return sparse_indices, sparse_topk_lens
|
||||
|
||||
window_block_size = triton.next_power_of_2(max(swa_index_width, 1))
|
||||
window_block_size = triton.next_power_of_2(max(swa_total_width, 1))
|
||||
topk_block_size = triton.next_power_of_2(max(padded_topk, 1))
|
||||
max_block_size = max(window_block_size, topk_block_size)
|
||||
num_warps = 4 if max_block_size >= 256 else 1
|
||||
@@ -1281,8 +1220,6 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
decode_is_valid_token,
|
||||
prefill_topk_indices,
|
||||
prefill_topk_indices.stride(0),
|
||||
prefill_left_visible if has_image else token_to_req_indices,
|
||||
prefill_right_visible if has_image else token_to_req_indices,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
token_to_req_indices,
|
||||
@@ -1296,8 +1233,7 @@ def build_flashinfer_mixed_sparse_indices(
|
||||
compressed_span,
|
||||
NUM_DECODE_TOKENS=num_decode_tokens,
|
||||
WINDOW_SIZE=window_size,
|
||||
SWA_INDEX_WIDTH=swa_index_width,
|
||||
IMAGE_WIDTH=image_width,
|
||||
SWA_INDEX_WIDTH=swa_total_width,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
TOP_K=topk,
|
||||
PADDED_TOP_K=padded_topk,
|
||||
@@ -1352,8 +1288,6 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
decode_is_valid_token_ptr,
|
||||
prefill_topk_indices_ptr,
|
||||
prefill_topk_stride,
|
||||
left_visible_ptr,
|
||||
right_visible_ptr,
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
token_to_req_indices_ptr,
|
||||
@@ -1368,7 +1302,6 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
NUM_DECODE_TOKENS,
|
||||
WINDOW_SIZE: tl.constexpr,
|
||||
SWA_INDEX_WIDTH: tl.constexpr,
|
||||
IMAGE_WIDTH: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
TOP_K: tl.constexpr,
|
||||
PADDED_TOP_K: tl.constexpr,
|
||||
@@ -1380,18 +1313,14 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
TOPK_BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
token_idx = tl.program_id(0)
|
||||
# Total SWA column count; > SWA_INDEX_WIDTH only for in-image
|
||||
# bidirectional visibility (vision variant), where the extra columns are
|
||||
# -1-padded for decode rows.
|
||||
SWA_TOTAL_WIDTH: tl.constexpr = SWA_INDEX_WIDTH + IMAGE_WIDTH
|
||||
|
||||
if token_idx < NUM_DECODE_TOKENS:
|
||||
for i in range(0, SWA_TOTAL_WIDTH, WINDOW_BLOCK_SIZE):
|
||||
for i in range(0, SWA_INDEX_WIDTH, WINDOW_BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, WINDOW_BLOCK_SIZE)
|
||||
mask = offset < SWA_TOTAL_WIDTH
|
||||
mask = offset < SWA_INDEX_WIDTH
|
||||
values = tl.load(
|
||||
decode_swa_indices_ptr + token_idx * decode_swa_stride + offset,
|
||||
mask=offset < SWA_INDEX_WIDTH,
|
||||
mask=mask,
|
||||
other=-1,
|
||||
)
|
||||
values = _remap_flashinfer_index(values, swa_block_size, swa_block_span)
|
||||
@@ -1434,7 +1363,7 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
tl.store(
|
||||
sparse_indices_ptr
|
||||
+ token_idx * sparse_indices_stride
|
||||
+ SWA_TOTAL_WIDTH
|
||||
+ SWA_INDEX_WIDTH
|
||||
+ offset,
|
||||
values,
|
||||
mask=mask,
|
||||
@@ -1448,7 +1377,7 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
else:
|
||||
compressed_len = tl.full((), DECODE_COMPRESSED_TOPK, dtype=tl.int32)
|
||||
|
||||
tl.store(sparse_topk_lens_ptr + token_idx, SWA_TOTAL_WIDTH + compressed_len)
|
||||
tl.store(sparse_topk_lens_ptr + token_idx, SWA_INDEX_WIDTH + compressed_len)
|
||||
return
|
||||
|
||||
prefill_idx = token_idx - NUM_DECODE_TOKENS
|
||||
@@ -1460,26 +1389,17 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
start_pos = seq_len - query_len
|
||||
token_idx_in_query = token_idx - query_start
|
||||
pos = start_pos + token_idx_in_query
|
||||
if IMAGE_WIDTH > 0:
|
||||
# In-image bidirectional visibility: window starts up to
|
||||
# max(left - (window - 1), 0) earlier and extends `right` past pos.
|
||||
left = tl.load(left_visible_ptr + token_idx)
|
||||
right = tl.load(right_visible_ptr + token_idx)
|
||||
else:
|
||||
left = 0
|
||||
right = 0
|
||||
left_add = tl.maximum(left - (WINDOW_SIZE - 1), 0)
|
||||
swa_start_pos = tl.maximum(pos - (WINDOW_SIZE - 1) - left_add, 0)
|
||||
swa_len = pos + right - swa_start_pos + 1
|
||||
swa_start_pos = tl.maximum(pos - (WINDOW_SIZE - 1), 0)
|
||||
swa_len = pos - swa_start_pos + 1
|
||||
if COMPRESS_RATIO > 0:
|
||||
topk_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOP_K)
|
||||
else:
|
||||
# SWA-only layers (ratio 0): no indexer topk; div by constexpr 0 is UB.
|
||||
topk_len = 0
|
||||
|
||||
for i in range(0, SWA_TOTAL_WIDTH, WINDOW_BLOCK_SIZE):
|
||||
for i in range(0, SWA_INDEX_WIDTH, WINDOW_BLOCK_SIZE):
|
||||
offset = i + tl.arange(0, WINDOW_BLOCK_SIZE)
|
||||
mask = offset < SWA_TOTAL_WIDTH
|
||||
mask = offset < SWA_INDEX_WIDTH
|
||||
pos_offset = swa_start_pos + offset
|
||||
block_indices = pos_offset // swa_block_size
|
||||
block_numbers = tl.load(
|
||||
@@ -1523,10 +1443,10 @@ def _build_flashinfer_mixed_sparse_indices_kernel(
|
||||
tl.store(
|
||||
sparse_indices_ptr
|
||||
+ token_idx * sparse_indices_stride
|
||||
+ SWA_TOTAL_WIDTH
|
||||
+ SWA_INDEX_WIDTH
|
||||
+ offset,
|
||||
slot_ids,
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
tl.store(sparse_topk_lens_ptr + token_idx, SWA_TOTAL_WIDTH + topk_len)
|
||||
tl.store(sparse_topk_lens_ptr + token_idx, SWA_INDEX_WIDTH + topk_len)
|
||||
|
||||
@@ -58,6 +58,7 @@ def fused_save_compress_norm(
|
||||
rms_norm_eps: RMSNorm epsilon.
|
||||
compress_ratio: Group size, either 1 or 2.
|
||||
latent_out: BF16 [tokens, 512], written only at valid group boundaries.
|
||||
|
||||
"""
|
||||
assert compress_ratio in (1, 2)
|
||||
assert kv_score.dtype == torch.float32
|
||||
|
||||
@@ -46,11 +46,13 @@ def indexer_k_norm_rope_store(
|
||||
cos_sin_cache: [max_pos, rope_head_dim] GPT-J layout (cos half, then
|
||||
sin half), from the layer's compress-RoPE instance.
|
||||
rms_norm_weight: [128] k_norm weight.
|
||||
rms_norm_eps: Epsilon of the k_norm RMSNorm.
|
||||
k_cache: uint8 paged indexer cache [num_blocks, block_size, row_bytes].
|
||||
kv_slot_mapping: [num_tokens] slots in the indexer cache (-1 = skip).
|
||||
compress_ratio: group size; keys are emitted at group boundaries.
|
||||
use_fp4_cache: MXFP4 (2 nibbles/byte + ue8m0 per 32) when True, else
|
||||
per-token FP8 with a single fp32 scale.
|
||||
|
||||
"""
|
||||
num_tokens = kv_slot_mapping.numel()
|
||||
assert k_pre.ndim == 2 and k_pre.shape[1] == 128
|
||||
|
||||
@@ -311,7 +311,7 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
|
||||
else:
|
||||
assert self.topk_indices_buffer is not None
|
||||
top_k = self.topk_indices_buffer.shape[-1]
|
||||
combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128)
|
||||
combined_topk = round_up(top_k + self.window_size, 128)
|
||||
current_workspace_manager().get_simultaneous(
|
||||
((self.PREFILL_CHUNK_SIZE, m, q.shape[-1]), torch.bfloat16),
|
||||
((self.max_num_batched_tokens, combined_topk), torch.int32),
|
||||
@@ -411,7 +411,7 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
|
||||
)
|
||||
assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0"
|
||||
workspace_manager = current_workspace_manager()
|
||||
combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128)
|
||||
combined_topk = round_up(top_k + self.window_size, 128)
|
||||
for chunk_start, chunk_end, chunk_n, chunk_m in chunk_plan:
|
||||
chunk_size = chunk_end - chunk_start
|
||||
kv_ws, idx_ws, lens_ws = workspace_manager.get_simultaneous(
|
||||
@@ -457,21 +457,6 @@ class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
|
||||
chunk_m,
|
||||
chunk_n,
|
||||
out=(idx_ws[: qe - qs], lens_ws[: qe - qs]),
|
||||
left_visible=(
|
||||
swa_metadata.prefill_left_visible[
|
||||
num_decode_tokens + qs : num_decode_tokens + qe
|
||||
]
|
||||
if swa_metadata.prefill_left_visible is not None
|
||||
else None
|
||||
),
|
||||
right_visible=(
|
||||
swa_metadata.prefill_right_visible[
|
||||
num_decode_tokens + qs : num_decode_tokens + qe
|
||||
]
|
||||
if swa_metadata.prefill_right_visible is not None
|
||||
else None
|
||||
),
|
||||
max_image_tokens=self.max_image_tokens,
|
||||
)
|
||||
chunk_out = _token_slice(out, token_base + qs, token_base + qe)
|
||||
# Mega attention over the gathered non-paged bf16 KV (RoPE already
|
||||
|
||||
@@ -417,10 +417,6 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
|
||||
decode_is_valid_token=decode_is_valid_token,
|
||||
swa_block_span=swa_block_span,
|
||||
compressed_block_span=compressed_block_span,
|
||||
prefill_left_visible=swa_metadata.prefill_left_visible,
|
||||
prefill_right_visible=swa_metadata.prefill_right_visible,
|
||||
# getattr for tests that bypass __init__ via object.__new__.
|
||||
max_image_tokens=getattr(self, "max_image_tokens", 0),
|
||||
)
|
||||
if swa_only:
|
||||
swa_metadata.flashinfer_sparse_index_cache["swa_only"] = (
|
||||
|
||||
@@ -120,9 +120,7 @@ class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
|
||||
else:
|
||||
assert self.topk_indices_buffer is not None
|
||||
top_k = self.topk_indices_buffer.shape[-1]
|
||||
combined_topk = round_up(
|
||||
top_k + self.window_size + self.max_image_tokens, 128
|
||||
)
|
||||
combined_topk = round_up(top_k + self.window_size, 128)
|
||||
current_workspace_manager().get_simultaneous(
|
||||
((self.PREFILL_CHUNK_SIZE, M, q.shape[-1]), torch.bfloat16),
|
||||
((self.max_num_batched_tokens, combined_topk), torch.int32),
|
||||
@@ -303,7 +301,7 @@ class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
|
||||
)
|
||||
assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0"
|
||||
workspace_manager = current_workspace_manager()
|
||||
combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128)
|
||||
combined_topk = round_up(top_k + self.window_size, 128)
|
||||
for chunk_start, chunk_end, chunk_N, chunk_M in chunk_plan:
|
||||
chunk_size = chunk_end - chunk_start
|
||||
workspace = workspace_manager.get_simultaneous(
|
||||
@@ -361,21 +359,6 @@ class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
|
||||
chunk_M,
|
||||
chunk_N,
|
||||
out=(combined_indices_out, combined_lens_out),
|
||||
left_visible=(
|
||||
swa_metadata.prefill_left_visible[
|
||||
num_decode_tokens + query_start : num_decode_tokens + query_end
|
||||
]
|
||||
if swa_metadata.prefill_left_visible is not None
|
||||
else None
|
||||
),
|
||||
right_visible=(
|
||||
swa_metadata.prefill_right_visible[
|
||||
num_decode_tokens + query_start : num_decode_tokens + query_end
|
||||
]
|
||||
if swa_metadata.prefill_right_visible is not None
|
||||
else None
|
||||
),
|
||||
max_image_tokens=self.max_image_tokens,
|
||||
)
|
||||
flash_mla_sparse_fwd(
|
||||
q=q[query_start:query_end],
|
||||
|
||||
@@ -34,6 +34,7 @@ from vllm.multimodal.processing import (
|
||||
PromptUpdate,
|
||||
PromptUpdateDetails,
|
||||
)
|
||||
from vllm.multimodal.processing.processor import HFMultiModalInputs
|
||||
from vllm.transformers_utils.repo_utils import get_hf_file_to_dict
|
||||
|
||||
from .video import preprocess_dots3_note_video
|
||||
@@ -630,26 +631,33 @@ class Dots3NoteDummyInputsBuilder(BaseDummyInputsBuilder[Dots3NoteProcessingInfo
|
||||
|
||||
|
||||
class Dots3NoteMultiModalProcessor(BaseMultiModalProcessor[Dots3NoteProcessingInfo]):
|
||||
def _get_hf_mm_data(
|
||||
def _get_hf_mm_inputs(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
) -> tuple[Mapping[str, object], Mapping[str, object]]:
|
||||
processor_data, passthrough_data = super()._get_hf_mm_data(mm_items)
|
||||
if "video" not in mm_items:
|
||||
return processor_data, passthrough_data
|
||||
hf_kwargs: Mapping[str, object],
|
||||
) -> HFMultiModalInputs:
|
||||
hf_inputs = super()._get_hf_mm_inputs(mm_items, hf_kwargs)
|
||||
|
||||
videos = mm_items.get_items("video", VideoProcessorItems)
|
||||
raw_videos: list[object] = []
|
||||
for index, item in enumerate(videos.data):
|
||||
if isinstance(item, MediaWithBytes):
|
||||
raw_videos.append(item.original_bytes)
|
||||
else:
|
||||
raw_videos.append(videos.get(index))
|
||||
processor_data = dict(processor_data)
|
||||
processor_data["videos"] = raw_videos
|
||||
return processor_data, passthrough_data
|
||||
# The Dots3Note processor accepts "audios" instead of "audio"
|
||||
hf_data = hf_inputs.hf_data
|
||||
if "audio" in hf_data:
|
||||
hf_data["audios"] = hf_data.pop("audio")
|
||||
|
||||
def _get_hf_processor_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
if "video" in mm_items:
|
||||
videos = mm_items.get_items("video", VideoProcessorItems)
|
||||
|
||||
raw_videos: list[object] = []
|
||||
for index, item in enumerate(videos.data):
|
||||
if isinstance(item, MediaWithBytes):
|
||||
raw_videos.append(item.original_bytes)
|
||||
else:
|
||||
raw_videos.append(videos.get(index))
|
||||
|
||||
hf_data["videos"] = raw_videos
|
||||
|
||||
return hf_inputs
|
||||
|
||||
def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return self.dummy_inputs.get_dummy_text(mm_counts)
|
||||
|
||||
def _get_mm_fields_config(
|
||||
|
||||
@@ -194,7 +194,7 @@ class WhisperPositionalEmbedding(nn.Embedding):
|
||||
|
||||
|
||||
class WhisperAttention(nn.Module):
|
||||
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
||||
"""Multi-headed attention from 'Attention Is All You Need' paper."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -346,8 +346,7 @@ class WhisperEncoderLayer(nn.Module):
|
||||
rotary_cos: torch.Tensor | None = None,
|
||||
rotary_sin: torch.Tensor | None = None,
|
||||
) -> tuple[Any, ...]:
|
||||
"""
|
||||
Args:
|
||||
"""Args:
|
||||
hidden_states: Input to the layer of shape `(batch, seq_len,
|
||||
embed_dim)`, or `(total_tokens, embed_dim)` when `cu_seqlens_q`
|
||||
is given.
|
||||
@@ -365,6 +364,7 @@ class WhisperEncoderLayer(nn.Module):
|
||||
Returns:
|
||||
A tuple of the output hidden states, followed by the attention
|
||||
weights if `output_attentions` is `True`.
|
||||
|
||||
"""
|
||||
residual = hidden_states
|
||||
hidden_states = self.self_attn_layer_norm(hidden_states)
|
||||
@@ -435,12 +435,12 @@ class DotsSpeechPreTrainedModel(PreTrainedModel):
|
||||
|
||||
|
||||
class DotsSpeechEncoder(DotsSpeechPreTrainedModel):
|
||||
"""
|
||||
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
||||
"""Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
||||
[`WhisperEncoderLayer`].
|
||||
|
||||
Args:
|
||||
config: WhisperConfig
|
||||
|
||||
"""
|
||||
|
||||
def __init__(self, config: WhisperConfig):
|
||||
|
||||
@@ -212,6 +212,13 @@ def kpool_compress_and_write_cache(
|
||||
slot_score: ``[n_pools, pool_size, head_dim]`` — per-token gate score.
|
||||
ape: ``[pool_size, head_dim]`` fp32 — per-slot position bias.
|
||||
loc: ``[n_pools]`` int64 — flat physical slot per pool.
|
||||
pool_size: Number of tokens compressed into one cache entry.
|
||||
head_dim: Indexer head dimension.
|
||||
write_mask: ``[n_pools]`` bool — pools to write, or None for all.
|
||||
round_scale: Round each fp8 scale down to a power of two.
|
||||
return_compressed: Also return the compressed K and scales.
|
||||
write_cache: Write the compressed result into ``kv_cache``.
|
||||
|
||||
"""
|
||||
assert slot_k.ndim == 3
|
||||
assert slot_score.shape == slot_k.shape
|
||||
@@ -592,6 +599,10 @@ def kpool_decode_update_and_maybe_write_cache_batched(
|
||||
ape: ``[pool_size, head_dim]`` fp32.
|
||||
slot_mapping: ``[num_requests, next_n]`` int32.
|
||||
positions: ``[num_requests, next_n]`` int32.
|
||||
pool_size: Number of tokens compressed into one cache entry.
|
||||
head_dim: Indexer head dimension.
|
||||
round_scale: Round each fp8 scale down to a power of two.
|
||||
|
||||
"""
|
||||
num_requests, next_n = key.shape[0], key.shape[1]
|
||||
if num_requests == 0 or next_n == 0:
|
||||
|
||||
@@ -564,8 +564,7 @@ def fused_recurrent_gated_delta_rule(
|
||||
num_accepted_tokens: torch.Tensor | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
r"""
|
||||
Args:
|
||||
r"""Args:
|
||||
q (torch.Tensor):
|
||||
queries of shape `[B, T, H, K]`.
|
||||
k (torch.Tensor):
|
||||
@@ -627,6 +626,7 @@ def fused_recurrent_gated_delta_rule(
|
||||
initial_state=h0,
|
||||
cu_seqlens=cu_seqlens
|
||||
)
|
||||
|
||||
"""
|
||||
if cu_seqlens is not None and q.shape[0] != 1:
|
||||
raise ValueError(
|
||||
|
||||
+17
-12
@@ -406,19 +406,24 @@ def chunk_kda_scaled_dot_kkt_fwd(
|
||||
chunk_size: int = FLA_CHUNK_SIZE,
|
||||
output_dtype: torch.dtype = torch.float32,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
r"""
|
||||
Compute beta * K * K^T.
|
||||
r"""Compute beta * K * K^T.
|
||||
|
||||
Args:
|
||||
q (torch.Tensor):
|
||||
The query tensor of shape `[B, T, H, K]`.
|
||||
k (torch.Tensor):
|
||||
The key tensor of shape `[B, T, H, K]`.
|
||||
beta (torch.Tensor):
|
||||
The beta tensor of shape `[B, T, H]`.
|
||||
gk (torch.Tensor):
|
||||
The cumulative sum of the gate tensor of shape `[B, T, H, K]` applied to the key tensor. Default: `None`.
|
||||
scale (float):
|
||||
Scale applied to the query-key products. Default: `None`.
|
||||
cu_seqlens (torch.Tensor):
|
||||
The cumulative sequence lengths of the input tensor.
|
||||
Default: None
|
||||
chunk_indices (torch.Tensor):
|
||||
Precomputed chunk indices for `cu_seqlens`. Default: `None`.
|
||||
chunk_size (int):
|
||||
The chunk size. Default: 64.
|
||||
output_dtype (torch.dtype):
|
||||
@@ -426,6 +431,7 @@ def chunk_kda_scaled_dot_kkt_fwd(
|
||||
|
||||
Returns:
|
||||
beta * K * K^T of shape `[B, T, H, BT]` where `BT` is the chunk size.
|
||||
|
||||
"""
|
||||
B, T, H, K = k.shape
|
||||
assert K <= 256
|
||||
@@ -1318,16 +1324,15 @@ def fused_kda_gate(
|
||||
safe_gate: bool = False,
|
||||
lower_bound: float | None = -5.0,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter (softplus branch only)
|
||||
threshold: softplus threshold parameter (softplus branch only)
|
||||
safe_gate: when False (default) compute y = -exp(A)*softplus(g+g_bias);
|
||||
when True compute the bounded y = lower_bound*sigmoid(exp(A)*(g+g_bias))
|
||||
lower_bound: floor for the safe_gate branch (default -5.0)
|
||||
return : [..., H, D]
|
||||
"""Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter (softplus branch only)
|
||||
threshold: softplus threshold parameter (softplus branch only)
|
||||
safe_gate: when False (default) compute y = -exp(A)*softplus(g+g_bias);
|
||||
when True compute the bounded y = lower_bound*sigmoid(exp(A)*(g+g_bias))
|
||||
lower_bound: floor for the safe_gate branch (default -5.0)
|
||||
return : [..., H, D]
|
||||
"""
|
||||
orig_shape = g.shape[:-1]
|
||||
|
||||
|
||||
@@ -116,6 +116,7 @@ def fwht128_quant_fp8(q: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
|
||||
Returns:
|
||||
(q_fp8 ``[rows, 128]`` float8_e4m3fn, scale ``[rows, 1]`` float32).
|
||||
|
||||
"""
|
||||
assert q.ndim == 2 and q.shape[1] == 128, q.shape
|
||||
assert q.dtype == torch.bfloat16
|
||||
@@ -276,6 +277,13 @@ def kpool_compress_and_write_cache(
|
||||
slot_score: ``[n_pools, pool_size, head_dim]`` — per-token gate score.
|
||||
ape: ``[pool_size, head_dim]`` fp32 — per-slot position bias.
|
||||
loc: ``[n_pools]`` int64 — flat physical slot per pool.
|
||||
pool_size: Number of tokens compressed into one cache entry.
|
||||
head_dim: Indexer head dimension.
|
||||
write_mask: ``[n_pools]`` bool — pools to write, or None for all.
|
||||
round_scale: Round each fp8 scale down to a power of two.
|
||||
return_compressed: Also return the compressed K and scales.
|
||||
write_cache: Write the compressed result into ``kv_cache``.
|
||||
|
||||
"""
|
||||
assert slot_k.ndim == 3
|
||||
assert slot_score.shape == slot_k.shape
|
||||
@@ -642,6 +650,10 @@ def kpool_decode_update_and_maybe_write_cache_batched(
|
||||
ape: ``[pool_size, head_dim]`` fp32.
|
||||
slot_mapping: ``[num_requests, next_n]`` int32.
|
||||
positions: ``[num_requests, next_n]`` int32.
|
||||
pool_size: Number of tokens compressed into one cache entry.
|
||||
head_dim: Indexer head dimension.
|
||||
round_scale: Round each fp8 scale down to a power of two.
|
||||
|
||||
"""
|
||||
num_requests, next_n = key.shape[0], key.shape[1]
|
||||
if num_requests == 0 or next_n == 0:
|
||||
|
||||
@@ -590,8 +590,7 @@ def fused_recurrent_gated_delta_rule(
|
||||
num_accepted_tokens: torch.Tensor | None = None,
|
||||
use_qk_l2norm_in_kernel: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
r"""
|
||||
Args:
|
||||
r"""Args:
|
||||
q (torch.Tensor):
|
||||
queries of shape `[B, T, H, K]`.
|
||||
k (torch.Tensor):
|
||||
@@ -653,6 +652,7 @@ def fused_recurrent_gated_delta_rule(
|
||||
initial_state=h0,
|
||||
cu_seqlens=cu_seqlens
|
||||
)
|
||||
|
||||
"""
|
||||
if cu_seqlens is not None and q.shape[0] != 1:
|
||||
raise ValueError(
|
||||
|
||||
+17
-12
@@ -416,19 +416,24 @@ def chunk_kda_scaled_dot_kkt_fwd(
|
||||
chunk_size: int = FLA_CHUNK_SIZE,
|
||||
output_dtype: torch.dtype = torch.float32,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
r"""
|
||||
Compute beta * K * K^T.
|
||||
r"""Compute beta * K * K^T.
|
||||
|
||||
Args:
|
||||
q (torch.Tensor):
|
||||
The query tensor of shape `[B, T, H, K]`.
|
||||
k (torch.Tensor):
|
||||
The key tensor of shape `[B, T, H, K]`.
|
||||
beta (torch.Tensor):
|
||||
The beta tensor of shape `[B, T, H]`.
|
||||
gk (torch.Tensor):
|
||||
The cumulative sum of the gate tensor of shape `[B, T, H, K]` applied to the key tensor. Default: `None`.
|
||||
scale (float):
|
||||
Scale applied to the query-key products. Default: `None`.
|
||||
cu_seqlens (torch.Tensor):
|
||||
The cumulative sequence lengths of the input tensor.
|
||||
Default: None
|
||||
chunk_indices (torch.Tensor):
|
||||
Precomputed chunk indices for `cu_seqlens`. Default: `None`.
|
||||
chunk_size (int):
|
||||
The chunk size. Default: 64.
|
||||
output_dtype (torch.dtype):
|
||||
@@ -436,6 +441,7 @@ def chunk_kda_scaled_dot_kkt_fwd(
|
||||
|
||||
Returns:
|
||||
beta * K * K^T of shape `[B, T, H, BT]` where `BT` is the chunk size.
|
||||
|
||||
"""
|
||||
B, T, H, K = k.shape
|
||||
assert K <= 256
|
||||
@@ -1328,16 +1334,15 @@ def fused_kda_gate(
|
||||
safe_gate: bool = False,
|
||||
lower_bound: float | None = -5.0,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter (softplus branch only)
|
||||
threshold: softplus threshold parameter (softplus branch only)
|
||||
safe_gate: when False (default) compute y = -exp(A)*softplus(g+g_bias);
|
||||
when True compute the bounded y = lower_bound*sigmoid(exp(A)*(g+g_bias))
|
||||
lower_bound: floor for the safe_gate branch (default -5.0)
|
||||
return : [..., H, D]
|
||||
"""Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter (softplus branch only)
|
||||
threshold: softplus threshold parameter (softplus branch only)
|
||||
safe_gate: when False (default) compute y = -exp(A)*softplus(g+g_bias);
|
||||
when True compute the bounded y = lower_bound*sigmoid(exp(A)*(g+g_bias))
|
||||
lower_bound: floor for the safe_gate branch (default -5.0)
|
||||
return : [..., H, D]
|
||||
"""
|
||||
orig_shape = g.shape[:-1]
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ def compute_skip_topk_layers(config: PretrainedConfig) -> set[int]:
|
||||
Raises:
|
||||
ValueError: If ``indexer_types`` has the wrong length or an unknown
|
||||
entry, or if ``index_topk_freq`` is not a positive integer.
|
||||
|
||||
"""
|
||||
if not hasattr(config, "index_topk"):
|
||||
return set()
|
||||
@@ -115,6 +116,7 @@ def is_skip_topk_indexer_weight(weight_name: str, skip_topk_layers: set[int]) ->
|
||||
Returns:
|
||||
True when the weight is an indexer weight of a layer that has no
|
||||
indexer module and therefore must be dropped.
|
||||
|
||||
"""
|
||||
if ".indexer." not in weight_name or not skip_topk_layers:
|
||||
return False
|
||||
@@ -557,6 +559,7 @@ class HYV4MLAAttention(nn.Module):
|
||||
The backend class to bind, or None when no sink-capable backend is
|
||||
available; the caller then loads the sink weight but disables the
|
||||
bias.
|
||||
|
||||
"""
|
||||
head_size = self.kv_lora_rank + self.qk_rope_head_dim
|
||||
dtype = torch.get_default_dtype()
|
||||
|
||||
@@ -99,6 +99,7 @@ class HYV4FlashMLASparseImpl(FlashMLASparseImpl):
|
||||
Raises:
|
||||
ValueError: If the dtype is not float32 or the shape is not
|
||||
``(num_heads,)``.
|
||||
|
||||
"""
|
||||
if sinks is None:
|
||||
return
|
||||
@@ -134,6 +135,7 @@ class HYV4FlashMLASparseImpl(FlashMLASparseImpl):
|
||||
Raises:
|
||||
ValueError: If the sink and query head layouts disagree, or if they
|
||||
live on different devices.
|
||||
|
||||
"""
|
||||
sinks = self.sinks
|
||||
if sinks is None:
|
||||
|
||||
@@ -107,6 +107,7 @@ class HYV4HCPreLayer(nn.Module):
|
||||
Returns:
|
||||
A tuple of the pre-gated reduction ``[num_tokens, d]`` and the post
|
||||
gates ``[num_tokens, hc]`` consumed by `HYV4HCPostLayer`.
|
||||
|
||||
"""
|
||||
if self.hpc_op is not None:
|
||||
return self.hpc_op(x)
|
||||
@@ -186,6 +187,7 @@ class HYV4HCPostLayer(nn.Module):
|
||||
|
||||
Returns:
|
||||
The updated residual channels ``[num_tokens, hc, d]``.
|
||||
|
||||
"""
|
||||
if self.hpc_op is not None:
|
||||
return self.hpc_op(x, residual, post)
|
||||
@@ -272,6 +274,7 @@ class HYV4HCHeadLayer(nn.Module):
|
||||
|
||||
Returns:
|
||||
The merged hidden state ``[num_tokens, d]``.
|
||||
|
||||
"""
|
||||
if self.hpc_op is not None:
|
||||
return self.hpc_op(x)
|
||||
@@ -367,6 +370,7 @@ class HYV4HCLayer(nn.Module):
|
||||
A tuple of the reduced hidden states ``[num_tokens, d]``, the post
|
||||
gates ``[num_tokens, hc]`` (``None`` when iHC is disabled) and the
|
||||
residual (the untouched input).
|
||||
|
||||
"""
|
||||
if not self.enable_ihc:
|
||||
return hidden_states, None, hidden_states
|
||||
|
||||
@@ -189,7 +189,7 @@ class HYV4DecoderLayer(nn.Module):
|
||||
positions: torch.Tensor,
|
||||
hidden_states: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, None]:
|
||||
"""iHC forward: each sub-block reduces and re-scatters the channels."""
|
||||
"""IHC forward: each sub-block reduces and re-scatters the channels."""
|
||||
hidden_states = self.hc_attn_layer.prepare_input(hidden_states)
|
||||
hidden_states, post_gates, residual = self.hc_attn_layer.pre(hidden_states)
|
||||
hidden_states = self.input_layernorm(hidden_states)
|
||||
|
||||
@@ -106,6 +106,7 @@ def _resolve_fused_expert_param(
|
||||
|
||||
Returns:
|
||||
The matching draft parameter name, or None when there is none.
|
||||
|
||||
"""
|
||||
if not ckpt_suffix:
|
||||
return param_base if param_base in params_dict else None
|
||||
@@ -164,6 +165,7 @@ def _create_mtp_quant_config(
|
||||
Returns:
|
||||
The quantization config to use for the MTP layers, or None when the MTP
|
||||
layers are unquantized.
|
||||
|
||||
"""
|
||||
mtp_quant_algo = getattr(hf_config, "mtp_quant_algo", None)
|
||||
|
||||
@@ -241,6 +243,7 @@ def _remap_mtp_quant_exclusions(
|
||||
|
||||
Returns:
|
||||
A shallow copy with the translated exclusions, or the input unchanged.
|
||||
|
||||
"""
|
||||
if quant_config is None:
|
||||
return None
|
||||
@@ -671,6 +674,7 @@ class HYV4MTP(nn.Module):
|
||||
Returns:
|
||||
True when the weight was consumed (even if this rank holds none of
|
||||
the addressed experts).
|
||||
|
||||
"""
|
||||
base = name.split(".experts.")[0]
|
||||
for ckpt_proj, tag in (
|
||||
|
||||
@@ -37,6 +37,7 @@ class InklingLogitsProcessor(LogitsProcessor):
|
||||
soft_cap: Optional logit soft cap (``None`` for the served checkpoint).
|
||||
logits_mup_width_multiplier: muP width divisor for the final logits;
|
||||
``None`` or ``0`` disables it.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -182,20 +182,19 @@ class InklingMultiModalProcessor(BaseMultiModalProcessor[InklingProcessingInfo])
|
||||
def _apply_hf_processor_main(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
hf_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
valid_mm_items = mm_items.select(
|
||||
{k for k, c in mm_items.get_all_counts().items() if c > 0}
|
||||
mm_data, hf_kwargs, passthrough_data = self._get_hf_mm_inputs(
|
||||
mm_items, hf_kwargs
|
||||
)
|
||||
mm_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)
|
||||
|
||||
prompt_text = self.dummy_inputs.get_dummy_text(mm_items.get_all_counts())
|
||||
|
||||
processor = self.info.get_hf_processor(**hf_processor_mm_kwargs)
|
||||
processor = self.info.get_hf_processor(**hf_kwargs)
|
||||
tokenizer = self.info.get_tokenizer()
|
||||
|
||||
images = mm_data.get("images") or []
|
||||
audios = mm_data.get("audios") or []
|
||||
audios = mm_data.get("audio") or []
|
||||
if not isinstance(images, list):
|
||||
images = list(cast(Iterable[Any], images))
|
||||
if not isinstance(audios, list):
|
||||
@@ -235,8 +234,9 @@ class InklingMultiModalProcessor(BaseMultiModalProcessor[InklingProcessingInfo])
|
||||
data["num_audio_tokens"] = torch.tensor(num_audio_tokens, dtype=torch.int64)
|
||||
|
||||
processed_data = BatchFeature(data=data, tensor_type=None)
|
||||
processed_data.update(passthrough_data)
|
||||
return processed_data
|
||||
return self._finalize_hf_mm_data(
|
||||
mm_data, hf_kwargs, passthrough_data, processed_data
|
||||
)
|
||||
|
||||
def _tokenize_with_placeholders(
|
||||
self,
|
||||
|
||||
@@ -37,6 +37,7 @@ class InklingLogitsProcessor(LogitsProcessor):
|
||||
soft_cap: Optional logit soft cap (``None`` for the served checkpoint).
|
||||
logits_mup_width_multiplier: muP width divisor for the final logits;
|
||||
``None`` or ``0`` disables it.
|
||||
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
|
||||
@@ -61,9 +61,7 @@ class ROCmLatentMoERunner(MoERunner):
|
||||
shared_output: torch.Tensor,
|
||||
trunc_size: int | None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Tier 2: column-parallel up-projection folded into the final reduce.
|
||||
"""
|
||||
"""Tier 2: column-parallel up-projection folded into the final reduce."""
|
||||
if not self._logged_sharded_tail:
|
||||
self._logged_sharded_tail = True
|
||||
logger.info_once(
|
||||
|
||||
@@ -317,9 +317,7 @@ class KimiMoE(nn.Module):
|
||||
|
||||
|
||||
class KimiMLAAttention(nn.Module):
|
||||
"""
|
||||
Main reference: DeepseekV2 vllm Implementation
|
||||
"""
|
||||
"""Main reference: DeepseekV2 vllm Implementation."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -213,9 +213,17 @@ def fused_kda_chunk(
|
||||
|
||||
Args:
|
||||
qg: ``q * exp2(gk_cumsum)``, ``[1, T, H, 128]``.
|
||||
w: chunk-local WY representation of the gated keys.
|
||||
u: chunk-local WY representation of the values.
|
||||
kg_t: chunk-major transposed gated keys, ``[chunks, H, 128, 64]``.
|
||||
aqk: intra-chunk query-key attention, ``[chunks, H, 64, 64]``.
|
||||
decay: ``exp2`` of each chunk's last gate row, ``[chunks, H, 128]``.
|
||||
out: output buffer, ``[1, T, H, 128]``; may alias ``u``'s source.
|
||||
scale: scale applied to the query-key products.
|
||||
cu_seqlens: int32 cumulative sequence lengths.
|
||||
initial_state: fp32 per-sequence initial recurrent state, or ``None``.
|
||||
output_final_state: whether to return the final recurrent state.
|
||||
chunk_offsets: int32 per-sequence first chunk index.
|
||||
checkpoint_state: destination for the mid-prefill state snapshots,
|
||||
fp32 ``[rows, H, 128, 128]``. Without
|
||||
``checkpoint_state_indices`` it is a staging buffer indexed by
|
||||
@@ -239,6 +247,7 @@ def fused_kda_chunk(
|
||||
has_initial_state: bool ``[N]``; a false entry starts that sequence
|
||||
from a zero state and its cache row is read only, never before the
|
||||
walk writes it.
|
||||
|
||||
"""
|
||||
if state_cache is not None:
|
||||
if initial_state is not None or output_final_state:
|
||||
|
||||
@@ -52,6 +52,22 @@ def chunk_kda_prefill(
|
||||
"""Run chunk KDA from raw gate and beta projections.
|
||||
|
||||
Args:
|
||||
q: query tensor, ``[1, T, H, K]``.
|
||||
k: key tensor, ``[1, T, H, K]``.
|
||||
v: value tensor, ``[1, T, H, V]``.
|
||||
raw_g: raw gate projection, before the activation.
|
||||
raw_beta: raw beta projection, before the activation.
|
||||
A_log: log of the per-head gate decay.
|
||||
g_bias: optional per-head gate bias.
|
||||
scale: scale applied to the query-key products. Defaults to
|
||||
``k.shape[-1] ** -0.5``.
|
||||
initial_state: fp32 per-sequence initial recurrent state, or ``None``.
|
||||
output_final_state: whether to return the final recurrent state.
|
||||
lower_bound: optional floor applied to the gate.
|
||||
use_qk_l2norm_in_kernel: fold the q/k L2 norm into the kernel.
|
||||
cu_seqlens: int32 cumulative sequence lengths.
|
||||
chunk_indices: precomputed chunk indices for ``cu_seqlens``.
|
||||
chunk_offsets: int32 per-sequence first chunk index.
|
||||
use_fused_chunk: request the two-kernel ROCm path. It is used only when
|
||||
every one of its preconditions holds; otherwise the Triton path
|
||||
runs unchanged.
|
||||
@@ -71,6 +87,7 @@ def chunk_kda_prefill(
|
||||
|
||||
Returns:
|
||||
The output and, when requested, the final recurrent state.
|
||||
|
||||
"""
|
||||
if scale is None:
|
||||
scale = k.shape[-1] ** -0.5
|
||||
|
||||
+6
-7
@@ -910,13 +910,12 @@ def fused_kda_gate(
|
||||
threshold: float = 20.0,
|
||||
lower_bound: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter
|
||||
threshold: softplus threshold parameter
|
||||
return : [..., H, D]
|
||||
"""Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter
|
||||
threshold: softplus threshold parameter
|
||||
return : [..., H, D]
|
||||
"""
|
||||
orig_shape = g.shape[:-1]
|
||||
|
||||
|
||||
@@ -59,8 +59,7 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
USE_SAFE_GATE: tl.constexpr,
|
||||
SOLVE_TRIL_DOT_PRECISION: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Fused kernel: compute inter-subchunk Akk + solve_tril in one pass.
|
||||
"""Fused kernel: compute inter-subchunk Akk + solve_tril in one pass.
|
||||
Prerequisite: token_parallel has already computed diagonal Akk blocks in Akkd.
|
||||
|
||||
This kernel:
|
||||
|
||||
@@ -151,8 +151,7 @@ def chunk_kda_fwd_intra_token_parallel(
|
||||
chunk_size: int = 64,
|
||||
sub_chunk_size: int = 16,
|
||||
) -> None:
|
||||
"""
|
||||
Token-parallel implementation: each token gets its own thread block.
|
||||
"""Token-parallel implementation: each token gets its own thread block.
|
||||
Supports both fixed-length and variable-length sequences.
|
||||
Reduces wasted computation on padding.
|
||||
|
||||
@@ -164,10 +163,12 @@ def chunk_kda_fwd_intra_token_parallel(
|
||||
gk: [B, T, HV, K] cumsum of gates (HV >= H for GVA)
|
||||
beta: [B, T, HV]
|
||||
Aqk: [B, T, HV, BT] output tensor to write to
|
||||
cu_seqlens: cumulative sequence lengths for variable-length input
|
||||
Akk: [B, T, HV, BC] output tensor for diagonal blocks (fp32)
|
||||
scale: attention scale
|
||||
chunk_size: BT (default 64)
|
||||
sub_chunk_size: BC (default 16)
|
||||
|
||||
"""
|
||||
B, T, H, K, HV = *q.shape, gk.shape[2]
|
||||
N = len(cu_seqlens) - 1 if cu_seqlens is not None else B
|
||||
|
||||
@@ -427,10 +427,33 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
|
||||
spec_token_start = None
|
||||
non_spec_token_start = None
|
||||
if num_spec_decodes == 0:
|
||||
# The runner orders ordinary decodes before prefills.
|
||||
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
|
||||
split_decodes_and_prefills(m, decode_threshold=1)
|
||||
# V2 already excludes prefills from full decode graphs via has_prefill.
|
||||
# Classify first chunks as prefills to mask recycled state;
|
||||
# resumed one-token chunks can still use the decode kernels.
|
||||
assert m.seq_lens_cpu_upper_bound is not None
|
||||
query_lens_cpu = query_start_loc_cpu.diff()
|
||||
no_prior_state = (query_lens_cpu > 0) & (
|
||||
m.seq_lens_cpu_upper_bound <= query_lens_cpu
|
||||
)
|
||||
# Capture batches also have seq_len == query_len, but are not prefills.
|
||||
if m.is_prefilling is not None:
|
||||
no_prior_state &= m.is_prefilling
|
||||
else:
|
||||
no_prior_state = torch.zeros_like(no_prior_state)
|
||||
num_decodes, num_prefills, num_decode_tokens, num_prefill_tokens = (
|
||||
split_decodes_and_prefills(
|
||||
m.replace(is_prefilling=no_prior_state),
|
||||
decode_threshold=1,
|
||||
treat_short_extends_as_decodes=False,
|
||||
)
|
||||
)
|
||||
# Exclude trailing padding from both prefill counts.
|
||||
if num_prefills:
|
||||
num_prefills -= int((query_lens_cpu[num_decodes:] == 0).sum())
|
||||
num_prefill_tokens = (
|
||||
int(query_start_loc_cpu[num_decodes + num_prefills])
|
||||
- num_decode_tokens
|
||||
)
|
||||
num_spec_decode_tokens = 0
|
||||
spec_token_indx = None
|
||||
non_spec_token_indx = None
|
||||
|
||||
@@ -275,9 +275,7 @@ class LatentMoERunner(MoERunner):
|
||||
shared_output: torch.Tensor,
|
||||
trunc_size: int | None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Tier 2: column-parallel up-projection folded into the final reduce.
|
||||
"""
|
||||
"""Tier 2: column-parallel up-projection folded into the final reduce."""
|
||||
transform = self.routed_output_transform
|
||||
assert transform is not None
|
||||
|
||||
|
||||
@@ -751,6 +751,7 @@ def run_kda_projection_overlap(
|
||||
|
||||
Returns:
|
||||
The Q/K/V/G projection, F_B output, and beta projection.
|
||||
|
||||
"""
|
||||
num_tokens = hidden_states.shape[0]
|
||||
qkvg_weight = packed_weight[:_KDA_QKVG_SIZE]
|
||||
|
||||
@@ -339,6 +339,7 @@ class KimiRoutedOutputTransform(nn.Module):
|
||||
residual: Optional tensor of the up-projection's output shape to
|
||||
accumulate into. It is consumed in the GEMM's beta-add
|
||||
epilogue, so adding it costs no extra kernel.
|
||||
|
||||
"""
|
||||
if self.norm is not None:
|
||||
hidden_states = self.norm(hidden_states)
|
||||
@@ -796,6 +797,7 @@ class KimiMoE(nn.Module):
|
||||
``router_output`` holds the grouped top-k weights and ``topk_ids``
|
||||
the selected experts; otherwise ``router_output`` holds the raw gate
|
||||
logits and ``topk_ids`` is ``None``.
|
||||
|
||||
"""
|
||||
|
||||
def _router(
|
||||
|
||||
-3
@@ -59,7 +59,6 @@ def _mapping(
|
||||
|
||||
def validate_shape(*, tp_size: int, latent_dim: int, hidden_dim: int) -> None:
|
||||
"""Validate constraints imposed by the fused collective mapping."""
|
||||
|
||||
if tp_size <= 0 or latent_dim <= 0 or hidden_dim <= 0:
|
||||
raise ValueError("collective dimensions must be positive")
|
||||
if hidden_dim % tp_size:
|
||||
@@ -86,7 +85,6 @@ def _select_routed_schedule(
|
||||
max_m: int,
|
||||
) -> tuple[int, int]:
|
||||
"""Match upstream MNNVL's one-cluster-per-token occupancy policy."""
|
||||
|
||||
_, cluster_ctas, threads, _ = _mapping(tp_size, latent_dim, hidden_dim)
|
||||
sm_count = torch.cuda.get_device_properties(
|
||||
torch.accelerator.current_device_index()
|
||||
@@ -886,7 +884,6 @@ def compile_kernel(
|
||||
top_k: int = 0,
|
||||
) -> None:
|
||||
"""Compile the rank/M specialization without retaining caller tensors."""
|
||||
|
||||
key = _compile_key(
|
||||
rank,
|
||||
tp_size,
|
||||
|
||||
@@ -79,7 +79,6 @@ def validate_configuration(
|
||||
b_prime_stages: int,
|
||||
) -> None:
|
||||
"""Validate constraints imposed by this BF16 SM100 GEMM."""
|
||||
|
||||
if latent_dim <= 0 or shard_dim <= 0:
|
||||
raise ValueError("GEMM K and N must be positive")
|
||||
if latent_dim % 8 or shard_dim % 8:
|
||||
|
||||
@@ -52,7 +52,6 @@ def to_cute_dynamic_m(
|
||||
mode is symbolic, so changing M within an Op's capacity reuses the same
|
||||
compiled kernel.
|
||||
"""
|
||||
|
||||
return to_cute(tensor, assumed_align).mark_compact_shape_dynamic(
|
||||
mode=mode,
|
||||
stride_order=tensor.dim_order(),
|
||||
@@ -98,7 +97,6 @@ def load_global_u32x4(
|
||||
side-effecting prevents loop-invariant motion and common-subexpression
|
||||
elimination across polling iterations.
|
||||
"""
|
||||
|
||||
address = pointer.toint(loc=loc, ip=ip)
|
||||
opcode = "ld.volatile.global.v4.u32" if volatile else "ld.global.v4.u32"
|
||||
out = llvm.inline_asm(
|
||||
@@ -194,7 +192,6 @@ def finalize_top16_bf16(
|
||||
ip=None,
|
||||
):
|
||||
"""Finalize one Kimi K3 top-16 vector with wide metadata loads."""
|
||||
|
||||
addresses = [
|
||||
pointer.toint(loc=loc, ip=ip).ir_value(loc=loc, ip=ip)
|
||||
for pointer in (gemm2_vector, route_indices, route_weights)
|
||||
@@ -229,7 +226,6 @@ def store_global_u32x4(
|
||||
ip=None,
|
||||
) -> None:
|
||||
"""Store four packed words to an ordinary or NVLS multicast global VA."""
|
||||
|
||||
words = [packed[i].ir_value(loc=loc, ip=ip) for i in range(4)]
|
||||
opcode = "st.volatile.global.v4.u32" if volatile else "st.global.v4.u32"
|
||||
llvm.inline_asm(
|
||||
@@ -294,7 +290,6 @@ def store_global_u32(
|
||||
@dsl_user_op
|
||||
def stmc_bf16x8(address: Int64, packed, *, loc=None, ip=None) -> None:
|
||||
"""Publish eight BF16 values through an NVLS multicast mapping."""
|
||||
|
||||
words = [packed[i].ir_value(loc=loc, ip=ip) for i in range(4)]
|
||||
llvm.inline_asm(
|
||||
None,
|
||||
@@ -312,7 +307,6 @@ def stmc_bf16x8(address: Int64, packed, *, loc=None, ip=None) -> None:
|
||||
@dsl_user_op
|
||||
def store_lamport_sentinel_128(pointer: cute.Pointer, *, loc=None, ip=None) -> None:
|
||||
"""Reset one Lamport fragment to four FP32 negative-zero bit patterns."""
|
||||
|
||||
address = pointer.toint(loc=loc, ip=ip)
|
||||
value = Uint32(NEG_ZERO_F32_BITS).ir_value(loc=loc, ip=ip)
|
||||
llvm.inline_asm(
|
||||
@@ -333,7 +327,6 @@ def red_async_release_gpu_add_u32(
|
||||
pointer: cute.Pointer, value: Uint32, *, loc=None, ip=None
|
||||
) -> None:
|
||||
"""The exact SM100 arrival primitive used by upstream LamportFlags."""
|
||||
|
||||
address = pointer.toint(loc=loc, ip=ip)
|
||||
llvm.inline_asm(
|
||||
None,
|
||||
@@ -378,7 +371,6 @@ def map_shared_to_peer(
|
||||
ip=None,
|
||||
) -> Int32:
|
||||
"""Map a local shared-memory slot to the same slot in a peer CTA."""
|
||||
|
||||
smem_address = smem_ptr.toint(loc=loc, ip=ip).ir_value()
|
||||
return Int32(
|
||||
llvm.inline_asm(
|
||||
@@ -422,7 +414,6 @@ def store_shared_cluster_f32(
|
||||
@dsl_user_op
|
||||
def load_shared_f32x2(pointer: cute.Pointer, *, loc=None, ip=None):
|
||||
"""Load two aligned FP32 DSM partials from local shared memory."""
|
||||
|
||||
address = Int32(pointer.toint(loc=loc, ip=ip))
|
||||
out = llvm.inline_asm(
|
||||
llvm.StructType.get_literal([T.f32()] * 2),
|
||||
@@ -443,7 +434,6 @@ def load_shared_f32x2(pointer: cute.Pointer, *, loc=None, ip=None):
|
||||
@dsl_user_op
|
||||
def load_shared_f32x4(pointer: cute.Pointer, *, loc=None, ip=None):
|
||||
"""Load four aligned FP32 DSM partials from local shared memory."""
|
||||
|
||||
address = Int32(pointer.toint(loc=loc, ip=ip))
|
||||
out = llvm.inline_asm(
|
||||
llvm.StructType.get_literal([T.f32()] * 4),
|
||||
@@ -530,7 +520,6 @@ def sanitize_negative_zero_u32x2(packed):
|
||||
@cute.jit
|
||||
def sanitize_negative_zero(packed):
|
||||
"""Turn real BF16 -0 into +0 so it cannot equal the empty sentinel."""
|
||||
|
||||
result = cute.make_rmem_tensor(cute.make_layout((4,)), Uint32)
|
||||
for i in cutlass.range_constexpr(4):
|
||||
word = packed[i]
|
||||
@@ -547,7 +536,6 @@ def sanitize_negative_zero(packed):
|
||||
@cute.jit
|
||||
def fragment_is_dirty(packed):
|
||||
"""Bit-exact upstream sentinel check: one comparison per 32-bit word."""
|
||||
|
||||
dirty = packed[0] == Uint32(NEG_ZERO_F32_BITS)
|
||||
for i in cutlass.range_constexpr(1, 4):
|
||||
dirty = dirty | (packed[i] == Uint32(NEG_ZERO_F32_BITS))
|
||||
@@ -564,7 +552,6 @@ def warp_sum_specialized(
|
||||
last_warp_mask: cutlass.Constexpr[int],
|
||||
) -> Float32:
|
||||
"""Warp sum supporting a compile-time partial final warp."""
|
||||
|
||||
if warp_idx == Int32(warps - 1) and cutlass.const_expr(last_warp_lanes < 32):
|
||||
for offset in cutlass.range_constexpr(16, 0, -1):
|
||||
# range_constexpr does not provide powers-of-two stepping.
|
||||
|
||||
+7
-10
@@ -539,9 +539,7 @@ def fused_kda_gate_chunk_cumsum(
|
||||
)
|
||||
B, T, H, D = raw_g.shape
|
||||
if raw_beta.shape != (B, T, H):
|
||||
raise ValueError(
|
||||
f"Expected raw_beta shape {(B, T, H)}, got {raw_beta.shape}"
|
||||
)
|
||||
raise ValueError(f"Expected raw_beta shape {(B, T, H)}, got {raw_beta.shape}")
|
||||
if chunk_indices is None and cu_seqlens is not None:
|
||||
chunk_indices = prepare_chunk_indices(cu_seqlens, chunk_size)
|
||||
NT = cdiv(T, chunk_size) if cu_seqlens is None else len(chunk_indices)
|
||||
@@ -901,13 +899,12 @@ def fused_kda_gate(
|
||||
threshold: float = 20.0,
|
||||
lower_bound: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""
|
||||
Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter
|
||||
threshold: softplus threshold parameter
|
||||
return : [..., H, D]
|
||||
"""Forward pass for KDA gate:
|
||||
input g: [..., H*D]
|
||||
param A: [H] or [1, 1, H, 1]
|
||||
beta: softplus beta parameter
|
||||
threshold: softplus threshold parameter
|
||||
return : [..., H, D]
|
||||
"""
|
||||
orig_shape = g.shape[:-1]
|
||||
|
||||
|
||||
+200
-98
@@ -23,18 +23,20 @@ from .chunk_intra_token_parallel import chunk_kda_fwd_intra_token_parallel
|
||||
################################################################################
|
||||
|
||||
|
||||
@triton.heuristics({
|
||||
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
||||
})
|
||||
@triton.heuristics(
|
||||
{
|
||||
"IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
|
||||
}
|
||||
)
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({'BK': BK}, num_warps=num_warps)
|
||||
triton.Config({"BK": BK}, num_warps=num_warps)
|
||||
for BK in [32, 64]
|
||||
for num_warps in [1, 2, 4]
|
||||
],
|
||||
key=["H", "HV", "K", "BC"],
|
||||
)
|
||||
@triton.jit(do_not_specialize=['T'])
|
||||
@triton.jit(do_not_specialize=["T"])
|
||||
def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
q,
|
||||
k,
|
||||
@@ -57,8 +59,7 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
USE_SAFE_GATE: tl.constexpr,
|
||||
SOLVE_TRIL_DOT_PRECISION: tl.constexpr,
|
||||
):
|
||||
"""
|
||||
Fused kernel: compute inter-subchunk Akk + solve_tril in one pass.
|
||||
"""Fused kernel: compute inter-subchunk Akk + solve_tril in one pass.
|
||||
Prerequisite: token_parallel has already computed diagonal Akk blocks in Akkd.
|
||||
|
||||
This kernel:
|
||||
@@ -74,8 +75,14 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
i_h = i_hv // (HV // H)
|
||||
|
||||
if IS_VARLEN:
|
||||
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
||||
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
||||
i_n, i_t = (
|
||||
tl.load(chunk_indices + i_t * 2).to(tl.int32),
|
||||
tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32),
|
||||
)
|
||||
bos, eos = (
|
||||
tl.load(cu_seqlens + i_n).to(tl.int32),
|
||||
tl.load(cu_seqlens + i_n + 1).to(tl.int32),
|
||||
)
|
||||
T = eos - bos
|
||||
else:
|
||||
bos, eos = i_b * T, i_b * T + T
|
||||
@@ -122,21 +129,31 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
o_k = i_k * BK + tl.arange(0, BK)
|
||||
m_k = o_k < K
|
||||
|
||||
p_k0 = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_tc0, i_k * BK), (BC, BK), (1, 0))
|
||||
p_g0 = tl.make_block_ptr(g, (T, K), (HV*K, 1), (i_tc0, i_k * BK), (BC, BK), (1, 0))
|
||||
p_k0 = tl.make_block_ptr(
|
||||
k, (T, K), (H * K, 1), (i_tc0, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_g0 = tl.make_block_ptr(
|
||||
g, (T, K), (HV * K, 1), (i_tc0, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
b_k0 = tl.load(p_k0, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_g0 = tl.load(p_g0, boundary_check=(0, 1)).to(tl.float32)
|
||||
|
||||
if i_tc1 < T:
|
||||
p_q1 = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0))
|
||||
p_k1 = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0))
|
||||
p_g1 = tl.make_block_ptr(g, (T, K), (HV*K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0))
|
||||
p_q1 = tl.make_block_ptr(
|
||||
q, (T, K), (H * K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_k1 = tl.make_block_ptr(
|
||||
k, (T, K), (H * K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_g1 = tl.make_block_ptr(
|
||||
g, (T, K), (HV * K, 1), (i_tc1, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
# [BC, BK]
|
||||
b_q1 = tl.load(p_q1, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_k1 = tl.load(p_k1, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_g1 = tl.load(p_g1, boundary_check=(0, 1)).to(tl.float32)
|
||||
# [BK]
|
||||
b_gn1 = tl.load(g + i_tc1 * HV*K + o_k, mask=m_k, other=0).to(tl.float32)
|
||||
b_gn1 = tl.load(g + i_tc1 * HV * K + o_k, mask=m_k, other=0).to(tl.float32)
|
||||
# [BC, BK]
|
||||
b_gqn = tl.where(m_tc1[:, None], exp2(b_g1 - b_gn1[None, :]), 0)
|
||||
# [BK, BC]
|
||||
@@ -146,15 +163,23 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
b_Akk10 += tl.dot(b_k1 * b_gqn, b_kgt)
|
||||
|
||||
if i_tc2 < T:
|
||||
p_q2 = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0))
|
||||
p_k2 = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0))
|
||||
p_g2 = tl.make_block_ptr(g, (T, K), (HV*K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0))
|
||||
p_q2 = tl.make_block_ptr(
|
||||
q, (T, K), (H * K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_k2 = tl.make_block_ptr(
|
||||
k, (T, K), (H * K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_g2 = tl.make_block_ptr(
|
||||
g, (T, K), (HV * K, 1), (i_tc2, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
# [BC, BK]
|
||||
b_q2 = tl.load(p_q2, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_k2 = tl.load(p_k2, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_g2 = tl.load(p_g2, boundary_check=(0, 1)).to(tl.float32)
|
||||
# [BK]
|
||||
b_gn2 = tl.load(g + i_tc2 * HV*K + o_k, mask=m_k, other=0).to(tl.float32)
|
||||
b_gn2 = tl.load(g + i_tc2 * HV * K + o_k, mask=m_k, other=0).to(
|
||||
tl.float32
|
||||
)
|
||||
# [BC, BK]
|
||||
b_gqn2 = tl.where(m_tc2[:, None], exp2(b_g2 - b_gn2[None, :]), 0)
|
||||
b_qg2 = b_q2 * b_gqn2
|
||||
@@ -170,15 +195,23 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
b_Akk21 += tl.dot(b_kg2, b_kgt)
|
||||
|
||||
if i_tc3 < T:
|
||||
p_q3 = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0))
|
||||
p_k3 = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0))
|
||||
p_g3 = tl.make_block_ptr(g, (T, K), (HV*K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0))
|
||||
p_q3 = tl.make_block_ptr(
|
||||
q, (T, K), (H * K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_k3 = tl.make_block_ptr(
|
||||
k, (T, K), (H * K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
p_g3 = tl.make_block_ptr(
|
||||
g, (T, K), (HV * K, 1), (i_tc3, i_k * BK), (BC, BK), (1, 0)
|
||||
)
|
||||
# [BC, BK]
|
||||
b_q3 = tl.load(p_q3, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_k3 = tl.load(p_k3, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_g3 = tl.load(p_g3, boundary_check=(0, 1)).to(tl.float32)
|
||||
# [BK]
|
||||
b_gn3 = tl.load(g + i_tc3 * HV*K + o_k, mask=m_k, other=0).to(tl.float32)
|
||||
b_gn3 = tl.load(g + i_tc3 * HV * K + o_k, mask=m_k, other=0).to(
|
||||
tl.float32
|
||||
)
|
||||
# [BC, BK]
|
||||
b_gqn3 = tl.where(m_tc3[:, None], exp2(b_g3 - b_gn3[None, :]), 0)
|
||||
b_qg3 = b_q3 * b_gqn3
|
||||
@@ -203,40 +236,78 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
# save off-diagonal Aqk blocks and prepare Akk
|
||||
################################################################################
|
||||
if i_tc1 < T:
|
||||
p_Aqk10 = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_tc1, 0), (BC, BC), (1, 0))
|
||||
tl.store(p_Aqk10, (b_Aqk10 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
p_Aqk10 = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_tc1, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
tl.store(
|
||||
p_Aqk10, (b_Aqk10 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
|
||||
)
|
||||
|
||||
p_b1 = tl.make_block_ptr(beta + bos * HV + i_hv, (T,), (HV,), (i_tc1,), (BC,), (0,))
|
||||
p_b1 = tl.make_block_ptr(
|
||||
beta + bos * HV + i_hv, (T,), (HV,), (i_tc1,), (BC,), (0,)
|
||||
)
|
||||
b_b1 = tl.load(p_b1, boundary_check=(0,)).to(tl.float32)
|
||||
b_Akk10 = b_Akk10 * b_b1[:, None]
|
||||
if i_tc2 < T:
|
||||
p_Aqk20 = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_tc2, 0), (BC, BC), (1, 0))
|
||||
p_Aqk21 = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_tc2, BC), (BC, BC), (1, 0))
|
||||
tl.store(p_Aqk20, (b_Aqk20 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
tl.store(p_Aqk21, (b_Aqk21 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
p_Aqk20 = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_tc2, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Aqk21 = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_tc2, BC), (BC, BC), (1, 0)
|
||||
)
|
||||
tl.store(
|
||||
p_Aqk20, (b_Aqk20 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
|
||||
)
|
||||
tl.store(
|
||||
p_Aqk21, (b_Aqk21 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
|
||||
)
|
||||
|
||||
p_b2 = tl.make_block_ptr(beta + bos * HV + i_hv, (T,), (HV,), (i_tc2,), (BC,), (0,))
|
||||
p_b2 = tl.make_block_ptr(
|
||||
beta + bos * HV + i_hv, (T,), (HV,), (i_tc2,), (BC,), (0,)
|
||||
)
|
||||
b_b2 = tl.load(p_b2, boundary_check=(0,)).to(tl.float32)
|
||||
b_Akk20 = b_Akk20 * b_b2[:, None]
|
||||
b_Akk21 = b_Akk21 * b_b2[:, None]
|
||||
if i_tc3 < T:
|
||||
p_Aqk30 = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_tc3, 0), (BC, BC), (1, 0))
|
||||
p_Aqk31 = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_tc3, BC), (BC, BC), (1, 0))
|
||||
p_Aqk32 = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_tc3, 2*BC), (BC, BC), (1, 0))
|
||||
tl.store(p_Aqk30, (b_Aqk30 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
tl.store(p_Aqk31, (b_Aqk31 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
tl.store(p_Aqk32, (b_Aqk32 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
p_Aqk30 = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_tc3, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Aqk31 = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_tc3, BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Aqk32 = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_tc3, 2 * BC), (BC, BC), (1, 0)
|
||||
)
|
||||
tl.store(
|
||||
p_Aqk30, (b_Aqk30 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
|
||||
)
|
||||
tl.store(
|
||||
p_Aqk31, (b_Aqk31 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
|
||||
)
|
||||
tl.store(
|
||||
p_Aqk32, (b_Aqk32 * scale).to(Aqk.dtype.element_ty), boundary_check=(0, 1)
|
||||
)
|
||||
|
||||
p_b3 = tl.make_block_ptr(beta + bos * HV + i_hv, (T,), (HV,), (i_tc3,), (BC,), (0,))
|
||||
p_b3 = tl.make_block_ptr(
|
||||
beta + bos * HV + i_hv, (T,), (HV,), (i_tc3,), (BC,), (0,)
|
||||
)
|
||||
b_b3 = tl.load(p_b3, boundary_check=(0,)).to(tl.float32)
|
||||
b_Akk30 = b_Akk30 * b_b3[:, None]
|
||||
b_Akk31 = b_Akk31 * b_b3[:, None]
|
||||
b_Akk32 = b_Akk32 * b_b3[:, None]
|
||||
|
||||
p_Akk00 = tl.make_block_ptr(Akkd, (T, BC), (HV*BC, 1), (i_tc0, 0), (BC, BC), (1, 0))
|
||||
p_Akk11 = tl.make_block_ptr(Akkd, (T, BC), (HV*BC, 1), (i_tc1, 0), (BC, BC), (1, 0))
|
||||
p_Akk22 = tl.make_block_ptr(Akkd, (T, BC), (HV*BC, 1), (i_tc2, 0), (BC, BC), (1, 0))
|
||||
p_Akk33 = tl.make_block_ptr(Akkd, (T, BC), (HV*BC, 1), (i_tc3, 0), (BC, BC), (1, 0))
|
||||
p_Akk00 = tl.make_block_ptr(
|
||||
Akkd, (T, BC), (HV * BC, 1), (i_tc0, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk11 = tl.make_block_ptr(
|
||||
Akkd, (T, BC), (HV * BC, 1), (i_tc1, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk22 = tl.make_block_ptr(
|
||||
Akkd, (T, BC), (HV * BC, 1), (i_tc2, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk33 = tl.make_block_ptr(
|
||||
Akkd, (T, BC), (HV * BC, 1), (i_tc3, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
b_Ai00 = tl.load(p_Akk00, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_Ai11 = tl.load(p_Akk11, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_Ai22 = tl.load(p_Akk22, boundary_check=(0, 1)).to(tl.float32)
|
||||
@@ -256,25 +327,25 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
b_Ai33 = -tl.where(m_A, b_Ai33, 0)
|
||||
|
||||
for i in range(2, min(BC, T - i_tc0)):
|
||||
b_a00 = -tl.load(Akkd + (i_tc0 + i) * HV*BC + o_i)
|
||||
b_a00 = tl.where(o_i < i, b_a00, 0.)
|
||||
b_a00 = -tl.load(Akkd + (i_tc0 + i) * HV * BC + o_i)
|
||||
b_a00 = tl.where(o_i < i, b_a00, 0.0)
|
||||
b_a00 += tl.sum(b_a00[:, None] * b_Ai00, 0)
|
||||
b_Ai00 = tl.where((o_i == i)[:, None], b_a00, b_Ai00)
|
||||
for i in range(BC + 2, min(2*BC, T - i_tc0)):
|
||||
b_a11 = -tl.load(Akkd + (i_tc0 + i) * HV*BC + o_i)
|
||||
b_a11 = tl.where(o_i < i - BC, b_a11, 0.)
|
||||
for i in range(BC + 2, min(2 * BC, T - i_tc0)):
|
||||
b_a11 = -tl.load(Akkd + (i_tc0 + i) * HV * BC + o_i)
|
||||
b_a11 = tl.where(o_i < i - BC, b_a11, 0.0)
|
||||
b_a11 += tl.sum(b_a11[:, None] * b_Ai11, 0)
|
||||
b_Ai11 = tl.where((o_i == i - BC)[:, None], b_a11, b_Ai11)
|
||||
for i in range(2*BC + 2, min(3*BC, T - i_tc0)):
|
||||
b_a22 = -tl.load(Akkd + (i_tc0 + i) * HV*BC + o_i)
|
||||
b_a22 = tl.where(o_i < i - 2*BC, b_a22, 0.)
|
||||
for i in range(2 * BC + 2, min(3 * BC, T - i_tc0)):
|
||||
b_a22 = -tl.load(Akkd + (i_tc0 + i) * HV * BC + o_i)
|
||||
b_a22 = tl.where(o_i < i - 2 * BC, b_a22, 0.0)
|
||||
b_a22 += tl.sum(b_a22[:, None] * b_Ai22, 0)
|
||||
b_Ai22 = tl.where((o_i == i - 2*BC)[:, None], b_a22, b_Ai22)
|
||||
for i in range(3*BC + 2, min(4*BC, T - i_tc0)):
|
||||
b_a33 = -tl.load(Akkd + (i_tc0 + i) * HV*BC + o_i)
|
||||
b_a33 = tl.where(o_i < i - 3*BC, b_a33, 0.)
|
||||
b_Ai22 = tl.where((o_i == i - 2 * BC)[:, None], b_a22, b_Ai22)
|
||||
for i in range(3 * BC + 2, min(4 * BC, T - i_tc0)):
|
||||
b_a33 = -tl.load(Akkd + (i_tc0 + i) * HV * BC + o_i)
|
||||
b_a33 = tl.where(o_i < i - 3 * BC, b_a33, 0.0)
|
||||
b_a33 += tl.sum(b_a33[:, None] * b_Ai33, 0)
|
||||
b_Ai33 = tl.where((o_i == i - 3*BC)[:, None], b_a33, b_Ai33)
|
||||
b_Ai33 = tl.where((o_i == i - 3 * BC)[:, None], b_a33, b_Ai33)
|
||||
|
||||
b_Ai00 += m_I
|
||||
b_Ai11 += m_I
|
||||
@@ -289,53 +360,73 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
b_Ai10 = -tl.dot(
|
||||
tl.dot(b_Ai11, b_Akk10, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
b_Ai00,
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION,
|
||||
)
|
||||
b_Ai21 = -tl.dot(
|
||||
tl.dot(b_Ai22, b_Akk21, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
b_Ai11,
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION,
|
||||
)
|
||||
b_Ai32 = -tl.dot(
|
||||
tl.dot(b_Ai33, b_Akk32, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
b_Ai22,
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION,
|
||||
)
|
||||
|
||||
b_Ai20 = -tl.dot(
|
||||
b_Ai22,
|
||||
tl.dot(b_Akk20, b_Ai00, input_precision=SOLVE_TRIL_DOT_PRECISION) +
|
||||
tl.dot(b_Akk21, b_Ai10, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION
|
||||
tl.dot(b_Akk20, b_Ai00, input_precision=SOLVE_TRIL_DOT_PRECISION)
|
||||
+ tl.dot(b_Akk21, b_Ai10, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION,
|
||||
)
|
||||
b_Ai31 = -tl.dot(
|
||||
b_Ai33,
|
||||
tl.dot(b_Akk31, b_Ai11, input_precision=SOLVE_TRIL_DOT_PRECISION) +
|
||||
tl.dot(b_Akk32, b_Ai21, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION
|
||||
tl.dot(b_Akk31, b_Ai11, input_precision=SOLVE_TRIL_DOT_PRECISION)
|
||||
+ tl.dot(b_Akk32, b_Ai21, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION,
|
||||
)
|
||||
b_Ai30 = -tl.dot(
|
||||
b_Ai33,
|
||||
tl.dot(b_Akk30, b_Ai00, input_precision=SOLVE_TRIL_DOT_PRECISION) +
|
||||
tl.dot(b_Akk31, b_Ai10, input_precision=SOLVE_TRIL_DOT_PRECISION) +
|
||||
tl.dot(b_Akk32, b_Ai20, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION
|
||||
tl.dot(b_Akk30, b_Ai00, input_precision=SOLVE_TRIL_DOT_PRECISION)
|
||||
+ tl.dot(b_Akk31, b_Ai10, input_precision=SOLVE_TRIL_DOT_PRECISION)
|
||||
+ tl.dot(b_Akk32, b_Ai20, input_precision=SOLVE_TRIL_DOT_PRECISION),
|
||||
input_precision=SOLVE_TRIL_DOT_PRECISION,
|
||||
)
|
||||
|
||||
################################################################################
|
||||
# store full Akk_inv to Akk
|
||||
################################################################################
|
||||
|
||||
p_Akk00 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc0, 0), (BC, BC), (1, 0))
|
||||
p_Akk10 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc1, 0), (BC, BC), (1, 0))
|
||||
p_Akk11 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc1, BC), (BC, BC), (1, 0))
|
||||
p_Akk20 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc2, 0), (BC, BC), (1, 0))
|
||||
p_Akk21 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc2, BC), (BC, BC), (1, 0))
|
||||
p_Akk22 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc2, 2*BC), (BC, BC), (1, 0))
|
||||
p_Akk30 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc3, 0), (BC, BC), (1, 0))
|
||||
p_Akk31 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc3, BC), (BC, BC), (1, 0))
|
||||
p_Akk32 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc3, 2*BC), (BC, BC), (1, 0))
|
||||
p_Akk33 = tl.make_block_ptr(Akk, (T, BT), (HV*BT, 1), (i_tc3, 3*BC), (BC, BC), (1, 0))
|
||||
p_Akk00 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc0, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk10 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc1, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk11 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc1, BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk20 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc2, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk21 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc2, BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk22 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc2, 2 * BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk30 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc3, 0), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk31 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc3, BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk32 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc3, 2 * BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk33 = tl.make_block_ptr(
|
||||
Akk, (T, BT), (HV * BT, 1), (i_tc3, 3 * BC), (BC, BC), (1, 0)
|
||||
)
|
||||
|
||||
tl.store(p_Akk00, b_Ai00.to(Akk.dtype.element_ty), boundary_check=(0, 1))
|
||||
tl.store(p_Akk10, b_Ai10.to(Akk.dtype.element_ty), boundary_check=(0, 1))
|
||||
@@ -349,18 +440,20 @@ def chunk_kda_fwd_kernel_inter_solve_fused(
|
||||
tl.store(p_Akk33, b_Ai33.to(Akk.dtype.element_ty), boundary_check=(0, 1))
|
||||
|
||||
|
||||
@triton.heuristics({
|
||||
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
||||
})
|
||||
@triton.heuristics(
|
||||
{
|
||||
"IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
|
||||
}
|
||||
)
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({}, num_warps=num_warps, num_stages=num_stages)
|
||||
for num_warps in [1, 2, 4, 8]
|
||||
for num_stages in [2, 3, 4]
|
||||
],
|
||||
key=['BK', 'NC', 'BT', 'HV'],
|
||||
key=["BK", "NC", "BT", "HV"],
|
||||
)
|
||||
@triton.jit(do_not_specialize=['B', 'T'])
|
||||
@triton.jit(do_not_specialize=["B", "T"])
|
||||
def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
q,
|
||||
k,
|
||||
@@ -386,8 +479,14 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
i_h = i_hv // (HV // H)
|
||||
|
||||
if IS_VARLEN:
|
||||
i_n, i_t = tl.load(chunk_indices + i_t * 2).to(tl.int32), tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32)
|
||||
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
||||
i_n, i_t = (
|
||||
tl.load(chunk_indices + i_t * 2).to(tl.int32),
|
||||
tl.load(chunk_indices + i_t * 2 + 1).to(tl.int32),
|
||||
)
|
||||
bos, eos = (
|
||||
tl.load(cu_seqlens + i_n).to(tl.int32),
|
||||
tl.load(cu_seqlens + i_n + 1).to(tl.int32),
|
||||
)
|
||||
T = eos - bos
|
||||
else:
|
||||
bos, eos = i_b * T, i_b * T + T
|
||||
@@ -406,9 +505,9 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
Aqk = Aqk + (bos * HV + i_hv) * BT
|
||||
Akk = Akk + (bos * HV + i_hv) * BC
|
||||
|
||||
p_q = tl.make_block_ptr(q, (T, K), (H*K, 1), (i_ti, 0), (BC, BK), (1, 0))
|
||||
p_k = tl.make_block_ptr(k, (T, K), (H*K, 1), (i_ti, 0), (BC, BK), (1, 0))
|
||||
p_g = tl.make_block_ptr(g, (T, K), (HV*K, 1), (i_ti, 0), (BC, BK), (1, 0))
|
||||
p_q = tl.make_block_ptr(q, (T, K), (H * K, 1), (i_ti, 0), (BC, BK), (1, 0))
|
||||
p_k = tl.make_block_ptr(k, (T, K), (H * K, 1), (i_ti, 0), (BC, BK), (1, 0))
|
||||
p_g = tl.make_block_ptr(g, (T, K), (HV * K, 1), (i_ti, 0), (BC, BK), (1, 0))
|
||||
|
||||
p_beta = tl.make_block_ptr(beta, (T,), (HV,), (i_ti,), (BC,), (0,))
|
||||
|
||||
@@ -418,10 +517,12 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
b_beta = tl.load(p_beta, boundary_check=(0,)).to(tl.float32)
|
||||
|
||||
if USE_GATHER:
|
||||
b_gn = gather(b_g, tl.full([1, BK], min(BC//2, T - i_ti - 1), dtype=tl.int16), axis=0)
|
||||
b_gn = gather(
|
||||
b_g, tl.full([1, BK], min(BC // 2, T - i_ti - 1), dtype=tl.int16), axis=0
|
||||
)
|
||||
else:
|
||||
# caculate offset
|
||||
p_gn = g + (i_ti + min(BC // 2, T - i_ti - 1)) * HV*K + tl.arange(0, BK)
|
||||
p_gn = g + (i_ti + min(BC // 2, T - i_ti - 1)) * HV * K + tl.arange(0, BK)
|
||||
b_gn = tl.load(p_gn, mask=tl.arange(0, BK) < K, other=0.0)
|
||||
b_gn = b_gn[None, :]
|
||||
|
||||
@@ -429,8 +530,8 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
# less than 85 to avoid overflow in exp2
|
||||
b_gm = (b_g - b_gn).to(tl.float32)
|
||||
|
||||
b_gq = tl.where(m_c[:, None], exp2(b_gm), 0.)
|
||||
b_gk = tl.where(m_c[:, None], exp2(-b_gm), 0.)
|
||||
b_gq = tl.where(m_c[:, None], exp2(b_gm), 0.0)
|
||||
b_gk = tl.where(m_c[:, None], exp2(-b_gm), 0.0)
|
||||
|
||||
b_kgt = tl.trans(b_k * b_gk)
|
||||
|
||||
@@ -445,8 +546,10 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
b_Aqk = tl.where(m_Aqk, b_Aqk, 0.0)
|
||||
b_Akk = tl.where(m_Akk, b_Akk, 0.0)
|
||||
|
||||
p_Aqk = tl.make_block_ptr(Aqk, (T, BT), (HV*BT, 1), (i_ti, i_i * BC), (BC, BC), (1, 0))
|
||||
p_Akk = tl.make_block_ptr(Akk, (T, BC), (HV*BC, 1), (i_ti, 0), (BC, BC), (1, 0))
|
||||
p_Aqk = tl.make_block_ptr(
|
||||
Aqk, (T, BT), (HV * BT, 1), (i_ti, i_i * BC), (BC, BC), (1, 0)
|
||||
)
|
||||
p_Akk = tl.make_block_ptr(Akk, (T, BC), (HV * BC, 1), (i_ti, 0), (BC, BC), (1, 0))
|
||||
tl.store(p_Aqk, b_Aqk.to(Aqk.dtype.element_ty), boundary_check=(0, 1))
|
||||
tl.store(p_Akk, b_Akk.to(Akk.dtype.element_ty), boundary_check=(0, 1))
|
||||
|
||||
@@ -458,8 +561,8 @@ def chunk_kda_fwd_kernel_intra_sub_chunk(
|
||||
|
||||
b_Ai = -b_Akk
|
||||
for i in range(2, min(BC, T - i_ti)):
|
||||
b_a = -tl.load(Akk + (i_ti + i) * HV*BC + o_i)
|
||||
b_a = tl.where(o_i < i, b_a, 0.)
|
||||
b_a = -tl.load(Akk + (i_ti + i) * HV * BC + o_i)
|
||||
b_a = tl.where(o_i < i, b_a, 0.0)
|
||||
b_a += tl.sum(b_a[:, None] * b_Ai, 0)
|
||||
b_Ai = tl.where((o_i == i)[:, None], b_a, b_Ai)
|
||||
b_Ai += m_I
|
||||
@@ -531,8 +634,7 @@ def chunk_kda_fwd_intra(
|
||||
# Step 2: Fused inter + solve_tril (works for both fixed-len and varlen)
|
||||
solve_tril_dot_precision = (
|
||||
"tf32"
|
||||
if current_platform.is_cuda()
|
||||
and current_platform.has_device_capability(80)
|
||||
if current_platform.is_cuda() and current_platform.has_device_capability(80)
|
||||
else "ieee"
|
||||
)
|
||||
grid = (NT, B * HV)
|
||||
|
||||
+38
-18
@@ -16,18 +16,20 @@ from vllm.third_party.flash_linear_attention.ops.op import exp2
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@triton.heuristics({
|
||||
'IS_VARLEN': lambda args: args['cu_seqlens'] is not None,
|
||||
})
|
||||
@triton.heuristics(
|
||||
{
|
||||
"IS_VARLEN": lambda args: args["cu_seqlens"] is not None,
|
||||
}
|
||||
)
|
||||
@triton.autotune(
|
||||
configs=[
|
||||
triton.Config({'BH': BH}, num_warps=num_warps)
|
||||
triton.Config({"BH": BH}, num_warps=num_warps)
|
||||
for BH in [1, 2, 4, 8]
|
||||
for num_warps in [1, 2, 4, 8]
|
||||
],
|
||||
key=["K", "H", "HV"],
|
||||
)
|
||||
@triton.jit(do_not_specialize=['T', 'N'])
|
||||
@triton.jit(do_not_specialize=["T", "N"])
|
||||
def chunk_kda_fwd_kernel_intra_token_parallel(
|
||||
q,
|
||||
k,
|
||||
@@ -65,7 +67,10 @@ def chunk_kda_fwd_kernel_intra_token_parallel(
|
||||
left = mid + 1
|
||||
i_n = left
|
||||
|
||||
bos, eos = tl.load(cu_seqlens + i_n).to(tl.int32), tl.load(cu_seqlens + i_n + 1).to(tl.int32)
|
||||
bos, eos = (
|
||||
tl.load(cu_seqlens + i_n).to(tl.int32),
|
||||
tl.load(cu_seqlens + i_n + 1).to(tl.int32),
|
||||
)
|
||||
T = eos - bos
|
||||
i_t = i_tg - bos
|
||||
else:
|
||||
@@ -82,11 +87,11 @@ def chunk_kda_fwd_kernel_intra_token_parallel(
|
||||
|
||||
G: tl.constexpr = HV // H
|
||||
|
||||
q += bos * H*K
|
||||
k += bos * H*K
|
||||
g += bos * HV*K
|
||||
Aqk += bos * HV*BT
|
||||
Akk += bos * HV*BC
|
||||
q += bos * H * K
|
||||
k += bos * H * K
|
||||
g += bos * HV * K
|
||||
Aqk += bos * HV * BT
|
||||
Akk += bos * HV * BC
|
||||
beta += bos * HV
|
||||
|
||||
BK: tl.constexpr = triton.next_power_of_2(K)
|
||||
@@ -103,7 +108,9 @@ def chunk_kda_fwd_kernel_intra_token_parallel(
|
||||
b_k = tl.load(k + i_t * H * K + p_qk, mask=m_hk, other=0).to(tl.float32)
|
||||
|
||||
# g: [B, T, HV, K], beta: [B, T, HV]
|
||||
p_g = tl.make_block_ptr(g + i_t * HV * K, (HV, K), (K, 1), (i_hg * BH, 0), (BH, BK), (1, 0))
|
||||
p_g = tl.make_block_ptr(
|
||||
g + i_t * HV * K, (HV, K), (K, 1), (i_hg * BH, 0), (BH, BK), (1, 0)
|
||||
)
|
||||
p_beta = tl.make_block_ptr(beta + i_t * HV, (HV,), (1,), (i_hg * BH,), (BH,), (0,))
|
||||
b_g = tl.load(p_g, boundary_check=(0, 1)).to(tl.float32)
|
||||
b_beta = tl.load(p_beta, boundary_check=(0,)).to(tl.float32)
|
||||
@@ -111,15 +118,25 @@ def chunk_kda_fwd_kernel_intra_token_parallel(
|
||||
|
||||
for j in range(i_ts, min(i_t + 1, min(T, i_ts + BC))):
|
||||
b_kj = tl.load(k + j * H * K + p_qk, mask=m_hk, other=0).to(tl.float32)
|
||||
p_gj = tl.make_block_ptr(g + j * HV * K, (HV, K), (K, 1), (i_hg * BH, 0), (BH, BK), (1, 0))
|
||||
p_gj = tl.make_block_ptr(
|
||||
g + j * HV * K, (HV, K), (K, 1), (i_hg * BH, 0), (BH, BK), (1, 0)
|
||||
)
|
||||
b_gj = tl.load(p_gj, boundary_check=(0, 1)).to(tl.float32)
|
||||
|
||||
b_kgj = tl.where(m_k[None, :], b_kj * exp2(b_g - b_gj), 0.0)
|
||||
b_Aqk = tl.sum(b_q * b_kgj, axis=1) * scale
|
||||
b_Akk = tl.sum(b_k * b_kgj, axis=1) * tl.where(j < i_t, 1.0, 0.0)
|
||||
|
||||
tl.store(Aqk + i_t * HV * BT + o_hv * BT + j % BT, b_Aqk.to(Aqk.dtype.element_ty), mask=m_hv)
|
||||
tl.store(Akk + i_t * HV * BC + o_hv * BC + j - i_ts, b_Akk.to(Akk.dtype.element_ty), mask=m_hv)
|
||||
tl.store(
|
||||
Aqk + i_t * HV * BT + o_hv * BT + j % BT,
|
||||
b_Aqk.to(Aqk.dtype.element_ty),
|
||||
mask=m_hv,
|
||||
)
|
||||
tl.store(
|
||||
Akk + i_t * HV * BC + o_hv * BC + j - i_ts,
|
||||
b_Akk.to(Akk.dtype.element_ty),
|
||||
mask=m_hv,
|
||||
)
|
||||
|
||||
|
||||
def chunk_kda_fwd_intra_token_parallel(
|
||||
@@ -134,8 +151,7 @@ def chunk_kda_fwd_intra_token_parallel(
|
||||
chunk_size: int = 64,
|
||||
sub_chunk_size: int = 16,
|
||||
) -> None:
|
||||
"""
|
||||
Token-parallel implementation: each token gets its own thread block.
|
||||
"""Token-parallel implementation: each token gets its own thread block.
|
||||
Supports both fixed-length and variable-length sequences.
|
||||
Reduces wasted computation on padding.
|
||||
|
||||
@@ -147,17 +163,21 @@ def chunk_kda_fwd_intra_token_parallel(
|
||||
gk: [B, T, HV, K] cumsum of gates (HV >= H for GVA)
|
||||
beta: [B, T, HV]
|
||||
Aqk: [B, T, HV, BT] output tensor to write to
|
||||
cu_seqlens: cumulative sequence lengths for variable-length input
|
||||
Akk: [B, T, HV, BC] output tensor for diagonal blocks (fp32)
|
||||
scale: attention scale
|
||||
chunk_size: BT (default 64)
|
||||
sub_chunk_size: BC (default 16)
|
||||
|
||||
"""
|
||||
B, T, H, K, HV = *q.shape, gk.shape[2]
|
||||
N = len(cu_seqlens) - 1 if cu_seqlens is not None else B
|
||||
BT = chunk_size
|
||||
BC = sub_chunk_size
|
||||
|
||||
def grid(meta): return (B * T, triton.cdiv(HV, meta['BH']))
|
||||
def grid(meta):
|
||||
return (B * T, triton.cdiv(HV, meta["BH"]))
|
||||
|
||||
chunk_kda_fwd_kernel_intra_token_parallel[grid](
|
||||
q=q,
|
||||
k=k,
|
||||
|
||||
@@ -483,9 +483,7 @@ def fused_recurrent_kda(
|
||||
)
|
||||
|
||||
|
||||
@triton.jit(
|
||||
do_not_specialize=["stride_beta_token", "stride_state_indices"]
|
||||
)
|
||||
@triton.jit(do_not_specialize=["stride_beta_token", "stride_state_indices"])
|
||||
def fused_recurrent_kda_packed_decode_kernel(
|
||||
mixed_qkv,
|
||||
raw_g,
|
||||
|
||||
@@ -32,6 +32,7 @@ from vllm.multimodal.processing import (
|
||||
PromptUpdate,
|
||||
PromptUpdateDetails,
|
||||
)
|
||||
from vllm.multimodal.processing.processor import HFMultiModalInputs
|
||||
from vllm.multimodal.video import (
|
||||
VIDEO_LOADER_REGISTRY,
|
||||
VideoBackend,
|
||||
@@ -307,26 +308,21 @@ class MiniMaxM3VLDummyInputsBuilder(BaseDummyInputsBuilder[MiniMaxM3VLProcessing
|
||||
class MiniMaxM3VLMultiModalProcessor(
|
||||
BaseMultiModalProcessor[MiniMaxM3VLProcessingInfo]
|
||||
):
|
||||
def _apply_hf_processor_main(
|
||||
def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return self.dummy_inputs.get_dummy_text(mm_counts)
|
||||
|
||||
def _get_hf_mm_inputs(
|
||||
self,
|
||||
mm_items: MultiModalDataItems,
|
||||
hf_processor_mm_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
valid_mm_items = mm_items.select(
|
||||
{k for k, c in mm_items.get_all_counts().items() if c > 0}
|
||||
)
|
||||
mm_data, passthrough_data = self._get_hf_mm_data(valid_mm_items)
|
||||
hf_kwargs: Mapping[str, object],
|
||||
) -> HFMultiModalInputs:
|
||||
hf_inputs = super()._get_hf_mm_inputs(mm_items, hf_kwargs)
|
||||
hf_data = hf_inputs.hf_data
|
||||
|
||||
if not mm_data:
|
||||
return BatchFeature(dict(passthrough_data))
|
||||
|
||||
prompt_text = self.dummy_inputs.get_dummy_text(mm_items.get_all_counts())
|
||||
|
||||
mm_data = dict(mm_data)
|
||||
# With ``video_needs_metadata=True`` each video arrives as a
|
||||
# ``(frames, metadata)`` tuple. Split the frames back out and forward the
|
||||
# metadata as ``VideoMetadata`` so the processor emits timestamps.
|
||||
videos = cast(list | None, mm_data.get("videos"))
|
||||
videos = cast(list | None, hf_data.get("videos"))
|
||||
video_metadata: list[VideoMetadata] | None = None
|
||||
if videos:
|
||||
frames_only = []
|
||||
@@ -346,21 +342,25 @@ class MiniMaxM3VLMultiModalProcessor(
|
||||
# stays consistent with _get_prompt_updates.
|
||||
meta.setdefault("total_num_frames", len(frames))
|
||||
video_metadata.append(VideoMetadata(**meta))
|
||||
mm_data["videos"] = frames_only
|
||||
hf_data["videos"] = frames_only
|
||||
|
||||
# Override the video processor's default do_resize=False (set for a
|
||||
# pre-resized pipeline) to True for vLLM's raw-frame inputs.
|
||||
merged = dict(do_resize=True, **hf_processor_mm_kwargs)
|
||||
data = dict(text=prompt_text, **mm_data)
|
||||
if video_metadata is not None:
|
||||
data["video_metadata"] = video_metadata
|
||||
processed_data = self.info.ctx.call_hf_processor(
|
||||
self.info.get_hf_processor(**hf_processor_mm_kwargs),
|
||||
data,
|
||||
hf_data["video_metadata"] = video_metadata
|
||||
|
||||
return hf_inputs
|
||||
|
||||
def _call_hf_processor(
|
||||
self,
|
||||
hf_data: Mapping[str, object],
|
||||
hf_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
# Override the video processor's default for vLLM's raw-frame inputs.
|
||||
merged = dict(do_resize=True, **hf_kwargs)
|
||||
return self.info.ctx.call_hf_processor(
|
||||
self.info.get_hf_processor(**hf_kwargs),
|
||||
hf_data,
|
||||
merged,
|
||||
)
|
||||
processed_data.update(passthrough_data)
|
||||
return processed_data
|
||||
|
||||
def _get_mm_fields_config(
|
||||
self,
|
||||
|
||||
@@ -33,7 +33,6 @@ def apply_qsa_rope(
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the main attention's exact 1D/MRoPE composition to QSA heads."""
|
||||
|
||||
num_tokens, _, head_dim = tensor.shape
|
||||
rotary_dim = rotary_emb.rotary_dim
|
||||
cache = rotary_emb._match_cos_sin_cache_dtype(tensor) # noqa: SLF001
|
||||
@@ -67,7 +66,6 @@ def apply_qsa_rmsnorm(
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Use vLLM's portable RMSNorm implementation on ROCm."""
|
||||
|
||||
return cast(torch.Tensor, norm(tensor))
|
||||
|
||||
|
||||
@@ -153,7 +151,6 @@ class QSAIndexer(nn.Module):
|
||||
positions: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Project replicated Q/K, normalize+rotate Q, and preserve raw K."""
|
||||
|
||||
qk, _ = self.index_qk_proj(hidden_states)
|
||||
q_raw, token_k = qk.split(
|
||||
(
|
||||
@@ -176,7 +173,6 @@ class QSAIndexer(nn.Module):
|
||||
first_rope_positions: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Normalize pooled K and apply the first token's exact group position."""
|
||||
|
||||
keys = compressed_keys.reshape(-1, self.index_head_dim)
|
||||
keys = apply_qsa_rmsnorm(self.k_layernorm, keys).reshape(
|
||||
-1, 1, self.index_head_dim
|
||||
@@ -284,7 +280,6 @@ class QSAIndexer(nn.Module):
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Return fixed-width request-relative token indices padded with ``-1``."""
|
||||
|
||||
metadata = self._metadata()
|
||||
if metadata is None:
|
||||
# Preserve step-0 indices when later MTP steps reuse the buffer.
|
||||
|
||||
@@ -11,5 +11,4 @@ def enable_qwen4_exp_low_latency_gemm(
|
||||
dtype: torch.dtype,
|
||||
) -> None:
|
||||
"""Keep the standard vLLM linear methods on AMD ROCm."""
|
||||
|
||||
del module, dtype
|
||||
|
||||
@@ -77,7 +77,7 @@ from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
from ..common.mtp import make_mtp_hidden_buffer
|
||||
from ..config import Qwen4ExpConfig
|
||||
from ..config import ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .ple_layer import Qwen4ExpPLELayer
|
||||
@@ -88,7 +88,6 @@ def without_modelopt_fp4(
|
||||
quant_config: QuantizationConfig | None,
|
||||
) -> QuantizationConfig | None:
|
||||
"""Return ``None`` for weights excluded from Qwen4Exp ModelOpt-FP4."""
|
||||
|
||||
if quant_config is not None and quant_config.get_name() == "modelopt_fp4":
|
||||
return None
|
||||
return quant_config
|
||||
@@ -104,7 +103,6 @@ def _remap_qsa_cache_scale_name(
|
||||
that cache directly, so only QSA layers need the final path component
|
||||
moved to the owner's persistent ``_k_scale``/``_v_scale`` buffers.
|
||||
"""
|
||||
|
||||
scale_suffixes = {
|
||||
"k_proj.k_scale": "_k_scale",
|
||||
"k_proj.output_scale": "_k_scale",
|
||||
@@ -215,8 +213,11 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
prefix=f"{prefix}.linear_attn",
|
||||
gqa_interleaved_layout=False,
|
||||
)
|
||||
elif layer_type == "full_attention":
|
||||
use_qsa = getattr(config, "indexer_n_heads", None) is not None
|
||||
elif layer_type in ATTENTION_LAYER_TYPES:
|
||||
use_qsa = (
|
||||
layer_type == QSA_LAYER_TYPE
|
||||
or getattr(config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
if not use_qsa:
|
||||
self.self_attn = Qwen3NextAttention(
|
||||
config,
|
||||
@@ -312,7 +313,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
attn_out = self.linear_attn(hidden_states=block_input)
|
||||
elif self.layer_type == "full_attention":
|
||||
elif self.layer_type in ATTENTION_LAYER_TYPES:
|
||||
attn_out = self.self_attn(
|
||||
hidden_states=block_input,
|
||||
positions=positions,
|
||||
@@ -403,8 +404,11 @@ class Qwen4ExpModel(nn.Module):
|
||||
self._qsa_layer_ids = frozenset(
|
||||
layer_idx
|
||||
for layer_idx, layer_type in enumerate(config.layer_types)
|
||||
if layer_type == "full_attention"
|
||||
and getattr(config, "indexer_n_heads", None) is not None
|
||||
if layer_type == QSA_LAYER_TYPE
|
||||
or (
|
||||
layer_type == "full_attention"
|
||||
and getattr(config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
)
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, config.hidden_size)
|
||||
|
||||
|
||||
@@ -91,7 +91,6 @@ def _remap_quantized_layers(
|
||||
|
||||
def _remap_mtp_weight_name(name: str) -> str | None:
|
||||
"""Map Qwen4Exp checkpoint paths into the standalone draft model."""
|
||||
|
||||
for checkpoint_prefix in (
|
||||
"model.language_model.",
|
||||
"language_model.",
|
||||
@@ -260,7 +259,6 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
|
||||
def _iter_qsa_attentions(self):
|
||||
"""Yield MTP attention modules that own a QSA indexer."""
|
||||
|
||||
for layer in self.layers:
|
||||
attention = getattr(layer, "self_attn", None)
|
||||
if (
|
||||
@@ -271,13 +269,11 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
|
||||
def set_skip_topk(self, skip: bool) -> None:
|
||||
"""Select on MTP step 0 and reuse its QSA indices on later steps."""
|
||||
|
||||
for attention in self._iter_qsa_attentions():
|
||||
attention.indexer.skip_topk = skip
|
||||
|
||||
def compact_topk_indices(self, row_indices: torch.Tensor) -> None:
|
||||
"""Keep each request's target-aligned step-0 sparse-index row."""
|
||||
|
||||
num_rows = row_indices.numel()
|
||||
for attention in self._iter_qsa_attentions():
|
||||
buffer = attention.topk_indices_buffer
|
||||
|
||||
@@ -600,7 +600,6 @@ def qsa_mqa_paged(
|
||||
score_scale: float | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Compute QSA scores directly from a paged compressed-key cache."""
|
||||
|
||||
_validate_mqa(q)
|
||||
if not q.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("paged QSA scoring requires a GPU and Triton")
|
||||
@@ -678,7 +677,6 @@ def expand_qsa_block_indices_cuda(
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Expand compressed blocks and compact the causal tail of the open group."""
|
||||
|
||||
if not block_indices.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("QSA index expansion requires a GPU and Triton")
|
||||
if token_topk % compress_ratio:
|
||||
@@ -738,7 +736,6 @@ def qsa_select_paged_tokens(
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Score, select, and expand QSA indices without host synchronization."""
|
||||
|
||||
rows = q.shape[0]
|
||||
output_width = token_topk + compress_ratio - 1
|
||||
if out is None:
|
||||
@@ -829,7 +826,6 @@ def qsa_sparse_paged_attention(
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Run sparse GQA directly over paged BF16 K/V caches."""
|
||||
|
||||
if not q.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("paged QSA sparse attention requires a GPU and Triton")
|
||||
if q.ndim != 3 or k_cache.ndim != 4 or v_cache.shape != k_cache.shape:
|
||||
@@ -971,7 +967,6 @@ def qsa_store_cache_rows(
|
||||
rows: torch.Tensor,
|
||||
) -> None:
|
||||
"""Store fixed-width rows in a QSA cache without boolean indexing."""
|
||||
|
||||
if not cache.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("QSA cache stores require a GPU and Triton")
|
||||
if cache.ndim != 4 or cache.shape[2] != 1:
|
||||
@@ -1017,7 +1012,6 @@ def qsa_compress_groups_with_ratio(
|
||||
rope_cache: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Pool completed groups from the compressor-state ring and raw token rows."""
|
||||
|
||||
if not raw_keys.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("QSA compression requires a GPU and Triton")
|
||||
rows = token_to_req.numel()
|
||||
|
||||
@@ -357,7 +357,6 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load hash buffers and checkpoint-split embedding rows."""
|
||||
|
||||
persistent_buffers = {
|
||||
"layer_multipliers": self.layer_multipliers,
|
||||
"ngram_heads_offsets": self.ngram_heads_offsets,
|
||||
|
||||
@@ -430,7 +430,6 @@ def qwen4_exp_qsa_with_output(
|
||||
layer_name: LayerNameType,
|
||||
) -> None:
|
||||
"""Run the complete QSA state/update/attend transaction."""
|
||||
|
||||
layer_name = _resolve_layer_name(layer_name)
|
||||
layer = get_forward_context().no_compile_layers[layer_name]
|
||||
if not isinstance(layer, Qwen4ExpQSAAttention):
|
||||
|
||||
@@ -28,7 +28,6 @@ def compute_ple_shard_overlap(
|
||||
tp_end: int,
|
||||
) -> PLEShardOverlap | None:
|
||||
"""Compute the overlap of a checkpoint shard and one TP vocabulary range."""
|
||||
|
||||
if checkpoint_start < 0 or checkpoint_rows < 0:
|
||||
raise ValueError("checkpoint shard bounds must be non-negative")
|
||||
if tp_start < 0 or tp_end < tp_start:
|
||||
@@ -54,7 +53,6 @@ def copy_ple_embedding_shard_(
|
||||
tp_end: int,
|
||||
) -> int:
|
||||
"""Copy the overlapping rows of a PLE checkpoint shard into a TP table."""
|
||||
|
||||
if destination.ndim == 0 or loaded_weight.ndim != destination.ndim:
|
||||
raise ValueError("destination and loaded weight must have matching ranks")
|
||||
if destination.shape[1:] != loaded_weight.shape[1:]:
|
||||
|
||||
@@ -47,7 +47,6 @@ from vllm.v1.kv_cache_interface import (
|
||||
|
||||
def canonical_qsa_rope_positions(positions: torch.Tensor) -> torch.Tensor:
|
||||
"""Return exact per-token positions as ``[tokens, 1, 3]`` int64 rows."""
|
||||
|
||||
if positions.ndim == 1:
|
||||
positions = positions.unsqueeze(0).expand(3, -1)
|
||||
elif positions.ndim != 2 or positions.shape[0] not in (1, 3):
|
||||
@@ -115,7 +114,6 @@ def circular_qsa_slot_mapping(
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Map each request to its fixed physical block as a circular token ring."""
|
||||
|
||||
if compressor_state_size <= 0:
|
||||
raise ValueError("QSA circular buffer size must be positive")
|
||||
if block_table.ndim != 2:
|
||||
@@ -167,7 +165,6 @@ def compressed_qsa_slot_mapping(
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Build boundary-only slots for an ``MLAAttentionSpec`` QSA cache."""
|
||||
|
||||
if storage_block_size <= 0 or compress_ratio <= 0:
|
||||
raise ValueError("QSA block size and compression ratio must be positive")
|
||||
compressed_positions = torch.div(
|
||||
|
||||
@@ -19,6 +19,12 @@ _QSA_CONFIG_FIELDS = (
|
||||
"indexer_compress_ratio",
|
||||
)
|
||||
|
||||
# Transformers labels Qwen4Exp's sparse-attention layers `qwen_sparse_attention`.
|
||||
# Older checkpoints label them `full_attention` and mark QSA by setting the
|
||||
# indexer fields for the whole model.
|
||||
QSA_LAYER_TYPE = "qwen_sparse_attention"
|
||||
ATTENTION_LAYER_TYPES = ("full_attention", QSA_LAYER_TYPE)
|
||||
|
||||
|
||||
class Qwen4ExpVisionConfig(Qwen3VLVisionConfig):
|
||||
model_type = "qwen4_exp"
|
||||
@@ -152,6 +158,11 @@ class Qwen4ExpTextConfig(Qwen3NextConfig):
|
||||
def _validate_qsa_config(self) -> None:
|
||||
configured = {name: getattr(self, name, None) for name in _QSA_CONFIG_FIELDS}
|
||||
if all(value is None for value in configured.values()):
|
||||
if QSA_LAYER_TYPE in (self.layer_types or ()):
|
||||
raise ValueError(
|
||||
f"{QSA_LAYER_TYPE} layers require the QSA config fields: "
|
||||
f"{list(_QSA_CONFIG_FIELDS)}"
|
||||
)
|
||||
return
|
||||
|
||||
missing = [name for name, value in configured.items() if value is None]
|
||||
@@ -183,7 +194,7 @@ class Qwen4ExpTextConfig(Qwen3NextConfig):
|
||||
@property
|
||||
def layers_block_type(self) -> list[str]:
|
||||
return [
|
||||
"attention" if layer_type == "full_attention" else layer_type
|
||||
"attention" if layer_type in ATTENTION_LAYER_TYPES else layer_type
|
||||
for layer_type in self.layer_types
|
||||
]
|
||||
|
||||
|
||||
@@ -32,7 +32,6 @@ def apply_qsa_rope(
|
||||
tensor: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Apply the main attention's exact 1D/MRoPE composition to QSA heads."""
|
||||
|
||||
num_tokens, _, head_dim = tensor.shape
|
||||
rotary_dim = rotary_emb.rotary_dim
|
||||
cache = rotary_emb._match_cos_sin_cache_dtype(tensor) # noqa: SLF001
|
||||
@@ -245,7 +244,6 @@ class QSAIndexer(nn.Module):
|
||||
valid-entry count (the attention kernel's loop bound, never a token
|
||||
index).
|
||||
"""
|
||||
|
||||
metadata = self._metadata()
|
||||
if metadata is None:
|
||||
# Preserve step-0 indices when later MTP steps reuse the buffer.
|
||||
|
||||
@@ -76,7 +76,7 @@ from vllm.v1.attention.backends.registry import MambaAttentionBackendEnum
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
|
||||
from ..common.mtp import make_mtp_hidden_buffer
|
||||
from ..config import Qwen4ExpConfig
|
||||
from ..config import ATTENTION_LAYER_TYPES, QSA_LAYER_TYPE, Qwen4ExpConfig
|
||||
from .hyperconnection import GatedResidual, HyperConnectionConfig
|
||||
from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .ple_layer import Qwen4ExpPLELayer
|
||||
@@ -87,7 +87,6 @@ def without_modelopt_fp4(
|
||||
quant_config: QuantizationConfig | None,
|
||||
) -> QuantizationConfig | None:
|
||||
"""Return ``None`` for weights excluded from Qwen4Exp ModelOpt-FP4."""
|
||||
|
||||
if quant_config is not None and quant_config.get_name() == "modelopt_fp4":
|
||||
return None
|
||||
return quant_config
|
||||
@@ -103,7 +102,6 @@ def _remap_qsa_cache_scale_name(
|
||||
that cache directly, so only QSA layers need the final path component
|
||||
moved to the owner's persistent ``_k_scale``/``_v_scale`` buffers.
|
||||
"""
|
||||
|
||||
scale_suffixes = {
|
||||
"k_proj.k_scale": "_k_scale",
|
||||
"k_proj.output_scale": "_k_scale",
|
||||
@@ -216,8 +214,11 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
prefix=f"{prefix}.linear_attn",
|
||||
gqa_interleaved_layout=False,
|
||||
)
|
||||
elif layer_type == "full_attention":
|
||||
use_qsa = getattr(config, "indexer_n_heads", None) is not None
|
||||
elif layer_type in ATTENTION_LAYER_TYPES:
|
||||
use_qsa = (
|
||||
layer_type == QSA_LAYER_TYPE
|
||||
or getattr(config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
if not use_qsa:
|
||||
self.self_attn = Qwen3NextAttention(
|
||||
config,
|
||||
@@ -315,7 +316,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
attn_out = self.linear_attn(hidden_states=block_input)
|
||||
elif self.layer_type == "full_attention":
|
||||
elif self.layer_type in ATTENTION_LAYER_TYPES:
|
||||
attn_out = self.self_attn(
|
||||
hidden_states=block_input,
|
||||
positions=positions,
|
||||
@@ -395,8 +396,11 @@ class Qwen4ExpModel(nn.Module):
|
||||
self._qsa_layer_ids = frozenset(
|
||||
layer_idx
|
||||
for layer_idx, layer_type in enumerate(config.layer_types)
|
||||
if layer_type == "full_attention"
|
||||
and getattr(config, "indexer_n_heads", None) is not None
|
||||
if layer_type == QSA_LAYER_TYPE
|
||||
or (
|
||||
layer_type == "full_attention"
|
||||
and getattr(config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
)
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, config.hidden_size)
|
||||
|
||||
|
||||
@@ -90,7 +90,6 @@ def _remap_quantized_layers(
|
||||
|
||||
def _remap_mtp_weight_name(name: str) -> str | None:
|
||||
"""Map Qwen4Exp checkpoint paths into the standalone draft model."""
|
||||
|
||||
for checkpoint_prefix in (
|
||||
"model.language_model.",
|
||||
"language_model.",
|
||||
@@ -250,7 +249,6 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
|
||||
def _iter_qsa_attentions(self):
|
||||
"""Yield MTP attention modules that own a QSA indexer."""
|
||||
|
||||
for layer in self.layers:
|
||||
attention = getattr(layer, "self_attn", None)
|
||||
if (
|
||||
@@ -261,13 +259,11 @@ class Qwen4ExpMultiTokenPredictor(nn.Module):
|
||||
|
||||
def set_skip_topk(self, skip: bool) -> None:
|
||||
"""Select on MTP step 0 and reuse its QSA indices on later steps."""
|
||||
|
||||
for attention in self._iter_qsa_attentions():
|
||||
attention.indexer.skip_topk = skip
|
||||
|
||||
def compact_topk_indices(self, row_indices: torch.Tensor) -> None:
|
||||
"""Keep each request's target-aligned step-0 sparse-index row."""
|
||||
|
||||
num_rows = row_indices.numel()
|
||||
for attention in self._iter_qsa_attentions():
|
||||
buffer = attention.topk_indices_buffer
|
||||
|
||||
@@ -869,7 +869,6 @@ class Qwen4ExpNGramEmbedding(nn.Module):
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""Load hash buffers and checkpoint-split embedding rows."""
|
||||
|
||||
persistent_buffers = {
|
||||
"layer_multipliers": self.layer_multipliers,
|
||||
"ngram_heads_offsets": self.ngram_heads_offsets,
|
||||
|
||||
@@ -4,15 +4,24 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
|
||||
TritonWarmupTensor,
|
||||
triton_scalar_specialization_rep,
|
||||
)
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, tl, triton
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _is_sm120() -> bool:
|
||||
"""True on sm_120 (RTX PRO 6000 Blackwell): selects the sm_120 tuning table."""
|
||||
return current_platform.get_device_capability() == (12, 0)
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_rows", "num_requests"])
|
||||
def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
q_ptr,
|
||||
@@ -24,6 +33,8 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
partial_output_ptr,
|
||||
partial_lse_ptr,
|
||||
output_ptr,
|
||||
softmax_scale,
|
||||
output_scale,
|
||||
output_gate_ptr,
|
||||
stride_q_row,
|
||||
stride_q_head,
|
||||
@@ -52,6 +63,7 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
NUM_TILES: tl.constexpr,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
IS_FP8: tl.constexpr,
|
||||
) -> None:
|
||||
row = tl.program_id(0)
|
||||
kv_head = tl.program_id(1)
|
||||
@@ -81,7 +93,10 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
max_value = tl.full((BLOCK_M,), -1.0e20, dtype=tl.float32)
|
||||
normalizer = tl.zeros((BLOCK_M,), dtype=tl.float32)
|
||||
accumulator = tl.zeros((BLOCK_M, HEAD_DIM), dtype=tl.float32)
|
||||
softmax_scale_log2: tl.constexpr = (HEAD_DIM**-0.5) * 1.4426950408889634
|
||||
# softmax_scale is the host-side attention scale (1/sqrt(head_dim), with the
|
||||
# fp8 K dequant scale already pre-multiplied in); convert to log2 units once
|
||||
# here for the exp2-based online softmax.
|
||||
score_scale = softmax_scale * 1.4426950408889634
|
||||
|
||||
tile_end = tl.minimum(NUM_TILES, tl.cdiv(tl.minimum(valid_count, TOPK), BLOCK_N))
|
||||
|
||||
@@ -129,15 +144,26 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
mask=valid[:, None],
|
||||
other=0.0,
|
||||
)
|
||||
if IS_FP8:
|
||||
# e4m3 -> Q dtype is exact; keep the QK dot in Q's dtype (fp8 QK
|
||||
# measured slower here and less accurate).
|
||||
keys = keys.to(query.dtype)
|
||||
scores = tl.dot(query, keys)
|
||||
# Scaling scores avoids re-quantizing a scaled query to BF16.
|
||||
scores *= softmax_scale_log2
|
||||
# Scaling scores avoids re-quantizing a scaled query to BF16; for fp8
|
||||
# caches the K dequant scale is already folded into softmax_scale on the
|
||||
# host.
|
||||
scores *= score_scale
|
||||
scores = tl.where(valid[None, :], scores, -1.0e20)
|
||||
next_max = tl.maximum(max_value, tl.max(scores, axis=1))
|
||||
alpha = tl.math.exp2(max_value - next_max)
|
||||
probabilities = tl.where(
|
||||
valid[None, :], tl.math.exp2(scores - next_max[:, None]), 0.0
|
||||
)
|
||||
if IS_FP8:
|
||||
# Dequant V to fp16 (not bf16) for the PV dot: P <= 1 (online
|
||||
# softmax) so fp16 has the range, its wider mantissa is more
|
||||
# accurate, and the fp8->fp16 upcast with an fp16 PV dot is faster.
|
||||
values = values.to(tl.float16)
|
||||
accumulator = tl.dot(
|
||||
probabilities.to(values.dtype),
|
||||
values,
|
||||
@@ -147,9 +173,14 @@ def _qsa_sparse_paged_gqa_splitk_kernel(
|
||||
max_value = next_max
|
||||
|
||||
has_values = normalizer > 0
|
||||
# Fold the fp8 V dequant scale (output_scale, 1.0 for bf16) into a per-row
|
||||
# reciprocal normalizer, so the output is a per-row multiply rather than a
|
||||
# HEAD_DIM-wide scale. The split-K LSE below keeps the unscaled normalizer,
|
||||
# so the merge stays correct.
|
||||
inv_normalizer = output_scale / tl.maximum(normalizer, 1.0e-20)
|
||||
normalized_output = tl.where(
|
||||
has_values[:, None],
|
||||
accumulator / tl.maximum(normalizer[:, None], 1.0e-20),
|
||||
accumulator * inv_normalizer[:, None],
|
||||
0.0,
|
||||
)
|
||||
output_mask = head_offsets[:, None] < GROUP_SIZE
|
||||
@@ -439,18 +470,65 @@ def _compress_qsa_groups_kernel(
|
||||
)
|
||||
|
||||
|
||||
def _select_sm120_config(
|
||||
base_programs: int, use_prefill_config: bool, is_fp8: bool
|
||||
) -> tuple[int, int, int]:
|
||||
"""(block_n, target_splits, num_warps) retuned on sm_120 (RTX PRO 6000
|
||||
Blackwell), split by cache dtype: bf16 and fp8 favour different configs on
|
||||
sm_120, most visibly on the large-prefill region. Each entry is the fastest
|
||||
config that stays correct on its own path; the main win is more warps."""
|
||||
if is_fp8:
|
||||
if base_programs > 2048:
|
||||
return (32, 2, 1) if use_prefill_config else (64, 1, 2)
|
||||
if base_programs <= 24:
|
||||
return 64, 64, 8
|
||||
if base_programs <= 32:
|
||||
return 128, 8, 4
|
||||
if base_programs <= 64:
|
||||
return 64, 8, 4
|
||||
if base_programs <= 128:
|
||||
return 32, 4, 4
|
||||
if base_programs <= 256:
|
||||
return 128, 4, 4
|
||||
if base_programs <= 512:
|
||||
return 64, 4, 4
|
||||
return 32, 2, 1
|
||||
# bf16 K/V cache.
|
||||
if base_programs > 2048:
|
||||
return 64, 2, 2
|
||||
if base_programs <= 24:
|
||||
return 64, 64, 8
|
||||
if base_programs <= 64:
|
||||
return 64, 8, 8
|
||||
if base_programs <= 128:
|
||||
return 32, 8, 8
|
||||
if base_programs <= 256:
|
||||
return 32, 8, 1
|
||||
if base_programs <= 512:
|
||||
return 64, 4, 2
|
||||
return 32, 4, 1
|
||||
|
||||
|
||||
def _select_config(
|
||||
num_rows: int, num_kv_heads: int, use_prefill_config: bool, num_columns: int
|
||||
num_rows: int,
|
||||
num_kv_heads: int,
|
||||
use_prefill_config: bool,
|
||||
num_columns: int,
|
||||
is_fp8: bool = False,
|
||||
) -> tuple[int, int, int, int]:
|
||||
"""Select (block_n, num_warps, num_tiles, num_splits) for the kernel.
|
||||
|
||||
Tuned on GB300 for the Qwen3.8-Flash-Next TP1/TP2/TP4 shapes, keyed on
|
||||
base_programs = num_rows * num_kv_heads. The bp > 2048 region splits on
|
||||
use_prefill_config (capture-stable: at FULL-graph capture max_query_len is the
|
||||
uniform decode/verify length).
|
||||
Keyed on base_programs = num_rows * num_kv_heads. The bp > 2048 region splits
|
||||
on use_prefill_config (capture-stable: at FULL-graph capture max_query_len is
|
||||
the uniform decode/verify length). This default table was tuned on GB300;
|
||||
sm_120 (RTX PRO 6000 Blackwell) dispatches to _select_sm120_config instead.
|
||||
"""
|
||||
base_programs = num_rows * num_kv_heads
|
||||
if base_programs > 2048:
|
||||
if _is_sm120():
|
||||
BLOCK_N, target_splits, num_warps = _select_sm120_config(
|
||||
base_programs, use_prefill_config, is_fp8
|
||||
)
|
||||
elif base_programs > 2048:
|
||||
BLOCK_N, target_splits, num_warps = (
|
||||
(32, 1, 1) if use_prefill_config else (64, 1, 2)
|
||||
)
|
||||
@@ -483,10 +561,17 @@ def qsa_sparse_paged_attention(
|
||||
token_to_req: torch.Tensor,
|
||||
use_prefill_config: bool,
|
||||
out: torch.Tensor | None = None,
|
||||
k_scale: float | None = None,
|
||||
v_scale: float | None = None,
|
||||
*,
|
||||
output_gate: torch.Tensor,
|
||||
) -> torch.Tensor:
|
||||
"""Run sparse GQA directly over paged BF16 K/V caches.
|
||||
"""Run sparse GQA directly over paged BF16 or FP8-e4m3 K/V caches.
|
||||
|
||||
With fp8 caches, k_scale/v_scale are the layer's per-tensor dequant scales
|
||||
as host floats (e.g. layer._k_scale_float/_v_scale_float): k_scale is
|
||||
pre-multiplied into the softmax scale and v_scale becomes the kernel's
|
||||
output scale, so the kernel needs no device scale buffers.
|
||||
|
||||
logical_indices is the PACKED selection buffer: [rows, selection_width + 1]
|
||||
with the trailing column holding each row's valid-entry count (written by
|
||||
@@ -510,7 +595,19 @@ def qsa_sparse_paged_attention(
|
||||
raise ValueError("QSA sparse attention requires valid grouped-query heads")
|
||||
head_dim = q.shape[2]
|
||||
assert head_dim >= 16 and (head_dim & (head_dim - 1)) == 0
|
||||
assert q.dtype == k_cache.dtype == v_cache.dtype == torch.bfloat16
|
||||
assert q.dtype == torch.bfloat16
|
||||
assert k_cache.dtype == v_cache.dtype
|
||||
is_fp8 = k_cache.dtype == torch.float8_e4m3fn
|
||||
if is_fp8:
|
||||
assert k_scale is not None and v_scale is not None
|
||||
# Host pre-multiply: fold the K dequant scale into the attention scale
|
||||
# and pass V's dequant scale as the kernel's output scale.
|
||||
softmax_scale = (head_dim**-0.5) * float(k_scale)
|
||||
output_scale = float(v_scale)
|
||||
else:
|
||||
assert k_cache.dtype == torch.bfloat16
|
||||
softmax_scale = head_dim**-0.5
|
||||
output_scale = 1.0
|
||||
assert logical_indices.dtype == block_table.dtype == torch.int32
|
||||
assert token_to_req.dtype == torch.int32
|
||||
assert q.device == k_cache.device == v_cache.device
|
||||
@@ -535,7 +632,7 @@ def qsa_sparse_paged_attention(
|
||||
block_m = triton.next_power_of_2(group_size)
|
||||
selection_width = logical_indices.shape[1] - 1 # trailing column is the count
|
||||
block_n, partial_warps, num_tiles, num_splits = _select_config(
|
||||
q.shape[0], k_cache.shape[2], use_prefill_config, selection_width
|
||||
q.shape[0], k_cache.shape[2], use_prefill_config, selection_width, is_fp8
|
||||
)
|
||||
|
||||
# Split=1 writes output directly and compiles out all workspace accesses.
|
||||
@@ -565,6 +662,8 @@ def qsa_sparse_paged_attention(
|
||||
partial_output,
|
||||
partial_lse,
|
||||
out,
|
||||
softmax_scale,
|
||||
output_scale,
|
||||
output_gate_view,
|
||||
q.stride(0),
|
||||
q.stride(1),
|
||||
@@ -593,6 +692,7 @@ def qsa_sparse_paged_attention(
|
||||
NUM_TILES=num_tiles,
|
||||
BLOCK_M=block_m,
|
||||
BLOCK_N=block_n,
|
||||
IS_FP8=is_fp8,
|
||||
num_warps=partial_warps,
|
||||
num_stages=2,
|
||||
)
|
||||
@@ -627,16 +727,20 @@ def warmup_qsa_sparse_paged_attention(
|
||||
selection_width: int,
|
||||
) -> tuple[tuple[int, int, int], ...]:
|
||||
"""Compile every production-reachable split-K/merge specialization."""
|
||||
|
||||
head_dim = kv_cache.shape[-1] // 2
|
||||
key_cache, value_cache = kv_cache.transpose(1, 2).split(head_dim, dim=-1)
|
||||
# An fp8 cache is allocated as uint8 and viewed as e4m3 at attention time.
|
||||
is_fp8 = kv_cache.dtype == torch.uint8
|
||||
cache_dtype = torch.float8_e4m3fn if is_fp8 else key_cache.dtype
|
||||
num_kv_heads = key_cache.shape[2]
|
||||
group_size = num_query_heads // num_kv_heads
|
||||
block_m = triton.next_power_of_2(group_size)
|
||||
|
||||
# Every config the dispatch can pick for this group size.
|
||||
profiles = {
|
||||
_select_config(num_rows, num_kv_heads, use_prefill_config, selection_width)
|
||||
_select_config(
|
||||
num_rows, num_kv_heads, use_prefill_config, selection_width, is_fp8
|
||||
)
|
||||
for num_rows in range(1, 8193)
|
||||
for use_prefill_config in (False, True)
|
||||
}
|
||||
@@ -650,12 +754,12 @@ def warmup_qsa_sparse_paged_attention(
|
||||
torch.bfloat16, shape=(num_rows, num_query_heads, head_dim)
|
||||
)
|
||||
k_cache_ptr = TritonWarmupTensor(
|
||||
key_cache.dtype,
|
||||
cache_dtype,
|
||||
shape=tuple(key_cache.shape),
|
||||
strides=tuple(key_cache.stride()),
|
||||
)
|
||||
v_cache_ptr = TritonWarmupTensor(
|
||||
value_cache.dtype,
|
||||
cache_dtype,
|
||||
shape=tuple(value_cache.shape),
|
||||
strides=tuple(value_cache.stride()),
|
||||
)
|
||||
@@ -701,6 +805,8 @@ def warmup_qsa_sparse_paged_attention(
|
||||
partial_output_ptr,
|
||||
partial_lse_ptr,
|
||||
output_ptr,
|
||||
1.0,
|
||||
1.0,
|
||||
output_gate_ptr,
|
||||
row_stride,
|
||||
head_stride,
|
||||
@@ -729,6 +835,7 @@ def warmup_qsa_sparse_paged_attention(
|
||||
NUM_TILES=num_tiles,
|
||||
BLOCK_M=block_m,
|
||||
BLOCK_N=block_n,
|
||||
IS_FP8=is_fp8,
|
||||
num_warps=warps,
|
||||
num_stages=2,
|
||||
grid=(num_rows, num_kv_heads, num_splits),
|
||||
@@ -762,7 +869,6 @@ def qsa_store_cache_rows(
|
||||
rows: torch.Tensor,
|
||||
) -> None:
|
||||
"""Store fixed-width rows in a QSA cache without boolean indexing."""
|
||||
|
||||
if not cache.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("QSA CUDA cache stores require Triton")
|
||||
if cache.ndim != 4 or cache.shape[2] != 1:
|
||||
@@ -808,7 +914,6 @@ def qsa_compress_groups_with_ratio(
|
||||
rope_cache: torch.Tensor | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Pool completed groups from the compressor-state ring and raw token rows."""
|
||||
|
||||
if not raw_keys.is_cuda or not HAS_TRITON:
|
||||
raise RuntimeError("QSA CUDA compression requires Triton")
|
||||
rows = token_to_req.numel()
|
||||
|
||||
@@ -317,7 +317,6 @@ def warmup_qsa_mqa_paged_decode(
|
||||
max_num_batched_tokens: int,
|
||||
) -> tuple[tuple[int, int], ...]:
|
||||
"""Compile every reachable decode specialization without launching it."""
|
||||
|
||||
page_size = k_cache.shape[1]
|
||||
page_table_width = page_table.shape[1]
|
||||
columns = page_table_width * page_size
|
||||
@@ -444,7 +443,6 @@ def expand_qsa_block_indices(
|
||||
out: torch.Tensor,
|
||||
) -> None:
|
||||
"""Expand compressed blocks and compact the causal tail of the open group."""
|
||||
|
||||
assert token_topk % compress_ratio == 0
|
||||
block_topk = token_topk // compress_ratio
|
||||
output_width = token_topk + compress_ratio - 1
|
||||
@@ -524,8 +522,8 @@ def qsa_select_paged_decode(
|
||||
compress_ratio: Number of logical tokens represented by a cache row.
|
||||
decode_query_len: Number of query tokens per request.
|
||||
block_indices: Compressed-index output buffer.
|
||||
"""
|
||||
|
||||
"""
|
||||
assert token_topk % compress_ratio == 0
|
||||
assert block_indices.shape == (q.shape[0], token_topk // compress_ratio)
|
||||
assert decode_query_len > 0 and q.shape[0] % decode_query_len == 0
|
||||
@@ -599,8 +597,8 @@ def qsa_select_paged_prefill(
|
||||
max_query_len: Maximum number of query tokens in one request.
|
||||
block_indices: Compressed-index output buffer.
|
||||
max_seq_len: Longest context length in the batch this step.
|
||||
"""
|
||||
|
||||
"""
|
||||
assert token_topk % compress_ratio == 0
|
||||
assert block_indices.shape == (q.shape[0], token_topk // compress_ratio)
|
||||
assert q.dtype == k_cache.dtype, "Q and the compressed K cache must match"
|
||||
|
||||
@@ -146,7 +146,6 @@ class Qwen4ExpPLELayer(nn.Module, MambaBase):
|
||||
output_dtype: torch.dtype,
|
||||
) -> torch.Tensor:
|
||||
"""Dequantize PLE lookup output."""
|
||||
|
||||
return self.ple_embedding.ngram_embedding.dequantize(
|
||||
embeddings,
|
||||
output_dtype,
|
||||
|
||||
@@ -24,6 +24,7 @@ from vllm.model_executor.layers.quantization import QuantizationConfig
|
||||
from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding, get_rope
|
||||
from vllm.model_executor.models.qwen3_next import Qwen3NextAttention
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.transformers_utils.configs.qwen4_exp import (
|
||||
Qwen4ExpTextConfig,
|
||||
)
|
||||
@@ -64,7 +65,38 @@ class Qwen4ExpQSAFlashAttentionBackend(FlashAttentionBackend):
|
||||
"""FullAttentionSpec backend used by the merged QSA owner."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["auto", "bfloat16"]
|
||||
# fp8/fp8_e4m3: e4m3 bytes in a uint8 cache, written by reshape_and_cache
|
||||
# with the layer's per-tensor scales and dequantized on load inside the QSA
|
||||
# Triton kernel. flash-attn never runs over this cache, so its fp8 probe
|
||||
# does not apply (see supports_kv_cache_dtype and the impl constructor).
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool:
|
||||
return kv_cache_dtype is None or kv_cache_dtype in cls.supported_kv_cache_dtypes
|
||||
|
||||
@classmethod
|
||||
def supports_combination(
|
||||
cls,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
kv_cache_dtype: CacheDType | None,
|
||||
block_size: int | None,
|
||||
use_mla: bool,
|
||||
has_sink: bool,
|
||||
use_sparse: bool,
|
||||
use_mm_prefix: bool,
|
||||
device_capability: DeviceCapability,
|
||||
) -> str | None:
|
||||
# QSA dequantizes the fp8 KV in its own Triton kernel and never runs
|
||||
# flash-attn over the quantized cache, so the parent's fp8-KV rejection
|
||||
# does not apply and every combination it is handed is accepted here.
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
@@ -98,16 +130,53 @@ class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
supports_dcp: bool = False
|
||||
supports_pcp: bool = False
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
scale: float,
|
||||
num_kv_heads: int,
|
||||
alibi_slopes: list[float] | None,
|
||||
sliding_window: int | None,
|
||||
kv_cache_dtype: str,
|
||||
logits_soft_cap: float | None = None,
|
||||
attn_type: AttentionType = AttentionType.DECODER,
|
||||
kv_sharing_target_layer_name: str | None = None,
|
||||
sinks: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
# The parent constructor probes flash-attn for quantized-KV support and
|
||||
# raises where it is unavailable (sm120), but QSA dequantizes fp8 inside
|
||||
# its own Triton kernel and never runs flash-attn over the cache. Hand
|
||||
# the parent "auto" for that probe and restore the real dtype afterwards:
|
||||
# the parent only uses it there, and do_kv_cache_update reads the
|
||||
# attribute at call time.
|
||||
real_kv_cache_dtype = kv_cache_dtype
|
||||
if kv_cache_dtype in ("fp8", "fp8_e4m3"):
|
||||
kv_cache_dtype = "auto"
|
||||
super().__init__(
|
||||
num_heads,
|
||||
head_size,
|
||||
scale,
|
||||
num_kv_heads,
|
||||
alibi_slopes,
|
||||
sliding_window,
|
||||
kv_cache_dtype,
|
||||
logits_soft_cap,
|
||||
attn_type,
|
||||
kv_sharing_target_layer_name,
|
||||
sinks,
|
||||
)
|
||||
self.kv_cache_dtype = real_kv_cache_dtype
|
||||
if not is_flash_attn_varlen_func_available():
|
||||
raise NotImplementedError("Qwen4Exp QSA requires FlashAttention")
|
||||
if self.dcp_world_size != 1:
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA does not support decode context parallelism"
|
||||
)
|
||||
if self.kv_cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
if self.kv_cache_dtype not in ("auto", "bfloat16", "fp8", "fp8_e4m3"):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA requires a BF16 or FP8-e4m3 main KV cache"
|
||||
)
|
||||
self.supports_quant_query_input = False
|
||||
|
||||
def forward_qsa(
|
||||
@@ -144,8 +213,23 @@ class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
logical_indices = topk_buffer[:num_tokens]
|
||||
token_to_req = token_to_req[:num_tokens]
|
||||
key_cache, value_cache = kv_cache.transpose(1, 2).split(self.head_size, dim=-1)
|
||||
if key_cache.dtype != torch.bfloat16 or query.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 Q/K/V")
|
||||
k_scale = v_scale = None
|
||||
if self.kv_cache_dtype in ("fp8", "fp8_e4m3"):
|
||||
# The cache is allocated as uint8; reinterpret the e4m3 bytes
|
||||
# (same itemsize, so shape and strides are preserved).
|
||||
key_cache = key_cache.view(torch.float8_e4m3fn)
|
||||
value_cache = value_cache.view(torch.float8_e4m3fn)
|
||||
# Host-side per-tensor dequant scales (Python floats), as used by
|
||||
# other host-scale backends; folded into the kernel's scales.
|
||||
k_scale = layer._k_scale_float
|
||||
v_scale = layer._v_scale_float
|
||||
if query.dtype != torch.bfloat16 or key_cache.dtype not in (
|
||||
torch.bfloat16,
|
||||
torch.float8_e4m3fn,
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA requires BF16 Q and BF16 or FP8-e4m3 K/V"
|
||||
)
|
||||
|
||||
from .ops.qsa import qsa_sparse_paged_attention
|
||||
|
||||
@@ -158,6 +242,8 @@ class Qwen4ExpQSAFlashAttentionImpl(FlashAttentionImpl):
|
||||
token_to_req,
|
||||
use_prefill_config,
|
||||
output[:num_tokens],
|
||||
k_scale=k_scale,
|
||||
v_scale=v_scale,
|
||||
output_gate=output_gate[:num_tokens],
|
||||
)
|
||||
return output
|
||||
@@ -185,8 +271,15 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
|
||||
raise ValueError("Qwen4Exp QSA requires a paged KV cache")
|
||||
if model_config.dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA currently requires BF16")
|
||||
if cache_config.cache_dtype not in ("auto", "bfloat16"):
|
||||
raise NotImplementedError("Qwen4Exp QSA requires a BF16 main KV cache")
|
||||
if cache_config.cache_dtype not in (
|
||||
"auto",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA requires a BF16 or FP8-e4m3 main KV cache"
|
||||
)
|
||||
if getattr(quant_config, "kv_cache_scheme", None) is not None:
|
||||
raise NotImplementedError("Qwen4Exp QSA does not support KV quantization")
|
||||
parallel_config = vllm_config.parallel_config
|
||||
@@ -285,8 +378,10 @@ class Qwen4ExpQSAAttention(Qwen3NextAttention, AttentionLayerBase):
|
||||
self.kv_cache_torch_dtype = kv_cache_dtype_str_to_dtype(
|
||||
self.kv_cache_dtype, model_config
|
||||
)
|
||||
if self.kv_cache_torch_dtype != torch.bfloat16:
|
||||
raise NotImplementedError("Qwen4Exp QSA requires BF16 cache storage")
|
||||
if self.kv_cache_torch_dtype not in (torch.bfloat16, torch.uint8):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp QSA requires BF16 or FP8-e4m3 (uint8) cache storage"
|
||||
)
|
||||
self.kv_sharing_target_layer_name = None
|
||||
self.kv_cache = torch.tensor([])
|
||||
set_default_quant_scales(self, register_buffer=True)
|
||||
|
||||
Reference in New Issue
Block a user