[ROCm][Perf] Kimi-K3 Fused kernel for KDA decode (#50654)
Signed-off-by: kliuae <kuanfu.liu@embeddedllm.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: TJian <tunjian.tan@embeddedllm.com>
This commit is contained in:
@@ -5,10 +5,12 @@ import torch
|
||||
from einops import rearrange
|
||||
from torch import nn
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed import divide
|
||||
from vllm.forward_context import get_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
RowParallelLinear,
|
||||
@@ -38,6 +40,11 @@ from vllm.model_executor.layers.mamba.ops.gather_initial_states import (
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import sharded_weight_loader
|
||||
from vllm.model_executor.utils import set_weight_attrs
|
||||
from vllm.models.kimi_k3.amd.ops.kda_decode import (
|
||||
is_fused_kda_decode_supported,
|
||||
make_decode_conv1d_weight_loader,
|
||||
make_decode_norm_weight_loader,
|
||||
)
|
||||
from vllm.models.kimi_k3.amd.ops.third_party.kda import (
|
||||
chunk_kda_with_fused_gate,
|
||||
fused_recurrent_kda,
|
||||
@@ -47,6 +54,8 @@ from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
|
||||
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
|
||||
from vllm.v1.attention.backends.gdn_attn import GDNAttentionMetadata
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class KimiK3DeltaAttention(GatedDeltaNetAttention):
|
||||
def get_state_dtype(self) -> tuple[torch.dtype, torch.dtype]:
|
||||
@@ -137,16 +146,44 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
|
||||
)
|
||||
self.conv1d.weight.data = self.conv1d.weight.data.unsqueeze(1)
|
||||
delattr(self.conv1d.weight, "weight_loader")
|
||||
set_weight_attrs(
|
||||
self.conv1d.weight,
|
||||
{
|
||||
"weight_loader": _make_fused_conv1d_weight_loader(
|
||||
[self.projection_size] * 3,
|
||||
self.tp_size,
|
||||
self.tp_rank,
|
||||
)
|
||||
},
|
||||
# ROCm can fuse the whole decode step (conv + recurrence + gated norm)
|
||||
# into one kernel, which wants a width-major fp32 conv weight staged at
|
||||
# load time. Everything else keeps the [channel, width] layout.
|
||||
conv_state_dtype, _ = self.get_state_dtype()
|
||||
decode_conv1d_weight = None
|
||||
if is_fused_kda_decode_supported(
|
||||
self.local_num_heads,
|
||||
self.head_dim,
|
||||
self.conv_size,
|
||||
self.num_spec,
|
||||
vllm_config.model_config.dtype,
|
||||
conv_state_dtype,
|
||||
):
|
||||
logger.info_once("Fused KDA decode kernel (conv+KDA+norm) is enabled.")
|
||||
decode_conv1d_weight = torch.empty(
|
||||
3,
|
||||
self.conv_size,
|
||||
self.local_projection_size,
|
||||
dtype=self.conv1d.weight.dtype,
|
||||
device=self.conv1d.weight.device,
|
||||
)
|
||||
self.register_buffer(
|
||||
"decode_conv1d_weight", decode_conv1d_weight, persistent=False
|
||||
)
|
||||
if decode_conv1d_weight is None:
|
||||
conv1d_weight_loader = _make_fused_conv1d_weight_loader(
|
||||
[self.projection_size] * 3,
|
||||
self.tp_size,
|
||||
self.tp_rank,
|
||||
)
|
||||
else:
|
||||
conv1d_weight_loader = make_decode_conv1d_weight_loader(
|
||||
[self.projection_size] * 3,
|
||||
self.tp_size,
|
||||
self.tp_rank,
|
||||
decode_conv1d_weight,
|
||||
)
|
||||
set_weight_attrs(self.conv1d.weight, {"weight_loader": conv1d_weight_loader})
|
||||
|
||||
self.A_log = nn.Parameter(
|
||||
torch.empty(self.local_num_heads, dtype=torch.float32)
|
||||
@@ -175,6 +212,22 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
|
||||
)
|
||||
|
||||
self.o_norm = FusedRMSNormGated(self.head_dim, activation="sigmoid")
|
||||
decode_norm_weight = None
|
||||
if decode_conv1d_weight is not None:
|
||||
# Upcast once at load time; a BF16 norm weight slows the fused
|
||||
# decode kernel's epilogue.
|
||||
decode_norm_weight = torch.empty(
|
||||
self.head_dim,
|
||||
dtype=torch.float32,
|
||||
device=self.o_norm.weight.device,
|
||||
)
|
||||
if hasattr(self.o_norm.weight, "weight_loader"):
|
||||
delattr(self.o_norm.weight, "weight_loader")
|
||||
set_weight_attrs(
|
||||
self.o_norm.weight,
|
||||
{"weight_loader": make_decode_norm_weight_loader(decode_norm_weight)},
|
||||
)
|
||||
self.register_buffer("decode_norm_weight", decode_norm_weight, persistent=False)
|
||||
self.o_proj = RowParallelLinear(
|
||||
self.projection_size,
|
||||
self.hidden_size,
|
||||
@@ -280,6 +333,33 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
|
||||
if not is_conv_state_dim_first():
|
||||
conv_state = conv_state.transpose(-1, -2)
|
||||
|
||||
if (
|
||||
self.decode_conv1d_weight is not None
|
||||
and self.decode_norm_weight is not None
|
||||
and spec_sequence_masks is None
|
||||
and m.num_prefills == 0
|
||||
and m.num_decodes > 0
|
||||
):
|
||||
assert non_spec_state_indices_tensor is not None
|
||||
ops.fused_kda_decode(
|
||||
x=mixed_qkv,
|
||||
weight=self.decode_conv1d_weight,
|
||||
bias=self.conv1d.bias,
|
||||
conv_state=conv_state,
|
||||
raw_g=g1,
|
||||
raw_beta=beta,
|
||||
A_log=self.A_log,
|
||||
dt_bias=self.dt_bias,
|
||||
state_indices=non_spec_state_indices_tensor[:num_actual_tokens],
|
||||
state=recurrent_state,
|
||||
out=core_attn_out[:, :num_actual_tokens],
|
||||
lower_bound=self.gate_lower_bound,
|
||||
output_gate=g2[:num_actual_tokens],
|
||||
norm_weight=self.decode_norm_weight,
|
||||
norm_eps=self.o_norm.eps,
|
||||
)
|
||||
return
|
||||
|
||||
conv_weights = self.conv1d.weight.view(
|
||||
self.conv1d.weight.size(0), self.conv1d.weight.size(2)
|
||||
)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""ROCm entry points for the fused Kimi-K3 KDA decode kernel.
|
||||
|
||||
The kernel in ``csrc/libtorch_stable/kimi_k3/fused_kda_decode_kernel_rocm.cu``
|
||||
replaces, for a pure non-speculative decode batch, the three Triton launches
|
||||
and two copies the AMD KDA layer otherwise runs per layer: the packed causal
|
||||
conv1d update, the recurrent delta-rule step, and the gated output RMSNorm.
|
||||
|
||||
The kernel wants a width-major conv weight and an fp32 norm weight, so both are
|
||||
staged once at load time by the weight loaders below.
|
||||
"""
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.mamba.mamba_utils import is_conv_state_dim_first
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Head counts the kernel is instantiated for (Kimi-K3 has 96 KDA heads, so this
|
||||
# covers TP1/2/4/8).
|
||||
SUPPORTED_NUM_HEADS = (12, 24, 48, 96)
|
||||
|
||||
|
||||
def is_fused_kda_decode_supported(
|
||||
num_heads: int,
|
||||
head_dim: int,
|
||||
conv_width: int,
|
||||
num_spec: int,
|
||||
input_dtype: torch.dtype,
|
||||
conv_state_dtype: torch.dtype,
|
||||
) -> bool:
|
||||
"""Whether the fused decode kernel can serve this layer on this device."""
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
if (
|
||||
num_heads not in SUPPORTED_NUM_HEADS
|
||||
or head_dim != 128
|
||||
or conv_width != 4
|
||||
or num_spec != 0
|
||||
or input_dtype != torch.bfloat16
|
||||
or conv_state_dtype != torch.bfloat16
|
||||
or is_conv_state_dim_first()
|
||||
or not hasattr(torch.ops._C, "fused_kda_decode")
|
||||
):
|
||||
return False
|
||||
# TODO: Verify on other archs; only measured on gfx950 for now
|
||||
return on_gfx950()
|
||||
|
||||
|
||||
def make_decode_conv1d_weight_loader(
|
||||
dims: list[int],
|
||||
tp_size: int,
|
||||
tp_rank: int,
|
||||
decode_conv1d_weight: torch.Tensor | None,
|
||||
) -> Callable[..., None]:
|
||||
"""Load the packed conv1d weight, mirroring a width-major fp32 copy.
|
||||
|
||||
The fused kernel indexes the weight as ``[qkv, width, channel]`` so the
|
||||
channel dimension is the contiguous one; the Triton prefill and fallback
|
||||
decode kernels keep the ``[channel, width]`` layout.
|
||||
"""
|
||||
sharded_dims = [dim // tp_size for dim in dims]
|
||||
|
||||
def weight_loader(
|
||||
param: torch.Tensor,
|
||||
loaded_weight: torch.Tensor,
|
||||
loaded_shard_id: int,
|
||||
) -> None:
|
||||
if loaded_weight.dim() == 2:
|
||||
loaded_weight = loaded_weight.unsqueeze(1)
|
||||
shard_size = sharded_dims[loaded_shard_id]
|
||||
source_start = tp_rank * shard_size
|
||||
target_start = sum(sharded_dims[:loaded_shard_id])
|
||||
loaded_shard = loaded_weight[source_start : source_start + shard_size]
|
||||
param.data[target_start : target_start + shard_size].copy_(loaded_shard)
|
||||
if decode_conv1d_weight is not None and not param.is_meta:
|
||||
decode_conv1d_weight[loaded_shard_id].copy_(
|
||||
loaded_shard.squeeze(1).transpose(0, 1)
|
||||
)
|
||||
|
||||
return weight_loader
|
||||
|
||||
|
||||
def make_decode_norm_weight_loader(
|
||||
decode_norm_weight: torch.Tensor,
|
||||
) -> Callable[..., None]:
|
||||
"""Load the gated-norm weight, mirroring an fp32 copy for the kernel."""
|
||||
|
||||
def weight_loader(param: torch.Tensor, loaded_weight: torch.Tensor) -> None:
|
||||
default_weight_loader(param, loaded_weight)
|
||||
if not param.is_meta:
|
||||
decode_norm_weight.copy_(param.data)
|
||||
|
||||
return weight_loader
|
||||
Reference in New Issue
Block a user