[Mini-VLLM] Cut dead subsystems across serving, connectors, parsers
- Remove P/D transfer connectors: nixl, nixl_chat, mooncake x2, hf3fs, moriio, hisparse, example and hidden-states connectors - Reduce weight_transfer to the base API used by model loading - Remove kv_offload tiering, simple_kv_offload, ec cpu/example, snapshot command, engine snapshot server - Remove transformers model fallback, dsv4 tokenizers, dead platforms cpu/tpu/xpu, flashmla third_party, dsa, megamoe/flydsl, dead attn ops, dead layers (short_conv, fused_embed_norm, indexer_topk, relu2 gemma_ar, lightning_attn, minimax_rms_norm), gemm_rs_ar - Keep MoE LoRA op (imported eagerly by punica_gpu); drop fp8 variant - Rebuild parser hubs around Qwen3 adapters only (36 dead adapters) - Remove dead tests with the code they covered Co-authored-by: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -1,394 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.model_executor.warmup.jit_warmup import kernel_launcher
|
||||
from vllm.model_executor.warmup.jit_warmup_triton_helper import (
|
||||
LaunchSpec,
|
||||
TritonWarmupTensor,
|
||||
VllmTritonJitKernel,
|
||||
)
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
class PackSeqTritonKernel(VllmTritonJitKernel["PackSeqTritonKernel.CompileKey"]):
|
||||
@dataclass(frozen=True)
|
||||
class CompileKey:
|
||||
dtype: torch.dtype
|
||||
pad_value: float | int
|
||||
pad_is_uint8: bool
|
||||
block_t: int
|
||||
block_d: int
|
||||
|
||||
# N is unused; D and Lmax only affect runtime addressing and masks. The
|
||||
# compile-time tile shape remains controlled by BLOCK_T and BLOCK_D.
|
||||
@staticmethod
|
||||
@triton.jit(do_not_specialize=["N", "D", "Lmax"])
|
||||
def kernel(
|
||||
x_ptr, # [N, D]
|
||||
out_ptr, # [B, Lmax, D]
|
||||
lengths_ptr, # *i32, [B]
|
||||
N,
|
||||
D,
|
||||
Lmax,
|
||||
PAD_VALUE: tl.constexpr,
|
||||
PAD_IS_UINT8: tl.constexpr,
|
||||
BLOCK_T: tl.constexpr, # timesteps per program
|
||||
BLOCK_D: tl.constexpr, # features per program
|
||||
):
|
||||
pid_b = tl.program_id(0) # batch id
|
||||
pid_t = tl.program_id(1) # block over time dimension
|
||||
pid_d = tl.program_id(2) # block over feature dimension
|
||||
off_t = pid_t * BLOCK_T + tl.arange(0, BLOCK_T) # [BLOCK_T]
|
||||
off_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D) # [BLOCK_D]
|
||||
|
||||
# Compute start index and sequence length from cumulative lengths
|
||||
in_start = 0
|
||||
for i in range(pid_b):
|
||||
in_start += tl.load(lengths_ptr + i)
|
||||
seq_len = tl.load(lengths_ptr + pid_b)
|
||||
|
||||
# valid time positions for this block
|
||||
t_mask = off_t < Lmax
|
||||
|
||||
# compute input row indices for valid (b, t)
|
||||
in_row = in_start + off_t
|
||||
valid_row = (off_t < seq_len) & t_mask
|
||||
|
||||
# Pointers
|
||||
# x_ptr: row-major [N, D]
|
||||
x_row_ptr = x_ptr + in_row[:, None] * D + off_d[None, :]
|
||||
|
||||
# out_ptr: row-major [B, Lmax, D]
|
||||
out_row_ptr = out_ptr + (pid_b * Lmax + off_t)[:, None] * D + off_d[None, :]
|
||||
|
||||
# Initialize with PAD. PAD_IS_UINT8 selects the pad tensor's dtype so
|
||||
# integer-typed outputs (e.g. MXFP4 packed nibbles, ue8m0 scale bytes)
|
||||
# get an exact-byte pad rather than going through an fp32→uint8 cast
|
||||
# that's implementation-defined outside of value 0.
|
||||
d_mask = off_d[None, :] < D
|
||||
if PAD_IS_UINT8:
|
||||
pad_vals = tl.full([BLOCK_T, BLOCK_D], PAD_VALUE, tl.uint8)
|
||||
else:
|
||||
pad_vals = tl.full([BLOCK_T, BLOCK_D], PAD_VALUE, tl.float32)
|
||||
tl.store(out_row_ptr, pad_vals, mask=t_mask[:, None] & d_mask)
|
||||
|
||||
# Load & write only where within seq_len
|
||||
x_vals = tl.load(x_row_ptr, mask=valid_row[:, None] & d_mask)
|
||||
tl.store(out_row_ptr, x_vals, mask=valid_row[:, None] & d_mask)
|
||||
|
||||
def dispatch( # type: ignore[override]
|
||||
self,
|
||||
*,
|
||||
dtype: torch.dtype,
|
||||
pad_value: float | int,
|
||||
**compile_key_fields: int,
|
||||
) -> CompileKey:
|
||||
is_uint8 = dtype == torch.uint8
|
||||
return self.CompileKey(
|
||||
**compile_key_fields,
|
||||
dtype=dtype,
|
||||
pad_value=int(pad_value) if is_uint8 else float(pad_value),
|
||||
pad_is_uint8=is_uint8,
|
||||
)
|
||||
|
||||
def get_warmup_keys(
|
||||
self,
|
||||
*,
|
||||
dtype: torch.dtype,
|
||||
pad_value: float | int,
|
||||
) -> list[CompileKey]:
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
dtype=dtype,
|
||||
pad_value=pad_value,
|
||||
block_t=64,
|
||||
block_d=64,
|
||||
)
|
||||
|
||||
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
|
||||
return dict(
|
||||
x_reshaped=TritonWarmupTensor(compile_key.dtype),
|
||||
out=TritonWarmupTensor(compile_key.dtype),
|
||||
lengths=TritonWarmupTensor(torch.int32),
|
||||
N=1,
|
||||
D=1,
|
||||
Lmax=1,
|
||||
pad_value=compile_key.pad_value,
|
||||
pad_is_uint8=compile_key.pad_is_uint8,
|
||||
block_t=compile_key.block_t,
|
||||
block_d=compile_key.block_d,
|
||||
)
|
||||
|
||||
@kernel_launcher
|
||||
def __call__(
|
||||
self,
|
||||
x_reshaped: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lengths: torch.Tensor,
|
||||
*,
|
||||
N: int,
|
||||
D: int,
|
||||
Lmax: int,
|
||||
pad_value: float | int,
|
||||
pad_is_uint8: bool,
|
||||
block_t: int,
|
||||
block_d: int,
|
||||
) -> LaunchSpec:
|
||||
grid = (
|
||||
lengths.shape[0],
|
||||
triton.cdiv(Lmax, block_t),
|
||||
triton.cdiv(D, block_d),
|
||||
)
|
||||
return grid, dict(
|
||||
x_ptr=x_reshaped,
|
||||
lengths_ptr=lengths,
|
||||
PAD_VALUE=pad_value,
|
||||
PAD_IS_UINT8=pad_is_uint8,
|
||||
BLOCK_T=block_t,
|
||||
BLOCK_D=block_d,
|
||||
num_warps=4,
|
||||
num_stages=2,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def pack_ue8m0_x4(scale):
|
||||
"""Encode a power-of-two fp32 scale as four equal packed UE8M0 bytes, the
|
||||
MX scales of a 128-wide row (see `mqa_logits_use_mx_scales`)."""
|
||||
return ((scale.to(tl.int32, bitcast=True) >> 23) & 0xFF) * 0x01010101
|
||||
|
||||
|
||||
def pack_seq_triton(
|
||||
x: torch.Tensor,
|
||||
lengths: torch.Tensor,
|
||||
pad_value: float | int = -float("inf"),
|
||||
block_t: int = 64,
|
||||
block_d: int = 64,
|
||||
) -> torch.Tensor:
|
||||
"""Pack sequences of different lengths into a batched tensor.
|
||||
|
||||
Supports float dtypes (any, via fp32 pad) and ``torch.uint8`` (exact-byte
|
||||
pad — e.g. MXFP4 packed nibbles or ue8m0 scale bytes). For uint8 inputs
|
||||
``pad_value`` must be an integer in ``[0, 255]``.
|
||||
|
||||
Args:
|
||||
x: [N, ...] — input tensor where N is total number of tokens.
|
||||
lengths: [B] — sequence lengths for each batch.
|
||||
pad_value: value to use for padding. Defaults to ``-inf`` which is
|
||||
only sensible for float dtypes; pass ``0`` (or any byte) for
|
||||
uint8 inputs.
|
||||
block_t: block size for time dimension.
|
||||
block_d: block size for feature dimension.
|
||||
|
||||
Returns:
|
||||
packed: [B, Lmax, ...] — packed tensor.
|
||||
|
||||
"""
|
||||
is_uint8 = x.dtype == torch.uint8
|
||||
if is_uint8:
|
||||
assert isinstance(pad_value, int) and 0 <= pad_value <= 255, (
|
||||
f"uint8 pack requires an integer pad in [0, 255], got {pad_value!r}"
|
||||
)
|
||||
pad_constexpr: int | float = int(pad_value)
|
||||
else:
|
||||
pad_constexpr = float(pad_value)
|
||||
|
||||
# Handle multi-dimensional input by reshaping to (N, -1)
|
||||
original_shape = x.shape
|
||||
if len(original_shape) > 2:
|
||||
N = original_shape[0]
|
||||
x_reshaped = x.reshape(N, -1)
|
||||
D = x_reshaped.shape[1]
|
||||
else:
|
||||
N, D = x.shape
|
||||
x_reshaped = x
|
||||
|
||||
B = lengths.numel()
|
||||
Lmax = int(lengths.max().item())
|
||||
|
||||
out = torch.empty((B, Lmax, D), device=x.device, dtype=x.dtype)
|
||||
|
||||
lengths = lengths.int()
|
||||
_PACK_SEQ_TRITON_KERNEL(
|
||||
x_reshaped,
|
||||
out,
|
||||
lengths,
|
||||
N=N,
|
||||
D=D,
|
||||
Lmax=Lmax,
|
||||
pad_value=pad_constexpr,
|
||||
pad_is_uint8=is_uint8,
|
||||
block_t=block_t,
|
||||
block_d=block_d,
|
||||
)
|
||||
|
||||
if len(original_shape) > 2:
|
||||
out = out.reshape((B, Lmax) + original_shape[1:])
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class UnpackSeqTritonKernel(VllmTritonJitKernel["UnpackSeqTritonKernel.CompileKey"]):
|
||||
@dataclass(frozen=True)
|
||||
class CompileKey:
|
||||
dtype: torch.dtype
|
||||
block_t: int
|
||||
block_d: int
|
||||
|
||||
# B, Lmax, and D only affect runtime addressing and masks. The compile-time
|
||||
# tile shape remains controlled by BLOCK_T and BLOCK_D.
|
||||
@staticmethod
|
||||
@triton.jit(do_not_specialize=["B", "Lmax", "D"])
|
||||
def kernel(
|
||||
packed_ptr, # [B, Lmax, D]
|
||||
out_ptr, # [N, D]
|
||||
lengths_ptr, # *i32, [B]
|
||||
B,
|
||||
Lmax,
|
||||
D,
|
||||
BLOCK_T: tl.constexpr, # timesteps per program
|
||||
BLOCK_D: tl.constexpr, # features per program
|
||||
):
|
||||
pid_b = tl.program_id(0) # batch id
|
||||
pid_t = tl.program_id(1) # block over time dimension
|
||||
pid_d = tl.program_id(2) # block over feature dimension
|
||||
off_t = pid_t * BLOCK_T + tl.arange(0, BLOCK_T) # [BLOCK_T]
|
||||
off_d = pid_d * BLOCK_D + tl.arange(0, BLOCK_D) # [BLOCK_D]
|
||||
|
||||
# bounds: compute start from cumulative lengths
|
||||
in_start = 0
|
||||
for i in range(pid_b):
|
||||
in_start += tl.load(lengths_ptr + i)
|
||||
seq_len = tl.load(lengths_ptr + pid_b)
|
||||
|
||||
# valid time positions for this block
|
||||
t_mask = off_t < Lmax
|
||||
valid_row = (off_t < seq_len) & t_mask
|
||||
|
||||
# compute output row indices for valid (b, t)
|
||||
out_row = in_start + off_t
|
||||
|
||||
# Pointers
|
||||
# packed_ptr: row-major [B, Lmax, D]
|
||||
packed_row_ptr = (
|
||||
packed_ptr + (pid_b * Lmax + off_t)[:, None] * D + off_d[None, :]
|
||||
)
|
||||
|
||||
# out_ptr: row-major [N, D]
|
||||
out_row_ptr = out_ptr + out_row[:, None] * D + off_d[None, :]
|
||||
|
||||
# Load from packed tensor and store to output
|
||||
d_mask = off_d[None, :] < D
|
||||
packed_vals = tl.load(packed_row_ptr, mask=valid_row[:, None] & d_mask)
|
||||
tl.store(out_row_ptr, packed_vals, mask=valid_row[:, None] & d_mask)
|
||||
|
||||
def dispatch( # type: ignore[override]
|
||||
self,
|
||||
*,
|
||||
dtype: torch.dtype,
|
||||
**compile_key_fields: int,
|
||||
) -> CompileKey:
|
||||
return self.CompileKey(**compile_key_fields, dtype=dtype)
|
||||
|
||||
def get_warmup_keys(self) -> list[CompileKey]:
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
dtype=torch.int32,
|
||||
block_t=64,
|
||||
block_d=64,
|
||||
)
|
||||
|
||||
def warmup_inputs(self, compile_key: CompileKey) -> dict[str, Any]:
|
||||
return dict(
|
||||
packed_reshaped=TritonWarmupTensor(compile_key.dtype),
|
||||
out=TritonWarmupTensor(compile_key.dtype),
|
||||
lengths=TritonWarmupTensor(torch.int32),
|
||||
B=1,
|
||||
Lmax=1,
|
||||
D=1,
|
||||
block_t=compile_key.block_t,
|
||||
block_d=compile_key.block_d,
|
||||
)
|
||||
|
||||
@kernel_launcher
|
||||
def __call__(
|
||||
self,
|
||||
packed_reshaped: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
lengths: torch.Tensor,
|
||||
*,
|
||||
B: int,
|
||||
Lmax: int,
|
||||
D: int,
|
||||
block_t: int,
|
||||
block_d: int,
|
||||
) -> LaunchSpec:
|
||||
grid = (B, triton.cdiv(Lmax, block_t), triton.cdiv(D, block_d))
|
||||
return grid, dict(
|
||||
packed_ptr=packed_reshaped,
|
||||
lengths_ptr=lengths,
|
||||
BLOCK_T=block_t,
|
||||
BLOCK_D=block_d,
|
||||
num_warps=4,
|
||||
num_stages=2,
|
||||
)
|
||||
|
||||
|
||||
def unpack_seq_triton(
|
||||
packed_tensor: torch.Tensor,
|
||||
lengths: torch.Tensor,
|
||||
block_t: int = 64,
|
||||
block_d: int = 64,
|
||||
) -> torch.Tensor:
|
||||
"""Unpack a packed decode query tensor back to the original format.
|
||||
Efficient Triton implementation.
|
||||
|
||||
Args:
|
||||
packed_tensor: [B, Lmax, ...] - packed tensor from pack_seq_triton
|
||||
lengths: [B] - sequence lengths for each batch
|
||||
block_t: block size for time dimension
|
||||
block_d: block size for feature dimension
|
||||
|
||||
Returns:
|
||||
unpacked_tensor: [N, ...] where N = sum(lengths)
|
||||
|
||||
"""
|
||||
# Handle multi-dimensional input by reshaping to (B, Lmax, -1)
|
||||
original_shape = packed_tensor.shape
|
||||
if len(original_shape) > 3:
|
||||
B, Lmax = original_shape[:2]
|
||||
packed_reshaped = packed_tensor.reshape(B, Lmax, -1)
|
||||
D = packed_reshaped.shape[2]
|
||||
else:
|
||||
B, Lmax, D = packed_tensor.shape
|
||||
packed_reshaped = packed_tensor
|
||||
|
||||
# Calculate total number of elements
|
||||
N = int(lengths.sum().item())
|
||||
|
||||
out = torch.empty((N, D), device=packed_tensor.device, dtype=packed_tensor.dtype)
|
||||
|
||||
lengths = lengths.int()
|
||||
_UNPACK_SEQ_TRITON_KERNEL(
|
||||
packed_reshaped,
|
||||
out,
|
||||
lengths,
|
||||
B=B,
|
||||
Lmax=Lmax,
|
||||
D=D,
|
||||
block_t=block_t,
|
||||
block_d=block_d,
|
||||
)
|
||||
|
||||
# Reshape output back to original dimensions (except first dimension)
|
||||
if len(original_shape) > 3:
|
||||
output_shape = (N,) + original_shape[2:]
|
||||
out = out.reshape(output_shape)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
_PACK_SEQ_TRITON_KERNEL = PackSeqTritonKernel()
|
||||
_UNPACK_SEQ_TRITON_KERNEL = UnpackSeqTritonKernel()
|
||||
@@ -1,2 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -1,115 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import torch
|
||||
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_pcp_group,
|
||||
get_tp_group,
|
||||
)
|
||||
|
||||
|
||||
def _gather_prefill_cache_inputs(
|
||||
tensors: tuple[torch.Tensor, ...],
|
||||
slot_mapping: torch.Tensor,
|
||||
num_decode_tokens: int,
|
||||
shard_decode_requests: bool = False,
|
||||
) -> tuple[tuple[torch.Tensor, ...], torch.Tensor]:
|
||||
"""Gather PCP cache inputs while preserving replicated KV-cache state.
|
||||
|
||||
PCP-only execution shards decode requests across ranks. In that mode each
|
||||
rank must gather the other owners' decode KV as well as partitioned prefill
|
||||
KV so every PCP rank retains a complete cache replica. DCP execution keeps
|
||||
decode requests replicated and uses the legacy prefill-only gather.
|
||||
"""
|
||||
local_num_tokens = tensors[0].shape[0]
|
||||
assert all(tensor.shape[0] == local_num_tokens for tensor in tensors)
|
||||
assert 0 <= num_decode_tokens <= local_num_tokens
|
||||
|
||||
# Replicated draft decodes use unexpanded slot mappings, even with DP padding.
|
||||
if slot_mapping.shape[0] <= local_num_tokens:
|
||||
return (
|
||||
tuple(tensor[:num_decode_tokens] for tensor in tensors),
|
||||
slot_mapping[:num_decode_tokens],
|
||||
)
|
||||
|
||||
pcp_group = get_pcp_group()
|
||||
pcp_size = pcp_group.world_size
|
||||
gathered_slot_mapping = slot_mapping[: pcp_size * local_num_tokens]
|
||||
if shard_decode_requests:
|
||||
gathered_inputs = tuple(
|
||||
pcp_group.all_gather(tensor.contiguous(), dim=0) for tensor in tensors
|
||||
)
|
||||
return gathered_inputs, gathered_slot_mapping
|
||||
|
||||
if num_decode_tokens == local_num_tokens:
|
||||
return tensors, slot_mapping[:num_decode_tokens]
|
||||
|
||||
gathered_prefills = tuple(
|
||||
pcp_group.all_gather(tensor[num_decode_tokens:].contiguous(), dim=0)
|
||||
for tensor in tensors
|
||||
)
|
||||
if num_decode_tokens == 0:
|
||||
return gathered_prefills, gathered_slot_mapping
|
||||
|
||||
cache_inputs = tuple(
|
||||
torch.cat((tensor[:num_decode_tokens], gathered_prefill), dim=0)
|
||||
for tensor, gathered_prefill in zip(tensors, gathered_prefills)
|
||||
)
|
||||
rank_slot_mappings = gathered_slot_mapping.view(pcp_size, local_num_tokens)
|
||||
cache_slot_mapping = torch.cat(
|
||||
(
|
||||
rank_slot_mappings[0, :num_decode_tokens],
|
||||
rank_slot_mappings[:, num_decode_tokens:].flatten(),
|
||||
)
|
||||
)
|
||||
return cache_inputs, cache_slot_mapping
|
||||
|
||||
|
||||
def maybe_gather_mla_latent_cache_inputs(
|
||||
kv_c_normed: torch.Tensor,
|
||||
k_pe: torch.Tensor,
|
||||
slot_mapping: torch.Tensor | None,
|
||||
num_decode_tokens: int | None,
|
||||
use_pcp: bool,
|
||||
pcp_shard_decode_requests: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
if not use_pcp or num_decode_tokens is None:
|
||||
return kv_c_normed, k_pe, slot_mapping
|
||||
assert slot_mapping is not None
|
||||
num_tokens = kv_c_normed.shape[0]
|
||||
k_pe_flat = k_pe.reshape(num_tokens, -1)
|
||||
(cache_kv_c, cache_k_pe_flat), cache_slot_mapping = _gather_prefill_cache_inputs(
|
||||
(kv_c_normed, k_pe_flat),
|
||||
slot_mapping,
|
||||
num_decode_tokens,
|
||||
pcp_shard_decode_requests,
|
||||
)
|
||||
cache_k_pe = cache_k_pe_flat.view(-1, *k_pe.shape[1:])
|
||||
return cache_kv_c, cache_k_pe, cache_slot_mapping
|
||||
|
||||
|
||||
def maybe_gather_indexer_k(
|
||||
k: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
num_decode_tokens: int,
|
||||
use_pcp: bool,
|
||||
pcp_shard_decode_requests: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if not use_pcp:
|
||||
return k, slot_mapping
|
||||
(cache_k,), cache_slot_mapping = _gather_prefill_cache_inputs(
|
||||
(k,), slot_mapping, num_decode_tokens, pcp_shard_decode_requests
|
||||
)
|
||||
return cache_k, cache_slot_mapping
|
||||
|
||||
|
||||
def finalize_mla_pcp_decode(
|
||||
output: torch.Tensor,
|
||||
num_heads: int,
|
||||
) -> torch.Tensor:
|
||||
if output.shape[1] < num_heads:
|
||||
output = get_pcp_group().all_gather(output, dim=1)
|
||||
elif output.shape[1] > num_heads:
|
||||
head_start = get_tp_group().rank_in_group * num_heads
|
||||
output = output[:, head_start : head_start + num_heads]
|
||||
return output
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,817 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
# Adapted from
|
||||
# https://github.com/sgl-project/sglang/blob/9f635ea50de920aa507f486daafba26a5b837574/python/sglang/srt/layers/attention/triton_ops/decode_attention.py
|
||||
# which was originally adapted from
|
||||
# https://github.com/ModelTC/lightllm/blob/96353e868a840db4d103138caf15ed9dbea8c186/lightllm/models/deepseek2/triton_kernel/gqa_flash_decoding_stage1.py
|
||||
# https://github.com/ModelTC/lightllm/blob/96353e868a840db4d103138caf15ed9dbea8c186/lightllm/models/deepseek2/triton_kernel/gqa_flash_decoding_stage2.py
|
||||
|
||||
# Changes:
|
||||
# - Add support for page size >= 1.
|
||||
|
||||
# Copyright 2025 vLLM Team
|
||||
# Copyright 2023-2024 SGLang Team
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ==============================================================================
|
||||
"""Memory-efficient attention for decoding.
|
||||
It supports page size >= 1.
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import torch
|
||||
from packaging import version
|
||||
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
is_hip_ = current_platform.is_rocm()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Only print the following warnings when triton version < 3.2.0.
|
||||
# The issue won't affect performance or accuracy.
|
||||
if version.parse(triton.__version__) < version.parse("3.2.0"):
|
||||
logger.warning(
|
||||
"The following error message 'operation scheduled before its operands' "
|
||||
"can be ignored."
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def tanh(x):
|
||||
# Tanh is just a scaled sigmoid
|
||||
return 2 * tl.sigmoid(2 * x) - 1
|
||||
|
||||
|
||||
def _page_stride(buf, page_size):
|
||||
# Stride between pages. 4D buffers have a page dim; 3D buffers pack pages
|
||||
# along the token dim, so split it out first. Read the real stride (a
|
||||
# cross-layer view has gaps), don't assume PAGE_SIZE * token stride.
|
||||
if buf.ndim == 3:
|
||||
buf = buf.unflatten(-3, (-1, page_size))
|
||||
return buf.stride(-4)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwd_kernel_stage1(
|
||||
Q,
|
||||
K_Buffer,
|
||||
V_Buffer,
|
||||
sm_scale,
|
||||
Req_to_tokens,
|
||||
B_Seqlen,
|
||||
Att_Out,
|
||||
stride_req_to_tokens_b,
|
||||
stride_qbs,
|
||||
stride_qh,
|
||||
stride_buf_kpbs,
|
||||
stride_buf_kbs,
|
||||
stride_buf_kh,
|
||||
stride_buf_vpbs,
|
||||
stride_buf_vbs,
|
||||
stride_buf_vh,
|
||||
stride_mid_ob,
|
||||
stride_mid_oh,
|
||||
stride_mid_os,
|
||||
k_scale,
|
||||
v_scale,
|
||||
kv_group_num: tl.constexpr,
|
||||
BLOCK_DMODEL: tl.constexpr,
|
||||
BLOCK_DV: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
NUM_KV_SPLITS: tl.constexpr,
|
||||
PAGE_SIZE: tl.constexpr,
|
||||
logit_cap: tl.constexpr,
|
||||
Lk: tl.constexpr,
|
||||
Lv: tl.constexpr,
|
||||
):
|
||||
cur_batch = tl.program_id(0)
|
||||
cur_head = tl.program_id(1)
|
||||
split_kv_id = tl.program_id(2)
|
||||
|
||||
cur_kv_head = cur_head // kv_group_num
|
||||
|
||||
offs_d = tl.arange(0, BLOCK_DMODEL)
|
||||
offs_dv = tl.arange(0, BLOCK_DV)
|
||||
mask_d = offs_d < Lk
|
||||
mask_dv = offs_dv < Lv
|
||||
cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)
|
||||
cur_batch_req_idx = cur_batch
|
||||
|
||||
off_q = cur_batch * stride_qbs + cur_head * stride_qh + offs_d
|
||||
q = tl.load(Q + off_q, mask=mask_d, other=0.0)
|
||||
|
||||
kv_len_per_split = tl.cdiv(cur_batch_seq_len, NUM_KV_SPLITS)
|
||||
split_kv_start = kv_len_per_split * split_kv_id
|
||||
split_kv_end = tl.minimum(split_kv_start + kv_len_per_split, cur_batch_seq_len)
|
||||
|
||||
e_max = -float("inf")
|
||||
e_sum = 0.0
|
||||
acc = tl.zeros([BLOCK_DV], dtype=tl.float32)
|
||||
|
||||
if split_kv_end > split_kv_start:
|
||||
ks = tl.load(k_scale)
|
||||
vs = tl.load(v_scale)
|
||||
for start_n in range(split_kv_start, split_kv_end, BLOCK_N):
|
||||
offs_n = start_n + tl.arange(0, BLOCK_N)
|
||||
kv_page_number = tl.load(
|
||||
Req_to_tokens
|
||||
+ stride_req_to_tokens_b * cur_batch_req_idx
|
||||
+ offs_n // PAGE_SIZE,
|
||||
mask=offs_n < split_kv_end,
|
||||
other=0,
|
||||
).to(tl.int64) # page_number * page stride overflows int32
|
||||
kv_in_page = offs_n % PAGE_SIZE
|
||||
offs_buf_k = (
|
||||
(kv_page_number * stride_buf_kpbs + kv_in_page * stride_buf_kbs)[
|
||||
:, None
|
||||
]
|
||||
+ cur_kv_head * stride_buf_kh
|
||||
+ offs_d[None, :]
|
||||
)
|
||||
k = tl.load(
|
||||
K_Buffer + offs_buf_k,
|
||||
mask=(offs_n[:, None] < split_kv_end) & (mask_d[None, :]),
|
||||
other=0.0,
|
||||
)
|
||||
if k.dtype.is_fp8():
|
||||
k = (k.to(tl.float32) * ks).to(q.dtype)
|
||||
qk = tl.sum(q[None, :] * k, 1)
|
||||
qk *= sm_scale
|
||||
|
||||
if logit_cap > 0:
|
||||
qk = logit_cap * tanh(qk / logit_cap)
|
||||
|
||||
qk = tl.where(offs_n < split_kv_end, qk, float("-inf"))
|
||||
|
||||
offs_buf_v = (
|
||||
(kv_page_number * stride_buf_vpbs + kv_in_page * stride_buf_vbs)[
|
||||
:, None
|
||||
]
|
||||
+ cur_kv_head * stride_buf_vh
|
||||
+ offs_dv[None, :]
|
||||
)
|
||||
v = tl.load(
|
||||
V_Buffer + offs_buf_v,
|
||||
mask=(offs_n[:, None] < split_kv_end) & (mask_dv[None, :]),
|
||||
other=0.0,
|
||||
)
|
||||
if v.dtype.is_fp8():
|
||||
v = (v.to(tl.float32) * vs).to(q.dtype)
|
||||
|
||||
n_e_max = tl.maximum(tl.max(qk, 0), e_max)
|
||||
re_scale = tl.exp(e_max - n_e_max)
|
||||
p = tl.exp(qk - n_e_max)
|
||||
acc *= re_scale
|
||||
acc += tl.sum(p[:, None] * v, 0)
|
||||
|
||||
e_sum = e_sum * re_scale + tl.sum(p, 0)
|
||||
e_max = n_e_max
|
||||
|
||||
offs_mid_o = (
|
||||
cur_batch * stride_mid_ob
|
||||
+ cur_head * stride_mid_oh
|
||||
+ split_kv_id * stride_mid_os
|
||||
+ offs_dv
|
||||
)
|
||||
|
||||
tl.store(
|
||||
Att_Out + offs_mid_o,
|
||||
acc / e_sum,
|
||||
mask=(mask_dv),
|
||||
)
|
||||
|
||||
offs_mid_o_1 = (
|
||||
cur_batch * stride_mid_ob
|
||||
+ cur_head * stride_mid_oh
|
||||
+ split_kv_id * stride_mid_os
|
||||
+ Lv
|
||||
)
|
||||
|
||||
tl.store(
|
||||
Att_Out + offs_mid_o_1,
|
||||
e_max + tl.log(e_sum),
|
||||
)
|
||||
|
||||
|
||||
def _decode_att_m_fwd(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
att_out,
|
||||
Req_to_tokens,
|
||||
B_Seqlen,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap,
|
||||
k_scale,
|
||||
v_scale,
|
||||
):
|
||||
BLOCK = 64 if not is_hip_ else 8
|
||||
|
||||
NUM_KV_SPLITS = num_kv_splits
|
||||
Lk = k_buffer.shape[-1]
|
||||
Lv = v_buffer.shape[-1]
|
||||
|
||||
batch, head_num = q.shape[0], q.shape[1]
|
||||
|
||||
grid = (batch, head_num, NUM_KV_SPLITS)
|
||||
kv_group_num = q.shape[1] // k_buffer.shape[-2]
|
||||
|
||||
num_warps = 4
|
||||
if kv_group_num != 1:
|
||||
num_warps = 1 if is_hip_ else 2
|
||||
|
||||
BLOCK_DMODEL = triton.next_power_of_2(Lk)
|
||||
BLOCK_DV = triton.next_power_of_2(Lv)
|
||||
|
||||
_fwd_kernel_stage1[grid](
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
sm_scale,
|
||||
Req_to_tokens,
|
||||
B_Seqlen,
|
||||
att_out,
|
||||
Req_to_tokens.stride(0),
|
||||
q.stride(0),
|
||||
q.stride(1),
|
||||
_page_stride(k_buffer, page_size),
|
||||
k_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
k_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
_page_stride(v_buffer, page_size),
|
||||
v_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
v_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
att_out.stride(0),
|
||||
att_out.stride(1),
|
||||
att_out.stride(2),
|
||||
k_scale,
|
||||
v_scale,
|
||||
kv_group_num=kv_group_num,
|
||||
BLOCK_DMODEL=BLOCK_DMODEL,
|
||||
BLOCK_DV=BLOCK_DV,
|
||||
BLOCK_N=BLOCK,
|
||||
NUM_KV_SPLITS=NUM_KV_SPLITS,
|
||||
PAGE_SIZE=page_size,
|
||||
logit_cap=logit_cap,
|
||||
num_warps=num_warps,
|
||||
num_stages=2,
|
||||
Lk=Lk,
|
||||
Lv=Lv,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwd_grouped_kernel_stage1(
|
||||
Q,
|
||||
K_Buffer,
|
||||
V_Buffer,
|
||||
sm_scale,
|
||||
Req_to_tokens,
|
||||
B_Seqlen,
|
||||
Att_Out,
|
||||
stride_req_to_tokens_b,
|
||||
stride_qbs,
|
||||
stride_qh,
|
||||
stride_buf_kpbs,
|
||||
stride_buf_kbs,
|
||||
stride_buf_kh,
|
||||
stride_buf_vpbs,
|
||||
stride_buf_vbs,
|
||||
stride_buf_vh,
|
||||
stride_mid_ob,
|
||||
stride_mid_oh,
|
||||
stride_mid_os,
|
||||
k_scale,
|
||||
v_scale,
|
||||
kv_group_num: tl.constexpr,
|
||||
q_head_num: tl.constexpr,
|
||||
BLOCK_DMODEL: tl.constexpr,
|
||||
BLOCK_DPE: tl.constexpr,
|
||||
BLOCK_DV: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
BLOCK_H: tl.constexpr,
|
||||
NUM_KV_SPLITS: tl.constexpr,
|
||||
PAGE_SIZE: tl.constexpr,
|
||||
logit_cap: tl.constexpr,
|
||||
Lk: tl.constexpr,
|
||||
Lv: tl.constexpr,
|
||||
IS_MLA: tl.constexpr = False,
|
||||
):
|
||||
cur_batch = tl.program_id(0)
|
||||
cur_head_id = tl.program_id(1)
|
||||
cur_kv_head = cur_head_id // tl.cdiv(kv_group_num, BLOCK_H)
|
||||
split_kv_id = tl.program_id(2)
|
||||
|
||||
VALID_BLOCK_H: tl.constexpr = BLOCK_H if kv_group_num > BLOCK_H else kv_group_num
|
||||
cur_head = cur_head_id * VALID_BLOCK_H + tl.arange(0, BLOCK_H)
|
||||
mask_h = cur_head < (cur_head_id + 1) * VALID_BLOCK_H
|
||||
mask_h = mask_h & (cur_head < q_head_num)
|
||||
|
||||
offs_d = tl.arange(0, BLOCK_DMODEL)
|
||||
offs_dv = tl.arange(0, BLOCK_DV)
|
||||
mask_d = offs_d < Lk
|
||||
mask_dv = offs_dv < Lv
|
||||
cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)
|
||||
cur_batch_req_idx = cur_batch
|
||||
|
||||
offs_q = cur_batch * stride_qbs + cur_head[:, None] * stride_qh + offs_d[None, :]
|
||||
q = tl.load(
|
||||
Q + offs_q,
|
||||
mask=(mask_h[:, None]) & (mask_d[None, :]),
|
||||
other=0.0,
|
||||
cache_modifier=".ca",
|
||||
)
|
||||
|
||||
if BLOCK_DPE > 0:
|
||||
offs_dpe = BLOCK_DMODEL + tl.arange(0, BLOCK_DPE)
|
||||
mask_dpe = offs_dpe < Lk
|
||||
off_qpe = (
|
||||
cur_batch * stride_qbs + cur_head[:, None] * stride_qh + offs_dpe[None, :]
|
||||
)
|
||||
qpe = tl.load(
|
||||
Q + off_qpe,
|
||||
mask=(mask_h[:, None]) & (mask_dpe[None, :]),
|
||||
other=0.0,
|
||||
cache_modifier=".ca",
|
||||
)
|
||||
|
||||
kv_len_per_split = tl.cdiv(cur_batch_seq_len, NUM_KV_SPLITS)
|
||||
split_kv_start = kv_len_per_split * split_kv_id
|
||||
split_kv_end = tl.minimum(split_kv_start + kv_len_per_split, cur_batch_seq_len)
|
||||
|
||||
e_max = tl.zeros([BLOCK_H], dtype=tl.float32) - float("inf")
|
||||
e_sum = tl.zeros([BLOCK_H], dtype=tl.float32)
|
||||
acc = tl.zeros([BLOCK_H, BLOCK_DV], dtype=tl.float32)
|
||||
|
||||
if split_kv_end > split_kv_start:
|
||||
base_offs_k = cur_kv_head * stride_buf_kh + offs_d[:, None]
|
||||
base_offs_v = cur_kv_head * stride_buf_vh + offs_dv[None, :]
|
||||
if BLOCK_DPE > 0:
|
||||
base_offs_kpe = cur_kv_head * stride_buf_kh + offs_dpe[:, None]
|
||||
|
||||
ks = tl.load(k_scale)
|
||||
vs = tl.load(v_scale)
|
||||
for start_n in tl.range(split_kv_start, split_kv_end, BLOCK_N):
|
||||
offs_n = start_n + tl.arange(0, BLOCK_N)
|
||||
kv_page_number = tl.load(
|
||||
Req_to_tokens
|
||||
+ stride_req_to_tokens_b * cur_batch_req_idx
|
||||
+ offs_n // PAGE_SIZE,
|
||||
mask=offs_n < split_kv_end,
|
||||
other=0,
|
||||
cache_modifier=".ca",
|
||||
).to(tl.int64) # page_number * page stride overflows int32
|
||||
kv_off_k = (
|
||||
kv_page_number * stride_buf_kpbs + (offs_n % PAGE_SIZE) * stride_buf_kbs
|
||||
)
|
||||
|
||||
# explicitly facilitate overlapping load/compute
|
||||
offs_buf_k = kv_off_k[None, :] + base_offs_k
|
||||
k = tl.load(
|
||||
K_Buffer + offs_buf_k,
|
||||
mask=(offs_n[None, :] < split_kv_end) & (mask_d[:, None]),
|
||||
other=0.0,
|
||||
cache_modifier=".cg",
|
||||
)
|
||||
|
||||
if k.dtype.is_fp8():
|
||||
k = (k.to(tl.float32) * ks).to(q.dtype)
|
||||
qk = tl.dot(q, k.to(q.dtype))
|
||||
if BLOCK_DPE > 0:
|
||||
offs_buf_kpe = kv_off_k[None, :] + base_offs_kpe
|
||||
kpe = tl.load(
|
||||
K_Buffer + offs_buf_kpe,
|
||||
mask=(offs_n[None, :] < split_kv_end) & (mask_dpe[:, None]),
|
||||
other=0.0,
|
||||
cache_modifier=".cg",
|
||||
)
|
||||
if kpe.dtype.is_fp8():
|
||||
kpe = (kpe.to(tl.float32) * ks).to(qpe.dtype)
|
||||
qk += tl.dot(qpe, kpe.to(qpe.dtype))
|
||||
qk *= sm_scale
|
||||
|
||||
if logit_cap > 0:
|
||||
qk = logit_cap * tanh(qk / logit_cap)
|
||||
|
||||
qk = tl.where(
|
||||
mask_h[:, None] & (offs_n[None, :] < split_kv_end), qk, float("-inf")
|
||||
)
|
||||
|
||||
if not IS_MLA:
|
||||
kv_off_v = (
|
||||
kv_page_number * stride_buf_vpbs
|
||||
+ (offs_n % PAGE_SIZE) * stride_buf_vbs
|
||||
)
|
||||
offs_buf_v = kv_off_v[:, None] + base_offs_v
|
||||
v = tl.load(
|
||||
V_Buffer + offs_buf_v,
|
||||
mask=(offs_n[:, None] < split_kv_end) & (mask_dv[None, :]),
|
||||
other=0.0,
|
||||
)
|
||||
if v.dtype.is_fp8():
|
||||
v = (v.to(tl.float32) * vs).to(q.dtype)
|
||||
else:
|
||||
# MLA uses a single c_kv.
|
||||
# loading the same c_kv to interpret it as v is not necessary.
|
||||
# transpose the existing c_kv (aka k) for the dot product.
|
||||
v = tl.trans(k)
|
||||
|
||||
n_e_max = tl.maximum(tl.max(qk, 1), e_max)
|
||||
re_scale = tl.exp(e_max - n_e_max)
|
||||
p = tl.exp(qk - n_e_max[:, None])
|
||||
acc *= re_scale[:, None]
|
||||
acc += tl.dot(p.to(v.dtype), v)
|
||||
|
||||
e_sum = e_sum * re_scale + tl.sum(p, 1)
|
||||
e_max = n_e_max
|
||||
|
||||
offs_mid_o = (
|
||||
cur_batch * stride_mid_ob
|
||||
+ cur_head[:, None] * stride_mid_oh
|
||||
+ split_kv_id * stride_mid_os
|
||||
+ offs_dv[None, :]
|
||||
)
|
||||
|
||||
tl.store(
|
||||
Att_Out + offs_mid_o,
|
||||
acc / e_sum[:, None],
|
||||
mask=(mask_h[:, None]) & (mask_dv[None, :]),
|
||||
)
|
||||
|
||||
offs_mid_o_1 = (
|
||||
cur_batch * stride_mid_ob
|
||||
+ cur_head * stride_mid_oh
|
||||
+ split_kv_id * stride_mid_os
|
||||
+ Lv
|
||||
)
|
||||
|
||||
tl.store(
|
||||
Att_Out + offs_mid_o_1,
|
||||
e_max + tl.log(e_sum),
|
||||
mask=mask_h,
|
||||
)
|
||||
|
||||
|
||||
def _decode_grouped_att_m_fwd(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
att_out,
|
||||
Req_to_tokens,
|
||||
B_Seqlen,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap,
|
||||
k_scale,
|
||||
v_scale,
|
||||
is_mla=False,
|
||||
):
|
||||
# with is_mla there is only a single c_kv in smem.
|
||||
# could increase BLOCK or num_stages.
|
||||
Lk = k_buffer.shape[-1]
|
||||
Lv = v_buffer.shape[-1]
|
||||
|
||||
# Align tile dimensions with latent rank for MLA to avoid shape mismatch.
|
||||
if is_mla:
|
||||
if not is_hip_ and Lk == 576:
|
||||
BLOCK_DMODEL = 512
|
||||
BLOCK_DPE = 64
|
||||
elif not is_hip_ and Lk == 288:
|
||||
BLOCK_DMODEL = 256
|
||||
BLOCK_DPE = 32
|
||||
else:
|
||||
BLOCK_DMODEL = triton.next_power_of_2(Lv)
|
||||
BLOCK_DPE = triton.next_power_of_2(Lk - Lv) if Lk > Lv else 0
|
||||
else:
|
||||
BLOCK_DMODEL = triton.next_power_of_2(Lk)
|
||||
BLOCK_DPE = 0
|
||||
BLOCK_DV = triton.next_power_of_2(Lv)
|
||||
|
||||
BLOCK = 32
|
||||
if is_hip_:
|
||||
BLOCK = 16
|
||||
|
||||
batch, head_num = q.shape[0], q.shape[1]
|
||||
kv_group_num = q.shape[1] // k_buffer.shape[-2]
|
||||
|
||||
BLOCK_H = 16
|
||||
NUM_KV_SPLITS = num_kv_splits
|
||||
grid = (
|
||||
batch,
|
||||
triton.cdiv(head_num, min(BLOCK_H, kv_group_num)),
|
||||
NUM_KV_SPLITS,
|
||||
)
|
||||
|
||||
extra_kargs = {}
|
||||
num_stages = 2
|
||||
if is_hip_:
|
||||
# https://rocm.docs.amd.com/en/latest/how-to/rocm-for-ai/inference-optimization/workload.html#mi300x-triton-kernel-performance-optimization
|
||||
# https://github.com/triton-lang/triton/blob/main/third_party/amd/backend/compiler.py
|
||||
extra_kargs = {"waves_per_eu": 1, "matrix_instr_nonkdim": 16, "kpack": 2}
|
||||
num_stages = 1
|
||||
elif not is_hip_ and BLOCK_DMODEL >= 1024:
|
||||
# Avoid shared memory overflow on NVIDIA when BLOCK_DMODEL is large
|
||||
# like non-MLA D_QK=576, BLOCK_DMODEL=1024, BLOCK_H=16
|
||||
# exceeds 101376 bytes limit
|
||||
num_stages = 1
|
||||
|
||||
_fwd_grouped_kernel_stage1[grid](
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
sm_scale,
|
||||
Req_to_tokens,
|
||||
B_Seqlen,
|
||||
att_out,
|
||||
Req_to_tokens.stride(0),
|
||||
q.stride(0),
|
||||
q.stride(1),
|
||||
_page_stride(k_buffer, page_size),
|
||||
k_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
k_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
_page_stride(v_buffer, page_size),
|
||||
v_buffer.stride(-3), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
v_buffer.stride(-2), # Assume (..., PAGE_SIZE, NUM_HEADS, HEAD_DIM)
|
||||
att_out.stride(0),
|
||||
att_out.stride(1),
|
||||
att_out.stride(2),
|
||||
k_scale,
|
||||
v_scale,
|
||||
kv_group_num=kv_group_num,
|
||||
q_head_num=head_num,
|
||||
BLOCK_DMODEL=BLOCK_DMODEL,
|
||||
BLOCK_DPE=BLOCK_DPE,
|
||||
BLOCK_DV=BLOCK_DV,
|
||||
BLOCK_N=BLOCK,
|
||||
BLOCK_H=BLOCK_H,
|
||||
NUM_KV_SPLITS=NUM_KV_SPLITS,
|
||||
PAGE_SIZE=page_size,
|
||||
logit_cap=logit_cap,
|
||||
num_warps=4,
|
||||
num_stages=num_stages,
|
||||
Lk=Lk,
|
||||
Lv=Lv,
|
||||
IS_MLA=is_mla,
|
||||
**extra_kargs,
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _fwd_kernel_stage2(
|
||||
Mid_O,
|
||||
o,
|
||||
lse,
|
||||
B_Seqlen,
|
||||
stride_mid_ob,
|
||||
stride_mid_oh,
|
||||
stride_mid_os,
|
||||
stride_obs,
|
||||
stride_oh,
|
||||
stride_lse_bs,
|
||||
NUM_KV_SPLITS: tl.constexpr,
|
||||
BLOCK_DV: tl.constexpr,
|
||||
Lv: tl.constexpr,
|
||||
OUTPUT_FP16: tl.constexpr = 0,
|
||||
):
|
||||
cur_batch = tl.program_id(0)
|
||||
cur_head = tl.program_id(1)
|
||||
|
||||
cur_batch_seq_len = tl.load(B_Seqlen + cur_batch)
|
||||
|
||||
offs_d = tl.arange(0, BLOCK_DV)
|
||||
mask_d = offs_d < Lv
|
||||
|
||||
e_sum = 0.0
|
||||
e_max = -float("inf")
|
||||
acc = tl.zeros([BLOCK_DV], dtype=tl.float32)
|
||||
|
||||
offs_v = cur_batch * stride_mid_ob + cur_head * stride_mid_oh + offs_d
|
||||
offs_logic = cur_batch * stride_mid_ob + cur_head * stride_mid_oh + Lv
|
||||
|
||||
for split_kv_id in range(0, NUM_KV_SPLITS):
|
||||
kv_len_per_split = tl.cdiv(cur_batch_seq_len, NUM_KV_SPLITS)
|
||||
split_kv_start = kv_len_per_split * split_kv_id
|
||||
split_kv_end = tl.minimum(split_kv_start + kv_len_per_split, cur_batch_seq_len)
|
||||
|
||||
if split_kv_end > split_kv_start:
|
||||
tv = tl.load(
|
||||
Mid_O + offs_v + split_kv_id * stride_mid_os, mask=mask_d, other=0.0
|
||||
)
|
||||
tlogic = tl.load(Mid_O + offs_logic + split_kv_id * stride_mid_os)
|
||||
n_e_max = tl.maximum(tlogic, e_max)
|
||||
|
||||
old_scale = tl.exp(e_max - n_e_max)
|
||||
acc *= old_scale
|
||||
exp_logic = tl.exp(tlogic - n_e_max)
|
||||
acc += exp_logic * tv
|
||||
|
||||
e_sum = e_sum * old_scale + exp_logic
|
||||
e_max = n_e_max
|
||||
|
||||
result = acc / e_sum
|
||||
if OUTPUT_FP16:
|
||||
result = result.to(tl.float16)
|
||||
tl.store(
|
||||
o + cur_batch * stride_obs + cur_head * stride_oh + offs_d,
|
||||
result,
|
||||
mask=mask_d,
|
||||
)
|
||||
lse_val = e_max + tl.log(e_sum)
|
||||
tl.store(
|
||||
lse + cur_batch * stride_lse_bs + cur_head,
|
||||
lse_val,
|
||||
)
|
||||
|
||||
|
||||
def _decode_softmax_reducev_fwd(
|
||||
logits,
|
||||
q,
|
||||
o,
|
||||
lse,
|
||||
v_buffer,
|
||||
b_seq_len,
|
||||
num_kv_splits,
|
||||
):
|
||||
batch, head_num = q.shape[0], q.shape[1]
|
||||
Lv = v_buffer.shape[-1]
|
||||
BLOCK_DV = triton.next_power_of_2(Lv)
|
||||
|
||||
NUM_KV_SPLITS = num_kv_splits
|
||||
|
||||
extra_kargs = {}
|
||||
if is_hip_:
|
||||
# https://rocm.docs.amd.com/en/docs-6.2.0/how-to/llm-fine-tuning-optimization/optimizing-triton-kernel.html
|
||||
# https://github.com/triton-lang/triton/blob/main/third_party/amd/backend/compiler.py
|
||||
extra_kargs = {"waves_per_eu": 4, "matrix_instr_nonkdim": 16, "kpack": 2}
|
||||
|
||||
grid = (batch, head_num)
|
||||
_fwd_kernel_stage2[grid](
|
||||
logits,
|
||||
o,
|
||||
lse,
|
||||
b_seq_len,
|
||||
logits.stride(0),
|
||||
logits.stride(1),
|
||||
logits.stride(2),
|
||||
o.stride(0),
|
||||
o.stride(1),
|
||||
lse.stride(0),
|
||||
NUM_KV_SPLITS=NUM_KV_SPLITS,
|
||||
BLOCK_DV=BLOCK_DV,
|
||||
Lv=Lv,
|
||||
num_warps=4,
|
||||
num_stages=2,
|
||||
**extra_kargs,
|
||||
)
|
||||
|
||||
|
||||
def decode_attention_fwd_normal(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
o,
|
||||
lse,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
attn_logits,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap=0.0,
|
||||
k_scale=None,
|
||||
v_scale=None,
|
||||
):
|
||||
_decode_att_m_fwd(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
attn_logits,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap,
|
||||
k_scale,
|
||||
v_scale,
|
||||
)
|
||||
_decode_softmax_reducev_fwd(
|
||||
attn_logits, q, o, lse, v_buffer, b_seq_len, num_kv_splits
|
||||
)
|
||||
|
||||
|
||||
def decode_attention_fwd_grouped(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
o,
|
||||
lse,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
attn_logits,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap=0.0,
|
||||
k_scale=None,
|
||||
v_scale=None,
|
||||
is_mla=False,
|
||||
):
|
||||
_decode_grouped_att_m_fwd(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
attn_logits,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap,
|
||||
k_scale,
|
||||
v_scale,
|
||||
is_mla=is_mla,
|
||||
)
|
||||
_decode_softmax_reducev_fwd(
|
||||
attn_logits, q, o, lse, v_buffer, b_seq_len, num_kv_splits
|
||||
)
|
||||
|
||||
|
||||
def decode_attention_fwd(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
o,
|
||||
lse,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
attn_logits,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size=1,
|
||||
logit_cap=0.0,
|
||||
k_scale=None,
|
||||
v_scale=None,
|
||||
is_mla=False,
|
||||
):
|
||||
assert num_kv_splits == attn_logits.shape[2]
|
||||
|
||||
if k_scale is None:
|
||||
k_scale = torch.tensor(1.0, dtype=torch.float32, device=q.device)
|
||||
if v_scale is None:
|
||||
v_scale = torch.tensor(1.0, dtype=torch.float32, device=q.device)
|
||||
|
||||
kv_group_num = q.shape[1] // v_buffer.shape[-2]
|
||||
|
||||
if kv_group_num == 1:
|
||||
# MHA
|
||||
decode_attention_fwd_normal(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
o,
|
||||
lse,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
attn_logits,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap,
|
||||
k_scale,
|
||||
v_scale,
|
||||
)
|
||||
else:
|
||||
# GQA/MQA/MLA
|
||||
decode_attention_fwd_grouped(
|
||||
q,
|
||||
k_buffer,
|
||||
v_buffer,
|
||||
o,
|
||||
lse,
|
||||
req_to_token,
|
||||
b_seq_len,
|
||||
attn_logits,
|
||||
num_kv_splits,
|
||||
sm_scale,
|
||||
page_size,
|
||||
logit_cap,
|
||||
k_scale,
|
||||
v_scale,
|
||||
is_mla=is_mla,
|
||||
)
|
||||
@@ -1,589 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Triton unified attention with different K/V head dimensions (DiffKV).
|
||||
|
||||
This is a slimmed fork of ``triton_unified_attention.py`` for models like
|
||||
MiMo-V2.5 where the V tensor's head dimension differs from K's. The KV cache
|
||||
is the same packed layout used by ``FlashAttentionDiffKVBackend``:
|
||||
|
||||
kv_cache: [num_blocks, block_size, num_kv_heads, head_size_qk + head_size_v]
|
||||
|
||||
We slice ``key_cache = kv_cache[..., :head_size_qk]`` and
|
||||
``value_cache = kv_cache[..., head_size_qk:]`` on the host, so the kernel
|
||||
takes two cache pointers but with two distinct head sizes.
|
||||
|
||||
Both 2D and 3D launches are supported:
|
||||
- 2D: one program per (q-block, kv-head); tile-loop walks the full KV
|
||||
sequence; final output written directly. Used for prefill and large
|
||||
decode batches.
|
||||
- 3D: one program per (q-block, kv-head, segm); each program covers a
|
||||
KV slice and writes per-segment partials (max/expsum/output). A
|
||||
follow-up ``kernel_reduce_segments_diffkv`` combines them. Selected
|
||||
for decode-only batches whose 2D grid would under-fill the GPU.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.ops.triton_attention_helpers import (
|
||||
apply_alibi_to_score,
|
||||
apply_softcap,
|
||||
cdiv_fn,
|
||||
compute_kv_seq_mask,
|
||||
compute_tile_loop_bounds,
|
||||
find_seq_idx,
|
||||
init_softmax_M,
|
||||
resolve_seq_and_query_len,
|
||||
softmax_step,
|
||||
store_segm_reduce_scalars,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
is_batch_invariant = envs.VLLM_BATCH_INVARIANT
|
||||
|
||||
# Whole-verify split-KV grouping: one program covers all q tokens of a
|
||||
# spec-decode verify request (BLOCK_M = q_len * GQA group, capped at 128).
|
||||
_SPEC_3D_MAX_Q = 16
|
||||
_SPEC_3D_BLOCK_M = 128
|
||||
_SPEC_3D_NUM_WARPS = 8
|
||||
_SPEC_3D_TILE = 16
|
||||
|
||||
|
||||
@triton.jit
|
||||
def kernel_unified_attention_diffkv(
|
||||
# Output destinations. In 2D mode we write the final result into
|
||||
# ``output_ptr``; in 3D mode we write per-segment partials into
|
||||
# ``segm_*`` and ``output_ptr`` is unused (callers may pass any
|
||||
# non-null pointer).
|
||||
output_ptr,
|
||||
segm_output_ptr,
|
||||
segm_max_ptr,
|
||||
segm_expsum_ptr,
|
||||
query_ptr,
|
||||
key_cache_ptr, # view of packed cache: [..., :head_size_qk]
|
||||
value_cache_ptr, # view of packed cache: [..., head_size_qk:hqk+hv]
|
||||
q_descale_ptr,
|
||||
k_descale_ptr,
|
||||
v_descale_ptr,
|
||||
sink_ptr,
|
||||
block_tables_ptr,
|
||||
seq_lens_ptr,
|
||||
alibi_slopes_ptr,
|
||||
scale,
|
||||
softcap,
|
||||
num_query_heads: tl.constexpr,
|
||||
num_queries_per_kv: tl.constexpr,
|
||||
block_table_stride: tl.int64,
|
||||
query_stride_0: tl.int64,
|
||||
query_stride_1: tl.int64, # == HEAD_SIZE_QK
|
||||
output_stride_0: tl.int64,
|
||||
output_stride_1: tl.int64, # == HEAD_SIZE_V
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
TILE_SIZE: tl.constexpr,
|
||||
HEAD_SIZE_QK: tl.constexpr,
|
||||
HEAD_SIZE_QK_PADDED: tl.constexpr,
|
||||
HEAD_SIZE_V: tl.constexpr,
|
||||
HEAD_SIZE_V_PADDED: tl.constexpr,
|
||||
USE_ALIBI_SLOPES: tl.constexpr,
|
||||
USE_ALIBI_SQRT: tl.constexpr,
|
||||
USE_SOFTCAP: tl.constexpr,
|
||||
USE_SINKS: tl.constexpr,
|
||||
USE_Q_SCALE: tl.constexpr,
|
||||
USE_KV_SCALES: tl.constexpr,
|
||||
SLIDING_WINDOW: tl.constexpr,
|
||||
# Strides for both cache views (they share the same packed buffer, so
|
||||
# dims 0/1/2 strides match; only the per-head extent differs).
|
||||
stride_k_cache_0: tl.int64,
|
||||
stride_k_cache_1: tl.int64,
|
||||
stride_k_cache_2: tl.int64,
|
||||
stride_k_cache_3: tl.constexpr,
|
||||
stride_v_cache_0: tl.int64,
|
||||
stride_v_cache_1: tl.int64,
|
||||
stride_v_cache_2: tl.int64,
|
||||
stride_v_cache_3: tl.constexpr,
|
||||
query_start_len_ptr,
|
||||
BLOCK_Q: tl.constexpr,
|
||||
num_seqs: tl.int32,
|
||||
BLOCK_M: tl.constexpr,
|
||||
NUM_SEGMENTS_PER_SEQ: tl.constexpr,
|
||||
# ``IS_3D`` toggles between 2D layout (one program walks the full KV
|
||||
# sequence) and 3D layout (split-KV / FlashDecoding-style: per-segm
|
||||
# programs write partials, finalized by ``kernel_reduce_segments_diffkv``).
|
||||
IS_3D: tl.constexpr,
|
||||
):
|
||||
q_block_global_idx = tl.program_id(0)
|
||||
kv_head_idx = tl.program_id(1)
|
||||
segm_idx = tl.program_id(2) if IS_3D else 0
|
||||
|
||||
(
|
||||
seq_idx,
|
||||
q_block_local_idx,
|
||||
cur_batch_in_all_start_index,
|
||||
cur_batch_query_len,
|
||||
seq_len,
|
||||
) = resolve_seq_and_query_len(
|
||||
query_start_len_ptr, seq_lens_ptr, q_block_global_idx, num_seqs, BLOCK_Q
|
||||
)
|
||||
|
||||
if q_block_local_idx * BLOCK_Q >= cur_batch_query_len:
|
||||
return
|
||||
|
||||
if IS_3D:
|
||||
tiles_per_segment = cdiv_fn(seq_len, NUM_SEGMENTS_PER_SEQ * TILE_SIZE)
|
||||
if segm_idx * tiles_per_segment * TILE_SIZE >= seq_len:
|
||||
return
|
||||
else:
|
||||
tiles_per_segment = 0
|
||||
|
||||
offs_m = tl.arange(0, BLOCK_M)
|
||||
offs_d_qk = tl.arange(0, HEAD_SIZE_QK_PADDED)
|
||||
offs_d_v = tl.arange(0, HEAD_SIZE_V_PADDED)
|
||||
offs_t = tl.arange(0, TILE_SIZE)
|
||||
query_pos = q_block_local_idx * BLOCK_Q + offs_m // num_queries_per_kv
|
||||
|
||||
query_offset_0 = cur_batch_in_all_start_index + query_pos
|
||||
query_offset_1 = kv_head_idx * num_queries_per_kv + offs_m % num_queries_per_kv
|
||||
query_offset = (
|
||||
query_offset_0[:, None] * query_stride_0
|
||||
+ query_offset_1[:, None] * query_stride_1
|
||||
+ offs_d_qk[None, :]
|
||||
)
|
||||
|
||||
dim_mask_qk = tl.where(offs_d_qk < HEAD_SIZE_QK, 1, 0).to(tl.int1)
|
||||
dim_mask_v = tl.where(offs_d_v < HEAD_SIZE_V, 1, 0).to(tl.int1)
|
||||
query_mask_0 = tl.where(query_pos < cur_batch_query_len, 1, 0).to(tl.int1)
|
||||
query_mask_1 = tl.where(query_offset_1 < num_query_heads, 1, 0).to(tl.int1)
|
||||
|
||||
# Q : (BLOCK_M, HEAD_SIZE_QK_PADDED)
|
||||
Q = tl.load(
|
||||
query_ptr + query_offset,
|
||||
mask=dim_mask_qk[None, :] & query_mask_0[:, None] & query_mask_1[:, None],
|
||||
other=0.0,
|
||||
)
|
||||
|
||||
if USE_Q_SCALE:
|
||||
scale *= tl.load(q_descale_ptr)
|
||||
if USE_KV_SCALES:
|
||||
scale *= tl.load(k_descale_ptr)
|
||||
v_descale = tl.load(v_descale_ptr)
|
||||
|
||||
block_table_offset = seq_idx * block_table_stride
|
||||
|
||||
M = init_softmax_M(
|
||||
sink_ptr, query_offset_1, query_mask_1, segm_idx, BLOCK_M, USE_SINKS, IS_3D
|
||||
)
|
||||
L = tl.full([BLOCK_M], 1.0, dtype=tl.float32)
|
||||
# acc : (BLOCK_M, HEAD_SIZE_V_PADDED)
|
||||
acc = tl.zeros([BLOCK_M, HEAD_SIZE_V_PADDED], dtype=tl.float32)
|
||||
|
||||
context_len = seq_len - cur_batch_query_len
|
||||
|
||||
if USE_ALIBI_SLOPES:
|
||||
alibi_slope = tl.load(
|
||||
alibi_slopes_ptr + query_offset_1, mask=query_mask_1, other=0.0
|
||||
)
|
||||
|
||||
loop_lo, loop_hi, max_seq_prefix_len = compute_tile_loop_bounds(
|
||||
context_len,
|
||||
seq_len,
|
||||
cur_batch_query_len,
|
||||
q_block_local_idx,
|
||||
segm_idx,
|
||||
tiles_per_segment,
|
||||
TILE_SIZE,
|
||||
BLOCK_M,
|
||||
BLOCK_Q,
|
||||
num_queries_per_kv,
|
||||
SLIDING_WINDOW,
|
||||
False, # USE_MM_PREFIX
|
||||
IS_3D,
|
||||
)
|
||||
|
||||
for j in range(loop_lo, loop_hi):
|
||||
seq_offset = j * TILE_SIZE + offs_t
|
||||
tile_mask = seq_offset < max_seq_prefix_len
|
||||
|
||||
physical_block_idx = tl.load(
|
||||
block_tables_ptr + block_table_offset + seq_offset // BLOCK_SIZE
|
||||
).to(tl.int64)
|
||||
|
||||
v_offset = (
|
||||
physical_block_idx[:, None] * stride_v_cache_0
|
||||
+ kv_head_idx * stride_v_cache_2
|
||||
+ offs_d_v[None, :] * stride_v_cache_3
|
||||
+ (seq_offset % BLOCK_SIZE)[:, None] * stride_v_cache_1
|
||||
)
|
||||
k_offset = (
|
||||
physical_block_idx[None, :] * stride_k_cache_0
|
||||
+ kv_head_idx * stride_k_cache_2
|
||||
+ offs_d_qk[:, None] * stride_k_cache_3
|
||||
+ (seq_offset % BLOCK_SIZE)[None, :] * stride_k_cache_1
|
||||
)
|
||||
# K : (HEAD_SIZE_QK_PADDED, TILE_SIZE)
|
||||
K_load = tl.load(
|
||||
key_cache_ptr + k_offset,
|
||||
mask=dim_mask_qk[:, None] & tile_mask[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
K = K_load.to(Q.dtype)
|
||||
# V : (TILE_SIZE, HEAD_SIZE_V_PADDED)
|
||||
V_load = tl.load(
|
||||
value_cache_ptr + v_offset,
|
||||
mask=dim_mask_v[None, :] & tile_mask[:, None],
|
||||
other=0.0,
|
||||
)
|
||||
V = V_load.to(Q.dtype)
|
||||
|
||||
query_abs_pos = context_len + query_pos[:, None]
|
||||
seq_mask = compute_kv_seq_mask(
|
||||
query_abs_pos,
|
||||
seq_offset,
|
||||
seq_idx,
|
||||
seq_len,
|
||||
None, # mm_prefix_range_ptr
|
||||
SLIDING_WINDOW,
|
||||
False, # USE_MM_PREFIX
|
||||
0, # MAX_MM_RANGES
|
||||
)
|
||||
|
||||
# S : (BLOCK_M, TILE_SIZE)
|
||||
S = tl.zeros(shape=(BLOCK_M, TILE_SIZE), dtype=tl.float32)
|
||||
S += scale * tl.dot(Q, K)
|
||||
|
||||
if USE_SOFTCAP:
|
||||
S = apply_softcap(S, softcap)
|
||||
|
||||
S = tl.where(
|
||||
query_mask_1[:, None] & query_mask_0[:, None] & seq_mask, S, float("-inf")
|
||||
)
|
||||
|
||||
if USE_ALIBI_SLOPES:
|
||||
S = apply_alibi_to_score(
|
||||
S, alibi_slope, seq_offset, context_len, query_pos, USE_ALIBI_SQRT
|
||||
)
|
||||
|
||||
M, L, P, alpha = softmax_step(S, M, L)
|
||||
acc = acc * alpha[:, None]
|
||||
|
||||
if SLIDING_WINDOW:
|
||||
qpos_lo = q_block_local_idx * BLOCK_Q
|
||||
V = tl.where(
|
||||
(context_len + qpos_lo - seq_offset[:, None]) < SLIDING_WINDOW,
|
||||
V,
|
||||
0.0,
|
||||
)
|
||||
acc += tl.dot(P.to(V.dtype), V)
|
||||
|
||||
# ---- Epilogue --------------------------------------------------------
|
||||
if USE_KV_SCALES:
|
||||
acc *= v_descale
|
||||
|
||||
if IS_3D:
|
||||
# Store per-segment partials; finalized by reduce_segments_diffkv.
|
||||
segm_output_offset = (
|
||||
query_offset_0[:, None].to(tl.int64)
|
||||
* (num_query_heads * NUM_SEGMENTS_PER_SEQ * HEAD_SIZE_V_PADDED)
|
||||
+ query_offset_1[:, None] * (NUM_SEGMENTS_PER_SEQ * HEAD_SIZE_V_PADDED)
|
||||
+ segm_idx * HEAD_SIZE_V_PADDED
|
||||
+ tl.arange(0, HEAD_SIZE_V_PADDED)[None, :]
|
||||
)
|
||||
tl.store(
|
||||
segm_output_ptr + segm_output_offset,
|
||||
acc,
|
||||
mask=dim_mask_v[None, :] & query_mask_0[:, None] & query_mask_1[:, None],
|
||||
)
|
||||
# A row whose keys are all masked in this segment ends at M=0, L=0;
|
||||
# -inf makes reduce_segments treat that segment as absent.
|
||||
M = tl.where(L > 0.0, M, float("-inf"))
|
||||
store_segm_reduce_scalars(
|
||||
segm_max_ptr,
|
||||
segm_expsum_ptr,
|
||||
query_offset_0,
|
||||
query_offset_1,
|
||||
segm_idx,
|
||||
M,
|
||||
L,
|
||||
query_mask_0,
|
||||
query_mask_1,
|
||||
num_query_heads,
|
||||
NUM_SEGMENTS_PER_SEQ,
|
||||
)
|
||||
else:
|
||||
acc = acc / L[:, None]
|
||||
output_offset = (
|
||||
query_offset_0[:, None] * output_stride_0
|
||||
+ query_offset_1[:, None] * output_stride_1
|
||||
+ offs_d_v[None, :]
|
||||
)
|
||||
tl.store(
|
||||
output_ptr + output_offset,
|
||||
acc,
|
||||
mask=dim_mask_v[None, :] & query_mask_0[:, None] & query_mask_1[:, None],
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def kernel_reduce_segments_diffkv(
|
||||
output_ptr, # [num_tokens, num_query_heads, head_size_v]
|
||||
segm_output_ptr,
|
||||
# [num_tokens, num_query_heads, max_num_segments, head_size_v]
|
||||
segm_max_ptr, # [num_tokens, num_query_heads, max_num_segments]
|
||||
segm_expsum_ptr, # [num_tokens, num_query_heads, max_num_segments]
|
||||
seq_lens_ptr, # [num_seqs]
|
||||
num_seqs,
|
||||
num_query_heads: tl.constexpr,
|
||||
output_stride_0: tl.int64,
|
||||
output_stride_1: tl.int64, # == HEAD_SIZE_V
|
||||
TILE_SIZE: tl.constexpr,
|
||||
HEAD_SIZE_V: tl.constexpr,
|
||||
HEAD_SIZE_V_PADDED: tl.constexpr,
|
||||
query_start_len_ptr, # [num_seqs+1]
|
||||
BLOCK_Q: tl.constexpr,
|
||||
NUM_SEGMENTS_PER_SEQ: tl.constexpr,
|
||||
):
|
||||
"""Combine per-segment partials into the final softmax output.
|
||||
|
||||
Mirrors ``reduce_segments`` from triton_unified_attention.py but
|
||||
indexes V's head size (``HEAD_SIZE_V``) instead of the shared one.
|
||||
"""
|
||||
query_token_idx = tl.program_id(0)
|
||||
query_head_idx = tl.program_id(1)
|
||||
|
||||
seq_idx = find_seq_idx(
|
||||
query_start_len_ptr, query_token_idx, num_seqs, BLOCK_Q, False
|
||||
)
|
||||
seq_len = tl.load(seq_lens_ptr + seq_idx)
|
||||
|
||||
tiles_per_segment = cdiv_fn(seq_len, NUM_SEGMENTS_PER_SEQ * TILE_SIZE)
|
||||
act_num_segments = cdiv_fn(seq_len, tiles_per_segment * TILE_SIZE)
|
||||
segm_mask = tl.arange(0, NUM_SEGMENTS_PER_SEQ) < tl.full(
|
||||
[NUM_SEGMENTS_PER_SEQ], act_num_segments, dtype=tl.int32
|
||||
)
|
||||
dim_mask = tl.where(tl.arange(0, HEAD_SIZE_V_PADDED) < HEAD_SIZE_V, 1, 0).to(
|
||||
tl.int1
|
||||
)
|
||||
|
||||
segm_offset = (
|
||||
query_token_idx.to(tl.int64) * (num_query_heads * NUM_SEGMENTS_PER_SEQ)
|
||||
+ query_head_idx * NUM_SEGMENTS_PER_SEQ
|
||||
+ tl.arange(0, NUM_SEGMENTS_PER_SEQ)
|
||||
)
|
||||
segm_max = tl.load(segm_max_ptr + segm_offset, mask=segm_mask, other=float("-inf"))
|
||||
overall_max = tl.max(segm_max)
|
||||
# Graph-capture dummy lengths can leave a query with no causal keys.
|
||||
overall_max = tl.where(overall_max > float("-inf"), overall_max, 0.0)
|
||||
|
||||
segm_expsum = tl.load(segm_expsum_ptr + segm_offset, mask=segm_mask, other=0.0)
|
||||
segm_expsum = segm_expsum * tl.exp(segm_max - overall_max)
|
||||
overall_expsum = tl.sum(segm_expsum)
|
||||
|
||||
segm_output_offset = (
|
||||
query_token_idx.to(tl.int64)
|
||||
* (num_query_heads * NUM_SEGMENTS_PER_SEQ * HEAD_SIZE_V_PADDED)
|
||||
+ query_head_idx * (NUM_SEGMENTS_PER_SEQ * HEAD_SIZE_V_PADDED)
|
||||
+ tl.arange(0, NUM_SEGMENTS_PER_SEQ)[:, None] * HEAD_SIZE_V_PADDED
|
||||
+ tl.arange(0, HEAD_SIZE_V_PADDED)[None, :]
|
||||
)
|
||||
segm_output = tl.load(
|
||||
segm_output_ptr + segm_output_offset,
|
||||
mask=segm_mask[:, None] & dim_mask[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
segm_output *= tl.exp(segm_max - overall_max)[:, None]
|
||||
acc_sum = tl.sum(segm_output, axis=0)
|
||||
acc = tl.where(overall_expsum == 0.0, 0.0, acc_sum / overall_expsum)
|
||||
|
||||
output_offset = (
|
||||
query_token_idx * output_stride_0
|
||||
+ query_head_idx * output_stride_1
|
||||
+ tl.arange(0, HEAD_SIZE_V_PADDED)
|
||||
)
|
||||
tl.store(output_ptr + output_offset, acc, mask=dim_mask)
|
||||
|
||||
|
||||
def unified_attention_diffkv(
|
||||
q, # [num_tokens, num_query_heads, head_size_qk]
|
||||
k, # view: [num_blocks, block_size, num_kv_heads, head_size_qk]
|
||||
v, # view: [num_blocks, block_size, num_kv_heads, head_size_v]
|
||||
out, # [num_tokens, num_query_heads, head_size_v]
|
||||
cu_seqlens_q,
|
||||
seqused_k,
|
||||
softmax_scale,
|
||||
causal,
|
||||
window_size,
|
||||
block_table,
|
||||
softcap,
|
||||
max_seqlen_q: int = 1,
|
||||
alibi_slopes=None,
|
||||
sinks=None,
|
||||
use_alibi_sqrt=False,
|
||||
# 3D / split-KV softmax buffers. When all four are provided and the
|
||||
# batch is decode-only with few sequences, the 3D path is taken.
|
||||
seq_threshold_3D: int | None = None,
|
||||
num_par_softmax_segments: int | None = None,
|
||||
softmax_segm_output: torch.Tensor | None = None,
|
||||
softmax_segm_max: torch.Tensor | None = None,
|
||||
softmax_segm_expsum: torch.Tensor | None = None,
|
||||
k_descale: torch.Tensor | None = None,
|
||||
v_descale: torch.Tensor | None = None,
|
||||
q_descale: torch.Tensor | None = None,
|
||||
):
|
||||
assert causal, "Only causal attention is supported"
|
||||
|
||||
if sinks is not None:
|
||||
assert sinks.shape[0] == q.shape[1], "Sinks must be num_query_heads size"
|
||||
|
||||
use_alibi_slopes = alibi_slopes is not None
|
||||
|
||||
block_size = v.shape[1]
|
||||
num_seqs = len(seqused_k)
|
||||
num_query_heads = q.shape[1]
|
||||
num_kv_heads = k.shape[2]
|
||||
num_queries_per_kv = num_query_heads // num_kv_heads
|
||||
head_size_qk = q.shape[2]
|
||||
head_size_v = v.shape[3]
|
||||
|
||||
BLOCK_M = (
|
||||
16 if num_queries_per_kv <= 16 else triton.next_power_of_2(num_queries_per_kv)
|
||||
)
|
||||
launch_kw: dict[str, int] = {}
|
||||
|
||||
sliding_window_val = 1 + window_size[0] if window_size[0] >= 0 else 0
|
||||
|
||||
# Decide between 2D and 3D launch. Mirrors the standard launcher:
|
||||
# 3D requires preallocated softmax buffers, decode-only batches, and
|
||||
# a small number of sequences (otherwise 2D already saturates the SM).
|
||||
# Spec-decode verify batches (q_len <= _SPEC_3D_MAX_Q, full attention)
|
||||
# also take 3D: their 2D grid is only q_blocks x kv_heads programs, each
|
||||
# walking the whole context. Sliding-window layers stay 2D: their loop
|
||||
# is already window-bounded.
|
||||
spec_3d = (
|
||||
1 < max_seqlen_q <= _SPEC_3D_MAX_Q
|
||||
and sliding_window_val == 0
|
||||
and softmax_segm_output is not None
|
||||
and q.shape[0] <= softmax_segm_output.shape[0]
|
||||
)
|
||||
use_3d = not (
|
||||
seq_threshold_3D is None
|
||||
or num_par_softmax_segments is None
|
||||
or softmax_segm_output is None
|
||||
or softmax_segm_max is None
|
||||
or softmax_segm_expsum is None
|
||||
or (max_seqlen_q > 1 and not spec_3d)
|
||||
or num_seqs > seq_threshold_3D
|
||||
or is_batch_invariant
|
||||
)
|
||||
|
||||
spec_tile: int | None = None
|
||||
if use_3d and spec_3d and _SPEC_3D_BLOCK_M > BLOCK_M:
|
||||
spec_bm = min(
|
||||
_SPEC_3D_BLOCK_M,
|
||||
triton.next_power_of_2(max_seqlen_q * num_queries_per_kv),
|
||||
)
|
||||
if spec_bm > BLOCK_M and spec_bm % num_queries_per_kv == 0:
|
||||
BLOCK_M = spec_bm
|
||||
launch_kw["num_warps"] = _SPEC_3D_NUM_WARPS if BLOCK_M >= 128 else 4
|
||||
spec_tile = _SPEC_3D_TILE
|
||||
BLOCK_Q = BLOCK_M // num_queries_per_kv
|
||||
|
||||
total_num_q_blocks = q.shape[0] // BLOCK_Q + num_seqs
|
||||
|
||||
# Tile size: 32 for prefill-class kernels. Decode (small Q) prefers
|
||||
# smaller tiles to expose more parallelism along the KV dim.
|
||||
tile_size = 32 if not use_3d else (16 if q.element_size() >= 2 else 32)
|
||||
if spec_tile is not None:
|
||||
tile_size = spec_tile
|
||||
|
||||
grid: tuple[Any, ...]
|
||||
if use_3d:
|
||||
grid = (total_num_q_blocks, num_kv_heads, num_par_softmax_segments)
|
||||
segm_output_ptr = softmax_segm_output
|
||||
segm_max_ptr = softmax_segm_max
|
||||
segm_expsum_ptr = softmax_segm_expsum
|
||||
num_segments = num_par_softmax_segments
|
||||
else:
|
||||
grid = (total_num_q_blocks, num_kv_heads)
|
||||
# 2D never touches the segm tensors but Triton wants a non-null
|
||||
# pointer; reuse ``out``.
|
||||
segm_output_ptr = out
|
||||
segm_max_ptr = out
|
||||
segm_expsum_ptr = out
|
||||
num_segments = 1
|
||||
|
||||
kernel_unified_attention_diffkv[grid](
|
||||
output_ptr=out,
|
||||
segm_output_ptr=segm_output_ptr,
|
||||
segm_max_ptr=segm_max_ptr,
|
||||
segm_expsum_ptr=segm_expsum_ptr,
|
||||
query_ptr=q,
|
||||
key_cache_ptr=k,
|
||||
value_cache_ptr=v,
|
||||
q_descale_ptr=q_descale,
|
||||
k_descale_ptr=k_descale,
|
||||
v_descale_ptr=v_descale,
|
||||
sink_ptr=sinks,
|
||||
block_tables_ptr=block_table,
|
||||
seq_lens_ptr=seqused_k,
|
||||
alibi_slopes_ptr=alibi_slopes,
|
||||
scale=softmax_scale,
|
||||
softcap=softcap,
|
||||
num_query_heads=num_query_heads,
|
||||
num_queries_per_kv=num_queries_per_kv,
|
||||
block_table_stride=block_table.stride(0),
|
||||
query_stride_0=q.stride(0),
|
||||
query_stride_1=q.stride(1),
|
||||
output_stride_0=out.stride(0),
|
||||
output_stride_1=out.stride(1),
|
||||
BLOCK_SIZE=block_size,
|
||||
TILE_SIZE=tile_size,
|
||||
HEAD_SIZE_QK=head_size_qk,
|
||||
HEAD_SIZE_QK_PADDED=triton.next_power_of_2(head_size_qk),
|
||||
HEAD_SIZE_V=head_size_v,
|
||||
HEAD_SIZE_V_PADDED=triton.next_power_of_2(head_size_v),
|
||||
USE_ALIBI_SLOPES=use_alibi_slopes,
|
||||
USE_ALIBI_SQRT=use_alibi_sqrt,
|
||||
USE_SOFTCAP=(softcap > 0),
|
||||
USE_SINKS=(sinks is not None),
|
||||
USE_Q_SCALE=q_descale is not None,
|
||||
USE_KV_SCALES=k_descale is not None,
|
||||
SLIDING_WINDOW=sliding_window_val,
|
||||
stride_k_cache_0=k.stride(0),
|
||||
stride_k_cache_1=k.stride(1),
|
||||
stride_k_cache_2=k.stride(2),
|
||||
stride_k_cache_3=k.stride(3),
|
||||
stride_v_cache_0=v.stride(0),
|
||||
stride_v_cache_1=v.stride(1),
|
||||
stride_v_cache_2=v.stride(2),
|
||||
stride_v_cache_3=v.stride(3),
|
||||
query_start_len_ptr=cu_seqlens_q,
|
||||
BLOCK_Q=BLOCK_Q,
|
||||
num_seqs=num_seqs,
|
||||
BLOCK_M=BLOCK_M,
|
||||
NUM_SEGMENTS_PER_SEQ=num_segments,
|
||||
IS_3D=use_3d,
|
||||
**launch_kw,
|
||||
)
|
||||
|
||||
if use_3d:
|
||||
kernel_reduce_segments_diffkv[(q.shape[0], num_query_heads)](
|
||||
output_ptr=out,
|
||||
segm_output_ptr=softmax_segm_output,
|
||||
segm_max_ptr=softmax_segm_max,
|
||||
segm_expsum_ptr=softmax_segm_expsum,
|
||||
seq_lens_ptr=seqused_k,
|
||||
num_seqs=num_seqs,
|
||||
num_query_heads=num_query_heads,
|
||||
output_stride_0=out.stride(0),
|
||||
output_stride_1=out.stride(1),
|
||||
TILE_SIZE=tile_size,
|
||||
HEAD_SIZE_V=head_size_v,
|
||||
HEAD_SIZE_V_PADDED=triton.next_power_of_2(head_size_v),
|
||||
query_start_len_ptr=cu_seqlens_q,
|
||||
BLOCK_Q=BLOCK_Q,
|
||||
NUM_SEGMENTS_PER_SEQ=num_par_softmax_segments,
|
||||
)
|
||||
@@ -62,8 +62,3 @@ class OffloadingSpecFactory:
|
||||
OffloadingSpecFactory.register_spec(
|
||||
"CPUOffloadingSpec", "vllm.v1.kv_offload.cpu.spec", "CPUOffloadingSpec"
|
||||
)
|
||||
OffloadingSpecFactory.register_spec(
|
||||
"TieringOffloadingSpec",
|
||||
"vllm.v1.kv_offload.tiering.spec",
|
||||
"TieringOffloadingSpec",
|
||||
)
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""DMA copy backend for GPU<->CPU block transfers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import queue
|
||||
import threading
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.simple_kv_offload.cuda_mem_ops import (
|
||||
CU_MEMCPY_SRC_ACCESS_ORDER_ANY,
|
||||
CU_MEMCPY_SRC_ACCESS_ORDER_STREAM,
|
||||
BatchMemcpyParams,
|
||||
build_params,
|
||||
copy_blocks,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class DmaCopyBackend:
|
||||
"""cuMemcpyBatchAsync copy backend (background thread)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._store_params: BatchMemcpyParams | None = None
|
||||
self._load_params: BatchMemcpyParams | None = None
|
||||
self._load_stream: torch.cuda.Stream | None = None
|
||||
self._store_stream: torch.cuda.Stream | None = None
|
||||
self._queue: queue.SimpleQueue | None = None
|
||||
self._thread: threading.Thread | None = None
|
||||
self._shutdown: bool = False
|
||||
|
||||
def init(
|
||||
self,
|
||||
gpu_caches: dict[str, torch.Tensor],
|
||||
cpu_caches: dict[str, torch.Tensor],
|
||||
device: torch.device,
|
||||
load_stream: torch.cuda.Stream,
|
||||
store_stream: torch.cuda.Stream,
|
||||
) -> None:
|
||||
self._load_stream = load_stream
|
||||
self._store_stream = store_stream
|
||||
|
||||
# Stores read the live KV cache -> STREAM (paired with the compute-done
|
||||
# wait in get_finished); loads read stable pinned host memory -> ANY.
|
||||
self._store_params = build_params(
|
||||
gpu_caches,
|
||||
cpu_caches,
|
||||
store_stream,
|
||||
src_access_order=CU_MEMCPY_SRC_ACCESS_ORDER_STREAM,
|
||||
)
|
||||
self._load_params = build_params(
|
||||
cpu_caches,
|
||||
gpu_caches,
|
||||
load_stream,
|
||||
src_access_order=CU_MEMCPY_SRC_ACCESS_ORDER_ANY,
|
||||
)
|
||||
|
||||
self._queue = queue.SimpleQueue()
|
||||
self._thread = threading.Thread(
|
||||
target=self._copy_loop,
|
||||
args=(self._queue, device, load_stream, store_stream),
|
||||
daemon=True,
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
def launch_copy(
|
||||
self,
|
||||
src_blocks: list[int],
|
||||
dst_blocks: list[int],
|
||||
is_store: bool,
|
||||
event_idx: int,
|
||||
events_list: list[tuple[int, torch.Event]],
|
||||
wait_event: torch.Event | None = None,
|
||||
) -> None:
|
||||
params = self._store_params if is_store else self._load_params
|
||||
assert params is not None and self._queue is not None
|
||||
self._queue.put(
|
||||
(
|
||||
src_blocks,
|
||||
dst_blocks,
|
||||
params,
|
||||
is_store,
|
||||
event_idx,
|
||||
events_list,
|
||||
wait_event,
|
||||
)
|
||||
)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._shutdown:
|
||||
return
|
||||
self._shutdown = True
|
||||
if self._queue is not None:
|
||||
self._queue.put(None)
|
||||
if self._thread is not None:
|
||||
self._thread.join(timeout=5.0)
|
||||
|
||||
@staticmethod
|
||||
def _copy_loop(
|
||||
q: queue.SimpleQueue,
|
||||
device: torch.device,
|
||||
load_stream: torch.cuda.Stream,
|
||||
store_stream: torch.cuda.Stream,
|
||||
) -> None:
|
||||
current_platform.set_device(device)
|
||||
while True:
|
||||
item = q.get()
|
||||
if item is None:
|
||||
return
|
||||
(
|
||||
src_blocks,
|
||||
dst_blocks,
|
||||
params,
|
||||
is_store,
|
||||
event_idx,
|
||||
events_list,
|
||||
wait_event,
|
||||
) = item
|
||||
stream = store_stream if is_store else load_stream
|
||||
if wait_event is not None:
|
||||
stream.wait_event(wait_event)
|
||||
copy_blocks(src_blocks, dst_blocks, params)
|
||||
event = torch.Event()
|
||||
event.record(stream)
|
||||
events_list.append((event_idx, event))
|
||||
@@ -1,343 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Disk I/O backend for GPU<->NVMe block transfers via pinned staging buffers.
|
||||
|
||||
Uses separate IO threads for store and load so that loads (latency-critical)
|
||||
never block behind stores (background work). Each thread owns its own pinned
|
||||
staging buffers to avoid contention.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.simple_kv_offload.cuda_mem_ops import (
|
||||
CU_MEMCPY_SRC_ACCESS_ORDER_ANY,
|
||||
CU_MEMCPY_SRC_ACCESS_ORDER_STREAM,
|
||||
BatchMemcpyParams,
|
||||
build_params,
|
||||
copy_blocks,
|
||||
pin_tensor,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
O_DIRECT = getattr(os, "O_DIRECT", 0)
|
||||
_ALIGNMENT = 4096
|
||||
|
||||
|
||||
def _alloc_aligned(num_slots: int, bpb: int) -> torch.Tensor:
|
||||
"""Allocate a staging buffer whose base address is O_DIRECT aligned.
|
||||
|
||||
The CPU allocator only guarantees 64-byte alignment, so over-allocate by
|
||||
one alignment unit and return an aligned view. The view keeps the backing
|
||||
storage alive.
|
||||
"""
|
||||
nbytes = num_slots * bpb
|
||||
raw = torch.zeros(nbytes + _ALIGNMENT, dtype=torch.int8, device="cpu")
|
||||
offset = -raw.data_ptr() % _ALIGNMENT
|
||||
return raw[offset : offset + nbytes].view(num_slots, bpb)
|
||||
|
||||
|
||||
class DiskBackend:
|
||||
"""Async disk offload backend with pipelined GPU DMA and interleaved IO.
|
||||
|
||||
Architecture:
|
||||
- Separate coordinator threads for store and load (never block each other)
|
||||
- Interleaved pipeline: DMA slot N while preadv/pwritev slot N-1
|
||||
- O_DIRECT by default; page cache is opt-in via use_page_cache
|
||||
|
||||
Same launch_copy interface as DmaCopyBackend so the worker can swap
|
||||
backends without changing calling code.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._store_params: BatchMemcpyParams | None = None
|
||||
self._load_params: BatchMemcpyParams | None = None
|
||||
self._load_stream: torch.cuda.Stream | None = None
|
||||
self._store_stream: torch.cuda.Stream | None = None
|
||||
self._store_queue: queue.SimpleQueue = queue.SimpleQueue()
|
||||
self._load_queue: queue.SimpleQueue = queue.SimpleQueue()
|
||||
self._store_thread: threading.Thread | None = None
|
||||
self._load_thread: threading.Thread | None = None
|
||||
self._shutdown: bool = False
|
||||
self._fd: int = -1
|
||||
self._disk_path: str = ""
|
||||
self._total_block_bytes: int = 0
|
||||
self._store_buffer_caches: dict[str, torch.Tensor] = {}
|
||||
self._load_buffer_caches: dict[str, torch.Tensor] = {}
|
||||
self._store_slot_views: list[list[memoryview]] = []
|
||||
self._load_slot_views: list[list[memoryview]] = []
|
||||
self._per_tensor_bpb: list[int] = []
|
||||
self._tensor_names: list[str] = []
|
||||
|
||||
def init(
|
||||
self,
|
||||
gpu_caches: dict[str, torch.Tensor],
|
||||
device: torch.device,
|
||||
load_stream: torch.cuda.Stream,
|
||||
store_stream: torch.cuda.Stream,
|
||||
disk_path: str,
|
||||
num_disk_slots: int,
|
||||
total_block_bytes: int,
|
||||
num_buffer_slots: int = 2,
|
||||
use_page_cache: bool = False,
|
||||
) -> None:
|
||||
self._load_stream = load_stream
|
||||
self._store_stream = store_stream
|
||||
self._total_block_bytes = total_block_bytes
|
||||
self._num_buffer_slots = num_buffer_slots
|
||||
self._tensor_names = list(gpu_caches.keys())
|
||||
self._per_tensor_bpb = [
|
||||
t.stride(0) * t.element_size() for t in gpu_caches.values()
|
||||
]
|
||||
|
||||
# The stride alignment is an O_DIRECT kernel-DMA requirement; buffered
|
||||
# I/O through the page cache has no alignment constraint.
|
||||
if not use_page_cache:
|
||||
assert total_block_bytes % _ALIGNMENT == 0, (
|
||||
f"total_block_bytes={total_block_bytes} not aligned to {_ALIGNMENT}"
|
||||
)
|
||||
|
||||
# Separate buffer pools for store and load threads
|
||||
self._store_buffer_caches = {}
|
||||
self._load_buffer_caches = {}
|
||||
for name, gpu_t in gpu_caches.items():
|
||||
bpb = gpu_t.stride(0) * gpu_t.element_size()
|
||||
store_buf = _alloc_aligned(num_buffer_slots, bpb)
|
||||
pin_tensor(store_buf)
|
||||
self._store_buffer_caches[name] = store_buf
|
||||
load_buf = _alloc_aligned(num_buffer_slots, bpb)
|
||||
pin_tensor(load_buf)
|
||||
self._load_buffer_caches[name] = load_buf
|
||||
|
||||
# Pre-built iovec views per slot (avoid per-transfer .numpy() calls)
|
||||
self._store_slot_views = [
|
||||
[
|
||||
memoryview(self._store_buffer_caches[name][slot].numpy())
|
||||
for name in self._tensor_names
|
||||
]
|
||||
for slot in range(num_buffer_slots)
|
||||
]
|
||||
self._load_slot_views = [
|
||||
[
|
||||
memoryview(self._load_buffer_caches[name][slot].numpy())
|
||||
for name in self._tensor_names
|
||||
]
|
||||
for slot in range(num_buffer_slots)
|
||||
]
|
||||
|
||||
self._store_params = build_params(
|
||||
gpu_caches,
|
||||
self._store_buffer_caches,
|
||||
store_stream,
|
||||
src_access_order=CU_MEMCPY_SRC_ACCESS_ORDER_STREAM,
|
||||
)
|
||||
self._load_params = build_params(
|
||||
self._load_buffer_caches,
|
||||
gpu_caches,
|
||||
load_stream,
|
||||
src_access_order=CU_MEMCPY_SRC_ACCESS_ORDER_ANY,
|
||||
)
|
||||
|
||||
os.makedirs(os.path.dirname(disk_path) or ".", exist_ok=True)
|
||||
# Slot contents never outlive the process, so unlink then O_EXCL rather
|
||||
# than reopening: a pre-existing file would otherwise keep its own
|
||||
# (possibly world-readable) mode, and blocks may encode user prompts.
|
||||
with contextlib.suppress(FileNotFoundError):
|
||||
os.unlink(disk_path)
|
||||
# O_DIRECT by default: page cache would consume the very host DRAM this
|
||||
# backend exists to conserve, and doubles the copy on the store path.
|
||||
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW
|
||||
if not use_page_cache:
|
||||
flags |= O_DIRECT
|
||||
self._fd = os.open(disk_path, flags, 0o600)
|
||||
self._disk_path = disk_path
|
||||
os.ftruncate(self._fd, num_disk_slots * total_block_bytes)
|
||||
|
||||
logger.info(
|
||||
"DiskBackend: path=%s, slots=%d, total=%.2f GB, buf=%dx%d bytes"
|
||||
" (page_cache=%s)",
|
||||
disk_path,
|
||||
num_disk_slots,
|
||||
(num_disk_slots * total_block_bytes) / (1024**3),
|
||||
num_buffer_slots,
|
||||
total_block_bytes,
|
||||
use_page_cache,
|
||||
)
|
||||
|
||||
self._store_thread = threading.Thread(
|
||||
target=self._store_loop,
|
||||
args=(device, store_stream),
|
||||
daemon=True,
|
||||
)
|
||||
self._load_thread = threading.Thread(
|
||||
target=self._load_loop,
|
||||
args=(device, load_stream),
|
||||
daemon=True,
|
||||
)
|
||||
self._store_thread.start()
|
||||
self._load_thread.start()
|
||||
|
||||
def launch_copy(
|
||||
self,
|
||||
src_blocks: list[int],
|
||||
dst_blocks: list[int],
|
||||
is_store: bool,
|
||||
event_idx: int,
|
||||
events_list: list[tuple[int, torch.Event]],
|
||||
wait_event: torch.Event | None = None,
|
||||
) -> None:
|
||||
q = self._store_queue if is_store else self._load_queue
|
||||
q.put((src_blocks, dst_blocks, event_idx, events_list, wait_event))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._shutdown:
|
||||
return
|
||||
self._shutdown = True
|
||||
self._store_queue.put(None)
|
||||
self._load_queue.put(None)
|
||||
if self._store_thread is not None:
|
||||
self._store_thread.join(timeout=10.0)
|
||||
if self._load_thread is not None:
|
||||
self._load_thread.join(timeout=10.0)
|
||||
if self._fd < 0:
|
||||
return
|
||||
# Slot contents can encode user prompts, so drop the name now rather
|
||||
# than leaving them readable until the next run overwrites the file.
|
||||
# Unlinking only removes the directory entry: any thread still holding
|
||||
# the fd keeps writing to the (now anonymous) inode, which the kernel
|
||||
# frees once the last fd goes away.
|
||||
with contextlib.suppress(OSError):
|
||||
os.unlink(self._disk_path)
|
||||
# Closing under a still-running IO thread would let the fd number be
|
||||
# reused by an unrelated open(), turning its next pwritev into a write
|
||||
# into that file. Leaking one fd for the remaining process lifetime is
|
||||
# the cheaper failure.
|
||||
if any(
|
||||
t is not None and t.is_alive()
|
||||
for t in (self._store_thread, self._load_thread)
|
||||
):
|
||||
logger.warning(
|
||||
"IO thread still running after shutdown timeout; leaking fd %d",
|
||||
self._fd,
|
||||
)
|
||||
return
|
||||
os.close(self._fd)
|
||||
self._fd = -1
|
||||
|
||||
def _store_loop(
|
||||
self,
|
||||
device: torch.device,
|
||||
stream: torch.cuda.Stream,
|
||||
) -> None:
|
||||
current_platform.set_device(device)
|
||||
while True:
|
||||
item = self._store_queue.get()
|
||||
if item is None:
|
||||
return
|
||||
(src_blocks, dst_blocks, event_idx, events_list, wait_event) = item
|
||||
if wait_event is not None:
|
||||
stream.wait_event(wait_event)
|
||||
self._do_store(src_blocks, dst_blocks, stream)
|
||||
event = torch.Event()
|
||||
event.record(stream)
|
||||
events_list.append((event_idx, event))
|
||||
|
||||
def _writev_slot(self, buf_slot: int, file_offset: int) -> None:
|
||||
written = os.pwritev(self._fd, self._store_slot_views[buf_slot], file_offset)
|
||||
if written < self._total_block_bytes:
|
||||
raise OSError(
|
||||
f"Short write: expected {self._total_block_bytes} bytes, "
|
||||
f"wrote {written}"
|
||||
)
|
||||
|
||||
def _readv_slot(self, buf_slot: int, file_offset: int) -> None:
|
||||
bytes_read = os.preadv(self._fd, self._load_slot_views[buf_slot], file_offset)
|
||||
if bytes_read < self._total_block_bytes:
|
||||
raise OSError(
|
||||
f"Short read: expected {self._total_block_bytes} bytes, "
|
||||
f"read {bytes_read}"
|
||||
)
|
||||
|
||||
def _load_loop(
|
||||
self,
|
||||
device: torch.device,
|
||||
stream: torch.cuda.Stream,
|
||||
) -> None:
|
||||
current_platform.set_device(device)
|
||||
while True:
|
||||
item = self._load_queue.get()
|
||||
if item is None:
|
||||
return
|
||||
(src_blocks, dst_blocks, event_idx, events_list, wait_event) = item
|
||||
if wait_event is not None:
|
||||
stream.wait_event(wait_event)
|
||||
self._do_load(src_blocks, dst_blocks, stream)
|
||||
event = torch.Event()
|
||||
event.record(stream)
|
||||
events_list.append((event_idx, event))
|
||||
|
||||
def _do_store(
|
||||
self,
|
||||
gpu_blocks: list[int],
|
||||
disk_slots: list[int],
|
||||
stream: torch.cuda.Stream,
|
||||
) -> None:
|
||||
"""GPU -> buffer (DMA) -> disk (pwritev), interleaved double-buffer."""
|
||||
assert self._store_params is not None
|
||||
n = self._num_buffer_slots
|
||||
# (DMA event, file offset) of the block already staged in each slot.
|
||||
pending: list[tuple[torch.Event, int] | None] = [None] * n
|
||||
|
||||
for i, (gpu_blk, disk_slot) in enumerate(zip(gpu_blocks, disk_slots)):
|
||||
buf_slot = i % n
|
||||
prev = pending[buf_slot]
|
||||
if prev is not None:
|
||||
prev[0].synchronize()
|
||||
self._writev_slot(buf_slot, prev[1])
|
||||
|
||||
copy_blocks([gpu_blk], [buf_slot], self._store_params)
|
||||
ev = torch.Event()
|
||||
ev.record(stream)
|
||||
pending[buf_slot] = (ev, disk_slot * self._total_block_bytes)
|
||||
|
||||
for slot, last in enumerate(pending):
|
||||
if last is not None:
|
||||
last[0].synchronize()
|
||||
self._writev_slot(slot, last[1])
|
||||
|
||||
def _do_load(
|
||||
self,
|
||||
disk_slots: list[int],
|
||||
gpu_blocks: list[int],
|
||||
stream: torch.cuda.Stream,
|
||||
) -> None:
|
||||
"""Disk (preadv) -> buffer -> GPU (DMA), interleaved double-buffer."""
|
||||
assert self._load_params is not None
|
||||
n = self._num_buffer_slots
|
||||
prev_dma_events: list[torch.Event | None] = [None] * n
|
||||
|
||||
for i, (disk_slot, gpu_blk) in enumerate(zip(disk_slots, gpu_blocks)):
|
||||
buf_slot = i % n
|
||||
prev = prev_dma_events[buf_slot]
|
||||
if prev is not None:
|
||||
prev.synchronize()
|
||||
|
||||
self._readv_slot(buf_slot, disk_slot * self._total_block_bytes)
|
||||
|
||||
copy_blocks([buf_slot], [gpu_blk], self._load_params)
|
||||
ev = torch.Event()
|
||||
ev.record(stream)
|
||||
prev_dma_events[buf_slot] = ev
|
||||
|
||||
for ev in prev_dma_events:
|
||||
if ev is not None:
|
||||
ev.synchronize()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,59 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Metadata for SimpleCPUOffloadConnector."""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.base import (
|
||||
KVConnectorMetadata,
|
||||
KVConnectorWorkerMetadata,
|
||||
)
|
||||
|
||||
INVALID_JOB_ID = -1
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimpleCPUOffloadMetadata(KVConnectorMetadata):
|
||||
"""Metadata passed from scheduler to worker for CPU offload operations.
|
||||
|
||||
The worker receives flat block lists keyed by a monotonic event_idx.
|
||||
Job->req_id translation is handled by the scheduler-side manager
|
||||
(via inverse maps), so the worker never knows about request identities.
|
||||
"""
|
||||
|
||||
# Load event per step. INVALID_JOB_ID means no blocks to load this step.
|
||||
load_event: int = INVALID_JOB_ID
|
||||
load_gpu_blocks: list[int] = field(default_factory=list)
|
||||
load_cpu_blocks: list[int] = field(default_factory=list)
|
||||
# Reverse map: load_event->req_ids, for tracking requests with finished load events
|
||||
load_event_to_reqs: dict[int, list[str]] = field(default_factory=dict)
|
||||
|
||||
# Store event per step. INVALID_JOB_ID means no blocks to store this step.
|
||||
store_event: int = INVALID_JOB_ID
|
||||
store_gpu_blocks: list[int] = field(default_factory=list)
|
||||
store_cpu_blocks: list[int] = field(default_factory=list)
|
||||
|
||||
# Whether any requests were preempted this step and need flush pending transfers.
|
||||
need_flush: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimpleCPUOffloadWorkerMetadata(KVConnectorWorkerMetadata):
|
||||
"""Worker -> Scheduler metadata for completed store events.
|
||||
|
||||
Each worker reports {event_idx: 1} for newly completed stores.
|
||||
``aggregate()`` sums counts across workers within a step.
|
||||
The scheduler-side manager accumulates across steps and processes
|
||||
a store completion only when count reaches ``world_size``.
|
||||
"""
|
||||
|
||||
completed_store_events: dict[int, int]
|
||||
|
||||
def aggregate(
|
||||
self, other: "KVConnectorWorkerMetadata"
|
||||
) -> "KVConnectorWorkerMetadata":
|
||||
assert isinstance(other, SimpleCPUOffloadWorkerMetadata)
|
||||
merged = dict(self.completed_store_events)
|
||||
for k, v in other.completed_store_events.items():
|
||||
merged[k] = merged.get(k, 0) + v
|
||||
return SimpleCPUOffloadWorkerMetadata(completed_store_events=merged)
|
||||
@@ -1,284 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Prometheus metrics for SimpleCPUOffloadConnector.
|
||||
|
||||
The stats payload uses the same self-describing wire format as the
|
||||
offloading connector, so it survives IPC serialization without the
|
||||
metric classes on the receiving side.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import (
|
||||
KVConnectorPromMetrics,
|
||||
KVConnectorStats,
|
||||
PromMetric,
|
||||
PromMetricT,
|
||||
)
|
||||
|
||||
|
||||
class MetricName:
|
||||
"""Metric names for SimpleCPUOffloadConnector."""
|
||||
|
||||
SAVE_OUTCOMES = "vllm:simple_kv_offload_save_outcomes_total"
|
||||
LOAD_BLOCKS = "vllm:simple_kv_offload_load_blocks_total"
|
||||
USED_BLOCKS = "vllm:simple_kv_offload_used_blocks"
|
||||
PENDING_STORE_BLOCKS = "vllm:simple_kv_offload_pending_store_blocks"
|
||||
INFO = "vllm:simple_kv_offload_info"
|
||||
|
||||
|
||||
# outcome label value -> BoundaryStoreStats field name.
|
||||
# ``published`` is the sum of all outcomes and is not labeled.
|
||||
OUTCOME_TO_FIELD = {
|
||||
"stored": "stored",
|
||||
"dropped_cpu_full": "dropped_cpu_full",
|
||||
"dropped_request_gone": "dropped_request_gone",
|
||||
"dropped_null_block": "dropped_null_block",
|
||||
"dropped_not_hashed": "dropped_not_hashed",
|
||||
"skipped_already_cached": "skipped_already_cached",
|
||||
"skipped_in_flight": "skipped_in_flight",
|
||||
}
|
||||
|
||||
INFO_LABELS = ["backend", "page_cache", "lazy_offload", "capacity_blocks"]
|
||||
|
||||
|
||||
class _MetricType:
|
||||
"""Type tags embedded in the serialized stats payload."""
|
||||
|
||||
COUNTER = "counter"
|
||||
GAUGE = "gauge"
|
||||
|
||||
|
||||
class _StatsKey:
|
||||
"""Top-level keys in the serialized stats dict."""
|
||||
|
||||
# Maps metric name -> _MetricType value
|
||||
TYPES = "types"
|
||||
# Maps metric name -> {label values tuple -> observed value}
|
||||
DATA = "data"
|
||||
|
||||
|
||||
@dataclass
|
||||
class SimpleCPUOffloadStats(KVConnectorStats):
|
||||
"""Stats payload for SimpleCPUOffloadConnector.
|
||||
|
||||
The ``data`` dict is structured as::
|
||||
|
||||
{
|
||||
_StatsKey.TYPES: {name: _MetricType.*, ...},
|
||||
_StatsKey.DATA: {name: {labelvalues: value, ...}, ...},
|
||||
}
|
||||
|
||||
Counter values are summed when aggregating, gauge values keep the
|
||||
latest snapshot, and unlabeled metrics use ``()`` as their
|
||||
labelvalues tuple.
|
||||
"""
|
||||
|
||||
def __post_init__(self):
|
||||
if _StatsKey.DATA not in self.data:
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
self.data: dict[str, Any] = {
|
||||
_StatsKey.TYPES: {},
|
||||
_StatsKey.DATA: {},
|
||||
}
|
||||
|
||||
@property
|
||||
def _types(self) -> dict[str, str]:
|
||||
return self.data[_StatsKey.TYPES]
|
||||
|
||||
@property
|
||||
def _values(self) -> dict[str, Any]:
|
||||
return self.data[_StatsKey.DATA]
|
||||
|
||||
def aggregate(self, other: "KVConnectorStats") -> "KVConnectorStats":
|
||||
if other.is_empty():
|
||||
return self
|
||||
assert isinstance(other, SimpleCPUOffloadStats)
|
||||
for key, other_label_values in other._values.items():
|
||||
type_str = other._types.get(key)
|
||||
if type_str is None:
|
||||
raise AssertionError(f"Unknown simple KV offload stats key: {key}")
|
||||
self._types.setdefault(key, type_str)
|
||||
current_label_values = self._values.setdefault(key, {})
|
||||
for labelvalues, value in other_label_values.items():
|
||||
if type_str == _MetricType.COUNTER:
|
||||
assert isinstance(value, int | float)
|
||||
current_label_values[labelvalues] = (
|
||||
current_label_values.get(labelvalues, 0) + value
|
||||
)
|
||||
elif type_str == _MetricType.GAUGE:
|
||||
assert isinstance(value, int | float)
|
||||
current_label_values[labelvalues] = value
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Unknown metric type '{type_str}' for key: {key}"
|
||||
)
|
||||
return self
|
||||
|
||||
def reduce(self) -> dict[str, int | float]:
|
||||
"""Reduce the interval observations to a flat summary for logging."""
|
||||
return_dict: dict[str, int | float] = {}
|
||||
for key, label_value_map in self._values.items():
|
||||
if key == MetricName.INFO:
|
||||
# Constant config fingerprint; exclude from the log summary.
|
||||
continue
|
||||
type_str = self._types.get(key)
|
||||
if type_str is None:
|
||||
raise AssertionError(f"Unknown simple KV offload stats key: {key}")
|
||||
for labelvalues, value in label_value_map.items():
|
||||
key_with_labels = f"{key}:{labelvalues}" if labelvalues else key
|
||||
if type_str in (_MetricType.COUNTER, _MetricType.GAUGE):
|
||||
assert isinstance(value, int | float)
|
||||
return_dict[key_with_labels] = value
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Unknown metric type '{type_str}' for key: {key}"
|
||||
)
|
||||
return return_dict
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return not self.data.get(_StatsKey.DATA)
|
||||
|
||||
def increase_counter(
|
||||
self,
|
||||
counter_name: str,
|
||||
counter_increase_value: int | float = 1,
|
||||
labelvalues: tuple[str, ...] = (),
|
||||
) -> None:
|
||||
"""Increase a counter on the stats payload."""
|
||||
self._types.setdefault(counter_name, _MetricType.COUNTER)
|
||||
counter_values = self._values.setdefault(counter_name, {})
|
||||
counter_values[labelvalues] = (
|
||||
counter_values.get(labelvalues, 0) + counter_increase_value
|
||||
)
|
||||
|
||||
def set_gauge(
|
||||
self,
|
||||
gauge_name: str,
|
||||
gauge_value: int | float,
|
||||
labelvalues: tuple[str, ...] = (),
|
||||
) -> None:
|
||||
"""Set a gauge snapshot on the stats payload."""
|
||||
self._types.setdefault(gauge_name, _MetricType.GAUGE)
|
||||
gauge_values = self._values.setdefault(gauge_name, {})
|
||||
gauge_values[labelvalues] = gauge_value
|
||||
|
||||
|
||||
class SimpleCPUOffloadPromMetrics(KVConnectorPromMetrics):
|
||||
"""Prometheus registration and recording for SimpleCPUOffloadConnector."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
metric_types: dict[type[PromMetric], type[PromMetricT]],
|
||||
labelnames: list[str],
|
||||
per_engine_labelvalues: dict[int, list[object]],
|
||||
):
|
||||
super().__init__(vllm_config, metric_types, labelnames, per_engine_labelvalues)
|
||||
# (engine_idx, metric_name, labelvalues) -> bound child metric
|
||||
self._metrics: dict[tuple[int, str, tuple[str, ...]], PromMetricT] = {}
|
||||
|
||||
self._counter_save_outcomes = self._counter_cls(
|
||||
name="vllm:simple_kv_offload_save_outcomes_total",
|
||||
documentation=(
|
||||
"Store admission decisions in SimpleCPUOffloadConnector, by "
|
||||
"outcome. Outcomes classify eager-mode boundary hand-off "
|
||||
"stores; lazy-mode stores are not classified."
|
||||
),
|
||||
labelnames=self._labelnames + ["outcome"],
|
||||
)
|
||||
self._counter_load_blocks = self._counter_cls(
|
||||
name="vllm:simple_kv_offload_load_blocks_total",
|
||||
documentation=(
|
||||
"KV blocks restored to GPU from the offload pool, counted "
|
||||
"when a load finishes. This is prefill work avoided "
|
||||
"through offload cache hits."
|
||||
),
|
||||
labelnames=self._labelnames,
|
||||
)
|
||||
self._gauge_used_blocks = self._gauge_cls(
|
||||
name="vllm:simple_kv_offload_used_blocks",
|
||||
documentation=(
|
||||
"Offload-pool blocks currently pinned by in-flight "
|
||||
"transfers or cache hits (capacity minus free). Evictable "
|
||||
"cached blocks are not counted; capacity_blocks is on "
|
||||
"vllm:simple_kv_offload_info."
|
||||
),
|
||||
labelnames=self._labelnames,
|
||||
multiprocess_mode="mostrecent",
|
||||
)
|
||||
self._gauge_pending_store_blocks = self._gauge_cls(
|
||||
name="vllm:simple_kv_offload_pending_store_blocks",
|
||||
documentation=(
|
||||
"Offload blocks in pending stores: queued for dispatch, "
|
||||
"issued to workers, or awaiting release after a cache "
|
||||
"reset. A persistently growing value indicates a stuck "
|
||||
"transfer."
|
||||
),
|
||||
labelnames=self._labelnames,
|
||||
multiprocess_mode="mostrecent",
|
||||
)
|
||||
self._gauge_info = self._gauge_cls(
|
||||
name="vllm:simple_kv_offload_info",
|
||||
documentation=(
|
||||
"SimpleCPUOffloadConnector deployment facts. Value is "
|
||||
"always 1. backend is cpu or disk; page_cache and "
|
||||
"lazy_offload are true/false; capacity_blocks is the "
|
||||
"offload pool size."
|
||||
),
|
||||
labelnames=self._labelnames + INFO_LABELS,
|
||||
multiprocess_mode="mostrecent",
|
||||
)
|
||||
|
||||
self._defs: dict[str, PromMetricT] = {
|
||||
MetricName.SAVE_OUTCOMES: self._counter_save_outcomes,
|
||||
MetricName.LOAD_BLOCKS: self._counter_load_blocks,
|
||||
MetricName.USED_BLOCKS: self._gauge_used_blocks,
|
||||
MetricName.PENDING_STORE_BLOCKS: self._gauge_pending_store_blocks,
|
||||
MetricName.INFO: self._gauge_info,
|
||||
}
|
||||
self._num_label_values: dict[str, int] = {
|
||||
MetricName.SAVE_OUTCOMES: 1,
|
||||
MetricName.LOAD_BLOCKS: 0,
|
||||
MetricName.USED_BLOCKS: 0,
|
||||
MetricName.PENDING_STORE_BLOCKS: 0,
|
||||
MetricName.INFO: len(INFO_LABELS),
|
||||
}
|
||||
|
||||
def observe(self, transfer_stats_data: dict[str, Any], engine_idx: int = 0):
|
||||
"""Observe transfer statistics."""
|
||||
metric_types = transfer_stats_data.get(_StatsKey.TYPES, {})
|
||||
metric_data = transfer_stats_data.get(_StatsKey.DATA, {})
|
||||
for key, label_value_map in metric_data.items():
|
||||
prom_metric = self._defs.get(key)
|
||||
if prom_metric is None:
|
||||
raise AssertionError(f"Unknown simple KV offload stats key: {key}")
|
||||
type_str = metric_types.get(key)
|
||||
for labelvalues, value in label_value_map.items():
|
||||
if len(labelvalues) != self._num_label_values[key]:
|
||||
raise AssertionError(
|
||||
f"Metric {key} expects "
|
||||
f"{self._num_label_values[key]} labels, "
|
||||
f"got {len(labelvalues)}"
|
||||
)
|
||||
child = self._metrics.get((engine_idx, key, labelvalues))
|
||||
if child is None:
|
||||
engine_labelvalues = self.per_engine_labelvalues[engine_idx]
|
||||
child = prom_metric.labels(
|
||||
*(engine_labelvalues + list(labelvalues))
|
||||
)
|
||||
self._metrics[(engine_idx, key, labelvalues)] = child
|
||||
if type_str == _MetricType.COUNTER:
|
||||
assert isinstance(value, int | float)
|
||||
child.inc(value)
|
||||
elif type_str == _MetricType.GAUGE:
|
||||
assert isinstance(value, int | float)
|
||||
child.set(value)
|
||||
else:
|
||||
raise AssertionError(
|
||||
f"Unknown metric type '{type_str}' for key: {key}"
|
||||
)
|
||||
@@ -1,394 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Worker-side handler for SimpleCPUOffloadConnector."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.torch_utils import PIN_MEMORY
|
||||
from vllm.v1.simple_kv_offload.copy_backend import DmaCopyBackend
|
||||
from vllm.v1.simple_kv_offload.cuda_mem_ops import pin_tensor
|
||||
from vllm.v1.simple_kv_offload.disk_backend import DiskBackend
|
||||
from vllm.v1.simple_kv_offload.metadata import (
|
||||
SimpleCPUOffloadMetadata,
|
||||
SimpleCPUOffloadWorkerMetadata,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SimpleCPUOffloadWorker:
|
||||
"""Worker-side handler for CPU offloading transfers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_config: "KVCacheConfig | None",
|
||||
cpu_capacity_bytes: int,
|
||||
kv_offload_backend: str = "cpu",
|
||||
disk_path: str | None = None,
|
||||
disk_capacity_bytes: int = 0,
|
||||
disk_buffer_slots: int = 2,
|
||||
use_page_cache: bool = False,
|
||||
num_cpu_blocks: int | None = None,
|
||||
):
|
||||
self.vllm_config = vllm_config
|
||||
self.kv_cache_config = kv_cache_config
|
||||
self.cpu_capacity_bytes = cpu_capacity_bytes
|
||||
self._num_cpu_blocks_override = num_cpu_blocks
|
||||
self.disk_path = disk_path
|
||||
self.disk_capacity_bytes = disk_capacity_bytes
|
||||
self.disk_buffer_slots = disk_buffer_slots
|
||||
self.use_page_cache = use_page_cache
|
||||
self.disk_mode = kv_offload_backend == "disk"
|
||||
|
||||
self.gpu_kv_caches: dict[str, torch.Tensor] | None = None
|
||||
self.cpu_kv_caches: dict[str, torch.Tensor] | None = None
|
||||
self.device: torch.device | None = None
|
||||
self.num_cpu_blocks: int = 0
|
||||
|
||||
# CUDA streams for the async transfers
|
||||
self.load_stream: torch.cuda.Stream | None = None
|
||||
self.store_stream: torch.cuda.Stream | None = None
|
||||
|
||||
self._backend: DmaCopyBackend | DiskBackend | None = None
|
||||
|
||||
# Ordered (event_idx, Event). Events pre-allocated on main thread.
|
||||
self._load_events: list[tuple[int, torch.Event]] = []
|
||||
self._store_events: list[tuple[int, torch.Event]] = []
|
||||
# High-water marks: highest event_idx completed per stream.
|
||||
# When the event list is empty, the hwm covers all prior events.
|
||||
self._load_hwm: int = -1
|
||||
self._store_hwm: int = -1
|
||||
|
||||
# Metadata for the current step
|
||||
self._connector_metadata: SimpleCPUOffloadMetadata | None = None
|
||||
|
||||
# Compute-done event recorded before each store; reused across steps
|
||||
# (get_finished runs once per step, copy queue is FIFO).
|
||||
self._store_compute_done: torch.Event | None = None
|
||||
|
||||
# Pending event index sets, populated in bind_connector_metadata
|
||||
self._pending_load_event_indices: set[int] = set()
|
||||
self._pending_store_event_indices: set[int] = set()
|
||||
# Completed store events to report via build_connector_worker_meta
|
||||
self._completed_store_events: dict[int, int] = {}
|
||||
|
||||
def register_kv_caches(
|
||||
self,
|
||||
kv_caches: dict[str, torch.Tensor],
|
||||
) -> None:
|
||||
"""Register GPU KV caches and allocate pinned CPU tensors.
|
||||
The worker will infer the underlying raw storage from the kv_caches.
|
||||
|
||||
Args:
|
||||
kv_caches: Per-layer GPU KV caches. Values are either a single
|
||||
tensor (attention layers) or a list of tensors (Mamba layers
|
||||
in hybrid models). All values are included for offloading
|
||||
by resolving to their underlying raw storage.
|
||||
|
||||
"""
|
||||
if not kv_caches:
|
||||
logger.warning("No KV caches to offload.")
|
||||
return
|
||||
|
||||
self.device = next(iter(kv_caches.values())).device
|
||||
|
||||
assert self.kv_cache_config is not None
|
||||
num_blocks = self.kv_cache_config.num_blocks
|
||||
assert self.kv_cache_config.kv_cache_tensors
|
||||
|
||||
# The DMA backend copies blocks as base + block_id * stride(0), so every
|
||||
# region is a [num_blocks, block_bytes] view. Block bytes come from each
|
||||
# tensor's placement -- layers in one allocation can differ in page size.
|
||||
unique_gpu_caches: dict[str, torch.Tensor] = {}
|
||||
seen: set[tuple[torch.device, int]] = set()
|
||||
for kv_cache_tensor in self.kv_cache_config.kv_cache_tensors:
|
||||
name = next((n for n in kv_cache_tensor.layers if n in kv_caches), None)
|
||||
if name is None:
|
||||
continue
|
||||
num_layers = len(kv_cache_tensor.layers)
|
||||
block_bytes = kv_cache_tensor.block_stride
|
||||
blocks_span = num_blocks * block_bytes
|
||||
layer_outermost = kv_cache_tensor.layer_stride >= blocks_span
|
||||
if layer_outermost:
|
||||
# One region per layer, or per KV head group under LHBNC.
|
||||
start = kv_cache_tensor.offset
|
||||
span = num_layers * kv_cache_tensor.layer_stride
|
||||
layer_names = kv_cache_tensor.layers
|
||||
else:
|
||||
start = 0
|
||||
span = blocks_span
|
||||
layer_names = kv_cache_tensor.layers[:1]
|
||||
|
||||
cache = kv_caches[name]
|
||||
raw = torch.empty(0, dtype=torch.int8, device=cache.device).set_(
|
||||
cache.untyped_storage()
|
||||
)
|
||||
assert raw.numel() >= start + span, (
|
||||
f"KV cache {name!r} storage has {raw.numel()} bytes, smaller than "
|
||||
f"the {span} bytes it places at offset {start}"
|
||||
)
|
||||
regions = raw[start : start + span].view(-1, num_blocks, block_bytes)
|
||||
groups_per_layer, remainder = divmod(len(regions), len(layer_names))
|
||||
assert remainder == 0, (
|
||||
f"KV cache {name!r} places {len(layer_names)} layers in "
|
||||
f"{len(regions)} block-strided regions"
|
||||
)
|
||||
for idx, region in enumerate(regions):
|
||||
key = (region.device, region.data_ptr())
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
layer_name = layer_names[idx // groups_per_layer]
|
||||
key_name = (
|
||||
layer_name
|
||||
if groups_per_layer == 1
|
||||
else f"{layer_name}.{idx % groups_per_layer}"
|
||||
)
|
||||
unique_gpu_caches[key_name] = region
|
||||
|
||||
# Compute per-tensor bytes_per_block. Tensors may have different
|
||||
# page_size_bytes (e.g., UniformTypeKVCacheSpecs with varying head_size).
|
||||
per_tensor_bpb = [
|
||||
t.stride(0) * t.element_size() for t in unique_gpu_caches.values()
|
||||
]
|
||||
total_bytes_per_block = sum(per_tensor_bpb)
|
||||
|
||||
self.num_cpu_blocks = self._resolve_num_cpu_blocks(
|
||||
self.disk_capacity_bytes if self.disk_mode else self.cpu_capacity_bytes,
|
||||
total_bytes_per_block,
|
||||
)
|
||||
|
||||
# Use lowest priority so KV cache I/O yields to compute streams.
|
||||
low_pri, _ = torch.cuda.Stream.priority_range()
|
||||
self.load_stream = torch.cuda.Stream(priority=low_pri)
|
||||
self.store_stream = torch.cuda.Stream(priority=low_pri)
|
||||
|
||||
self.gpu_kv_caches = unique_gpu_caches
|
||||
|
||||
if self.disk_mode:
|
||||
self._init_disk_mode(unique_gpu_caches, total_bytes_per_block, self.device)
|
||||
else:
|
||||
self._init_cpu_mode(unique_gpu_caches, total_bytes_per_block, self.device)
|
||||
|
||||
def _resolve_num_cpu_blocks(self, capacity_bytes: int, bytes_per_block: int) -> int:
|
||||
local_capacity = capacity_bytes // bytes_per_block
|
||||
requested = self._num_cpu_blocks_override
|
||||
if requested is None:
|
||||
return max(1, local_capacity)
|
||||
if type(requested) is not int or not 0 < requested <= local_capacity:
|
||||
raise ValueError(
|
||||
f"num_cpu_blocks={requested!r} must be between 1 and "
|
||||
f"local offload capacity {local_capacity}"
|
||||
)
|
||||
return requested
|
||||
|
||||
def _init_disk_mode(
|
||||
self,
|
||||
unique_gpu_caches: dict[str, torch.Tensor],
|
||||
total_bytes_per_block: int,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
num_disk_slots = self._resolve_num_cpu_blocks(
|
||||
self.disk_capacity_bytes, total_bytes_per_block
|
||||
)
|
||||
self.num_cpu_blocks = num_disk_slots
|
||||
|
||||
logger.info(
|
||||
"SimpleCPUOffloadWorker [DISK]: %d tensors, %d disk slots (%.2f GB)",
|
||||
len(unique_gpu_caches),
|
||||
num_disk_slots,
|
||||
(num_disk_slots * total_bytes_per_block) / (1024**3),
|
||||
)
|
||||
|
||||
assert self.disk_path is not None
|
||||
rank_path = f"{self.disk_path}.rank_{device.index or 0}"
|
||||
self._backend = DiskBackend()
|
||||
self._backend.init(
|
||||
unique_gpu_caches,
|
||||
device,
|
||||
self.load_stream,
|
||||
self.store_stream,
|
||||
rank_path,
|
||||
num_disk_slots,
|
||||
total_bytes_per_block,
|
||||
self.disk_buffer_slots,
|
||||
self.use_page_cache,
|
||||
)
|
||||
|
||||
def _init_cpu_mode(
|
||||
self,
|
||||
unique_gpu_caches: dict[str, torch.Tensor],
|
||||
total_bytes_per_block: int,
|
||||
device: torch.device,
|
||||
) -> None:
|
||||
logger.info(
|
||||
"SimpleCPUOffloadWorker [CPU]: %d tensors, %d CPU blocks (%.2f GB)",
|
||||
len(unique_gpu_caches),
|
||||
self.num_cpu_blocks,
|
||||
(self.num_cpu_blocks * total_bytes_per_block) / (1024**3),
|
||||
)
|
||||
|
||||
pin_memory = PIN_MEMORY
|
||||
if not pin_memory:
|
||||
logger.warning(
|
||||
"Pinned memory not available. CPU offload performance may be degraded."
|
||||
)
|
||||
|
||||
self.cpu_kv_caches = {}
|
||||
for name, gpu_tensor in unique_gpu_caches.items():
|
||||
cpu_shape = (self.num_cpu_blocks,) + gpu_tensor.shape[1:]
|
||||
# Allocate non-pinned first, then pin via cudaHostRegister to
|
||||
# bypass PyTorch's CUDACachingHostAllocator which rounds up to
|
||||
# the next power of 2 (e.g. 100 GB -> 128 GB).
|
||||
tensor = torch.zeros(cpu_shape, dtype=gpu_tensor.dtype, device="cpu")
|
||||
if pin_memory:
|
||||
pin_tensor(tensor)
|
||||
self.cpu_kv_caches[name] = tensor
|
||||
|
||||
self._backend = DmaCopyBackend()
|
||||
self._backend.init(
|
||||
unique_gpu_caches,
|
||||
self.cpu_kv_caches,
|
||||
device,
|
||||
self.load_stream,
|
||||
self.store_stream,
|
||||
)
|
||||
|
||||
def bind_connector_metadata(self, metadata: SimpleCPUOffloadMetadata) -> None:
|
||||
self._connector_metadata = metadata
|
||||
if metadata.load_event >= 0:
|
||||
self._pending_load_event_indices.add(metadata.load_event)
|
||||
if metadata.store_event >= 0:
|
||||
self._pending_store_event_indices.add(metadata.store_event)
|
||||
|
||||
def clear_connector_metadata(self) -> None:
|
||||
self._connector_metadata = None
|
||||
|
||||
def start_load_kv(self) -> None:
|
||||
# Invoked after the forward launch on steps without sync loads
|
||||
# (SchedulerOutput.has_sync_kv_loads), so the CPU-side block copy
|
||||
# op overhead (~5ms) stays hidden behind GPU compute. Stores are
|
||||
# issued in wait_for_save().
|
||||
metadata = self._connector_metadata
|
||||
if metadata is not None and metadata.load_cpu_blocks:
|
||||
backend = self._backend
|
||||
assert backend is not None
|
||||
backend.launch_copy(
|
||||
metadata.load_cpu_blocks,
|
||||
metadata.load_gpu_blocks,
|
||||
is_store=False,
|
||||
event_idx=metadata.load_event,
|
||||
events_list=self._load_events,
|
||||
)
|
||||
|
||||
def wait_for_save(self) -> None:
|
||||
"""Submit async stores.
|
||||
|
||||
Stores (GPU->CPU) read the live KV cache, which the compute stream may
|
||||
still be writing under v1 overlapped execution, so they are ordered
|
||||
after a compute-done event recorded on the current stream. See
|
||||
#45704 for the bug and #39306 for the srcAccessOrder rationale.
|
||||
"""
|
||||
metadata = self._connector_metadata
|
||||
if metadata is not None and metadata.store_gpu_blocks:
|
||||
backend = self._backend
|
||||
assert backend is not None
|
||||
if self._store_compute_done is None:
|
||||
self._store_compute_done = torch.Event()
|
||||
self._store_compute_done.record(torch.cuda.current_stream())
|
||||
backend.launch_copy(
|
||||
metadata.store_gpu_blocks,
|
||||
metadata.store_cpu_blocks,
|
||||
is_store=True,
|
||||
event_idx=metadata.store_event,
|
||||
events_list=self._store_events,
|
||||
wait_event=self._store_compute_done,
|
||||
)
|
||||
|
||||
def get_finished(
|
||||
self, finished_req_ids: set[str]
|
||||
) -> tuple[set[str] | None, set[str] | None]:
|
||||
"""Report completed transfer events to the scheduler.
|
||||
|
||||
Loads are submitted in start_load_kv() and stores in wait_for_save().
|
||||
|
||||
Returns:
|
||||
tuple of (finished_sending, finished_recving).
|
||||
- finished_sending: always None (stores use worker metadata).
|
||||
- finished_recving: req_ids whose loads have completed.
|
||||
|
||||
"""
|
||||
metadata = self._connector_metadata
|
||||
finished_recving: set[str] = set()
|
||||
|
||||
if self._pending_load_event_indices:
|
||||
load_wm = self._poll_stream_events(is_store=False)
|
||||
for j in [j for j in self._pending_load_event_indices if j <= load_wm]:
|
||||
self._pending_load_event_indices.discard(j)
|
||||
req_ids = (
|
||||
metadata.load_event_to_reqs.get(j) if metadata is not None else None
|
||||
)
|
||||
if req_ids:
|
||||
finished_recving.update(req_ids)
|
||||
|
||||
if self._pending_store_event_indices:
|
||||
store_wm = self._poll_stream_events(is_store=True)
|
||||
for j in [j for j in self._pending_store_event_indices if j <= store_wm]:
|
||||
self._pending_store_event_indices.discard(j)
|
||||
self._completed_store_events[j] = 1
|
||||
|
||||
return None, finished_recving or None
|
||||
|
||||
def build_connector_worker_meta(self) -> SimpleCPUOffloadWorkerMetadata | None:
|
||||
"""Return completed store events since the last call."""
|
||||
if not self._completed_store_events:
|
||||
return None
|
||||
meta = SimpleCPUOffloadWorkerMetadata(
|
||||
completed_store_events=self._completed_store_events,
|
||||
)
|
||||
self._completed_store_events = {}
|
||||
return meta
|
||||
|
||||
def handle_preemptions(
|
||||
self, kv_connector_metadata: SimpleCPUOffloadMetadata
|
||||
) -> None:
|
||||
"""Sync all in-flight transfers before preempted blocks are reused."""
|
||||
if not kv_connector_metadata.need_flush:
|
||||
return
|
||||
self._flush_and_sync_all()
|
||||
|
||||
def _flush_and_sync_all(self) -> None:
|
||||
"""Synchronize all in-flight transfer events."""
|
||||
for event_idx, event in self._load_events:
|
||||
event.synchronize()
|
||||
self._load_hwm = event_idx
|
||||
self._load_events.clear()
|
||||
|
||||
for event_idx, event in self._store_events:
|
||||
event.synchronize()
|
||||
self._store_hwm = event_idx
|
||||
self._store_events.clear()
|
||||
|
||||
def _poll_stream_events(self, is_store: bool) -> int:
|
||||
"""Non-blocking poll for completed events and return the high-water mark."""
|
||||
events = self._store_events if is_store else self._load_events
|
||||
hwm = self._store_hwm if is_store else self._load_hwm
|
||||
while events:
|
||||
event_idx, event = events[0]
|
||||
if not event.query():
|
||||
break
|
||||
hwm = event_idx
|
||||
events.pop(0)
|
||||
if is_store:
|
||||
self._store_hwm = hwm
|
||||
else:
|
||||
self._load_hwm = hwm
|
||||
return hwm
|
||||
Reference in New Issue
Block a user