[Perf] Support internal prefill checkpoints for Mamba prefix caching, 9%~25% TTFT improvement (#52789)

Signed-off-by: yewentao256 <zhyanwentao@126.com>
Signed-off-by: Ziming Huang <zelda.huanghuang@gmail.com>
Signed-off-by: Wentao Ye <44945378+yewentao256@users.noreply.github.com>
Co-authored-by: Ziming Huang <zelda.huanghuang@gmail.com>
Co-authored-by: OpenAI Codex <codex@openai.com>
This commit is contained in:
Wentao Ye
2026-08-22 10:32:40 -07:00
committed by GitHub
co-authored by Ziming Huang OpenAI Codex
parent 020829f66b
commit 9eb9d9d395
12 changed files with 562 additions and 48 deletions
+161 -19
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
from dataclasses import replace
import torch
from einops import rearrange
@@ -45,7 +46,10 @@ from vllm.models.kimi_k3.nvidia.kda_metadata import (
from vllm.platforms import current_platform
from vllm.third_party.flash_linear_attention.ops.kda import FusedRMSNormGated
from vllm.transformers_utils.configs.kimi_linear import KimiLinearConfig
from vllm.triton_utils import tl, triton
from vllm.v1.attention.backend import AttentionBackend
from vllm.v1.attention.backends.utils import NULL_BLOCK_ID
from vllm.v1.kv_cache_interface import MambaSpec
from vllm.v1.worker.workspace import current_workspace_manager
logger = init_logger(__name__)
@@ -199,6 +203,8 @@ def _flashkda_prefill(
out: torch.Tensor,
final_state: torch.Tensor,
workspace: torch.Tensor,
checkpoint_state: torch.Tensor | None = None,
checkpoint_offsets: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
import vllm._flashkda_C # noqa: F401
@@ -221,10 +227,75 @@ def _flashkda_prefill(
initial_state.contiguous(),
final_state,
cu_seqlens.contiguous(),
checkpoint_state,
checkpoint_offsets.contiguous() if checkpoint_offsets is not None else None,
)
return out, final_state
@triton.jit
def _store_cache_checkpoints_kernel(
x_ptr,
conv_state_ptr,
recurrent_checkpoint_ptr,
recurrent_state_ptr,
query_start_loc_ptr,
checkpoint_offsets_ptr,
checkpoint_state_indices_ptr,
x_stride_0: tl.constexpr,
x_stride_1: tl.constexpr,
state_stride_0: tl.constexpr,
state_stride_1: tl.constexpr,
state_stride_2: tl.constexpr,
checkpoint_stride_0: tl.constexpr,
recurrent_state_stride_0: tl.constexpr,
checkpoint_offset_stride: tl.constexpr,
STATE_LEN: tl.constexpr,
WIDTH: tl.constexpr,
RECURRENT_ROW_SIZE: tl.constexpr,
NULL_STATE_IDX: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
# store checkpoints to cache
seq_idx = tl.program_id(0)
cols = tl.program_id(1) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
state_idx = tl.load(checkpoint_state_indices_ptr + seq_idx)
checkpoint_offset = tl.load(
checkpoint_offsets_ptr + seq_idx * checkpoint_offset_stride
)
valid_checkpoint = (state_idx != NULL_STATE_IDX) & (checkpoint_offset > 0)
valid_conv = (
(cols < WIDTH * STATE_LEN) & valid_checkpoint & (checkpoint_offset >= STATE_LEN)
)
width_idx = cols // STATE_LEN
history_idx = cols % STATE_LEN
checkpoint_end = tl.load(query_start_loc_ptr + seq_idx) + checkpoint_offset
token_idx = checkpoint_end - STATE_LEN + history_idx
values = tl.load(
x_ptr + token_idx * x_stride_0 + width_idx * x_stride_1,
mask=valid_conv,
)
tl.store(
conv_state_ptr
+ state_idx * state_stride_0
+ width_idx * state_stride_1
+ history_idx * state_stride_2,
values,
mask=valid_conv,
)
valid_recurrent = (cols < RECURRENT_ROW_SIZE) & valid_checkpoint
recurrent = tl.load(
recurrent_checkpoint_ptr + seq_idx * checkpoint_stride_0 + cols,
mask=valid_recurrent,
)
tl.store(
recurrent_state_ptr + state_idx * recurrent_state_stride_0 + cols,
recurrent,
mask=valid_recurrent,
)
def resolve_kda_prefill_backend(
backend: str,
head_dim: int,
@@ -471,6 +542,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
self._flashkda_buffer_specs = (
((1, T, H, D), self.model_config.dtype),
((N, H, D, D), self.get_state_dtype()[1]),
((N, H, D, D), self.get_state_dtype()[1]),
((workspace_size,), torch.uint8),
)
@@ -518,6 +590,14 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
raise ValueError(f"Duplicate layer name: {prefix}")
compilation_config.static_forward_context[prefix] = self
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> MambaSpec:
spec = super().get_kv_cache_spec(vllm_config)
assert isinstance(spec, MambaSpec)
return replace(
spec,
num_prefill_checkpoint_blocks=int(self.kda_prefill_backend == "flashkda"),
)
def forward(
self,
hidden_states: torch.Tensor,
@@ -590,6 +670,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
spec_query_start_loc = m.spec_query_start_loc
num_accepted_tokens = m.num_accepted_tokens
num_actual_tokens = m.num_actual_tokens
checkpoint = m.checkpoint
has_spec_decode = m.num_spec_decodes > 0
mixed_qkv = mixed_qkv[:num_actual_tokens]
g1 = g1[:, :num_actual_tokens]
@@ -780,7 +861,7 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
if self.kda_prefill_backend == "flashkda":
assert self.gate_lower_bound is not None
assert self._flashkda_buffer_specs is not None
workspace_out, final_state, workspace = (
workspace_out, final_state, checkpoint_state, workspace = (
current_workspace_manager().get_simultaneous(
*self._flashkda_buffer_specs
)
@@ -788,24 +869,85 @@ class KimiK3DeltaAttention(GatedDeltaNetAttention):
flashkda_out = (
workspace_out if has_spec_decode else core_attn_out
)[:, : q_ns.shape[1]]
(
core_attn_out_non_spec,
last_recurrent_state,
) = _flashkda_prefill(
q=q_ns,
k=k_ns,
v=v_ns,
g=g1_ns,
beta=beta_ns,
A_log=self.A_log,
dt_bias=self.dt_bias,
lower_bound=self.gate_lower_bound,
initial_state=initial_state,
cu_seqlens=non_spec_query_start_loc,
out=flashkda_out,
final_state=final_state[: initial_state.shape[0]],
workspace=workspace,
)
if checkpoint is not None:
assert non_spec_query_start_loc is not None
num_sequences = initial_state.shape[0]
assert checkpoint.checkpoint_offsets.shape == (num_sequences,)
final_state = final_state[:num_sequences]
checkpoint_state = checkpoint_state[:num_sequences]
checkpoint_offsets = checkpoint.checkpoint_offsets
_flashkda_prefill(
q=q_ns,
k=k_ns,
v=v_ns,
g=g1_ns,
beta=beta_ns,
A_log=self.A_log,
dt_bias=self.dt_bias,
lower_bound=self.gate_lower_bound,
initial_state=initial_state,
cu_seqlens=non_spec_query_start_loc,
out=flashkda_out,
final_state=final_state,
workspace=workspace,
checkpoint_state=checkpoint_state,
checkpoint_offsets=checkpoint_offsets,
)
core_attn_out_non_spec = flashkda_out
last_recurrent_state = final_state
state_len = conv_state.shape[-1]
width = mixed_qkv_ns.shape[-1]
recurrent_row_size = checkpoint_state[0].numel()
block_size = 256
_store_cache_checkpoints_kernel[
(
checkpoint_offsets.numel(),
triton.cdiv(
max(width * state_len, recurrent_row_size),
block_size,
),
)
](
mixed_qkv_ns,
conv_state,
checkpoint_state,
recurrent_state,
non_spec_query_start_loc,
checkpoint_offsets,
checkpoint.state_indices,
mixed_qkv_ns.stride(0),
mixed_qkv_ns.stride(1),
conv_state.stride(0),
conv_state.stride(1),
conv_state.stride(2),
checkpoint_state.stride(0),
recurrent_state.stride(0),
checkpoint_offsets.stride(0),
state_len,
width,
recurrent_row_size,
NULL_BLOCK_ID,
block_size,
)
else:
(
core_attn_out_non_spec,
last_recurrent_state,
) = _flashkda_prefill(
q=q_ns,
k=k_ns,
v=v_ns,
g=g1_ns,
beta=beta_ns,
A_log=self.A_log,
dt_bias=self.dt_bias,
lower_bound=self.gate_lower_bound,
initial_state=initial_state,
cu_seqlens=non_spec_query_start_loc,
out=flashkda_out,
final_state=final_state[: initial_state.shape[0]],
workspace=workspace,
)
else:
(
core_attn_out_non_spec,
@@ -44,6 +44,9 @@ if TYPE_CHECKING:
)
FLASHKDA_CHUNK_SIZE = 16
@cache
def _metadata_launch_pdl() -> bool:
return current_platform.is_arch_support_pdl()
@@ -257,12 +260,19 @@ class KDARecoverSSMCommitMetadata:
align: KDARecoverSSMAlignMetadata | None
@dataclass
class KDACheckpointMetadata:
checkpoint_offsets: torch.Tensor
state_indices: torch.Tensor
@dataclass
class KimiK3KDAMetadata(GDNAttentionMetadata, RecoverSSMMetadata):
recoverssm_commit: KDARecoverSSMCommitMetadata | None = None
recoverssm_context: "KDARecoverSSMCommitContext | None" = field(
default=None, repr=False, compare=False
)
checkpoint: KDACheckpointMetadata | None = None
def commit_recoverssm_state(
self, num_accepted_tokens: torch.Tensor
@@ -557,6 +567,62 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
else:
has_initial_state = None
checkpoint = None
if (
num_prefills > 0
and self.kv_cache_spec.num_prefill_checkpoint_blocks > 0
and self.vllm_config.cache_config.mamba_cache_mode == "align"
):
# prepare checkpoint metadata
assert m.seq_lens_cpu_upper_bound is not None
request_rows = list(range(m.num_reqs))
if spec_sequence_masks_cpu is not None:
# get non spec request rows
request_rows = active_non_spec_mask_cpu.nonzero().flatten().tolist()
all_query_lens = query_start_loc_cpu.diff().tolist()
query_lens = [all_query_lens[row] for row in request_rows]
seq_lens = m.seq_lens_cpu_upper_bound.tolist()
block_size = self.kv_cache_spec.block_size
checkpoint_splits = []
checkpoint_cols = []
for row, query_len in zip(request_rows, query_lens):
seq_len = seq_lens[row]
offset = seq_len // block_size * block_size - (seq_len - query_len)
# offset should be less than query_len
valid = (
seq_len % block_size != 0
and 0 < offset < query_len
and offset % FLASHKDA_CHUNK_SIZE == 0
)
offset = offset if valid else 0
first_len = offset or query_len
checkpoint_splits.append((first_len, query_len - first_len))
checkpoint_cols.append(seq_len // block_size - 1 if valid else -1)
if any(tail for _, tail in checkpoint_splits):
checkpoint_offsets_tensor = async_tensor_h2d(
[first if tail else 0 for first, tail in checkpoint_splits],
dtype=torch.int32,
device=query_start_loc.device,
)
request_rows_tensor = async_tensor_h2d(
request_rows, dtype=torch.int64, device=query_start_loc.device
)
checkpoint_cols_tensor = async_tensor_h2d(
checkpoint_cols, dtype=torch.int64, device=query_start_loc.device
)
checkpoint_state_indices = m.block_table_tensor[
request_rows_tensor, checkpoint_cols_tensor
]
checkpoint_state_indices = torch.where(
checkpoint_cols_tensor >= 0,
checkpoint_state_indices,
NULL_BLOCK_ID,
)
checkpoint = KDACheckpointMetadata(
checkpoint_offsets_tensor,
checkpoint_state_indices,
)
# Prepare per-request tensors for cudagraph replay. num_actual_tokens
# may be token-padded, while state/query/acceptance metadata is indexed
# by request.
@@ -647,6 +713,7 @@ class KimiK3KDAMetadataBuilder(GDNAttentionMetadataBuilder):
nums_dict=nums_dict,
batch_ptr=batch_ptr,
token_chunk_offset_ptr=token_chunk_offset_ptr,
checkpoint=checkpoint,
)