DCP supports hybrid attention (#40996)
Signed-off-by: YanXu <yancey.yx@alibaba-inc.com> Signed-off-by: Jingyi Yang <girasoleyang@gmail.com> Co-authored-by: Jingyi Yang <girasoleyang@gmail.com>
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from enum import Enum
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
@@ -10,11 +12,15 @@ from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.v1.attention.backends.utils import PAD_SLOT_ID
|
||||
from vllm.v1.utils import CpuGpuBuffer
|
||||
from vllm.v1.worker.cp_utils import get_total_cp_world_size
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SlotMappingMode(Enum):
|
||||
TOKEN_TO_KV_SLOT = "token_to_kv_slot"
|
||||
NONE = "none"
|
||||
|
||||
|
||||
class BlockTable:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -26,6 +32,7 @@ class BlockTable:
|
||||
device: torch.device,
|
||||
kernel_block_size: int,
|
||||
cp_kv_cache_interleave_size: int,
|
||||
slot_mapping_mode: SlotMappingMode = SlotMappingMode.TOKEN_TO_KV_SLOT,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
@@ -38,11 +45,15 @@ class BlockTable:
|
||||
kernel_block_size: The block_size of underlying attention kernel.
|
||||
Will be the same as `block_size` if `block_size` is supported
|
||||
by the attention kernel.
|
||||
slot_mapping_mode: How this cache group maps scheduled tokens to
|
||||
cache slots. Mamba-like state caches do not use token slot
|
||||
mappings and should use SlotMappingMode.NONE.
|
||||
"""
|
||||
self.max_num_reqs = max_num_reqs
|
||||
self.max_num_batched_tokens = max_num_batched_tokens
|
||||
self.pin_memory = pin_memory
|
||||
self.device = device
|
||||
self.kv_cache_block_size = block_size
|
||||
|
||||
if kernel_block_size == block_size:
|
||||
# Standard case: allocation and computation use same block size
|
||||
@@ -98,6 +109,7 @@ class BlockTable:
|
||||
self.dcp_world_size = 1
|
||||
self.dcp_rank = 0
|
||||
self.cp_kv_cache_interleave_size = cp_kv_cache_interleave_size
|
||||
self.slot_mapping_mode = slot_mapping_mode
|
||||
|
||||
def append_row(
|
||||
self,
|
||||
@@ -145,6 +157,12 @@ class BlockTable:
|
||||
positions: torch.Tensor,
|
||||
) -> None:
|
||||
num_tokens = positions.shape[0]
|
||||
if self.slot_mapping_mode == SlotMappingMode.NONE:
|
||||
# Mamba/GDN groups consume the block table as recurrent state
|
||||
# indices and do not use per-token slot mappings.
|
||||
return
|
||||
assert self.slot_mapping_mode == SlotMappingMode.TOKEN_TO_KV_SLOT
|
||||
|
||||
total_cp_world_size = self.pcp_world_size * self.dcp_world_size
|
||||
total_cp_rank = self.pcp_rank * self.dcp_world_size + self.dcp_rank
|
||||
_compute_slot_mapping_kernel[(num_reqs + 1,)](
|
||||
@@ -156,6 +174,8 @@ class BlockTable:
|
||||
self.block_table.gpu.stride(0),
|
||||
self.block_size,
|
||||
self.slot_mapping.gpu,
|
||||
KV_CACHE_BLOCK_SIZE=self.kv_cache_block_size,
|
||||
BLOCKS_PER_KV_BLOCK=self.blocks_per_kv_block,
|
||||
TOTAL_CP_WORLD_SIZE=total_cp_world_size,
|
||||
TOTAL_CP_RANK=total_cp_rank,
|
||||
CP_KV_CACHE_INTERLEAVE_SIZE=self.cp_kv_cache_interleave_size,
|
||||
@@ -226,30 +246,27 @@ class MultiGroupBlockTable:
|
||||
def __init__(
|
||||
self,
|
||||
max_num_reqs: int,
|
||||
max_model_len: int,
|
||||
max_num_batched_tokens: int,
|
||||
pin_memory: bool,
|
||||
device: torch.device,
|
||||
block_sizes: list[int],
|
||||
kernel_block_sizes: list[int],
|
||||
max_num_blocks: list[int] | None = None,
|
||||
max_num_blocks: list[int],
|
||||
cp_kv_cache_interleave_size: int = 1,
|
||||
slot_mapping_modes: list[SlotMappingMode] | None = None,
|
||||
) -> None:
|
||||
if len(kernel_block_sizes) != len(block_sizes):
|
||||
raise ValueError(
|
||||
f"kernel_block_sizes length ({len(kernel_block_sizes)}) "
|
||||
f"must match block_sizes length ({len(block_sizes)})"
|
||||
)
|
||||
if max_num_blocks is None:
|
||||
# Note(hc): each dcp rank only store
|
||||
# (max_model_len//dcp_world_size) tokens in kvcache,
|
||||
# so the block_size which used for calc max_num_blocks_per_req
|
||||
# must be multiplied by dcp_world_size.
|
||||
total_cp_world_size = get_total_cp_world_size()
|
||||
max_num_blocks = [
|
||||
cdiv(max_model_len, block_size * total_cp_world_size)
|
||||
for block_size in block_sizes
|
||||
]
|
||||
if slot_mapping_modes is None:
|
||||
slot_mapping_modes = [SlotMappingMode.TOKEN_TO_KV_SLOT] * len(block_sizes)
|
||||
if len(slot_mapping_modes) != len(block_sizes):
|
||||
raise ValueError(
|
||||
f"slot_mapping_modes length ({len(slot_mapping_modes)}) "
|
||||
f"must match block_sizes length ({len(block_sizes)})"
|
||||
)
|
||||
|
||||
if len(max_num_blocks) != len(block_sizes):
|
||||
raise ValueError(
|
||||
@@ -274,9 +291,15 @@ class MultiGroupBlockTable:
|
||||
device,
|
||||
kernel_block_size,
|
||||
cp_kv_cache_interleave_size,
|
||||
slot_mapping_mode=slot_mapping_mode,
|
||||
)
|
||||
for block_size, kernel_block_size, max_num_blocks_per_req in zip(
|
||||
block_sizes, kernel_block_sizes, max_num_blocks
|
||||
for (
|
||||
block_size,
|
||||
kernel_block_size,
|
||||
max_num_blocks_per_req,
|
||||
slot_mapping_mode,
|
||||
) in zip(
|
||||
block_sizes, kernel_block_sizes, max_num_blocks, slot_mapping_modes
|
||||
)
|
||||
]
|
||||
|
||||
@@ -332,6 +355,8 @@ def _compute_slot_mapping_kernel(
|
||||
block_table_stride, # max_num_blocks_per_req
|
||||
block_size,
|
||||
slot_mapping_ptr, # [max_num_tokens], int64
|
||||
KV_CACHE_BLOCK_SIZE: tl.constexpr,
|
||||
BLOCKS_PER_KV_BLOCK: tl.constexpr,
|
||||
TOTAL_CP_WORLD_SIZE: tl.constexpr,
|
||||
TOTAL_CP_RANK: tl.constexpr,
|
||||
CP_KV_CACHE_INTERLEAVE_SIZE: tl.constexpr,
|
||||
@@ -354,18 +379,14 @@ def _compute_slot_mapping_kernel(
|
||||
start_idx = tl.load(query_start_loc_ptr + req_idx).to(tl.int64)
|
||||
end_idx = tl.load(query_start_loc_ptr + req_idx + 1).to(tl.int64)
|
||||
|
||||
virtual_block_size = block_size * TOTAL_CP_WORLD_SIZE
|
||||
virtual_block_size = KV_CACHE_BLOCK_SIZE * TOTAL_CP_WORLD_SIZE
|
||||
row_offset = req_idx * block_table_stride
|
||||
for i in range(start_idx, end_idx, BLOCK_SIZE):
|
||||
offsets = i + tl.arange(0, BLOCK_SIZE)
|
||||
mask = offsets < end_idx
|
||||
pos = tl.load(positions_ptr + offsets, mask=mask, other=0)
|
||||
block_indices = pos // virtual_block_size
|
||||
block_numbers = tl.load(block_table_ptr + row_offset + block_indices).to(
|
||||
tl.int64
|
||||
)
|
||||
|
||||
virtual_block_offsets = pos - block_indices * virtual_block_size
|
||||
virtual_block_indices = pos // virtual_block_size
|
||||
virtual_block_offsets = pos - virtual_block_indices * virtual_block_size
|
||||
is_local = (
|
||||
virtual_block_offsets // CP_KV_CACHE_INTERLEAVE_SIZE
|
||||
) % TOTAL_CP_WORLD_SIZE == TOTAL_CP_RANK
|
||||
@@ -375,6 +396,16 @@ def _compute_slot_mapping_kernel(
|
||||
virtual_block_offsets % CP_KV_CACHE_INTERLEAVE_SIZE
|
||||
)
|
||||
|
||||
slot_ids = block_numbers * block_size + local_block_offsets
|
||||
block_indices = (
|
||||
virtual_block_indices * BLOCKS_PER_KV_BLOCK
|
||||
+ local_block_offsets // block_size
|
||||
)
|
||||
block_numbers = tl.load(
|
||||
block_table_ptr + row_offset + block_indices,
|
||||
mask=mask & is_local,
|
||||
other=0,
|
||||
).to(tl.int64)
|
||||
slot_offsets = local_block_offsets % block_size
|
||||
slot_ids = block_numbers * block_size + slot_offsets
|
||||
slot_ids = tl.where(is_local, slot_ids, PAD_ID)
|
||||
tl.store(slot_mapping_ptr + offsets, slot_ids, mask=mask)
|
||||
|
||||
@@ -1,15 +1,23 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig, get_layers_from_vllm_config
|
||||
from vllm.distributed import get_dcp_group, get_pcp_group
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import CommonAttentionMetadata
|
||||
from vllm.v1.attention.backends.utils import split_decodes_prefills_and_extends
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
|
||||
else:
|
||||
AttentionLayerBase = object
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def check_attention_cp_compatibility(vllm_config: VllmConfig) -> None:
|
||||
pcp_size = vllm_config.parallel_config.prefill_context_parallel_size
|
||||
@@ -56,3 +64,232 @@ def get_total_cp_world_size():
|
||||
# DCP might not be initialized in testing
|
||||
dcp_world_size = 1
|
||||
return dcp_world_size * pcp_world_size
|
||||
|
||||
|
||||
def get_dcp_dummy_context_len(
|
||||
dcp_world_size: int,
|
||||
cp_kv_cache_interleave_size: int,
|
||||
has_kv_cache_config: bool,
|
||||
create_mixed_batch: bool,
|
||||
is_graph_capturing: bool,
|
||||
uniform_decode: bool,
|
||||
) -> int:
|
||||
if (
|
||||
dcp_world_size <= 1
|
||||
or not has_kv_cache_config
|
||||
or not (create_mixed_batch or (is_graph_capturing and uniform_decode))
|
||||
):
|
||||
return 0
|
||||
return dcp_world_size * cp_kv_cache_interleave_size
|
||||
|
||||
|
||||
def prepare_dcp_dummy_context_metadata(
|
||||
*,
|
||||
input_batch: Any,
|
||||
kv_cache_config: Any,
|
||||
query_pos: Any,
|
||||
positions: torch.Tensor,
|
||||
query_start_loc: Any,
|
||||
num_reqs: int,
|
||||
num_tokens_unpadded: int,
|
||||
dcp_dummy_context_len: int,
|
||||
) -> None:
|
||||
"""Populate valid fake KV metadata for DCP CUDA graph warmup/capture."""
|
||||
if dcp_dummy_context_len == 0:
|
||||
return
|
||||
|
||||
# DCP graph warmup may exercise context attention, so block-table entries
|
||||
# must point at allocated KV blocks.
|
||||
assert kv_cache_config is not None
|
||||
max_valid_block_id = kv_cache_config.num_blocks - 1
|
||||
assert max_valid_block_id > 0
|
||||
for blk_table in input_batch.block_table.block_tables:
|
||||
max_row_blocks = (
|
||||
blk_table.max_num_blocks_per_req // blk_table.blocks_per_kv_block
|
||||
)
|
||||
block_ids = [
|
||||
(block_idx % max_valid_block_id) + 1 for block_idx in range(max_row_blocks)
|
||||
]
|
||||
for req_idx in range(num_reqs):
|
||||
blk_table.add_row(block_ids, req_idx)
|
||||
blk_table.commit_block_table(num_reqs)
|
||||
|
||||
query_pos.copy_to_gpu(num_tokens_unpadded)
|
||||
positions[:num_tokens_unpadded] = (
|
||||
query_pos.gpu[:num_tokens_unpadded] + dcp_dummy_context_len
|
||||
)
|
||||
input_batch.block_table.compute_slot_mapping(
|
||||
num_reqs,
|
||||
query_start_loc.gpu[: num_reqs + 1],
|
||||
positions[:num_tokens_unpadded],
|
||||
)
|
||||
|
||||
|
||||
def should_skip_dcp_context_attention(context_kv_lens_cpu: torch.Tensor) -> bool:
|
||||
"""Whether DCP context attention can be skipped for this batch.
|
||||
|
||||
Must be computed from rank-invariant inputs only (the global context
|
||||
lengths, NOT this rank's local share from get_dcp_local_seq_lens): the
|
||||
non-skip path in _forward_with_dcp issues DCP collectives (query
|
||||
all-gather + LSE combine), so every DCP rank must take the same branch.
|
||||
A rank can hold zero local context tokens while other ranks still hold
|
||||
context for the same batch.
|
||||
"""
|
||||
return int(context_kv_lens_cpu.max().item()) == 0
|
||||
|
||||
|
||||
def split_dcp_context_queries(
|
||||
query_start_loc: torch.Tensor,
|
||||
seq_lens_cpu_upper_bound: torch.Tensor | None,
|
||||
max_query_len: int,
|
||||
num_actual_tokens: int,
|
||||
) -> tuple[int, int, int, int]:
|
||||
"""Split reordered DCP context queries into decode and extend regions."""
|
||||
num_reqs = query_start_loc.shape[0] - 1
|
||||
if max_query_len <= 1:
|
||||
return num_reqs, 0, num_actual_tokens, 0
|
||||
if seq_lens_cpu_upper_bound is None:
|
||||
return 0, num_reqs, 0, num_actual_tokens
|
||||
|
||||
common_attn_metadata = cast(
|
||||
CommonAttentionMetadata,
|
||||
SimpleNamespace(
|
||||
max_query_len=max_query_len,
|
||||
num_reqs=num_reqs,
|
||||
num_actual_tokens=num_actual_tokens,
|
||||
query_start_loc_cpu=query_start_loc,
|
||||
seq_lens_cpu_upper_bound=seq_lens_cpu_upper_bound,
|
||||
is_prefilling=None,
|
||||
),
|
||||
)
|
||||
(
|
||||
num_decodes,
|
||||
num_extends,
|
||||
_num_prefills,
|
||||
num_decode_tokens,
|
||||
num_extend_tokens,
|
||||
_num_prefill_tokens,
|
||||
) = split_decodes_prefills_and_extends(common_attn_metadata)
|
||||
return num_decodes, num_extends, num_decode_tokens, num_extend_tokens
|
||||
|
||||
|
||||
def should_split_fa2_dcp_context_attention(
|
||||
fa_version: int | None,
|
||||
max_query_len: int,
|
||||
num_reqs: int,
|
||||
num_decode_reqs: int,
|
||||
num_context_prefill_reqs: int,
|
||||
) -> bool:
|
||||
num_prefills = num_reqs - num_decode_reqs
|
||||
# TODO: Remove this FA2-only DCP compatibility path once FA4 supports
|
||||
# the Qwen3.5 head_size=256 shape on Blackwell and can be used here.
|
||||
# FA2 paged-varlen context attention can fail for DCP mixed batches when
|
||||
# decode rows, context-bearing extend rows, and zero-context pure prefill
|
||||
# rows are submitted together.
|
||||
return (
|
||||
fa_version == 2
|
||||
and max_query_len > 1
|
||||
and num_prefills > 0
|
||||
and (num_decode_reqs > 0 or num_context_prefill_reqs < num_prefills)
|
||||
)
|
||||
|
||||
|
||||
def run_split_fa2_dcp_context_attention(
|
||||
flash_attn_varlen_func: Any,
|
||||
query_across_dcp: torch.Tensor,
|
||||
key_cache: torch.Tensor,
|
||||
value_cache: torch.Tensor,
|
||||
dcp_context_out: torch.Tensor,
|
||||
cu_seqlens_q: torch.Tensor,
|
||||
max_seqlen_q: int,
|
||||
dcp_context_kv_lens: torch.Tensor,
|
||||
max_dcp_context_kv_len: int,
|
||||
softmax_scale: float,
|
||||
alibi_slopes: torch.Tensor | None,
|
||||
sliding_window_size: list[int] | None,
|
||||
block_table: torch.Tensor,
|
||||
softcap: float,
|
||||
fa_version: int,
|
||||
q_descale: torch.Tensor | None,
|
||||
k_descale: torch.Tensor | None,
|
||||
v_descale: torch.Tensor | None,
|
||||
max_num_splits: int,
|
||||
num_heads: int,
|
||||
dcp_world_size: int,
|
||||
num_decode_reqs: int,
|
||||
num_context_prefill_reqs: int,
|
||||
num_decode_tokens: int,
|
||||
num_context_prefill_tokens: int,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
dcp_context_out.zero_()
|
||||
context_lse = torch.full(
|
||||
(num_heads * dcp_world_size, query_across_dcp.shape[0]),
|
||||
-torch.inf,
|
||||
dtype=torch.float32,
|
||||
device=query_across_dcp.device,
|
||||
)
|
||||
|
||||
if num_decode_tokens > 0:
|
||||
_, decode_context_lse = flash_attn_varlen_func(
|
||||
q=query_across_dcp[:num_decode_tokens],
|
||||
k=key_cache,
|
||||
v=value_cache,
|
||||
out=dcp_context_out[:num_decode_tokens],
|
||||
cu_seqlens_q=cu_seqlens_q[: num_decode_reqs + 1],
|
||||
max_seqlen_q=1,
|
||||
seqused_k=dcp_context_kv_lens[:num_decode_reqs],
|
||||
max_seqlen_k=max_dcp_context_kv_len,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=False,
|
||||
alibi_slopes=alibi_slopes,
|
||||
window_size=sliding_window_size,
|
||||
block_table=block_table[:num_decode_reqs],
|
||||
softcap=softcap,
|
||||
return_softmax_lse=True,
|
||||
scheduler_metadata=None,
|
||||
fa_version=fa_version,
|
||||
q_descale=q_descale[:num_decode_reqs] if q_descale is not None else None,
|
||||
k_descale=k_descale[:num_decode_reqs] if k_descale is not None else None,
|
||||
v_descale=v_descale[:num_decode_reqs] if v_descale is not None else None,
|
||||
num_splits=max_num_splits,
|
||||
)
|
||||
context_lse[:, :num_decode_tokens] = decode_context_lse
|
||||
|
||||
if num_context_prefill_tokens > 0:
|
||||
prefill_start = num_decode_tokens
|
||||
prefill_end = prefill_start + num_context_prefill_tokens
|
||||
prefill_query_start_loc = (
|
||||
cu_seqlens_q[
|
||||
num_decode_reqs : num_decode_reqs + num_context_prefill_reqs + 1
|
||||
]
|
||||
- num_decode_tokens
|
||||
)
|
||||
prefill_req_slice = slice(
|
||||
num_decode_reqs, num_decode_reqs + num_context_prefill_reqs
|
||||
)
|
||||
_, prefill_context_lse = flash_attn_varlen_func(
|
||||
q=query_across_dcp[prefill_start:prefill_end],
|
||||
k=key_cache,
|
||||
v=value_cache,
|
||||
out=dcp_context_out[prefill_start:prefill_end],
|
||||
cu_seqlens_q=prefill_query_start_loc,
|
||||
max_seqlen_q=max_seqlen_q,
|
||||
seqused_k=dcp_context_kv_lens[prefill_req_slice],
|
||||
max_seqlen_k=max_dcp_context_kv_len,
|
||||
softmax_scale=softmax_scale,
|
||||
causal=False,
|
||||
alibi_slopes=alibi_slopes,
|
||||
window_size=sliding_window_size,
|
||||
block_table=block_table[prefill_req_slice],
|
||||
softcap=softcap,
|
||||
return_softmax_lse=True,
|
||||
scheduler_metadata=None,
|
||||
fa_version=fa_version,
|
||||
q_descale=q_descale[prefill_req_slice] if q_descale is not None else None,
|
||||
k_descale=k_descale[prefill_req_slice] if k_descale is not None else None,
|
||||
v_descale=v_descale[prefill_req_slice] if v_descale is not None else None,
|
||||
num_splits=max_num_splits,
|
||||
)
|
||||
context_lse[:, prefill_start:prefill_end] = prefill_context_lse
|
||||
|
||||
return dcp_context_out, context_lse
|
||||
|
||||
@@ -28,7 +28,7 @@ from vllm.v1.sample.thinking_budget_state import (
|
||||
maybe_create_thinking_budget_state_holder,
|
||||
)
|
||||
from vllm.v1.utils import copy_slice
|
||||
from vllm.v1.worker.block_table import MultiGroupBlockTable
|
||||
from vllm.v1.worker.block_table import MultiGroupBlockTable, SlotMappingMode
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -99,13 +99,14 @@ class InputBatch:
|
||||
vocab_size: int,
|
||||
block_sizes: list[int], # The block_size of each kv cache group
|
||||
kernel_block_sizes: list[int],
|
||||
max_num_blocks_per_req: list[int] | None = None,
|
||||
max_num_blocks_per_req: list[int],
|
||||
logitsprocs: LogitsProcessors | None = None,
|
||||
logitsprocs_need_output_token_ids: bool = False,
|
||||
num_spec_tokens: int = 0,
|
||||
is_pooling_model: bool = False,
|
||||
cp_kv_cache_interleave_size: int = 1,
|
||||
reasoning_config: ReasoningConfig | None = None,
|
||||
slot_mapping_modes: list[SlotMappingMode] | None = None,
|
||||
):
|
||||
self.thinking_budget_state_holder = maybe_create_thinking_budget_state_holder(
|
||||
reasoning_config,
|
||||
@@ -171,7 +172,6 @@ class InputBatch:
|
||||
# Block table.
|
||||
self.block_table = MultiGroupBlockTable(
|
||||
max_num_reqs=max_num_reqs,
|
||||
max_model_len=max_model_len,
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
pin_memory=PIN_MEMORY,
|
||||
device=device,
|
||||
@@ -179,6 +179,7 @@ class InputBatch:
|
||||
kernel_block_sizes=kernel_block_sizes,
|
||||
max_num_blocks=max_num_blocks_per_req,
|
||||
cp_kv_cache_interleave_size=cp_kv_cache_interleave_size,
|
||||
slot_mapping_modes=slot_mapping_modes,
|
||||
)
|
||||
|
||||
# Sampling-related.
|
||||
|
||||
@@ -153,10 +153,12 @@ from vllm.v1.kv_cache_interface import (
|
||||
KVCacheConfig,
|
||||
KVCacheGroupSpec,
|
||||
KVCacheSpec,
|
||||
KVCacheSpecKind,
|
||||
KVQuantMode,
|
||||
MambaSpec,
|
||||
SlidingWindowSpec,
|
||||
UniformTypeKVCacheSpecs,
|
||||
get_kv_cache_spec_kind,
|
||||
)
|
||||
from vllm.v1.kv_cache_spec_registry import KVCacheSpecRegistry
|
||||
from vllm.v1.outputs import (
|
||||
@@ -201,9 +203,11 @@ from vllm.v1.spec_decode.utils import update_num_computed_tokens_for_batch_chang
|
||||
from vllm.v1.structured_output.utils import apply_grammar_bitmask
|
||||
from vllm.v1.utils import CpuGpuBuffer, record_function_or_nullcontext
|
||||
from vllm.v1.worker import mamba_utils
|
||||
from vllm.v1.worker.block_table import SlotMappingMode
|
||||
from vllm.v1.worker.cp_utils import (
|
||||
check_attention_cp_compatibility,
|
||||
get_total_cp_world_size,
|
||||
get_dcp_dummy_context_len,
|
||||
prepare_dcp_dummy_context_metadata,
|
||||
)
|
||||
from vllm.v1.worker.dp_utils import coordinate_batch_across_dp
|
||||
from vllm.v1.worker.ec_connector_model_runner_mixin import ECConnectorModelRunnerMixin
|
||||
@@ -681,8 +685,13 @@ class GPUModelRunner(
|
||||
placeholder_block_size = (
|
||||
self.cache_config.block_size or CacheConfig.DEFAULT_BLOCK_SIZE
|
||||
)
|
||||
placeholder_max_num_blocks = cdiv(
|
||||
max(self.max_model_len, self.max_encoder_len), placeholder_block_size
|
||||
)
|
||||
self._init_block_sizes = [placeholder_block_size]
|
||||
self._init_kernel_block_sizes = [placeholder_block_size]
|
||||
self._init_max_num_blocks = [placeholder_max_num_blocks]
|
||||
self._init_slot_mapping_modes = [SlotMappingMode.TOKEN_TO_KV_SLOT]
|
||||
self.input_batch = InputBatch(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
# We need to use the encoder length for encoder-decoder
|
||||
@@ -693,6 +702,7 @@ class GPUModelRunner(
|
||||
vocab_size=self.model_config.get_vocab_size(),
|
||||
block_sizes=[placeholder_block_size],
|
||||
kernel_block_sizes=[placeholder_block_size],
|
||||
max_num_blocks_per_req=[placeholder_max_num_blocks],
|
||||
num_spec_tokens=self.num_spec_tokens,
|
||||
logitsprocs=build_logitsprocs(
|
||||
self.vllm_config,
|
||||
@@ -5858,6 +5868,14 @@ class GPUModelRunner(
|
||||
num_reqs_padded = (
|
||||
batch_desc.num_reqs if batch_desc.num_reqs is not None else num_reqs
|
||||
)
|
||||
dcp_dummy_context_len = get_dcp_dummy_context_len(
|
||||
self.dcp_world_size,
|
||||
self.parallel_config.cp_kv_cache_interleave_size,
|
||||
hasattr(self, "kv_cache_config"),
|
||||
create_mixed_batch,
|
||||
is_graph_capturing,
|
||||
uniform_decode,
|
||||
)
|
||||
ubatch_slices, ubatch_slices_padded = maybe_create_ubatch_slices(
|
||||
should_ubatch,
|
||||
num_scheduled_tokens,
|
||||
@@ -5900,10 +5918,19 @@ class GPUModelRunner(
|
||||
# In the mixed batch mode (used for FI warmup), we use
|
||||
# shorter sequence lengths to run faster.
|
||||
# TODO(luka) better system for describing dummy batches
|
||||
seq_lens = torch.tensor( # type: ignore[assignment]
|
||||
[1] * num_decode_tokens + [num_prefill_tokens + 1],
|
||||
dtype=torch.int,
|
||||
)
|
||||
if dcp_dummy_context_len > 0:
|
||||
seq_lens = torch.tensor( # type: ignore[assignment]
|
||||
[1 + dcp_dummy_context_len] * num_decode_tokens
|
||||
+ [num_prefill_tokens + dcp_dummy_context_len],
|
||||
dtype=torch.int,
|
||||
)
|
||||
else:
|
||||
seq_lens = torch.tensor( # type: ignore[assignment]
|
||||
[1] * num_decode_tokens + [num_prefill_tokens + 1],
|
||||
dtype=torch.int,
|
||||
)
|
||||
elif dcp_dummy_context_len > 0:
|
||||
seq_lens = max_query_len + dcp_dummy_context_len # type: ignore[assignment]
|
||||
else:
|
||||
seq_lens = max_query_len # type: ignore[assignment]
|
||||
self.optimistic_seq_lens_cpu[:num_reqs] = seq_lens
|
||||
@@ -5919,6 +5946,17 @@ class GPUModelRunner(
|
||||
)
|
||||
self.query_start_loc.copy_to_gpu()
|
||||
|
||||
prepare_dcp_dummy_context_metadata(
|
||||
input_batch=self.input_batch,
|
||||
kv_cache_config=getattr(self, "kv_cache_config", None),
|
||||
query_pos=self.query_pos,
|
||||
positions=self.positions,
|
||||
query_start_loc=self.query_start_loc,
|
||||
num_reqs=num_reqs,
|
||||
num_tokens_unpadded=num_tokens_unpadded,
|
||||
dcp_dummy_context_len=dcp_dummy_context_len,
|
||||
)
|
||||
|
||||
# Sync block table CPU->GPU so cleared rows from
|
||||
# remove_request() are visible to the attention metadata
|
||||
# builder. Without this, stale block IDs from finished
|
||||
@@ -7029,29 +7067,34 @@ class GPUModelRunner(
|
||||
"""
|
||||
block_sizes = []
|
||||
max_num_blocks = []
|
||||
slot_mapping_modes = []
|
||||
max_model_len = max(self.max_model_len, self.max_encoder_len)
|
||||
for kv_cache_group in kv_cache_config.kv_cache_groups:
|
||||
if isinstance(kv_cache_group.kv_cache_spec, EncoderOnlyAttentionSpec):
|
||||
kv_cache_spec = kv_cache_group.kv_cache_spec
|
||||
kv_cache_spec_kind = get_kv_cache_spec_kind(kv_cache_spec)
|
||||
if kv_cache_spec_kind == KVCacheSpecKind.ENCODER_ONLY_ATTENTION:
|
||||
continue
|
||||
block_size = kv_cache_group.kv_cache_spec.block_size
|
||||
block_size = kv_cache_spec.block_size
|
||||
block_sizes.append(block_size)
|
||||
max_num_blocks_per_req = cdiv(
|
||||
max_model_len, block_size * get_total_cp_world_size()
|
||||
if kv_cache_spec_kind == KVCacheSpecKind.MAMBA:
|
||||
slot_mapping_modes.append(SlotMappingMode.NONE)
|
||||
else:
|
||||
slot_mapping_modes.append(SlotMappingMode.TOKEN_TO_KV_SLOT)
|
||||
max_num_blocks_per_req = kv_cache_spec.max_num_blocks_per_req(
|
||||
self.vllm_config, max_model_len
|
||||
)
|
||||
if isinstance(kv_cache_group.kv_cache_spec, MambaSpec):
|
||||
max_num_blocks_per_req = (
|
||||
max_num_blocks_per_req
|
||||
if self.cache_config.enable_prefix_caching
|
||||
else 1
|
||||
) + kv_cache_group.kv_cache_spec.num_speculative_blocks
|
||||
max_num_blocks.append(max_num_blocks_per_req)
|
||||
|
||||
if (
|
||||
block_sizes != self._init_block_sizes
|
||||
or kernel_block_sizes != self._init_kernel_block_sizes
|
||||
or max_num_blocks != self._init_max_num_blocks
|
||||
or slot_mapping_modes != self._init_slot_mapping_modes
|
||||
):
|
||||
self._init_block_sizes = block_sizes
|
||||
self._init_kernel_block_sizes = kernel_block_sizes
|
||||
self._init_max_num_blocks = max_num_blocks
|
||||
self._init_slot_mapping_modes = slot_mapping_modes
|
||||
self.input_batch = InputBatch(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
max_model_len=max_model_len,
|
||||
@@ -7065,7 +7108,9 @@ class GPUModelRunner(
|
||||
logitsprocs=self.input_batch.logitsprocs,
|
||||
logitsprocs_need_output_token_ids=self.input_batch.logitsprocs_need_output_token_ids,
|
||||
is_pooling_model=self.is_pooling_model,
|
||||
cp_kv_cache_interleave_size=self.parallel_config.cp_kv_cache_interleave_size,
|
||||
reasoning_config=self.vllm_config.reasoning_config,
|
||||
slot_mapping_modes=slot_mapping_modes,
|
||||
)
|
||||
|
||||
assert self._init_block_sizes == block_sizes, (
|
||||
|
||||
@@ -29,6 +29,7 @@ class InputBatch:
|
||||
vocab_size: int,
|
||||
block_sizes: list[int], # The block_size of each kv cache group
|
||||
kernel_block_sizes: list[int],
|
||||
max_num_blocks_per_req: list[int],
|
||||
):
|
||||
self.max_num_reqs = max_num_reqs
|
||||
self.max_model_len = max_model_len
|
||||
@@ -64,12 +65,12 @@ class InputBatch:
|
||||
# Block table.
|
||||
self.block_table = MultiGroupBlockTable(
|
||||
max_num_reqs=max_num_reqs,
|
||||
max_model_len=max_model_len,
|
||||
max_num_batched_tokens=max_num_batched_tokens,
|
||||
pin_memory=pin_memory,
|
||||
device=device,
|
||||
block_sizes=block_sizes,
|
||||
kernel_block_sizes=kernel_block_sizes,
|
||||
max_num_blocks=max_num_blocks_per_req,
|
||||
)
|
||||
|
||||
# Sampling-related.
|
||||
|
||||
Reference in New Issue
Block a user