Merge remote-tracking branch 'upstream/main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -54,6 +54,9 @@ class MultipleOf:
|
||||
def __init__(self, base: int):
|
||||
self.base = base
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"MultipleOf({self.base})"
|
||||
|
||||
|
||||
class AttentionBackend(ABC):
|
||||
"""Abstract class for attention backends."""
|
||||
|
||||
@@ -97,6 +97,7 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
|
||||
# Will be disabled if speculative decoding is used
|
||||
supports_update_block_table: bool = True
|
||||
needs_causal_conv1d_metadata: bool = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -603,10 +604,6 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
if num_computed_tokens is None:
|
||||
num_computed_tokens = common_attn_metadata.compute_num_computed_tokens()
|
||||
|
||||
query_start_loc_p_cpu = (
|
||||
common_attn_metadata.query_start_loc_cpu[-num_prefills - 1 :]
|
||||
- num_decode_tokens
|
||||
)
|
||||
query_start_loc_p = (
|
||||
common_attn_metadata.query_start_loc[-num_prefills - 1 :]
|
||||
- num_decode_tokens
|
||||
@@ -615,12 +612,17 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
num_computed_tokens[num_reqs - num_prefills : num_reqs] > 0
|
||||
)
|
||||
|
||||
nums_dict, batch_ptr, token_chunk_offset_ptr = (
|
||||
compute_causal_conv1d_metadata(
|
||||
query_start_loc_p_cpu,
|
||||
device=common_attn_metadata.query_start_loc.device,
|
||||
if self.needs_causal_conv1d_metadata:
|
||||
query_start_loc_p_cpu = (
|
||||
common_attn_metadata.query_start_loc_cpu[-num_prefills - 1 :]
|
||||
- num_decode_tokens
|
||||
)
|
||||
nums_dict, batch_ptr, token_chunk_offset_ptr = (
|
||||
compute_causal_conv1d_metadata(
|
||||
query_start_loc_p_cpu,
|
||||
device=common_attn_metadata.query_start_loc.device,
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if self.vllm_config.cache_config.mamba_cache_mode == "all":
|
||||
assert num_computed_tokens is not None
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
import functools
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, ClassVar, Final
|
||||
|
||||
import torch
|
||||
|
||||
from vllm import envs
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.cache import CacheDType
|
||||
@@ -239,6 +241,78 @@ def _segmented_dcp_verify_supported(dcp_world_size: int, cp_interleave: int) ->
|
||||
)
|
||||
|
||||
|
||||
# DCP decode routing
|
||||
#
|
||||
# With decode context parallelism each rank holds a round-robin shard of the KV
|
||||
# cache (token t on rank t % dcp_world_size; requires interleave size 1) and
|
||||
# attends over it with all DCP-gathered query heads. Partial outputs are merged
|
||||
# across ranks by LSE. Each decode batch takes one route:
|
||||
#
|
||||
# * plain: qlen == 1 or a non-causal block. Every query sees every local token.
|
||||
# * cprr: causal qlen >= _MIN_CPRR_QLEN, gfx950, speculative decoding. AITER's
|
||||
# round-robin ASM decode rebuilds global positions from g_kv_indptr, cp_rank
|
||||
# and cp_world_size and applies the causal window in-kernel. Kernels exist only
|
||||
# at _NATIVE_CPRR_HEADS; other gathered head counts are padded up.
|
||||
# * segmented: causal qlen > 1 when cprr is not selected or qlen is below
|
||||
# _MIN_CPRR_QLEN. Each verify token becomes a single-query row whose KV length
|
||||
# encodes its causal window.
|
||||
#
|
||||
# The plain kernel must never serve a causal qlen > 1 block: it applies
|
||||
# causality on local indices, which is wrong over a round-robin shard.
|
||||
_NATIVE_CPRR_HEADS: Final = (16, 32, 64, 128)
|
||||
_MIN_CPRR_QLEN: Final = 3
|
||||
|
||||
|
||||
class _DCPDecodeRoute(Enum):
|
||||
PLAIN = "plain"
|
||||
SEGMENTED = "segmented"
|
||||
CPRR = "cprr"
|
||||
|
||||
|
||||
def _asm_dcp_verify_heads(decode_num_heads: int) -> int:
|
||||
"""Head count the cprr asm decode runs at, or 0 if it cannot serve this shape."""
|
||||
if decode_num_heads in _NATIVE_CPRR_HEADS:
|
||||
return decode_num_heads
|
||||
for nat in _NATIVE_CPRR_HEADS:
|
||||
if nat >= decode_num_heads:
|
||||
return nat
|
||||
return 0
|
||||
|
||||
|
||||
def _select_dcp_decode_route(
|
||||
supports_segmented: bool,
|
||||
causal: bool,
|
||||
max_qo_len: int,
|
||||
asm_selected: bool,
|
||||
) -> _DCPDecodeRoute:
|
||||
"""Select one DCP decode route for this batch; see DCP decode routing."""
|
||||
if not causal or max_qo_len <= 1:
|
||||
return _DCPDecodeRoute.PLAIN
|
||||
if asm_selected and max_qo_len >= _MIN_CPRR_QLEN:
|
||||
return _DCPDecodeRoute.CPRR
|
||||
if supports_segmented:
|
||||
return _DCPDecodeRoute.SEGMENTED
|
||||
raise RuntimeError(
|
||||
"ROCM_AITER_MLA DCP multi-token verify requires either segmented "
|
||||
"MLA or the round-robin asm decode."
|
||||
)
|
||||
|
||||
|
||||
def _asm_dcp_verify_configured(
|
||||
dcp_world_size: int, cp_interleave: int, multi_token_decode: bool
|
||||
) -> bool:
|
||||
"""Whether asm cprr DCP verify is reachable in this process.
|
||||
|
||||
Requires DCP with interleave size 1, speculative decoding, and gfx950 (the
|
||||
only arch AITER builds cprr kernels for).
|
||||
"""
|
||||
if not (dcp_world_size > 1 and cp_interleave == 1 and multi_token_decode):
|
||||
return False
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
return bool(on_gfx950())
|
||||
|
||||
|
||||
def _aiter_mla_small_head_mode() -> str:
|
||||
"""Small-head (<16) MLA decode kernel selection.
|
||||
|
||||
@@ -410,8 +484,19 @@ class AiterMLADecodeMetadata(MLACommonDecodeMetadata):
|
||||
max_qo_len: int | None = None
|
||||
# Minimum KV length used by Gluon to choose a safe split count.
|
||||
min_kv_seq_len: int = 1
|
||||
# Exactly one DCP decode route is selected by the metadata builder.
|
||||
dcp_route: _DCPDecodeRoute = _DCPDecodeRoute.PLAIN
|
||||
# Set exactly when this batch routes to segmented DCP verification.
|
||||
dcp_verify: AiterMLADCPVerifyMetadata | None = None
|
||||
# cprr only: global per-request page indptr and this rank's position.
|
||||
g_kv_indptr: torch.Tensor | None = None
|
||||
cp_world_size: int = 1
|
||||
cp_rank: int = 0
|
||||
# Padded head count cprr runs at; 0 when this batch is not on cprr.
|
||||
asm_decode_num_heads: int = 0
|
||||
# Must equal the split cap the reduce scratch was sized with, or the kernel
|
||||
# writes past it and faults.
|
||||
mla_num_kv_splits: int = 0
|
||||
# Small-head decode uses Gluon (avoids padding to 16).
|
||||
use_gluon_decode: bool = False
|
||||
# Small-head non-DCP multi-token verify uses Gluon's native MTP entry.
|
||||
@@ -460,6 +545,9 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
# Set from the common metadata every build; a batch is causal unless the
|
||||
# drafter says otherwise.
|
||||
_decode_causal: bool = True
|
||||
# A non-causal draft needs no cross-shard causal window: the ordinary
|
||||
# mask0 decode returns per-row LSE for the DCP merge.
|
||||
supports_non_causal_multi_token_dcp: ClassVar[bool] = True
|
||||
|
||||
@staticmethod
|
||||
def _uniform_padded_mtp_qo_len(
|
||||
@@ -513,15 +601,48 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
parallel_config.decode_context_parallel_size,
|
||||
parallel_config.cp_kv_cache_interleave_size,
|
||||
)
|
||||
asm_dcp_verify_config = (
|
||||
_asm_dcp_verify_configured(
|
||||
parallel_config.decode_context_parallel_size,
|
||||
parallel_config.cp_kv_cache_interleave_size,
|
||||
multi_token_decode=vllm_config.speculative_config is not None,
|
||||
)
|
||||
and envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY == "asm"
|
||||
)
|
||||
super().__init__(
|
||||
kv_cache_spec,
|
||||
layer_names,
|
||||
vllm_config,
|
||||
device,
|
||||
AiterMLAMetadata,
|
||||
supports_dcp_with_varlen=supports_segmented_dcp_verify,
|
||||
supports_dcp_with_varlen=(
|
||||
supports_segmented_dcp_verify or asm_dcp_verify_config
|
||||
),
|
||||
)
|
||||
self._asm_dcp_verify = False
|
||||
self._asm_dcp_verify_heads = 0
|
||||
# The head-count half of the route decision needs self.num_heads, so only
|
||||
# the config half is known before super().__init__().
|
||||
if asm_dcp_verify_config:
|
||||
self._asm_dcp_verify_heads = _asm_dcp_verify_heads(
|
||||
self.num_heads * self.dcp_world_size
|
||||
)
|
||||
if not self._asm_dcp_verify_heads:
|
||||
raise ValueError(
|
||||
"VLLM_ROCM_AITER_MLA_DCP_VERIFY=asm, but the round-robin asm "
|
||||
f"decode has no kernel for {self.num_heads * self.dcp_world_size} "
|
||||
f"DCP-gathered heads (native counts: {_NATIVE_CPRR_HEADS}). "
|
||||
"Set VLLM_ROCM_AITER_MLA_DCP_VERIFY=segmented."
|
||||
)
|
||||
self._asm_dcp_verify = True
|
||||
self._supports_segmented_dcp_verify = supports_segmented_dcp_verify
|
||||
self._mla_max_split_per_batch = 0
|
||||
if self._asm_dcp_verify:
|
||||
# Cap on KV splits per batch; at low batch the KV axis is the only
|
||||
# parallelism. Buffer sizing and every runtime call must see this value.
|
||||
self._mla_max_split_per_batch = torch.cuda.get_device_properties(
|
||||
device
|
||||
).multi_processor_count
|
||||
|
||||
self.compilation_config = vllm_config.compilation_config
|
||||
self.decode_attn_out_dtype = vllm_config.model_config.dtype
|
||||
@@ -576,6 +697,12 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
self._num_attention_heads = AiterMLAHelper.get_actual_mla_num_heads(
|
||||
self._decode_num_heads
|
||||
)
|
||||
# the cprr kernel exists only at the native head
|
||||
# counts, so run (and size the persistent schedule) at the padded count.
|
||||
# 96 is 16-aligned, so get_actual_mla_num_heads leaves it alone and the
|
||||
# pad has to be applied here explicitly.
|
||||
if self._asm_dcp_verify:
|
||||
self._num_attention_heads = self._asm_dcp_verify_heads
|
||||
kv_cache_dtype_str = getattr(vllm_config.cache_config, "cache_dtype", "auto")
|
||||
if kv_cache_dtype_str in ("fp8", "fp8_e4m3", "fp8_e5m2"):
|
||||
kv_cache_dtype_str = "fp8"
|
||||
@@ -619,6 +746,13 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
kv_dtype,
|
||||
is_sparse=False,
|
||||
fast_mode=True,
|
||||
# Must match max_split_per_batch in get_mla_metadata_v1; without it
|
||||
# aiter sizes the reduce scratch from capacity (~9 GiB).
|
||||
**(
|
||||
dict(max_split_per_batch=self._mla_max_split_per_batch)
|
||||
if self._asm_dcp_verify
|
||||
else {}
|
||||
),
|
||||
)
|
||||
self._mla_work_meta_data = torch.empty(
|
||||
work_meta_data_size, dtype=work_meta_data_type, device=device
|
||||
@@ -664,6 +798,14 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
device,
|
||||
)
|
||||
|
||||
# Full cudagraphs need a stable address for the cprr global page indptr.
|
||||
# Zero-initialized; element 0 is the indptr base and is never rewritten.
|
||||
self._g_kv_indptr_buf: torch.Tensor | None = None
|
||||
if self._asm_dcp_verify:
|
||||
self._g_kv_indptr_buf = torch.zeros(
|
||||
max_num_reqs + 1, dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
# Persistent buffers for segmented DCP verification. Captured graphs
|
||||
# require stable addresses while row lengths vary between replays.
|
||||
self._dcp_verify_buffers: AiterMLADCPVerifyMetadata | None = None
|
||||
@@ -683,8 +825,11 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
)
|
||||
|
||||
if self._supports_segmented_dcp_verify and self._mtp_decode_qlen > 1:
|
||||
# A DCP rank's shard of the longest sequence bounds every verify
|
||||
# row, and full graphs need that bound to be constant.
|
||||
# Allocate even when CPRR is the preferred route: a later
|
||||
# replay can fall below _MIN_CPRR_QLEN and needs these
|
||||
# addresses. A DCP rank's shard of the longest sequence
|
||||
# bounds every verify row, and full graphs need that bound
|
||||
# to be constant.
|
||||
num_dcp_partitions = (
|
||||
self.dcp_world_size * self.cp_kv_cache_interleave_size
|
||||
)
|
||||
@@ -1063,6 +1208,12 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
pad_uniform_mtp = padded_mtp_qo_len > 0
|
||||
|
||||
seq_lens_for_kernel = seq_lens_device
|
||||
# the global lengths need the same dummy-row
|
||||
# treatment as the local ones below, but only for g_kv_indptr -- the
|
||||
# metadata field keeps the true values, which is what the segmented
|
||||
# route wants (it derives its own row lens and gives a dummy row
|
||||
# length 0, correctly).
|
||||
g_tot_seq_lens = dcp_tot_seq_lens_device
|
||||
num_kernel_reqs = num_reqs
|
||||
if pad_uniform_mtp:
|
||||
qo_lens_device = (
|
||||
@@ -1074,6 +1225,19 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
seq_lens_for_kernel,
|
||||
seq_lens_for_kernel.new_full((), max_qo_len),
|
||||
)
|
||||
# A dummy row just got a LOCAL length of max_qo_len, so its GLOBAL
|
||||
# length has to say the same thing or the cprr mask is degenerate:
|
||||
# global_len 0 puts the row query positions at {-3,-2,-1} while its
|
||||
# local shard sits at {rank, W+rank, 2W+rank}, so every entry is
|
||||
# masked and the row softmaxes over nothing. max_qo_len * W is
|
||||
# exactly the global length whose round-robin shard is max_qo_len
|
||||
# on every rank.
|
||||
if g_tot_seq_lens is not None:
|
||||
g_tot_seq_lens = torch.where(
|
||||
qo_lens_device > 0,
|
||||
g_tot_seq_lens,
|
||||
g_tot_seq_lens.new_full((), max_qo_len * self.dcp_world_size),
|
||||
)
|
||||
|
||||
if self._graph_seq_lens is not None:
|
||||
self._graph_seq_lens[:num_kernel_reqs].copy_(
|
||||
@@ -1106,16 +1270,21 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
causal,
|
||||
self._kv_cache_bytes,
|
||||
)
|
||||
use_segmented_dcp_verify = (
|
||||
self._supports_segmented_dcp_verify and max_qo_len > 1
|
||||
)
|
||||
dcp_route = _DCPDecodeRoute.PLAIN
|
||||
if self.dcp_world_size > 1:
|
||||
dcp_route = _select_dcp_decode_route(
|
||||
self._supports_segmented_dcp_verify,
|
||||
causal,
|
||||
int(max_qo_len),
|
||||
self._asm_dcp_verify,
|
||||
)
|
||||
|
||||
# Segmented DCP verify carries its own per-row subpage table, so the
|
||||
# flat per-token view is dead work for it. Leave the buffer alone and
|
||||
# hand the metadata None, so a future reader cannot pick up whatever
|
||||
# the previous batch left behind.
|
||||
paged_kv_indices = None
|
||||
if not use_segmented_dcp_verify:
|
||||
if dcp_route is not _DCPDecodeRoute.SEGMENTED:
|
||||
if self.compilation_config.cudagraph_mode.has_full_cudagraphs():
|
||||
self.paged_kv_indices.fill_(-1)
|
||||
|
||||
@@ -1169,6 +1338,19 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
else:
|
||||
qo_indptr = query_start_loc_device[: 1 + num_kernel_reqs]
|
||||
|
||||
g_kv_indptr = None
|
||||
if dcp_route is _DCPDecodeRoute.CPRR and g_tot_seq_lens is not None:
|
||||
assert self._g_kv_indptr_buf is not None
|
||||
_ngk = g_tot_seq_lens.shape[0]
|
||||
g_kv_indptr = self._g_kv_indptr_buf[: _ngk + 1]
|
||||
g_kv_indptr[1:].copy_(g_tot_seq_lens.cumsum(dim=0, dtype=torch.int32))
|
||||
# A FULL cudagraph replays at its capture-time request count, so a
|
||||
# smaller real batch leaves the tail holding the PREVIOUS step's
|
||||
# cumsum. Flatten it the way paged_kv_indptr is flattened below, so
|
||||
# padding rows read global_len == 0 and agree with their zero-length
|
||||
# local shard instead of a stale global length.
|
||||
self._g_kv_indptr_buf[_ngk + 1 :].fill_(g_kv_indptr[-1])
|
||||
|
||||
has_persistent_metadata = False
|
||||
# Only the asm decode consumes the schedule, so gate on the routing
|
||||
# rather than on num_heads >= 16, which denies it to a padded rank
|
||||
@@ -1178,7 +1360,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
use_persistent_metadata = (
|
||||
not use_gluon_decode
|
||||
and not use_gluon_verify
|
||||
and not use_segmented_dcp_verify
|
||||
and dcp_route is not _DCPDecodeRoute.SEGMENTED
|
||||
# A padded rank has no bf16 persistent kernel past qlen 4 where the
|
||||
# gfx950 fold is absent; the non-persistent entry covers it. fp8
|
||||
# keeps the schedule -- its fold rejects non-persistent outright.
|
||||
@@ -1218,13 +1400,28 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
uni_qo_len = (
|
||||
max_qo_len if pad_uniform_mtp or torch.all(qo_len == max_qo_len) else -1
|
||||
)
|
||||
cprr_kwargs: dict = {}
|
||||
is_causal = causal
|
||||
if self._asm_dcp_verify:
|
||||
cprr_kwargs = dict(
|
||||
max_split_per_batch=self._mla_max_split_per_batch,
|
||||
intra_batch_mode=False,
|
||||
)
|
||||
if dcp_route is _DCPDecodeRoute.CPRR:
|
||||
is_causal = False
|
||||
cprr_kwargs["is_cp_round_robin"] = True
|
||||
metadata_num_heads = (
|
||||
self._asm_dcp_verify_heads
|
||||
if dcp_route is _DCPDecodeRoute.CPRR
|
||||
else AiterMLAHelper.get_actual_mla_num_heads(self._decode_num_heads)
|
||||
)
|
||||
get_mla_metadata_v1(
|
||||
qo_indptr,
|
||||
paged_kv_indptr,
|
||||
paged_kv_last_page_len,
|
||||
self._num_attention_heads,
|
||||
metadata_num_heads,
|
||||
1,
|
||||
causal,
|
||||
is_causal,
|
||||
self._mla_work_meta_data,
|
||||
self._mla_work_info_set,
|
||||
self._mla_work_indptr,
|
||||
@@ -1238,6 +1435,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
fast_mode=True,
|
||||
dtype_q=self._mla_q_dtype,
|
||||
dtype_kv=self._mla_kv_dtype,
|
||||
**cprr_kwargs,
|
||||
)
|
||||
has_persistent_metadata = True
|
||||
|
||||
@@ -1261,7 +1459,7 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
min_kv_seq_len = int(per_req_len.min().item())
|
||||
|
||||
dcp_verify = None
|
||||
if use_segmented_dcp_verify:
|
||||
if dcp_route is _DCPDecodeRoute.SEGMENTED:
|
||||
assert dcp_tot_seq_lens_device is not None
|
||||
dcp_verify = self._build_dcp_verify_row_view(
|
||||
int(max_qo_len),
|
||||
@@ -1279,7 +1477,19 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
dcp_tot_seq_lens=dcp_tot_seq_lens_device,
|
||||
max_qo_len=max_qo_len,
|
||||
min_kv_seq_len=min_kv_seq_len,
|
||||
dcp_route=dcp_route,
|
||||
dcp_verify=dcp_verify,
|
||||
g_kv_indptr=g_kv_indptr,
|
||||
cp_world_size=self.dcp_world_size,
|
||||
cp_rank=self.dcp_rank,
|
||||
asm_decode_num_heads=(
|
||||
self._asm_dcp_verify_heads if dcp_route is _DCPDecodeRoute.CPRR else 0
|
||||
),
|
||||
mla_num_kv_splits=(
|
||||
self._mla_max_split_per_batch
|
||||
if dcp_route is _DCPDecodeRoute.CPRR
|
||||
else 0
|
||||
),
|
||||
use_gluon_decode=use_gluon_decode,
|
||||
use_gluon_verify=use_gluon_verify,
|
||||
attn_out_dtype=self.decode_attn_out_dtype,
|
||||
@@ -2062,8 +2272,10 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
)
|
||||
return o, None
|
||||
|
||||
verify = decode.dcp_verify
|
||||
if verify is not None:
|
||||
dcp_route = decode.dcp_route
|
||||
if dcp_route is _DCPDecodeRoute.SEGMENTED:
|
||||
verify = decode.dcp_verify
|
||||
assert verify is not None
|
||||
if type(q) is tuple:
|
||||
q_nope, q_pe = q
|
||||
else:
|
||||
@@ -2085,11 +2297,6 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
decode.attn_out_dtype,
|
||||
)
|
||||
|
||||
if self.dcp_world_size > 1 and int(decode.max_qo_len) > 1:
|
||||
raise RuntimeError(
|
||||
"ROCM_AITER_MLA DCP multi-token verify requires segmented MLA."
|
||||
)
|
||||
|
||||
if type(q) is tuple:
|
||||
q = torch.cat(q, dim=-1)
|
||||
|
||||
@@ -2102,8 +2309,19 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
"ROCM_AITER_MLA decode expected the DCP-gathered query head count "
|
||||
f"{self._decode_num_heads}, got {q.shape[1]}"
|
||||
)
|
||||
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self._decode_num_heads, q)
|
||||
mla_num_heads = AiterMLAHelper.get_actual_mla_num_heads(self._decode_num_heads)
|
||||
# cprr has kernels only at native head counts, so pad q up (e.g. 96 ->
|
||||
# 128). Heads are independent in MLA; the extras are sliced off below.
|
||||
asm_dcp_heads = decode.asm_decode_num_heads
|
||||
if asm_dcp_heads > self._decode_num_heads:
|
||||
mla_num_heads = asm_dcp_heads
|
||||
mla_padded_q = AiterMLAHelper.get_mla_padded_q(
|
||||
self._decode_num_heads, q, target_heads=mla_num_heads
|
||||
)
|
||||
else:
|
||||
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self._decode_num_heads, q)
|
||||
mla_num_heads = AiterMLAHelper.get_actual_mla_num_heads(
|
||||
self._decode_num_heads
|
||||
)
|
||||
o = torch.empty(
|
||||
B,
|
||||
mla_num_heads,
|
||||
@@ -2137,6 +2355,16 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
|
||||
lse = None
|
||||
if self.dcp_world_size > 1:
|
||||
if dcp_route is _DCPDecodeRoute.CPRR:
|
||||
# cprr only: global positions for the in-kernel causal window.
|
||||
assert decode.g_kv_indptr is not None
|
||||
mla_kwargs["g_kv_indptr"] = decode.g_kv_indptr
|
||||
mla_kwargs["cp_world_size"] = decode.cp_world_size
|
||||
mla_kwargs["cp_rank"] = decode.cp_rank
|
||||
# Must match the schedule get_mla_metadata_v1 was built with.
|
||||
assert decode.mla_num_kv_splits > 0
|
||||
mla_kwargs["num_kv_splits"] = decode.mla_num_kv_splits
|
||||
mla_kwargs["intra_batch_mode"] = False
|
||||
# The vLLM custom-op wrapper exposes only the in-place output and
|
||||
# drops aiter's final LSE, which the cross-shard merge needs, so go
|
||||
# through aiter's native entry point on the DCP path.
|
||||
@@ -2151,6 +2379,7 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
decode.max_qo_len,
|
||||
sm_scale=self.scale,
|
||||
return_lse=True,
|
||||
causal=attn_metadata.causal,
|
||||
**mla_kwargs,
|
||||
)
|
||||
assert lse is not None, (
|
||||
@@ -2172,7 +2401,13 @@ class AiterMLAImpl(MLACommonImpl[AiterMLAMetadata]):
|
||||
**mla_kwargs,
|
||||
)
|
||||
|
||||
output = AiterMLAHelper.get_mla_unpadded_o(self._decode_num_heads, o)
|
||||
if lse is not None:
|
||||
lse = AiterMLAHelper.get_mla_unpadded_lse(self._decode_num_heads, lse)
|
||||
if asm_dcp_heads > self._decode_num_heads:
|
||||
# Keep a view: a post-kernel copy races the symm-mem a2a combine.
|
||||
output = o[:, : self._decode_num_heads]
|
||||
if lse is not None:
|
||||
lse = lse[:, : self._decode_num_heads, ...]
|
||||
else:
|
||||
output = AiterMLAHelper.get_mla_unpadded_o(self._decode_num_heads, o)
|
||||
if lse is not None:
|
||||
lse = AiterMLAHelper.get_mla_unpadded_lse(self._decode_num_heads, lse)
|
||||
return output, lse
|
||||
|
||||
@@ -396,9 +396,11 @@ class ROCMAiterMLASparseMetadataBuilder(
|
||||
attention_context = vllm_config.compilation_config.static_forward_context
|
||||
# Sink decode must use AITER's nonpersistent path. In particular,
|
||||
# gfx942 has no persistent+LSE kernel, and its metadata heuristic
|
||||
# terminates for HY-V4's TP1 H64 shape.
|
||||
# terminates for HY-V4's TP1 H64 shape. The Triton sparse MLA kernel
|
||||
# never reads the persistent metadata either.
|
||||
self._use_persistent_metadata = all(
|
||||
getattr(attention_context[name].impl, "sinks", None) is None
|
||||
and not getattr(attention_context[name].impl, "use_aiter_sparse_mla", False)
|
||||
for name in layer_names
|
||||
)
|
||||
# Bounds the KV-split heuristic (see `_sparse_decode_max_split`).
|
||||
@@ -716,6 +718,7 @@ class ROCMAiterMLASparseImpl(
|
||||
is_sparse = True
|
||||
supports_dense_mha_prefill = False
|
||||
supports_dcp = False
|
||||
use_aiter_sparse_mla = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -765,6 +768,32 @@ class ROCMAiterMLASparseImpl(
|
||||
(self.q_concat_buffer,) = current_workspace_manager().get_simultaneous(
|
||||
(q_concat_shape, vllm_config.model_config.dtype),
|
||||
)
|
||||
self.qk_rope_head_dim: int = mla_args["qk_rope_head_dim"]
|
||||
|
||||
if rocm_aiter_ops.is_triton_sparse_mla_enabled():
|
||||
reason = self._aiter_sparse_mla_unsupported_reason(vllm_config)
|
||||
if reason is None:
|
||||
self.use_aiter_sparse_mla = True
|
||||
else:
|
||||
logger.warning_once(
|
||||
"VLLM_ROCM_USE_AITER_TRITON_SPARSE_MLA is set, but %s; "
|
||||
"using the default sparse MLA path instead.",
|
||||
reason,
|
||||
)
|
||||
|
||||
def _aiter_sparse_mla_unsupported_reason(
|
||||
self, vllm_config: VllmConfig
|
||||
) -> str | None:
|
||||
model_dtype = vllm_config.model_config.dtype
|
||||
if model_dtype != torch.bfloat16:
|
||||
return f"the model dtype is {model_dtype}, not bfloat16"
|
||||
cache_dtype = self.kv_cache_dtype
|
||||
if cache_dtype not in ("auto", "bfloat16", "fp8", "fp8_e4m3"):
|
||||
return f"kv-cache dtype {cache_dtype!r} is neither bfloat16 nor e4m3 fp8"
|
||||
# Context parallelism merges each rank's partials with a per-token LSE.
|
||||
if self.dcp_world_size > 1 or self.pcp_world_size > 1:
|
||||
return "context parallelism is not supported"
|
||||
return None
|
||||
|
||||
def record_logical_topk_ready(self) -> None:
|
||||
# This impl shares the top-k indices buffer via SharedTopkIndicesBuffer
|
||||
@@ -975,6 +1004,43 @@ class ROCMAiterMLASparseImpl(
|
||||
|
||||
return output, lse
|
||||
|
||||
def _forward_mla_aiter(
|
||||
self,
|
||||
layer: AttentionLayer,
|
||||
q: torch.Tensor, # [sq, heads, d_qk], not head-padded
|
||||
kv_c_and_k_pe_cache: torch.Tensor,
|
||||
attn_metadata: ROCMAiterMLASparseMetadata,
|
||||
) -> torch.Tensor:
|
||||
"""_forward_mla on aiter's Triton sparse MLA kernel.
|
||||
|
||||
Reads the same index stream, but needs no q head padding and no
|
||||
persistent metadata, and its launch depends on shapes only, so it is
|
||||
CUDA-graph capturable.
|
||||
"""
|
||||
num_actual_tokens = attn_metadata.num_actual_tokens
|
||||
output = torch.empty(
|
||||
[q.shape[0], self.num_heads, self.kv_lora_rank],
|
||||
dtype=attn_metadata.attn_out_dtype,
|
||||
device=q.device,
|
||||
)
|
||||
rocm_aiter_ops.triton_sparse_mla_fwd(
|
||||
q[:num_actual_tokens],
|
||||
kv_c_and_k_pe_cache.view(-1, 1, 1, q.shape[-1]),
|
||||
output[:num_actual_tokens],
|
||||
self.scale,
|
||||
attn_metadata.paged_kv_indptr,
|
||||
attn_metadata.paged_kv_indices,
|
||||
kv_lora_rank=self.kv_lora_rank,
|
||||
qk_rope_head_dim=self.qk_rope_head_dim,
|
||||
q_scale=layer._q_scale,
|
||||
kv_scale=layer._k_scale,
|
||||
attn_sink=self.sinks,
|
||||
# triton_convert_req_index_to_global_index writes 0, never -1,
|
||||
# for an invalid top-k entry, so no slot in the stream is negative.
|
||||
has_invalid=False,
|
||||
)
|
||||
return output
|
||||
|
||||
def forward_mqa(
|
||||
self,
|
||||
q: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
||||
@@ -1026,6 +1092,11 @@ class ROCMAiterMLASparseImpl(
|
||||
original_q_shape = q.shape
|
||||
q, _ = ops.scaled_fp8_quant(q.view(q.shape[0], -1), layer._q_scale)
|
||||
q = q.view(original_q_shape)
|
||||
if self.use_aiter_sparse_mla:
|
||||
output = self._forward_mla_aiter(
|
||||
layer, q, kv_c_and_k_pe_cache, attn_metadata
|
||||
)
|
||||
return output, None
|
||||
mla_padded_q = AiterMLAHelper.get_mla_padded_q(self.num_heads, q)
|
||||
return self._forward_mla(
|
||||
layer, mla_padded_q, kv_c_and_k_pe_cache, attn_metadata
|
||||
|
||||
@@ -83,7 +83,8 @@ class RocmAiterUnifiedAttentionBackend(RocmAttentionBackend):
|
||||
|
||||
@classmethod
|
||||
def supports_mm_prefix(cls) -> bool:
|
||||
return True
|
||||
# Not implemented
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
|
||||
@@ -193,7 +193,8 @@ class RocmAttentionBackend(AttentionBackend):
|
||||
|
||||
@classmethod
|
||||
def supports_mm_prefix(cls) -> bool:
|
||||
return True
|
||||
# Not implemented
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
|
||||
@@ -18,7 +18,6 @@ from vllm.v1.attention.backends.mamba_attn import (
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import (
|
||||
NULL_BLOCK_ID,
|
||||
compute_causal_conv1d_metadata,
|
||||
mamba_get_block_table_tensor,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import MambaSpec
|
||||
@@ -108,6 +107,7 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
_cudagraph_support = AttentionCGSupport.UNIFORM_BATCH
|
||||
reorder_batch_threshold: int = 1
|
||||
supports_update_block_table = False
|
||||
needs_causal_conv1d_metadata = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -281,18 +281,10 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
spec_sequence_masks_cpu, device=query_start_loc.device
|
||||
)
|
||||
|
||||
# For causal_conv1d (non-spec prefill Triton kernel metadata).
|
||||
nums_dict = None
|
||||
batch_ptr = None
|
||||
token_chunk_offset_ptr = None
|
||||
has_initial_states_p = None
|
||||
has_initial_states_d = None
|
||||
num_computed_tokens_p = None
|
||||
# Original request indices of the non-spec requests, ordered
|
||||
# [decodes, prefills]. Used to gather per-request data consistently.
|
||||
non_spec_req_idx_cpu: torch.Tensor | None = None
|
||||
|
||||
query_lens = torch.diff(query_start_loc)
|
||||
# Per-request classification by mask, NOT by position. With
|
||||
# spec-decode, the front decode group can contain both spec-decode
|
||||
# requests and plain non-spec single-token decodes. Spec requests are
|
||||
@@ -317,37 +309,32 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
else 0
|
||||
)
|
||||
|
||||
# Original request indices grouped as
|
||||
# [spec | non-spec decode | non-spec prefill]; each group keeps the
|
||||
# original (already reordered) relative order via a stable nonzero.
|
||||
spec_req_idx_cpu = spec_sequence_masks_cpu.nonzero(as_tuple=True)[0]
|
||||
decode_req_idx_cpu = decode_mask_cpu.nonzero(as_tuple=True)[0]
|
||||
prefill_req_idx_cpu = prefill_mask_cpu.nonzero(as_tuple=True)[0]
|
||||
non_spec_req_idx_cpu = torch.cat((decode_req_idx_cpu, prefill_req_idx_cpu))
|
||||
spec_req_idx = async_tensor_h2d(spec_req_idx_cpu, device=query_start_loc.device)
|
||||
assert num_accepted_tokens is not None
|
||||
non_spec_req_idx: torch.Tensor | None = None
|
||||
|
||||
if num_decodes == 0 and num_prefills == 0:
|
||||
# Pure speculative-decode batch: all real tokens are spec tokens.
|
||||
spec_token_indx = torch.arange(
|
||||
num_spec_decode_tokens,
|
||||
dtype=torch.int32,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
non_spec_token_indx = torch.empty(
|
||||
0, dtype=torch.int32, device=query_start_loc.device
|
||||
)
|
||||
spec_state_indices_tensor = block_table_tensor[spec_req_idx, 0]
|
||||
# All real requests are speculative; zero-length padding is trailing.
|
||||
spec_token_indx = None
|
||||
non_spec_token_indx = None
|
||||
spec_state_indices_tensor = block_table_tensor[:num_spec_decodes, 0]
|
||||
num_accepted_tokens = num_accepted_tokens[:num_spec_decodes]
|
||||
non_spec_state_indices_tensor = None
|
||||
spec_query_start_loc = query_start_loc[: num_spec_decodes + 1]
|
||||
non_spec_query_start_loc = None
|
||||
non_spec_query_start_loc_cpu = None
|
||||
else:
|
||||
# Mixed batch: build a per-token group key consistent with the
|
||||
# request grouping above (spec=0 | decode=1 | prefill=2) and a
|
||||
# stable sort, so tokens of each request stay contiguous and in
|
||||
# request order. This yields spec tokens first, then the non-spec
|
||||
# [decode, prefill] tokens.
|
||||
query_lens = torch.diff(query_start_loc)
|
||||
spec_req_idx_cpu = spec_sequence_masks_cpu.nonzero(as_tuple=True)[0]
|
||||
decode_req_idx_cpu = decode_mask_cpu.nonzero(as_tuple=True)[0]
|
||||
prefill_req_idx_cpu = prefill_mask_cpu.nonzero(as_tuple=True)[0]
|
||||
non_spec_req_idx_cpu = torch.cat((decode_req_idx_cpu, prefill_req_idx_cpu))
|
||||
spec_req_idx = async_tensor_h2d(
|
||||
spec_req_idx_cpu, device=query_start_loc.device
|
||||
)
|
||||
non_spec_req_idx = async_tensor_h2d(
|
||||
non_spec_req_idx_cpu, device=query_start_loc.device
|
||||
)
|
||||
@@ -360,14 +347,17 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
dtype=torch.int64,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
req_group[spec_req_idx] = 0
|
||||
req_group[decode_req_idx] = 1
|
||||
token_group = torch.repeat_interleave(req_group, query_lens)
|
||||
req_group.index_fill_(0, spec_req_idx, 0)
|
||||
req_group.index_fill_(0, decode_req_idx, 1)
|
||||
token_group = torch.repeat_interleave(
|
||||
req_group, query_lens, output_size=int(query_start_loc_cpu[-1])
|
||||
)
|
||||
token_perm = torch.argsort(token_group, stable=True)
|
||||
spec_token_indx = token_perm[:num_spec_decode_tokens]
|
||||
non_spec_token_indx = token_perm[num_spec_decode_tokens:]
|
||||
|
||||
spec_state_indices_tensor = block_table_tensor[spec_req_idx, 0]
|
||||
num_accepted_tokens = num_accepted_tokens[spec_req_idx]
|
||||
non_spec_state_indices_tensor = block_table_tensor[non_spec_req_idx, 0]
|
||||
spec_query_start_loc = torch.zeros(
|
||||
num_spec_decodes + 1,
|
||||
@@ -385,22 +375,8 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
dim=0,
|
||||
out=non_spec_query_start_loc[1:],
|
||||
)
|
||||
non_spec_query_start_loc_cpu = torch.zeros(
|
||||
num_decodes + num_prefills + 1, dtype=torch.int32
|
||||
)
|
||||
torch.cumsum(
|
||||
query_lens_cpu[non_spec_req_idx_cpu],
|
||||
dim=0,
|
||||
out=non_spec_query_start_loc_cpu[1:],
|
||||
)
|
||||
|
||||
assert num_accepted_tokens is not None
|
||||
# Accepted-token counts must follow the same request order as the
|
||||
# speculative state indices.
|
||||
num_accepted_tokens = num_accepted_tokens[spec_req_idx]
|
||||
|
||||
# Compute the conv-state slots for the non-spec decode/prefill split,
|
||||
# plus the initial-state masks and Triton causal_conv1d metadata.
|
||||
# Compute the conv-state slots for the non-spec decode/prefill split.
|
||||
if non_spec_state_indices_tensor is None:
|
||||
state_indices_tensor = block_table_tensor[:0, 0]
|
||||
else:
|
||||
@@ -431,20 +407,9 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
]
|
||||
has_initial_states_p = num_computed_tokens_p > 0
|
||||
assert non_spec_query_start_loc is not None
|
||||
assert non_spec_query_start_loc_cpu is not None
|
||||
query_start_loc_p = (
|
||||
non_spec_query_start_loc[num_decodes:] - num_decode_tokens
|
||||
)
|
||||
query_start_loc_p_cpu = (
|
||||
non_spec_query_start_loc_cpu[num_decodes:] - num_decode_tokens
|
||||
)
|
||||
if query_start_loc.device.type != "cpu":
|
||||
nums_dict, batch_ptr, token_chunk_offset_ptr = (
|
||||
compute_causal_conv1d_metadata(
|
||||
query_start_loc_p_cpu,
|
||||
device=query_start_loc.device,
|
||||
)
|
||||
)
|
||||
|
||||
# Prepare persistent tensors for CUDA graph capture and replay.
|
||||
# ``m.num_actual_tokens`` is already padded by the model runner.
|
||||
@@ -509,9 +474,6 @@ class PleShortConvAttentionMetadataBuilder(ShortConvAttentionMetadataBuilder):
|
||||
non_spec_token_indx=non_spec_token_indx,
|
||||
num_accepted_tokens=num_accepted_tokens,
|
||||
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
|
||||
nums_dict=nums_dict,
|
||||
batch_ptr=batch_ptr,
|
||||
token_chunk_offset_ptr=token_chunk_offset_ptr,
|
||||
query_start_loc_p=query_start_loc_p,
|
||||
query_start_loc_d=query_start_loc_d,
|
||||
state_indices_tensor_p=state_indices_tensor_p,
|
||||
|
||||
@@ -2017,7 +2017,48 @@ def _validate_dsv4_sparse_dims(
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _pack_dense_prefix_to_ragged_kernel(
|
||||
def _count_valid_row_entries_kernel(
|
||||
indices_ptr,
|
||||
lengths_ptr,
|
||||
counts_ptr,
|
||||
indptr_ptr,
|
||||
indices_stride0,
|
||||
num_rows_limit,
|
||||
num_queries,
|
||||
row_width,
|
||||
BLOCK_R: tl.constexpr,
|
||||
BLOCK_W: tl.constexpr,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
# The scan fills indptr[1:], so write indptr[0] here and skip a zero fill.
|
||||
if pid == 0:
|
||||
tl.store(indptr_ptr, 0)
|
||||
|
||||
rows = pid * BLOCK_R + tl.arange(0, BLOCK_R)
|
||||
row_ok = rows < num_queries
|
||||
row_len = tl.load(lengths_ptr + rows, mask=row_ok, other=0)
|
||||
|
||||
acc = tl.zeros((BLOCK_R,), dtype=tl.int32)
|
||||
for start in range(0, row_width, BLOCK_W):
|
||||
cols = start + tl.arange(0, BLOCK_W)
|
||||
in_row = cols[None, :] < row_width
|
||||
vals = tl.load(
|
||||
indices_ptr + rows[:, None] * indices_stride0 + cols[None, :],
|
||||
mask=row_ok[:, None] & in_row,
|
||||
other=-1,
|
||||
).to(tl.int32)
|
||||
keep = (
|
||||
row_ok[:, None] & in_row & (cols[None, :] < row_len[:, None]) & (vals >= 0)
|
||||
)
|
||||
if num_rows_limit >= 0:
|
||||
keep = keep & (vals < num_rows_limit)
|
||||
acc += tl.sum(keep.to(tl.int32), axis=1)
|
||||
|
||||
tl.store(counts_ptr + rows, acc, mask=row_ok)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _compact_dense_row_to_ragged_kernel(
|
||||
indices_ptr,
|
||||
lengths_ptr,
|
||||
indptr_ptr,
|
||||
@@ -2025,28 +2066,25 @@ def _pack_dense_prefix_to_ragged_kernel(
|
||||
indices_stride0,
|
||||
num_rows_limit,
|
||||
row_width,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
BLOCK_W: tl.constexpr,
|
||||
):
|
||||
row_idx = tl.program_id(0)
|
||||
block_idx = tl.program_id(1)
|
||||
offsets = block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
|
||||
row_len = tl.load(lengths_ptr + row_idx)
|
||||
if block_idx * BLOCK_SIZE >= row_len:
|
||||
return
|
||||
|
||||
mask = offsets < row_len
|
||||
safe_offsets = tl.where(offsets < row_width, offsets, 0)
|
||||
vals = tl.load(
|
||||
indices_ptr + row_idx * indices_stride0 + safe_offsets,
|
||||
mask=mask & (offsets < row_width),
|
||||
other=-1,
|
||||
).to(tl.int32)
|
||||
if num_rows_limit >= 0:
|
||||
vals = tl.where((vals >= 0) & (vals < num_rows_limit), vals, -1)
|
||||
|
||||
out_start = tl.load(indptr_ptr + row_idx)
|
||||
tl.store(out_ptr + out_start + offsets, vals, mask=mask)
|
||||
|
||||
written = 0
|
||||
for start in range(0, row_width, BLOCK_W):
|
||||
cols = start + tl.arange(0, BLOCK_W)
|
||||
in_row = cols < row_width
|
||||
vals = tl.load(
|
||||
indices_ptr + row_idx * indices_stride0 + cols, mask=in_row, other=-1
|
||||
).to(tl.int32)
|
||||
keep = in_row & (cols < row_len) & (vals >= 0)
|
||||
if num_rows_limit >= 0:
|
||||
keep = keep & (vals < num_rows_limit)
|
||||
rank = tl.cumsum(keep.to(tl.int32), axis=0) - 1
|
||||
tl.store(out_ptr + out_start + written + rank, vals, mask=keep)
|
||||
written += tl.sum(keep.to(tl.int32), axis=0)
|
||||
|
||||
|
||||
def build_ragged_indices_from_dense(
|
||||
@@ -2061,10 +2099,40 @@ def build_ragged_indices_from_dense(
|
||||
)
|
||||
|
||||
max_width = indices.shape[1] if indices.ndim == 2 else 0
|
||||
lengths = lengths.clamp(min=0, max=max_width).contiguous()
|
||||
# Both kernels bound the row by row_width and row_len, so no clamp needed.
|
||||
lengths = lengths.contiguous()
|
||||
|
||||
indptr = torch.zeros(indices.shape[0] + 1, dtype=torch.int32, device=indices.device)
|
||||
torch.cumsum(lengths, dim=0, out=indptr[1:])
|
||||
# Dense rows reserve slots they may not fill, leaving -1 anywhere in the
|
||||
# first `lengths` entries. Keep only the valid ones, since the consumers
|
||||
# index the KV pool without checking the sign.
|
||||
num_queries = indices.shape[0]
|
||||
# max_width is whatever the caller packed (align(topk + window, 128) for the
|
||||
# V4.1 indexer) and nothing caps it, so loop the row rather than size the
|
||||
# block by it.
|
||||
block = min(triton.next_power_of_2(max_width), 1024) if max_width > 0 else 1
|
||||
counts = torch.empty(num_queries, dtype=torch.int32, device=indices.device)
|
||||
indptr = torch.empty(num_queries + 1, dtype=torch.int32, device=indices.device)
|
||||
if num_queries > 0 and max_width > 0:
|
||||
# A program per row only gets row_width elements, which is launch
|
||||
# bound for narrow rows. Tile rows to fill the block.
|
||||
block_r = max(1, 1024 // block)
|
||||
_count_valid_row_entries_kernel[(triton.cdiv(num_queries, block_r),)](
|
||||
indices,
|
||||
lengths,
|
||||
counts,
|
||||
indptr,
|
||||
indices.stride(0),
|
||||
int(num_rows),
|
||||
num_queries,
|
||||
max_width,
|
||||
BLOCK_R=block_r,
|
||||
BLOCK_W=block,
|
||||
)
|
||||
else:
|
||||
counts.zero_()
|
||||
indptr.zero_()
|
||||
|
||||
torch.cumsum(counts, dim=0, out=indptr[1:])
|
||||
|
||||
if indices.numel() == 0:
|
||||
flat = torch.empty(0, dtype=torch.int32, device=indices.device)
|
||||
@@ -2075,10 +2143,7 @@ def build_ragged_indices_from_dense(
|
||||
device=indices.device,
|
||||
)
|
||||
if flat.numel() > 0:
|
||||
block_size = 128
|
||||
_pack_dense_prefix_to_ragged_kernel[
|
||||
(indices.shape[0], triton.cdiv(max_width, block_size))
|
||||
](
|
||||
_compact_dense_row_to_ragged_kernel[(indices.shape[0],)](
|
||||
indices,
|
||||
lengths,
|
||||
indptr,
|
||||
@@ -2086,7 +2151,7 @@ def build_ragged_indices_from_dense(
|
||||
indices.stride(0),
|
||||
int(num_rows),
|
||||
max_width,
|
||||
BLOCK_SIZE=block_size,
|
||||
BLOCK_W=block,
|
||||
)
|
||||
|
||||
return flat, indptr
|
||||
@@ -4241,3 +4306,99 @@ def rocm_sparse_attn_decode(
|
||||
if direct_out is None:
|
||||
output.copy_(attn_out.to(output.dtype))
|
||||
return output.shape[0] if inv_rope_positions is not None else 0
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["token_offset"])
|
||||
def _prefill_topk_global_slots_kernel(
|
||||
out_ptr,
|
||||
lens_ptr,
|
||||
topk_ptr,
|
||||
topk_stride,
|
||||
token_to_req_ptr,
|
||||
query_start_loc_ptr,
|
||||
seq_lens_ptr,
|
||||
is_valid_token_ptr,
|
||||
block_table_ptr,
|
||||
block_table_stride,
|
||||
token_offset,
|
||||
num_compressed,
|
||||
TOPK: tl.constexpr,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
BLOCK_W: tl.constexpr,
|
||||
):
|
||||
row = tl.program_id(0)
|
||||
token = row + token_offset
|
||||
req = tl.load(token_to_req_ptr + token)
|
||||
query_start = tl.load(query_start_loc_ptr + req)
|
||||
query_len = tl.load(query_start_loc_ptr + req + 1) - query_start
|
||||
pos = tl.load(seq_lens_ptr + req) - query_len + token - query_start
|
||||
# Only (pos + 1) // ratio compressed tokens exist yet; the rest of the row
|
||||
# can hold stale indices.
|
||||
row_len = tl.minimum((pos + 1) // COMPRESS_RATIO, TOPK)
|
||||
row_len = tl.where(tl.load(is_valid_token_ptr + token), row_len, 0)
|
||||
|
||||
for start in range(0, TOPK, BLOCK_W):
|
||||
cols = start + tl.arange(0, BLOCK_W)
|
||||
live = cols < row_len
|
||||
local = tl.load(topk_ptr + row * topk_stride + cols, mask=live, other=-1)
|
||||
valid = live & (local >= 0) & (local < num_compressed)
|
||||
local = tl.where(valid, local, 0)
|
||||
block = tl.load(
|
||||
block_table_ptr + req * block_table_stride + local // BLOCK_SIZE,
|
||||
mask=valid,
|
||||
other=0,
|
||||
)
|
||||
slot = tl.where(valid, block * BLOCK_SIZE + local % BLOCK_SIZE, -1)
|
||||
tl.store(out_ptr + row * TOPK + cols, slot, mask=cols < TOPK)
|
||||
tl.store(lens_ptr + row, row_len)
|
||||
|
||||
|
||||
def build_prefill_topk_ragged_indices(
|
||||
topk_indices: torch.Tensor,
|
||||
token_to_req_indices: torch.Tensor,
|
||||
query_start_loc: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
is_valid_token: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
block_size: int,
|
||||
compress_ratio: int,
|
||||
num_compressed: int,
|
||||
token_offset: int,
|
||||
num_rows: int = -1,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Map prefill top-k rows to a ragged stream of compressed-cache slots.
|
||||
|
||||
``topk_indices`` holds local compressed positions for the prefill tokens,
|
||||
which sit at ``token_offset`` in the batch; ``token_to_req_indices``,
|
||||
``query_start_loc``, ``seq_lens`` and ``block_table`` are batch-wide.
|
||||
``block_size`` is the compressed cache's, i.e. already divided by the ratio.
|
||||
"""
|
||||
topk_indices = topk_indices.reshape(topk_indices.shape[0], -1)
|
||||
num_tokens, width = topk_indices.shape
|
||||
dense = torch.empty(
|
||||
(num_tokens, width), dtype=torch.int32, device=topk_indices.device
|
||||
)
|
||||
lens = torch.empty(num_tokens, dtype=torch.int32, device=topk_indices.device)
|
||||
if num_tokens > 0 and width > 0:
|
||||
_prefill_topk_global_slots_kernel[(num_tokens,)](
|
||||
dense,
|
||||
lens,
|
||||
topk_indices,
|
||||
topk_indices.stride(0),
|
||||
token_to_req_indices,
|
||||
query_start_loc,
|
||||
seq_lens,
|
||||
is_valid_token,
|
||||
block_table,
|
||||
block_table.stride(0),
|
||||
token_offset,
|
||||
num_compressed,
|
||||
TOPK=width,
|
||||
COMPRESS_RATIO=compress_ratio,
|
||||
BLOCK_SIZE=block_size,
|
||||
BLOCK_W=min(triton.next_power_of_2(width), 1024),
|
||||
)
|
||||
else:
|
||||
lens.zero_()
|
||||
return build_ragged_indices_from_dense(dense, lens, num_rows=num_rows)
|
||||
|
||||
@@ -58,6 +58,13 @@ def flash_attn_maxseqlen_wrapper(
|
||||
max_seqlen = max_seqlen.item()
|
||||
|
||||
q, k, v = (einops.rearrange(x, "b s ... -> (b s) ...") for x in [q, k, v])
|
||||
|
||||
if current_platform.is_cuda() and torch.cuda.is_current_stream_capturing():
|
||||
# workaround for encoder CUDA-graph replay paddings with NaNs edge case
|
||||
kwargs["out"] = torch.zeros(
|
||||
q.shape[0], q.shape[1], v.shape[-1], dtype=q.dtype, device=q.device
|
||||
)
|
||||
|
||||
output = flash_attn_varlen_func(
|
||||
q,
|
||||
k,
|
||||
|
||||
@@ -41,7 +41,7 @@ class RequestQueue(ABC):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def prepend_requests(self, requests: "RequestQueue") -> None:
|
||||
def prepend_requests(self, requests: Iterable[Request]) -> None:
|
||||
"""Prepend all requests from another queue to the front of this
|
||||
queue."""
|
||||
pass
|
||||
@@ -93,7 +93,7 @@ class FCFSRequestQueue(deque[Request], RequestQueue):
|
||||
"""Prepend a request to the front of the queue."""
|
||||
self.appendleft(request)
|
||||
|
||||
def prepend_requests(self, requests: RequestQueue) -> None:
|
||||
def prepend_requests(self, requests: Iterable[Request]) -> None:
|
||||
"""Prepend all requests from another queue to the front of this
|
||||
queue.
|
||||
|
||||
@@ -163,7 +163,7 @@ class PriorityRequestQueue(RequestQueue):
|
||||
front. Requests are ordered by (priority, arrival_time)."""
|
||||
self.add_request(request)
|
||||
|
||||
def prepend_requests(self, requests: RequestQueue) -> None:
|
||||
def prepend_requests(self, requests: Iterable[Request]) -> None:
|
||||
"""Add all requests from another queue according to priority policy.
|
||||
|
||||
Note: In a priority queue, there is no concept of prepending to the
|
||||
|
||||
+118
-99
@@ -210,8 +210,13 @@ class Scheduler(SchedulerInterface):
|
||||
) from e
|
||||
# Priority queues for requests.
|
||||
self.waiting = create_request_queue(self.policy)
|
||||
# requests skipped in waiting flow due async deps or constraints.
|
||||
self.skipped_waiting = create_request_queue(self.policy)
|
||||
# Waiting requests that hold KV blocks are always drained before
|
||||
# self.waiting: a block-holder must never sit behind a request whose
|
||||
# failed allocation would stop the scheduling scan.
|
||||
self.kv_holding_waiting = create_request_queue(self.policy)
|
||||
# Waiting requests that are deferred, i.e. were skipped by the scheduling
|
||||
# scan or enqueued in a blocked status.
|
||||
self.deferred_waiting: set[Request] = set()
|
||||
self.running: list[Request] = []
|
||||
|
||||
# The request IDs that are finished in between the previous and the
|
||||
@@ -606,9 +611,8 @@ class Scheduler(SchedulerInterface):
|
||||
# `long_prefill_token_threshold` exists to stop a long prefill from
|
||||
# starving other requests of the token budget. When it is the only
|
||||
# request there is nobody to starve, so let it use the whole budget.
|
||||
num_eligible_reqs = (
|
||||
len(self.running) + len(self.waiting) + len(self.skipped_waiting)
|
||||
)
|
||||
num_running, num_waiting = self.get_request_counts()
|
||||
num_eligible_reqs = num_running + num_waiting
|
||||
long_prefill_token_threshold = (
|
||||
self.scheduler_config.long_prefill_token_threshold
|
||||
if num_eligible_reqs > 1
|
||||
@@ -867,10 +871,21 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
# Next, schedule the WAITING requests.
|
||||
if not preempted_reqs and self._pause_state == PauseState.UNPAUSED:
|
||||
step_skipped_waiting = create_request_queue(self.policy)
|
||||
step_skipped_waiting: deque[Request] = deque()
|
||||
step_skipped_kv_holding: deque[Request] = deque()
|
||||
|
||||
while (self.waiting or self.skipped_waiting) and token_budget > 0:
|
||||
if input_budget <= draft_slots:
|
||||
def skip_request(from_queue: RequestQueue) -> None:
|
||||
request_to_skip = from_queue.pop_request()
|
||||
self.deferred_waiting.add(request_to_skip)
|
||||
if self._holds_kv_blocks(request_to_skip):
|
||||
step_skipped_kv_holding.appendleft(request_to_skip)
|
||||
else:
|
||||
step_skipped_waiting.appendleft(request_to_skip)
|
||||
|
||||
while token_budget > 0:
|
||||
# Requests holding KV blocks are always drained first.
|
||||
request_queue = self.kv_holding_waiting or self.waiting
|
||||
if not request_queue or input_budget <= draft_slots:
|
||||
break
|
||||
# Paused streaming sessions (WAITING_FOR_STREAMING_REQ) are not
|
||||
# in `running` but still hold a model-runner request slot.
|
||||
@@ -878,38 +893,22 @@ class Scheduler(SchedulerInterface):
|
||||
if num_running >= self.max_num_active_reqs:
|
||||
break
|
||||
|
||||
request_queue = self._select_waiting_queue_for_scheduling()
|
||||
assert request_queue is not None
|
||||
|
||||
request = request_queue.peek_request()
|
||||
request_id = request.request_id
|
||||
|
||||
# try to promote blocked statuses while traversing skipped queue.
|
||||
if self._is_blocked_waiting_status(
|
||||
request.status
|
||||
) and not self._try_promote_blocked_waiting_request(request):
|
||||
if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
|
||||
logger.debug(
|
||||
"%s is still in WAITING_FOR_REMOTE_KVS state.",
|
||||
request_id,
|
||||
)
|
||||
request_queue.pop_request()
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
ready_to_schedule = self._handle_blocked_waiting_request(request)
|
||||
if not ready_to_schedule:
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
if (
|
||||
request.num_stale_output_tokens > 0
|
||||
and not request.drop_stale_output
|
||||
):
|
||||
if request.num_stale_output_tokens and not request.drop_stale_output:
|
||||
# Deliverable stale output still in flight: resuming now
|
||||
# could resample a position that output later delivers.
|
||||
# It drains within the pipeline depth.
|
||||
request_queue.pop_request()
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
# Check that adding the request still respects the max_loras
|
||||
# constraint.
|
||||
# Check that adding the request still respects the max_loras constraint.
|
||||
if (
|
||||
self.lora_config
|
||||
and request.lora_request
|
||||
@@ -919,8 +918,7 @@ class Scheduler(SchedulerInterface):
|
||||
)
|
||||
):
|
||||
# Scheduling would exceed max_loras, skip.
|
||||
request_queue.pop_request()
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
num_external_computed_tokens = 0
|
||||
@@ -959,8 +957,7 @@ class Scheduler(SchedulerInterface):
|
||||
# The request cannot be scheduled because
|
||||
# the KVConnector couldn't determine
|
||||
# the number of matched tokens.
|
||||
request_queue.pop_request()
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
if self.prefix_replay_tokens:
|
||||
@@ -1030,8 +1027,7 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
# Skip request with pending mm encoding prefetches
|
||||
if self._ec_transfer_pending(request, num_computed_tokens):
|
||||
request_queue.pop_request()
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
# Track first scheduled prefill, not post-preemption repeat prefills
|
||||
@@ -1052,8 +1048,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_computed_tokens = request.num_computed_tokens
|
||||
|
||||
if self._ec_transfer_pending(request, num_computed_tokens):
|
||||
request_queue.pop_request()
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
encoder_inputs_to_schedule = None
|
||||
@@ -1260,12 +1255,10 @@ class Scheduler(SchedulerInterface):
|
||||
request, num_new_local_computed_tokens
|
||||
)
|
||||
|
||||
request = request_queue.pop_request()
|
||||
if load_kv_async:
|
||||
# If loading async, allocate memory and put request
|
||||
# into the WAITING_FOR_REMOTE_KV state.
|
||||
request.status = RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
step_skipped_waiting.prepend_request(request)
|
||||
# Set num_computed_tokens even though KVs are not yet loaded.
|
||||
# request.num_computed_tokens will not be used anywhere until
|
||||
# the request finished the KV transfer.
|
||||
@@ -1286,13 +1279,16 @@ class Scheduler(SchedulerInterface):
|
||||
# overwrite; the zeroing could race the write.
|
||||
self._skip_zero_block_ids.update(
|
||||
self.kv_cache_manager.get_zeroing_block_ids_in_range(
|
||||
request.request_id,
|
||||
request_id,
|
||||
num_new_local_computed_tokens,
|
||||
num_computed_tokens,
|
||||
)
|
||||
)
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
request = request_queue.pop_request()
|
||||
self.deferred_waiting.discard(request)
|
||||
self.running.append(request)
|
||||
if num_external_computed_tokens > 0:
|
||||
# load_kv_async is False here
|
||||
@@ -1343,13 +1339,16 @@ class Scheduler(SchedulerInterface):
|
||||
self.ec_connector.update_state_after_alloc(request, i)
|
||||
|
||||
# re-queue requests skipped in this pass ahead of older skipped items.
|
||||
if step_skipped_kv_holding:
|
||||
self.kv_holding_waiting.prepend_requests(step_skipped_kv_holding)
|
||||
if step_skipped_waiting:
|
||||
self.skipped_waiting.prepend_requests(step_skipped_waiting)
|
||||
self.waiting.prepend_requests(step_skipped_waiting)
|
||||
|
||||
# DP prefill balancing: on a step that admitted prefills (release),
|
||||
# record whether it was capacity-bound.
|
||||
if not defer_prefills:
|
||||
self.prefill_capacity_bound = bool(self.waiting)
|
||||
_, num_waiting = self.get_request_counts()
|
||||
self.prefill_capacity_bound = num_waiting > len(self.deferred_waiting)
|
||||
|
||||
# Check if the scheduling constraints are satisfied.
|
||||
total_num_scheduled_tokens = sum(num_scheduled_tokens.values())
|
||||
@@ -1649,6 +1648,7 @@ class Scheduler(SchedulerInterface):
|
||||
session.num_prompt_tokens = len(session.prompt_token_ids)
|
||||
session.arrival_time = update.arrival_time
|
||||
session.sampling_params = update.sampling_params
|
||||
session.max_tokens = update.max_tokens
|
||||
if session.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
|
||||
self.num_waiting_for_streaming_input -= 1
|
||||
session.status = RequestStatus.WAITING
|
||||
@@ -1972,6 +1972,9 @@ class Scheduler(SchedulerInterface):
|
||||
sampled_token_ids = model_runner_output.sampled_token_ids
|
||||
logprobs = model_runner_output.logprobs
|
||||
prompt_logprobs_dict = model_runner_output.prompt_logprobs_dict
|
||||
prompt_token_id_logprobs_dict = (
|
||||
model_runner_output.prompt_token_id_logprobs_dict
|
||||
)
|
||||
num_scheduled_tokens = scheduler_output.num_scheduled_tokens
|
||||
pooler_outputs = model_runner_output.pooler_output
|
||||
num_nans_in_logits = model_runner_output.num_nans_in_logits
|
||||
@@ -2149,6 +2152,15 @@ class Scheduler(SchedulerInterface):
|
||||
self.kv_cache_manager.estimate_cached_tokens(request)
|
||||
)
|
||||
|
||||
# Extract sample logprobs before stop handling can replace the
|
||||
# sampling parameters for a streaming continuation.
|
||||
if (
|
||||
request.sampling_params is not None
|
||||
and request.sampling_params.num_logprobs is not None
|
||||
and logprobs
|
||||
):
|
||||
new_logprobs = logprobs.slice_request(req_index, len(new_token_ids))
|
||||
|
||||
finish_reason = None
|
||||
if stopped:
|
||||
# Capture finish_reason BEFORE _handle_stopped_request, which may
|
||||
@@ -2174,14 +2186,6 @@ class Scheduler(SchedulerInterface):
|
||||
else:
|
||||
stopped_preempted_reqs.add(request)
|
||||
|
||||
# Extract sample logprobs if needed.
|
||||
if (
|
||||
request.sampling_params is not None
|
||||
and request.sampling_params.num_logprobs is not None
|
||||
and logprobs
|
||||
):
|
||||
new_logprobs = logprobs.slice_request(req_index, len(new_token_ids))
|
||||
|
||||
if self.return_sampling_mask:
|
||||
sampling_masks = model_runner_output.sampling_masks
|
||||
if new_token_ids and sampling_masks is not None:
|
||||
@@ -2194,6 +2198,7 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
# Get prompt logprobs for this request.
|
||||
prompt_logprobs_tensors = prompt_logprobs_dict.get(req_id)
|
||||
prompt_token_id_logprobs = prompt_token_id_logprobs_dict.get(req_id)
|
||||
if should_emit_output:
|
||||
# Add EngineCoreOutput for this Request.
|
||||
outputs[request.client_index].append(
|
||||
@@ -2204,6 +2209,7 @@ class Scheduler(SchedulerInterface):
|
||||
new_logprobs=new_logprobs,
|
||||
new_sampling_mask=new_sampling_mask,
|
||||
new_prompt_logprobs_tensors=prompt_logprobs_tensors,
|
||||
prompt_token_id_logprobs=prompt_token_id_logprobs,
|
||||
pooling_output=pooler_output,
|
||||
stop_reason=request.stop_reason,
|
||||
events=request.take_events(),
|
||||
@@ -2223,6 +2229,7 @@ class Scheduler(SchedulerInterface):
|
||||
else:
|
||||
# Invariant: EngineCore returns no partial prefill outputs.
|
||||
assert not prompt_logprobs_tensors
|
||||
assert prompt_token_id_logprobs is None
|
||||
|
||||
# Remove the stopped requests from the running and waiting queues.
|
||||
if stopped_running_reqs:
|
||||
@@ -2230,7 +2237,8 @@ class Scheduler(SchedulerInterface):
|
||||
if stopped_preempted_reqs:
|
||||
# This is a rare case and unlikely to impact performance.
|
||||
self.waiting.remove_requests(stopped_preempted_reqs)
|
||||
self.skipped_waiting.remove_requests(stopped_preempted_reqs)
|
||||
self.kv_holding_waiting.remove_requests(stopped_preempted_reqs)
|
||||
self.deferred_waiting.difference_update(stopped_preempted_reqs)
|
||||
|
||||
error_req_ids = set(self.grammar_compile_error_reqs)
|
||||
self.grammar_compile_error_reqs.clear()
|
||||
@@ -2374,29 +2382,42 @@ class Scheduler(SchedulerInterface):
|
||||
RequestStatus.WAITING_FOR_STREAMING_REQ,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _holds_kv_blocks(request: Request) -> bool:
|
||||
# Whether a request currently has kv blocks allocated.
|
||||
# While always the case when status is WAITING_FOR_REMOTE_KVS
|
||||
# or WAITING_FOR_STREAMING_REQ, there are such cases where it's
|
||||
# WAITING or PREEMPTED.
|
||||
return (
|
||||
request.num_computed_tokens > 0
|
||||
# num_computed_tokens is reset to 0 if kv transfer fails for requests in
|
||||
# WAITING_FOR_REMOTE_KVS state, before their allocated blocks are freed.
|
||||
or request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
)
|
||||
|
||||
def _enqueue_waiting_request(self, request: Request) -> None:
|
||||
if self._is_blocked_waiting_status(request.status):
|
||||
self.skipped_waiting.add_request(request)
|
||||
self.deferred_waiting.add(request)
|
||||
if self._holds_kv_blocks(request):
|
||||
self.kv_holding_waiting.add_request(request)
|
||||
else:
|
||||
self.waiting.add_request(request)
|
||||
|
||||
def _select_waiting_queue_for_scheduling(self) -> RequestQueue | None:
|
||||
if self.policy == SchedulingPolicy.FCFS:
|
||||
return self.skipped_waiting or self.waiting or None
|
||||
|
||||
# PRIORITY mode: compare queue heads when both queues are non-empty.
|
||||
if self.waiting and self.skipped_waiting:
|
||||
waiting_req = self.waiting.peek_request()
|
||||
skipped_req = self.skipped_waiting.peek_request()
|
||||
return self.waiting if waiting_req < skipped_req else self.skipped_waiting
|
||||
|
||||
return self.waiting or self.skipped_waiting or None
|
||||
|
||||
def _handle_stopped_request(self, request: Request) -> bool:
|
||||
"""Return True if finished (can be False for resumable requests)."""
|
||||
if not request.resumable:
|
||||
return True
|
||||
|
||||
# Drop the finished turn's in-flight work and resume from the
|
||||
# materialized frontier.
|
||||
safe_frontier = request.num_computed_tokens - request.num_output_placeholders
|
||||
assert safe_frontier >= 0
|
||||
request.num_computed_tokens = safe_frontier
|
||||
request.spec_token_ids = []
|
||||
request.drop_stale_output = True
|
||||
request.num_stale_output_tokens = request.num_in_flight_tokens
|
||||
request.num_output_placeholders = 0
|
||||
|
||||
if request.streaming_queue:
|
||||
update = request.streaming_queue.popleft()
|
||||
if update is None:
|
||||
@@ -2527,7 +2548,7 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
def get_request_counts(self) -> tuple[int, int]:
|
||||
"""Returns (num_running_reqs, num_waiting_reqs)."""
|
||||
return len(self.running), len(self.waiting) + len(self.skipped_waiting)
|
||||
return len(self.running), len(self.waiting) + len(self.kv_holding_waiting)
|
||||
|
||||
def get_kv_cache_usage(self) -> float:
|
||||
"""Returns the fraction of the KV cache currently in use (0.0-1.0)."""
|
||||
@@ -2608,7 +2629,8 @@ class Scheduler(SchedulerInterface):
|
||||
self.running = remove_all(self.running, running_requests_to_remove)
|
||||
if waiting_requests_to_remove:
|
||||
self.waiting.remove_requests(waiting_requests_to_remove)
|
||||
self.skipped_waiting.remove_requests(waiting_requests_to_remove)
|
||||
self.kv_holding_waiting.remove_requests(waiting_requests_to_remove)
|
||||
self.deferred_waiting.difference_update(waiting_requests_to_remove)
|
||||
|
||||
# Second pass: set status and free requests
|
||||
for request in valid_requests:
|
||||
@@ -2716,14 +2738,11 @@ class Scheduler(SchedulerInterface):
|
||||
def get_num_unfinished_requests(self) -> int:
|
||||
if self._pause_state == PauseState.PAUSED_ALL:
|
||||
return 0
|
||||
num_running, num_waiting = self.get_request_counts()
|
||||
if self._pause_state == PauseState.PAUSED_NEW:
|
||||
return len(self.running)
|
||||
num_waiting = (
|
||||
len(self.waiting)
|
||||
+ len(self.skipped_waiting)
|
||||
- self.num_waiting_for_streaming_input
|
||||
)
|
||||
return num_waiting + len(self.running)
|
||||
return num_running
|
||||
num_waiting -= self.num_waiting_for_streaming_input
|
||||
return num_waiting + num_running
|
||||
|
||||
def has_finished_requests(self) -> bool:
|
||||
if self.finished_req_ids:
|
||||
@@ -2732,10 +2751,8 @@ class Scheduler(SchedulerInterface):
|
||||
return False
|
||||
# Finished requests waiting on delayed connector cleanup remain in
|
||||
# self.requests after they have been removed from scheduling queues.
|
||||
num_in_queues = (
|
||||
len(self.waiting) + len(self.skipped_waiting) + len(self.running)
|
||||
)
|
||||
return len(self.requests) > num_in_queues
|
||||
num_running, num_waiting = self.get_request_counts()
|
||||
return len(self.requests) > (num_running + num_waiting)
|
||||
|
||||
def has_requests(self) -> bool:
|
||||
# Override the interface default to also keep the engine alive while a
|
||||
@@ -2867,10 +2884,12 @@ class Scheduler(SchedulerInterface):
|
||||
ec_connector_stats_payload = (
|
||||
ec_connector_stats.data if ec_connector_stats else None
|
||||
)
|
||||
num_running, num_waiting = self.get_request_counts()
|
||||
num_deferred = len(self.deferred_waiting)
|
||||
return SchedulerStats(
|
||||
num_running_reqs=len(self.running),
|
||||
num_waiting_reqs=len(self.waiting),
|
||||
num_skipped_waiting_reqs=len(self.skipped_waiting),
|
||||
num_running_reqs=num_running,
|
||||
num_waiting_reqs=num_waiting - num_deferred,
|
||||
num_skipped_waiting_reqs=num_deferred,
|
||||
kv_cache_usage=self.kv_cache_manager.usage,
|
||||
prefix_cache_stats=prefix_cache_stats,
|
||||
connector_prefix_cache_stats=connector_prefix_cache_stats,
|
||||
@@ -3076,39 +3095,39 @@ class Scheduler(SchedulerInterface):
|
||||
request.num_computed_tokens = request.num_tokens - 1
|
||||
self.finished_recving_kv_req_ids.remove(request.request_id)
|
||||
|
||||
def _try_promote_blocked_waiting_request(self, request: Request) -> bool:
|
||||
"""Try to promote a blocked waiting request back to schedulable states."""
|
||||
def _handle_blocked_waiting_request(self, request: Request) -> bool:
|
||||
"""Returns True if scheduling of this request should proceed, False if
|
||||
it should be skipped for this step."""
|
||||
if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
|
||||
# finished_recving_kv_req_ids is populated during
|
||||
# update_from_output(), based on worker-side connector signals
|
||||
# in KVConnectorOutput.finished_recving
|
||||
if request.request_id not in self.finished_recving_kv_req_ids:
|
||||
# Check whether async loading requests are finished.
|
||||
request_id = request.request_id
|
||||
if request_id not in self.finished_recving_kv_req_ids:
|
||||
logger.debug("%s is still in WAITING_FOR_REMOTE_KVS state.", request_id)
|
||||
return False
|
||||
# Promote request to waiting or preempted.
|
||||
self._update_waiting_for_remote_kv(request)
|
||||
if request.num_preemptions:
|
||||
request.status = RequestStatus.PREEMPTED
|
||||
else:
|
||||
request.status = RequestStatus.WAITING
|
||||
return True
|
||||
|
||||
if request.status == RequestStatus.WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR:
|
||||
structured_output_req = request.structured_output_request
|
||||
if not structured_output_req or structured_output_req.grammar is None:
|
||||
elif request.status == RequestStatus.WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR:
|
||||
# Check whether grammar compilation has finished.
|
||||
struct_output_req = request.structured_output_request
|
||||
if not struct_output_req or struct_output_req.grammar is None:
|
||||
return False
|
||||
if isinstance(structured_output_req.grammar, Exception):
|
||||
if isinstance(struct_output_req.grammar, Exception):
|
||||
self.grammar_compile_error_reqs.add(request.request_id)
|
||||
return False
|
||||
# Grammar is ready, promote to waiting state.
|
||||
request.status = RequestStatus.WAITING
|
||||
return True
|
||||
|
||||
if request.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
|
||||
elif request.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
|
||||
# Streaming input request waiting for more input.
|
||||
assert not request.streaming_queue
|
||||
return False
|
||||
|
||||
raise AssertionError(
|
||||
"Unexpected blocked waiting status in promotion: "
|
||||
f"{request.status.name} for request {request.request_id}"
|
||||
)
|
||||
return True
|
||||
|
||||
def _update_from_kv_xfer_finished(self, kv_connector_output: KVConnectorOutput):
|
||||
"""KV Connector: update the scheduler state based on the output.
|
||||
@@ -3281,7 +3300,7 @@ class Scheduler(SchedulerInterface):
|
||||
# handle async KV loads (not cached yet, evict_blocks=False)
|
||||
async_load_reqs = (
|
||||
req
|
||||
for req in self.skipped_waiting
|
||||
for req in self.kv_holding_waiting
|
||||
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS
|
||||
)
|
||||
async_failed_req_ids, num_failed_tokens, _ = (
|
||||
|
||||
@@ -236,6 +236,9 @@ class EngineCoreOutput(
|
||||
# Appended last so `array_like` positional serialization stays compatible.
|
||||
spec_decode_metrics: RequestSpecDecodeMetrics | None = None
|
||||
|
||||
# [num_scored_rows, num_token_ids]; appended last for array_like compatibility.
|
||||
prompt_token_id_logprobs: torch.Tensor | None = None
|
||||
|
||||
@property
|
||||
def finished(self) -> bool:
|
||||
return self.finish_reason is not None
|
||||
|
||||
@@ -1587,6 +1587,10 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
) // client_count
|
||||
|
||||
def get_core_engine_for_request(self, request: EngineCoreRequest) -> EngineIdentity:
|
||||
if (engine := self.reqs_in_flight.get(request.request_id)) is not None:
|
||||
# This is for streaming-input session affinity.
|
||||
return engine
|
||||
|
||||
# Engines are in rank order.
|
||||
if (eng_index := request.data_parallel_rank) is None and (
|
||||
eng_index := get_late_interaction_engine_index(
|
||||
@@ -1889,13 +1893,29 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
await asyncio.to_thread(self._coord_store.wait, ready_keys)
|
||||
logger.info("[Elastic EP] Successfully started new engines")
|
||||
|
||||
def _eep_commit_pause_mode(self) -> PauseMode:
|
||||
from vllm.distributed.elastic_ep.elastic_execute import (
|
||||
can_reuse_fused_moe_kernel,
|
||||
)
|
||||
|
||||
# MRV2 re-warms through the request pool, so running requests must
|
||||
# finish first while new ones stay queued in the scheduler.
|
||||
parallel_config = self.vllm_config.parallel_config
|
||||
if self.vllm_config.use_v2_model_runner and not can_reuse_fused_moe_kernel(
|
||||
parallel_config
|
||||
):
|
||||
return "wait"
|
||||
return "keep"
|
||||
|
||||
async def _commit_scale_up_elastic_ep(self, new_data_parallel_size: int) -> None:
|
||||
new_core_engines = [
|
||||
rank.to_bytes(2, "little")
|
||||
for rank in range(len(self.core_engines), new_data_parallel_size)
|
||||
]
|
||||
|
||||
await self.pause_scheduler_async(mode="keep", clear_cache=False)
|
||||
await self.pause_scheduler_async(
|
||||
mode=self._eep_commit_pause_mode(), clear_cache=False
|
||||
)
|
||||
wait_future = self._eep_wait_for_setup_switch_complete()
|
||||
finish_futures = [
|
||||
asyncio.create_task(
|
||||
@@ -1967,7 +1987,8 @@ class DPLBAsyncMPClient(DPAsyncMPClient):
|
||||
for rank in range(new_data_parallel_size, cur_data_parallel_size):
|
||||
self._kv_event_sources.pop(rank, None)
|
||||
removed_dp_size = cur_data_parallel_size - new_data_parallel_size
|
||||
pause_modes = ["keep"] * new_data_parallel_size + ["abort"] * removed_dp_size
|
||||
eep_mode = self._eep_commit_pause_mode()
|
||||
pause_modes = [eep_mode] * new_data_parallel_size + ["abort"] * removed_dp_size
|
||||
pause_futures = [
|
||||
self._call_utility_async("pause_scheduler", mode, False, engine=engine)
|
||||
for mode, engine in zip(pause_modes, old_core_engines)
|
||||
|
||||
@@ -131,6 +131,19 @@ class InputProcessor:
|
||||
self.structured_outputs_config,
|
||||
self.tokenizer,
|
||||
)
|
||||
if params.prompt_logprob_token_ids is not None:
|
||||
if not self.vllm_config.use_v2_model_runner:
|
||||
raise VLLMValidationError(
|
||||
"prompt_logprob_token_ids requires the V2 model runner "
|
||||
"(VLLM_USE_V2_MODEL_RUNNER=1).",
|
||||
parameter="prompt_logprob_token_ids",
|
||||
)
|
||||
if self.vllm_config.cache_config.kv_sharing_fast_prefill:
|
||||
raise VLLMValidationError(
|
||||
"prompt_logprob_token_ids is incorrect with "
|
||||
"--kv-sharing-fast-prefill; disable it for scoring.",
|
||||
parameter="prompt_logprob_token_ids",
|
||||
)
|
||||
|
||||
self.validate_logits_processors_params(params)
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import itertools
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.logprobs import (
|
||||
FlatLogprobs,
|
||||
@@ -38,6 +40,8 @@ class LogprobsProcessor:
|
||||
cumulative_logprob: float | None
|
||||
num_logprobs: int | None
|
||||
num_prompt_logprobs: int | None
|
||||
# [num_scored_rows, num_token_ids], set once on the final prefill chunk.
|
||||
prompt_token_id_logprobs: np.ndarray | None = None
|
||||
|
||||
@classmethod
|
||||
def from_new_request(
|
||||
@@ -204,6 +208,12 @@ class LogprobsProcessor:
|
||||
self.prompt_logprobs = []
|
||||
return plp
|
||||
|
||||
def pop_prompt_token_id_logprobs(self) -> np.ndarray | None:
|
||||
"""Pop and return the fixed-ID prompt scores."""
|
||||
scores = self.prompt_token_id_logprobs
|
||||
self.prompt_token_id_logprobs = None
|
||||
return scores
|
||||
|
||||
@staticmethod
|
||||
def _get_sampled_context_ids(
|
||||
logprobs_source: SampleLogprobs | PromptLogprobs | None,
|
||||
@@ -352,3 +362,5 @@ class LogprobsProcessor:
|
||||
self._update_sample_logprobs(output.new_logprobs)
|
||||
if output.new_prompt_logprobs_tensors is not None:
|
||||
self._update_prompt_logprobs(output.new_prompt_logprobs_tensors)
|
||||
if output.prompt_token_id_logprobs is not None:
|
||||
self.prompt_token_id_logprobs = output.prompt_token_id_logprobs.numpy()
|
||||
|
||||
@@ -390,8 +390,12 @@ class RequestState:
|
||||
if self.output_kind == RequestOutputKind.DELTA:
|
||||
# Side effect: logprobs processor forgets prompt logprobs
|
||||
prompt_logprobs = self.logprobs_processor.pop_prompt_logprobs()
|
||||
prompt_token_id_logprobs = (
|
||||
self.logprobs_processor.pop_prompt_token_id_logprobs()
|
||||
)
|
||||
else:
|
||||
prompt_logprobs = self.logprobs_processor.prompt_logprobs
|
||||
prompt_token_id_logprobs = self.logprobs_processor.prompt_token_id_logprobs
|
||||
|
||||
return RequestOutput(
|
||||
request_id=external_req_id, # request_id is what was provided externally
|
||||
@@ -399,6 +403,7 @@ class RequestState:
|
||||
prompt=self.prompt,
|
||||
prompt_token_ids=prompt_token_ids,
|
||||
prompt_logprobs=prompt_logprobs,
|
||||
prompt_token_id_logprobs=prompt_token_id_logprobs,
|
||||
outputs=cast(list[CompletionOutput], outputs),
|
||||
finished=finished,
|
||||
kv_transfer_params=kv_transfer_params,
|
||||
|
||||
@@ -9,7 +9,6 @@ from typing import TYPE_CHECKING
|
||||
|
||||
import msgspec
|
||||
|
||||
from vllm.config import set_current_vllm_config
|
||||
from vllm.distributed import stateless_destroy_torch_distributed_process_group
|
||||
from vllm.distributed.utils import stateless_init_torch_distributed_process_group
|
||||
from vllm.logger import init_logger
|
||||
@@ -123,8 +122,7 @@ class EngineCoreSentinel:
|
||||
engine = self.engine
|
||||
executor = engine.model_executor
|
||||
|
||||
with set_current_vllm_config(engine.vllm_config):
|
||||
ft_request.params.update(self._reinit_dp_group())
|
||||
ft_request.params.update(self._reinit_dp_group())
|
||||
if hasattr(engine, "step_counter"):
|
||||
engine.step_counter = 0
|
||||
|
||||
@@ -165,6 +163,7 @@ class EngineCoreSentinel:
|
||||
parallel_config.data_parallel_size,
|
||||
backend="gloo",
|
||||
return_store=True,
|
||||
timeout=parallel_config.cpu_distributed_timeout,
|
||||
)
|
||||
)
|
||||
return {"new_stateless_dp_group_ports": worker_ports}
|
||||
|
||||
@@ -188,8 +188,9 @@ class SchedulerStats:
|
||||
|
||||
num_running_reqs: int = 0
|
||||
|
||||
num_waiting_reqs: int = 0 # length of the "waiting" request queue
|
||||
num_skipped_waiting_reqs: int = 0 # length of the "skipped waiting" queue
|
||||
num_waiting_reqs: int = 0 # waiting requests not deferred
|
||||
# waiting requests deferred by transient constraints or a blocked status
|
||||
num_skipped_waiting_reqs: int = 0
|
||||
|
||||
# These are used for internal DP load-balancing.
|
||||
step_counter: int = 0
|
||||
|
||||
@@ -283,6 +283,9 @@ class ModelRunnerOutput:
|
||||
default_factory=dict
|
||||
)
|
||||
|
||||
# req_id -> [num_scored_rows, num_token_ids] prompt_logprob_token_ids scores.
|
||||
prompt_token_id_logprobs_dict: dict[str, torch.Tensor] = field(default_factory=dict)
|
||||
|
||||
# [num_reqs, hidden_size]
|
||||
pooler_output: list[torch.Tensor | None] | None = None
|
||||
|
||||
|
||||
@@ -38,6 +38,10 @@ class XgrammarBackend(StructuredOutputBackend):
|
||||
self.disable_any_whitespace = (
|
||||
self.vllm_config.structured_outputs_config.disable_any_whitespace
|
||||
)
|
||||
model_config = self.vllm_config.model_config
|
||||
is_plamo3 = (
|
||||
model_config is not None and model_config.hf_config.model_type == "plamo3"
|
||||
)
|
||||
|
||||
if is_mistral_tokenizer(self.tokenizer):
|
||||
# NOTE: ideally, xgrammar should handle this accordingly.
|
||||
@@ -57,6 +61,10 @@ class XgrammarBackend(StructuredOutputBackend):
|
||||
stop_token_ids=stop_token_ids,
|
||||
add_prefix_space=True,
|
||||
)
|
||||
elif is_plamo3 and callable(
|
||||
init_xgrammar := getattr(self.tokenizer, "init_xgrammar", None)
|
||||
):
|
||||
tokenizer_info, _ = init_xgrammar()
|
||||
else:
|
||||
tokenizer_info = xgr.TokenizerInfo.from_huggingface(
|
||||
self.tokenizer,
|
||||
|
||||
@@ -156,6 +156,10 @@ class AsyncOutput(AsyncModelRunnerOutput):
|
||||
k: v.to_cpu_nonblocking() if v is not None else None
|
||||
for k, v in self.model_runner_output.prompt_logprobs_dict.items()
|
||||
}
|
||||
token_id_logprobs = self.model_runner_output.prompt_token_id_logprobs_dict
|
||||
self.prompt_token_id_logprobs_dict = {
|
||||
k: v.to("cpu", non_blocking=True) for k, v in token_id_logprobs.items()
|
||||
}
|
||||
if self.pending_aux_output is not None:
|
||||
self.pending_aux_output.enqueue_cpu_copy(
|
||||
num_sampled=self.num_sampled_tokens_np,
|
||||
@@ -194,6 +198,9 @@ class AsyncOutput(AsyncModelRunnerOutput):
|
||||
if self.logprobs_tensors is not None:
|
||||
self.model_runner_output.logprobs = self.logprobs_tensors.tolists()
|
||||
self.model_runner_output.prompt_logprobs_dict = self.prompt_logprobs_dict
|
||||
self.model_runner_output.prompt_token_id_logprobs_dict = (
|
||||
self.prompt_token_id_logprobs_dict
|
||||
)
|
||||
if self.pending_aux_output is not None:
|
||||
self.model_runner_output.aux_output_connector_output = (
|
||||
self.pending_aux_output.process_output()
|
||||
|
||||
@@ -15,6 +15,9 @@ from vllm.v1.worker.gpu.buffer_utils import (
|
||||
|
||||
|
||||
class BlockTables:
|
||||
# Set by the elastic EP warmup so KV writes land in the null block.
|
||||
redirect_writes_to_null_block = False
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
block_sizes: list[int],
|
||||
@@ -126,6 +129,8 @@ class BlockTables:
|
||||
bpk = self.blocks_per_kv_block[i]
|
||||
if bpk > 1:
|
||||
block_ids = [b * bpk + k for b in block_ids for k in range(bpk)]
|
||||
if self.redirect_writes_to_null_block:
|
||||
block_ids = [0] * len(block_ids)
|
||||
end = start + len(block_ids)
|
||||
row_capacity = self.block_tables[i].gpu.shape[1]
|
||||
if end > row_capacity:
|
||||
|
||||
@@ -161,7 +161,6 @@ class CudaGraphManager:
|
||||
# DBO supports FULL CUDA graphs only.
|
||||
self.ubatch_runner = ubatch_runner
|
||||
|
||||
self.dp_size = vllm_config.parallel_config.data_parallel_size
|
||||
self.tp_size = vllm_config.parallel_config.tensor_parallel_size
|
||||
self.is_first_pp_rank = get_pp_group().is_first_rank
|
||||
self.is_last_pp_rank = get_pp_group().is_last_rank
|
||||
@@ -385,6 +384,23 @@ class CudaGraphManager:
|
||||
self._candidates.setdefault(key, []).extend(matching)
|
||||
current_range_start = num_tokens + 1
|
||||
|
||||
@property
|
||||
def dp_size(self) -> int:
|
||||
# Not cached: elastic EP rewrites parallel_config in place on scale.
|
||||
return self.vllm_config.parallel_config.data_parallel_size
|
||||
|
||||
def release_graphs(self) -> None:
|
||||
"""Drop the captured graphs so a later capture() can refill them.
|
||||
|
||||
Elastic EP reallocates the MoE workspace when it grows, which leaves
|
||||
every captured graph holding a stale data pointer. `_capture_descs` is
|
||||
kept, so `needs_capture()` still reports the work to redo.
|
||||
"""
|
||||
self.graphs.clear()
|
||||
self._graphs_captured = False
|
||||
if self.breakable_cg_runner is not None:
|
||||
BreakableCUDAGraphWrapper.clear_all_graphs()
|
||||
|
||||
def needs_capture(self) -> bool:
|
||||
return len(self._capture_descs) > 0
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from functools import wraps
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
@@ -15,6 +16,9 @@ from vllm.model_executor.models.interfaces import (
|
||||
get_mixture_of_experts_model,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu.model_runner import GPUModelRunner
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@@ -37,6 +41,27 @@ def step_eplb_after(*, is_dummy: bool = False) -> Callable:
|
||||
return decorator
|
||||
|
||||
|
||||
@contextmanager
|
||||
def preserve_serving_state(model_runner: "GPUModelRunner") -> Iterator[None]:
|
||||
"""Keep the elastic EP warmup out of the request pool and the KV cache."""
|
||||
# After the drain only parked streaming sessions still hold a slot, and
|
||||
# those are re-added from NewRequestData on their next chunk.
|
||||
_remove_all_requests(model_runner)
|
||||
model_runner.block_tables.redirect_writes_to_null_block = True
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_remove_all_requests(model_runner)
|
||||
model_runner.block_tables.redirect_writes_to_null_block = False
|
||||
if model_runner.kv_block_zeroer is not None:
|
||||
model_runner.kv_block_zeroer.zero_block_ids([0])
|
||||
|
||||
|
||||
def _remove_all_requests(model_runner: "GPUModelRunner") -> None:
|
||||
for req_id in list(model_runner.req_states.req_id_to_index):
|
||||
model_runner._remove_request(req_id)
|
||||
|
||||
|
||||
class EPLBController:
|
||||
def __init__(self, parallel_config: Any, device: torch.device):
|
||||
self.parallel_config = parallel_config
|
||||
@@ -82,10 +107,8 @@ class EPLBController:
|
||||
self._has_registered_models = True
|
||||
return True
|
||||
|
||||
def maybe_register_model(
|
||||
self, model: nn.Module, model_config: Any, load_dummy_weights: bool
|
||||
) -> bool:
|
||||
if not self.parallel_config.enable_eplb or load_dummy_weights:
|
||||
def maybe_register_model(self, model: nn.Module, model_config: ModelConfig) -> bool:
|
||||
if not self.parallel_config.enable_eplb:
|
||||
return False
|
||||
|
||||
moe_model = get_mixture_of_experts_model(model)
|
||||
@@ -100,7 +123,13 @@ class EPLBController:
|
||||
self._has_registered_models = True
|
||||
return True
|
||||
|
||||
def maybe_start_async_loop(self, eplb_models_added: bool) -> None:
|
||||
def maybe_start_async_loop(
|
||||
self, eplb_models_added: bool, load_dummy_weights: bool = False
|
||||
) -> None:
|
||||
# A scaling-up worker registers to join the communicator handshake, but
|
||||
# its groups are not live yet, so _perform_eplb_reshuffle() starts this.
|
||||
if load_dummy_weights:
|
||||
return
|
||||
if eplb_models_added and self.state is not None and self.state.is_async:
|
||||
self.state.start_async_loop()
|
||||
|
||||
@@ -128,18 +157,10 @@ class EPLBController:
|
||||
|
||||
def setup_from_mapping(
|
||||
self,
|
||||
model: nn.Module,
|
||||
model_config: Any,
|
||||
model_config: ModelConfig,
|
||||
expanded_physical_to_logical: torch.Tensor,
|
||||
) -> None:
|
||||
moe_model = get_mixture_of_experts_model(model)
|
||||
assert moe_model is not None
|
||||
|
||||
self.state = EplbState.from_mapping(
|
||||
model=moe_model,
|
||||
model_config=model_config,
|
||||
device=self.device,
|
||||
parallel_config=self.parallel_config,
|
||||
expanded_physical_to_logical=expanded_physical_to_logical,
|
||||
)
|
||||
self._has_registered_models = True
|
||||
# Update in place: a fresh EplbState would build a second communicator
|
||||
# over a group the other ranks have already left.
|
||||
assert self.state is not None
|
||||
self.state.update_mapping(model_config, expanded_physical_to_logical)
|
||||
|
||||
@@ -81,6 +81,8 @@ class InputBatch:
|
||||
is_prefilling_np: np.ndarray
|
||||
# == np.any(is_prefilling_np)
|
||||
has_prefill: bool
|
||||
# No prefills, or only prefill rows that run as decodes.
|
||||
decode_graph_eligible: bool
|
||||
|
||||
# [num_tokens_after_padding]
|
||||
input_ids: torch.Tensor
|
||||
@@ -113,6 +115,11 @@ class InputBatch:
|
||||
# [num_reqs] set only under PCP+DCP (see CommonAttentionMetadata).
|
||||
dcp_local_seq_lens_cpu_upper_bound: torch.Tensor | None = None
|
||||
|
||||
# [num_reqs] prefilling rows that schedule one new prompt token (excluding
|
||||
# drafts) over existing context and so compute exactly like decodes.
|
||||
# None if there are no prefills.
|
||||
prefill_runs_as_decode_np: np.ndarray | None = None
|
||||
|
||||
@classmethod
|
||||
def make_dummy(
|
||||
cls,
|
||||
@@ -196,6 +203,7 @@ class InputBatch:
|
||||
num_computed_prefill_tokens_np=np.zeros(num_reqs, dtype=np.int32),
|
||||
is_prefilling_np=np.zeros(num_reqs, dtype=np.bool_),
|
||||
has_prefill=False,
|
||||
decode_graph_eligible=True,
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
is_padding=is_padding,
|
||||
|
||||
@@ -31,8 +31,9 @@ import torch.nn as nn
|
||||
import vllm.envs as envs
|
||||
from vllm.compilation.counter import compilation_counter
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat
|
||||
from vllm.compilation.wrapper import compile_model_with_stock_torch
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.config.compilation import CompilationMode, CUDAGraphMode
|
||||
from vllm.distributed.aux_output_connector.worker import (
|
||||
AuxOutputWorkerConnector,
|
||||
get_aux_output_connector,
|
||||
@@ -234,10 +235,6 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
# Persistent buffer for intermediate tensors (non-first PP ranks).
|
||||
self.intermediate_tensors: IntermediateTensors | None = None
|
||||
|
||||
# Data parallelism.
|
||||
self.dp_size = self.parallel_config.data_parallel_size
|
||||
self.dp_rank = self.parallel_config.data_parallel_rank
|
||||
|
||||
# Dual batch overlap. Created in initialize_kv_cache(), once everything
|
||||
# it runs the microbatched forward with exists.
|
||||
self.ubatch_runner: UBatchRunner | None = None
|
||||
@@ -494,7 +491,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
),
|
||||
)
|
||||
self.prompt_logprobs_worker = PromptLogprobsWorker(
|
||||
self.max_num_reqs, logprobs_mode=self.model_config.logprobs_mode
|
||||
self.max_num_reqs,
|
||||
self.device,
|
||||
logprobs_mode=self.model_config.logprobs_mode,
|
||||
)
|
||||
self.structured_outputs_worker = StructuredOutputsWorker(
|
||||
max_num_logits=self.max_num_reqs * self.decode_query_len,
|
||||
@@ -507,9 +506,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
if self.is_pooling_model and self.is_last_pp_rank:
|
||||
self.pooling_runner = PoolingRunner(self.model, self.vllm_config)
|
||||
eplb_models_added |= self.eplb.maybe_register_model(
|
||||
self.model, self.model_config, load_dummy_weights
|
||||
self.model, self.model_config
|
||||
)
|
||||
self.eplb.maybe_start_async_loop(eplb_models_added)
|
||||
self.eplb.maybe_start_async_loop(eplb_models_added, load_dummy_weights)
|
||||
|
||||
if not self.is_first_pp_rank:
|
||||
# For non-first PP ranks, create intermediate tensors sized
|
||||
@@ -524,6 +523,19 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
|
||||
get_offloader().post_init()
|
||||
|
||||
if self.compilation_config.mode == CompilationMode.STOCK_TORCH_COMPILE:
|
||||
compile_model_with_stock_torch(self.model, self.vllm_config)
|
||||
|
||||
@property
|
||||
def dp_size(self) -> int:
|
||||
# Not cached: elastic EP rewrites parallel_config in place on reconfigure.
|
||||
return self.parallel_config.data_parallel_size
|
||||
|
||||
@property
|
||||
def dp_rank(self) -> int:
|
||||
# Not cached: elastic EP rewrites parallel_config in place on reconfigure.
|
||||
return self.parallel_config.data_parallel_rank
|
||||
|
||||
def get_model(self) -> nn.Module:
|
||||
return self.model
|
||||
|
||||
@@ -797,7 +809,11 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
"skip_attn must only be True for initial memory profiling."
|
||||
)
|
||||
|
||||
# Create a dummy scheduler output.
|
||||
# Create a dummy scheduler output. Plain draft-model speculation adds
|
||||
# one correction slot per request during prefill. The scheduler
|
||||
# accounts for these slots, while dummy runs bypass the scheduler.
|
||||
# Adjust the dummy token count only when the expanded draft batch
|
||||
# would exceed the token budget.
|
||||
num_reqs = min(num_tokens, self.max_num_reqs)
|
||||
if uniform_decode:
|
||||
# HACK(lucas): for now since the worker is shared between MRV1 and MRV2,
|
||||
@@ -811,8 +827,15 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
num_reqs = min(
|
||||
num_reqs, self.max_num_tokens // self.speculator.num_query_per_req
|
||||
)
|
||||
num_tokens = min(
|
||||
num_tokens,
|
||||
self.max_num_tokens
|
||||
- num_reqs * self.speculator.num_extra_query_per_req,
|
||||
)
|
||||
|
||||
# Distribute the remainder evenly so no dummy request exceeds
|
||||
# ceil(num_tokens / num_reqs) <= max_model_len tokens.
|
||||
|
||||
num_tokens_per_request = [
|
||||
num_tokens // num_reqs + (i >= num_reqs - num_tokens % num_reqs)
|
||||
for i in range(num_reqs)
|
||||
@@ -1229,7 +1252,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
if dummy_run:
|
||||
# Dummy batches are uniform by construction.
|
||||
return None, get_uniform_decode_token_count(
|
||||
num_reqs, num_toks, max_query_len, has_prefill=False
|
||||
num_reqs, num_toks, max_query_len, decode_graph_eligible=True
|
||||
)
|
||||
|
||||
draft_tokens = scheduler_output.scheduled_spec_decode_tokens
|
||||
@@ -1248,24 +1271,48 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
idx_mapping_np
|
||||
]
|
||||
is_prefilling_np = num_computed_prefill_tokens_np < prefill_len_np
|
||||
has_prefill = bool(is_prefilling_np.any())
|
||||
|
||||
if self.adaptive_verification is not None and draft_tokens:
|
||||
num_toks = self.adaptive_verification.get_num_tokens(
|
||||
num_tokens_per_req, draft_tokens
|
||||
num_draft_tokens_np = None
|
||||
if draft_tokens:
|
||||
num_drafts_iter = (len(draft_tokens.get(req_id, ())) for req_id in req_ids)
|
||||
num_draft_tokens_np = np.fromiter(
|
||||
num_drafts_iter, dtype=np.int32, count=num_reqs
|
||||
)
|
||||
if self.adaptive_verification is not None:
|
||||
num_toks = self.adaptive_verification.get_num_tokens(
|
||||
num_tokens_per_req, draft_tokens
|
||||
)
|
||||
|
||||
prefill_runs_as_decode_np = None
|
||||
decode_graph_eligible = not has_prefill
|
||||
if has_prefill and self.pcp_manager is None:
|
||||
# One new prompt token over existing context (possibly padded with
|
||||
# placeholder drafts) runs as a decode. PCP partitions prefill rows.
|
||||
num_new_tokens = num_scheduled_tokens
|
||||
if num_draft_tokens_np is not None:
|
||||
num_new_tokens = num_new_tokens - num_draft_tokens_np
|
||||
one_token_ext = (num_new_tokens == 1) & (num_computed_prefill_tokens_np > 0)
|
||||
prefill_runs_as_decode_np = is_prefilling_np & one_token_ext
|
||||
decode_graph_eligible = bool(
|
||||
(prefill_runs_as_decode_np | ~is_prefilling_np).all()
|
||||
)
|
||||
|
||||
batch_state = BatchReqState(
|
||||
req_ids=req_ids,
|
||||
num_scheduled_tokens=num_scheduled_tokens,
|
||||
num_tokens=num_toks,
|
||||
num_draft_tokens_np=num_draft_tokens_np,
|
||||
idx_mapping_np=idx_mapping_np,
|
||||
prefill_len_np=prefill_len_np,
|
||||
num_computed_prefill_tokens_np=num_computed_prefill_tokens_np,
|
||||
is_prefilling_np=is_prefilling_np,
|
||||
has_prefill=bool(is_prefilling_np.any()),
|
||||
has_prefill=has_prefill,
|
||||
prefill_runs_as_decode_np=prefill_runs_as_decode_np,
|
||||
decode_graph_eligible=decode_graph_eligible,
|
||||
)
|
||||
return batch_state, get_uniform_decode_token_count(
|
||||
num_reqs, num_toks, max_query_len, batch_state.has_prefill
|
||||
num_reqs, num_toks, max_query_len, decode_graph_eligible
|
||||
)
|
||||
|
||||
def prepare_inputs(
|
||||
@@ -1307,11 +1354,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
num_reqs, dtype=torch.int32, device=self.device
|
||||
)
|
||||
else:
|
||||
num_draft_tokens_per_req = np.fromiter(
|
||||
(len(draft_tokens.get(req_id, ())) for req_id in req_ids),
|
||||
dtype=np.int32,
|
||||
count=num_reqs,
|
||||
)
|
||||
num_draft_tokens_per_req = batch_req_state.num_draft_tokens_np
|
||||
if num_draft_tokens_per_req is None:
|
||||
num_draft_tokens_per_req = np.zeros(num_reqs, dtype=np.int32)
|
||||
num_bonus_tokens = self.model_state.num_new_sampled_tokens_per_step
|
||||
total_num_draft_tokens = int(num_draft_tokens_per_req.sum())
|
||||
total_num_logits = num_reqs * num_bonus_tokens + total_num_draft_tokens
|
||||
@@ -1450,6 +1495,8 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
num_computed_prefill_tokens_np=batch_req_state.num_computed_prefill_tokens_np,
|
||||
is_prefilling_np=batch_req_state.is_prefilling_np,
|
||||
has_prefill=batch_req_state.has_prefill,
|
||||
prefill_runs_as_decode_np=batch_req_state.prefill_runs_as_decode_np,
|
||||
decode_graph_eligible=batch_req_state.decode_graph_eligible,
|
||||
input_ids=self.input_buffers.input_ids[:num_tokens_after_padding],
|
||||
positions=self.input_buffers.positions[:num_tokens_after_padding],
|
||||
is_padding=is_padding,
|
||||
@@ -2063,6 +2110,14 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.req_states.num_computed_tokens.gpu,
|
||||
self.req_states.prompt_len.np,
|
||||
)
|
||||
prompt_token_id_logprobs_dict = (
|
||||
self.prompt_logprobs_worker.compute_prompt_token_id_logprobs(
|
||||
self.model.compute_logits,
|
||||
hidden_states,
|
||||
input_batch,
|
||||
self.req_states.prompt_len.np,
|
||||
)
|
||||
)
|
||||
|
||||
# Prepare the model runner output.
|
||||
model_runner_output = ModelRunnerOutput(
|
||||
@@ -2072,6 +2127,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
req_id_to_index={req_id: i for i, req_id in enumerate(input_batch.req_ids)},
|
||||
sampled_token_ids=None, # type: ignore
|
||||
prompt_logprobs_dict=prompt_logprobs_dict, # type: ignore[arg-type]
|
||||
prompt_token_id_logprobs_dict=prompt_token_id_logprobs_dict,
|
||||
cudagraph_stats=cudagraph_stats,
|
||||
)
|
||||
pending_aux_output = None
|
||||
@@ -2291,9 +2347,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
def setup_eplb_from_mapping(
|
||||
self, expanded_physical_to_logical: torch.Tensor
|
||||
) -> None:
|
||||
self.eplb.setup_from_mapping(
|
||||
self.model, self.model_config, expanded_physical_to_logical
|
||||
)
|
||||
self.eplb.setup_from_mapping(self.model_config, expanded_physical_to_logical)
|
||||
|
||||
########### EPLB methods end ###########
|
||||
|
||||
@@ -2323,11 +2377,14 @@ class BatchReqState(NamedTuple):
|
||||
# May be less than scheduler_output.total_num_scheduled_tokens:
|
||||
# adaptive verification trims the draft budget before running.
|
||||
num_tokens: int
|
||||
num_draft_tokens_np: np.ndarray | None # [num_reqs], None if no drafts
|
||||
idx_mapping_np: np.ndarray # [num_reqs]
|
||||
prefill_len_np: np.ndarray # [num_reqs]
|
||||
num_computed_prefill_tokens_np: np.ndarray # [num_reqs]
|
||||
is_prefilling_np: np.ndarray # [num_reqs]
|
||||
has_prefill: bool
|
||||
prefill_runs_as_decode_np: np.ndarray | None # [num_reqs]
|
||||
decode_graph_eligible: bool
|
||||
|
||||
|
||||
def sort_batch_req_ids(
|
||||
|
||||
@@ -258,10 +258,13 @@ class MambaHybridModelState(DefaultModelState):
|
||||
else:
|
||||
max_seq_len = seq_lens_cpu_upper_bound[:num_reqs].max().item()
|
||||
|
||||
is_prefilling_np = input_batch.is_prefilling_np
|
||||
if input_batch.prefill_runs_as_decode_np is not None:
|
||||
# A prompt tail the scheduler padded with placeholder drafts must run
|
||||
# as a spec-decode row: the prefill kernels can't roll them back.
|
||||
is_prefilling_np = is_prefilling_np & ~input_batch.prefill_runs_as_decode_np
|
||||
is_prefilling = torch.zeros(num_reqs, dtype=torch.bool, device="cpu")
|
||||
is_prefilling[: input_batch.num_reqs] = torch.from_numpy(
|
||||
input_batch.is_prefilling_np
|
||||
)
|
||||
is_prefilling[: input_batch.num_reqs] = torch.from_numpy(is_prefilling_np)
|
||||
# During CUDAGraph capture, num_decode_draft_tokens_cpu and num_accepted_tokens
|
||||
# are created by attn_metadata_builder.build_for_cudagraph_capture, so we only
|
||||
# compute them during actual (non-capture) forward execution.
|
||||
@@ -281,16 +284,7 @@ class MambaHybridModelState(DefaultModelState):
|
||||
# Test request state, not num_scheduled_tokens == draft_count+1:
|
||||
# adaptive rewrites num_scheduled_tokens to an even split, so that
|
||||
# equality rarely holds and would demote every verify row to decode.
|
||||
# A one-token prompt tail over prior state that the scheduler padded
|
||||
# with placeholder drafts is also a spec-decode row: the prefill
|
||||
# kernels can't roll the placeholders back.
|
||||
num_computed = input_batch.num_computed_prefill_tokens_np
|
||||
is_prompt_tail = (num_computed > 0) & (
|
||||
input_batch.prefill_len_np - num_computed == 1
|
||||
)
|
||||
is_decode = (~input_batch.is_prefilling_np | is_prompt_tail) & (
|
||||
input_batch.num_scheduled_tokens > 0
|
||||
)
|
||||
is_decode = ~is_prefilling_np & (input_batch.num_scheduled_tokens > 0)
|
||||
spec_decode_mask = (num_draft_tokens_per_req > 0) & is_decode
|
||||
num_decode_draft_tokens_np[: input_batch.num_reqs] = np.where(
|
||||
spec_decode_mask, num_draft_tokens_per_req, -1
|
||||
|
||||
@@ -595,6 +595,7 @@ class PCPManager:
|
||||
)
|
||||
local_is_prefilling_np = np.zeros(num_reqs_after_padding, dtype=np.bool_)
|
||||
local_is_prefilling_np[:num_local_reqs] = real_local_is_prefilling_np
|
||||
local_has_prefill = bool(local_is_prefilling_np.any())
|
||||
seq_lens_cpu_upper_bound_np = np.zeros(num_reqs_after_padding, dtype=np.int32)
|
||||
seq_lens_cpu_upper_bound_np[:num_local_reqs] = (
|
||||
local_start_pos_np + local_num_scheduled_tokens
|
||||
@@ -645,7 +646,9 @@ class PCPManager:
|
||||
prefill_len_np=local_prefill_len_np,
|
||||
num_computed_prefill_tokens_np=local_num_computed_prefill_tokens_np,
|
||||
is_prefilling_np=local_is_prefilling_np,
|
||||
has_prefill=bool(local_is_prefilling_np.any()),
|
||||
has_prefill=local_has_prefill,
|
||||
decode_graph_eligible=not local_has_prefill,
|
||||
prefill_runs_as_decode_np=None,
|
||||
input_ids=input_buffers.input_ids[:num_local_tokens_padded],
|
||||
positions=input_buffers.positions[:num_local_tokens_padded],
|
||||
is_padding=is_padding,
|
||||
|
||||
@@ -19,6 +19,7 @@ def _topk_log_softmax_kernel(
|
||||
logits_ptr,
|
||||
logits_stride,
|
||||
topk_ids_ptr,
|
||||
topk_ids_stride,
|
||||
topk,
|
||||
vocab_size,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
@@ -49,7 +50,7 @@ def _topk_log_softmax_kernel(
|
||||
k_offset = j + tl.arange(0, TOPK_BLOCK_SIZE)
|
||||
k_mask = k_offset < topk
|
||||
topk_ids = tl.load(
|
||||
topk_ids_ptr + req_idx * topk + k_offset, mask=k_mask, other=0
|
||||
topk_ids_ptr + req_idx * topk_ids_stride + k_offset, mask=k_mask, other=0
|
||||
)
|
||||
logits = tl.load(row_ptr + topk_ids, mask=k_mask)
|
||||
logits = logits.to(tl.float32)
|
||||
@@ -98,6 +99,7 @@ def compute_token_logprobs(
|
||||
logits,
|
||||
logits.stride(0),
|
||||
token_ids,
|
||||
token_ids.stride(0),
|
||||
num_logprobs,
|
||||
vocab_size,
|
||||
BLOCK_SIZE=1024, # type: ignore
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -8,20 +9,41 @@ import torch
|
||||
from vllm.config.model import LogprobsMode
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.outputs import LogprobsTensors
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
|
||||
from vllm.v1.worker.gpu.sample.logprob import (
|
||||
compute_token_logprobs,
|
||||
compute_topk_scores,
|
||||
)
|
||||
|
||||
CHUNK_SIZE = 1024
|
||||
|
||||
|
||||
@dataclass
|
||||
class _TokenIdScores:
|
||||
token_ids: torch.Tensor # [num_ids], on device
|
||||
start: int # first prompt row to score
|
||||
scores: torch.Tensor | None = None # [num_rows, num_ids], filled per chunk
|
||||
|
||||
|
||||
class PromptLogprobsWorker:
|
||||
def __init__(self, max_num_reqs: int, logprobs_mode: LogprobsMode = "raw_logprobs"):
|
||||
def __init__(
|
||||
self,
|
||||
max_num_reqs: int,
|
||||
device: torch.device,
|
||||
logprobs_mode: LogprobsMode = "raw_logprobs",
|
||||
):
|
||||
self.max_num_reqs = max_num_reqs
|
||||
self.device = device
|
||||
self.logprobs_mode = logprobs_mode
|
||||
|
||||
self.uses_prompt_logprobs = np.zeros(self.max_num_reqs, dtype=bool)
|
||||
self.num_prompt_logprobs = np.zeros(self.max_num_reqs, dtype=np.int32)
|
||||
# req_idx -> list of in-progress LogprobsTensors
|
||||
self.in_progress_prompt_logprobs: dict[str, list[LogprobsTensors]] = {}
|
||||
# req_id -> fixed-ID scoring state
|
||||
self.token_id_scores: dict[str, _TokenIdScores] = {}
|
||||
|
||||
def add_request(self, req_id: str, req_idx: int, sampling_params: SamplingParams):
|
||||
uses_prompt_logprobs = sampling_params.prompt_logprobs is not None
|
||||
@@ -29,9 +51,69 @@ class PromptLogprobsWorker:
|
||||
self.num_prompt_logprobs[req_idx] = sampling_params.prompt_logprobs or 0
|
||||
if uses_prompt_logprobs:
|
||||
self.in_progress_prompt_logprobs[req_id] = []
|
||||
if sampling_params.prompt_logprob_token_ids is not None:
|
||||
self.token_id_scores[req_id] = _TokenIdScores(
|
||||
async_tensor_h2d(
|
||||
sampling_params.prompt_logprob_token_ids, self.device, torch.int64
|
||||
),
|
||||
sampling_params.prompt_logprob_start or 0,
|
||||
)
|
||||
|
||||
def remove_request(self, req_id: str) -> None:
|
||||
self.in_progress_prompt_logprobs.pop(req_id, None)
|
||||
self.token_id_scores.pop(req_id, None)
|
||||
|
||||
def compute_prompt_token_id_logprobs(
|
||||
self,
|
||||
logits_fn: Callable[[torch.Tensor], torch.Tensor],
|
||||
hidden_states: torch.Tensor,
|
||||
input_batch: InputBatch,
|
||||
prompt_lens: np.ndarray,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
"""Fill scores row (prompt row - req.start) per chunk; emit on the last."""
|
||||
if not self.token_id_scores:
|
||||
return {}
|
||||
logits_mode = self.logprobs_mode in ("raw_logits", "processed_logits")
|
||||
out: dict[str, torch.Tensor] = {}
|
||||
for i, req_id in enumerate(input_batch.req_ids):
|
||||
req = self.token_id_scores.get(req_id)
|
||||
if req is None:
|
||||
continue
|
||||
prompt_len = int(prompt_lens[input_batch.idx_mapping_np[i]])
|
||||
chunk_start = int(input_batch.num_computed_prefill_tokens_np[i])
|
||||
chunk_end = chunk_start + int(input_batch.num_scheduled_tokens[i])
|
||||
# Skip decode steps and, as compute_prompt_logprobs does, requests
|
||||
# resumed after preemption: their scores were already emitted.
|
||||
if chunk_start >= prompt_len or prompt_len < input_batch.prefill_len_np[i]:
|
||||
continue
|
||||
if req.scores is None:
|
||||
if chunk_start > req.start:
|
||||
# This prefill starts past the first scored row, so those
|
||||
# rows will never be written; drop the request instead of
|
||||
# emitting a buffer with unwritten rows.
|
||||
self.token_id_scores.pop(req_id, None)
|
||||
continue
|
||||
req.scores = hidden_states.new_empty(
|
||||
(max(prompt_len - 1 - req.start, 0), len(req.token_ids)),
|
||||
dtype=torch.float32,
|
||||
)
|
||||
# The last prompt row predicts the first decode token; skip it.
|
||||
lo = max(req.start, chunk_start)
|
||||
hi = min(chunk_end, prompt_len - 1)
|
||||
base = int(input_batch.query_start_loc_np[i]) - chunk_start
|
||||
for a in range(lo, hi, CHUNK_SIZE):
|
||||
b = min(a + CHUNK_SIZE, hi)
|
||||
logits = logits_fn(hidden_states[base + a : base + b])
|
||||
ids = req.token_ids.expand(b - a, -1)
|
||||
req.scores[a - req.start : b - req.start] = (
|
||||
logits.gather(-1, ids)
|
||||
if logits_mode
|
||||
else compute_token_logprobs(logits, ids)
|
||||
)
|
||||
if chunk_end >= prompt_len:
|
||||
out[req_id] = req.scores
|
||||
req.scores = None
|
||||
return out
|
||||
|
||||
def compute_prompt_logprobs(
|
||||
self,
|
||||
@@ -205,7 +287,6 @@ def compute_prompt_logprobs_with_chunking(
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
# Since materializing the full prompt logits can take too much memory,
|
||||
# we compute it in chunks.
|
||||
CHUNK_SIZE = 1024
|
||||
token_ids = []
|
||||
scores = []
|
||||
ranks = []
|
||||
|
||||
@@ -60,5 +60,11 @@ def init_speculator(vllm_config: VllmConfig, device: torch.device):
|
||||
)
|
||||
|
||||
return EagleSpeculator(vllm_config, device)
|
||||
elif speculative_config.uses_draft_model():
|
||||
from vllm.v1.worker.gpu.spec_decode.draft_model.speculator import (
|
||||
PlainDraftModelSpeculator,
|
||||
)
|
||||
|
||||
return PlainDraftModelSpeculator(vllm_config, device)
|
||||
else:
|
||||
raise NotImplementedError(f"{speculative_config.method} is not supported yet.")
|
||||
|
||||
@@ -20,7 +20,7 @@ _INIT_SLOPE = 0.5
|
||||
_INIT_BIAS = -0.2
|
||||
|
||||
|
||||
@triton.jit
|
||||
@triton.jit(do_not_specialize=["num_reqs"])
|
||||
def _accumulate_kernel(
|
||||
info_ptr,
|
||||
grad_ptr,
|
||||
@@ -160,7 +160,7 @@ def _refit_kernel(
|
||||
tl.store(counts_ptr + k, 0.0, mask=mask)
|
||||
|
||||
|
||||
@triton.jit
|
||||
@triton.jit(do_not_specialize=["num_tokens"])
|
||||
def _local_max_sumexp_kernel(
|
||||
local_max_ptr,
|
||||
local_max_stride,
|
||||
@@ -216,7 +216,7 @@ def _local_max_sumexp_kernel(
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
@triton.jit(do_not_specialize=["num_tokens"])
|
||||
def _predict_kernel(
|
||||
features_ptr,
|
||||
features_stride,
|
||||
@@ -422,7 +422,8 @@ class OnlineAcceptanceEstimator:
|
||||
self.predictions.stride(0),
|
||||
self.counts,
|
||||
num_reqs,
|
||||
BLOCK_R=triton.next_power_of_2(max(num_reqs, 1)),
|
||||
BLOCK_R=max(256, triton.next_power_of_2(num_reqs)),
|
||||
num_warps=1 if num_reqs <= 256 else 4,
|
||||
)
|
||||
|
||||
self._steps_since_refit += 1
|
||||
|
||||
@@ -282,7 +282,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
# the target model during FULL cudagraph.
|
||||
num_tokens,
|
||||
max_query_len,
|
||||
input_batch.has_prefill,
|
||||
input_batch.decode_graph_eligible,
|
||||
)
|
||||
prefill_batch_desc, prefill_batch_sync = dispatch_cg_and_sync_dp(
|
||||
self.prefill_cudagraph_manager,
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
@@ -0,0 +1,527 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.compilation.backends import set_model_tag
|
||||
from vllm.config import VllmConfig, replace
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.forward_context import BatchDescriptor, set_forward_context
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader import get_model
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.spec_decode.utils import next_power_of_2
|
||||
from vllm.v1.worker.gpu.attn_utils import build_slot_mappings_by_layer
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
from vllm.v1.worker.gpu.cudagraph_utils import BatchExecutionDescriptor
|
||||
from vllm.v1.worker.gpu.dp_utils import DPSyncState
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
|
||||
from vllm.v1.worker.gpu.model_states.interface import ModelState
|
||||
from vllm.v1.worker.gpu.spec_decode.speculator import DraftModelSpeculator
|
||||
from vllm.v1.worker.utils import AttentionGroup
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class PlainDraftModelSpeculator(DraftModelSpeculator):
|
||||
"""Speculative decoding using a separate smaller draft LM.
|
||||
|
||||
Unlike Eagle, the draft model runs fully independently of the target model.
|
||||
Step 0 builds an expanded buffer (accepted + correction token + rejected
|
||||
slots) via a Triton kernel; steps 1..k-1 are single-token decode steps.
|
||||
"""
|
||||
|
||||
# Plain draft model needs one extra slot per request for correction.
|
||||
num_extra_query_per_req = 1
|
||||
|
||||
def __init__(self, vllm_config: VllmConfig, device: torch.device):
|
||||
super().__init__(vllm_config, device)
|
||||
|
||||
# draft_max_seq_len is read by the parent's attention metadata builder.
|
||||
# Plain draft model doesn't do per-batch adjustment; cap at max.
|
||||
self.draft_max_seq_len = self.max_model_len
|
||||
|
||||
self.last_token_indices = torch.zeros(
|
||||
self.max_num_reqs, dtype=torch.int64, device=device
|
||||
)
|
||||
# GPU-side arange for decode query_start_loc initialisation.
|
||||
self.arange_gpu = torch.arange(
|
||||
self.max_num_reqs + 1, dtype=torch.int32, device=device
|
||||
)
|
||||
# Scalar step counter used as column index into draft_logits.
|
||||
self.current_draft_step = torch.tensor(0, dtype=torch.int64, device=device)
|
||||
|
||||
_expanded_max = self.max_num_tokens + self.max_num_reqs
|
||||
self.expanded_input_ids = torch.zeros(
|
||||
_expanded_max, dtype=torch.int32, device=device
|
||||
)
|
||||
self.expanded_positions = torch.zeros(
|
||||
_expanded_max, dtype=torch.int64, device=device
|
||||
)
|
||||
self.expanded_slot_mappings: torch.Tensor
|
||||
self.supports_mm_inputs = False
|
||||
|
||||
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
|
||||
pass # CUDA graph not yet supported for plain draft model speculator.
|
||||
|
||||
def capture(self) -> None:
|
||||
pass # CUDA graph not yet supported for plain draft model speculator.
|
||||
|
||||
def set_attn(
|
||||
self,
|
||||
model_state: ModelState,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
block_tables: BlockTables,
|
||||
target_input_buffers: InputBuffers,
|
||||
target_attn_groups: list[list[AttentionGroup]],
|
||||
) -> None:
|
||||
super().set_attn(
|
||||
model_state,
|
||||
kv_cache_config,
|
||||
block_tables,
|
||||
target_input_buffers,
|
||||
target_attn_groups,
|
||||
)
|
||||
self.expanded_slot_mappings = torch.empty(
|
||||
block_tables.num_kv_cache_groups,
|
||||
self.max_num_tokens + self.max_num_reqs,
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
)
|
||||
|
||||
def load_draft_model(
|
||||
self,
|
||||
target_model: nn.Module,
|
||||
target_attn_layer_names: set[str],
|
||||
) -> nn.Module:
|
||||
spec = self.speculative_config
|
||||
assert spec is not None
|
||||
draft_vllm_config = replace(
|
||||
self.vllm_config,
|
||||
model_config=self.draft_model_config,
|
||||
quant_config=None,
|
||||
parallel_config=replace(
|
||||
spec.draft_parallel_config,
|
||||
rank=self.vllm_config.parallel_config.rank,
|
||||
),
|
||||
)
|
||||
with set_model_tag("draft_model"):
|
||||
return get_model(
|
||||
vllm_config=draft_vllm_config,
|
||||
prefix="draft_model",
|
||||
)
|
||||
|
||||
@torch.inference_mode()
|
||||
def _run_model(
|
||||
self,
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
attn_metadata: dict[str, Any] | None,
|
||||
slot_mappings: dict[str, torch.Tensor] | None,
|
||||
num_tokens_across_dp: torch.Tensor | None,
|
||||
) -> torch.Tensor:
|
||||
num_tokens = input_ids.shape[0]
|
||||
batch_descriptor = BatchDescriptor(num_tokens=num_tokens)
|
||||
with set_forward_context(
|
||||
attn_metadata,
|
||||
self.vllm_config,
|
||||
num_tokens=num_tokens,
|
||||
cudagraph_runtime_mode=CUDAGraphMode.NONE,
|
||||
num_tokens_across_dp=num_tokens_across_dp,
|
||||
slot_mapping=slot_mappings,
|
||||
batch_descriptor=batch_descriptor,
|
||||
):
|
||||
hidden_states = self.model( # type: ignore[misc]
|
||||
input_ids=input_ids,
|
||||
positions=positions,
|
||||
)
|
||||
if isinstance(hidden_states, tuple):
|
||||
hidden_states = hidden_states[0]
|
||||
return hidden_states
|
||||
|
||||
def _accepted_last_indices(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
num_rejected: torch.Tensor,
|
||||
num_reqs: int,
|
||||
) -> torch.Tensor:
|
||||
qsl = input_batch.query_start_loc
|
||||
adjusted_lens = qsl[1 : num_reqs + 1] - qsl[:num_reqs] - num_rejected[:num_reqs]
|
||||
return qsl[:num_reqs] + adjusted_lens - 1
|
||||
|
||||
def _prefill(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
num_rejected: torch.Tensor,
|
||||
last_sampled: torch.Tensor,
|
||||
num_reqs: int,
|
||||
skip_attn: bool,
|
||||
num_tokens_across_dp: torch.Tensor | None,
|
||||
) -> None:
|
||||
if skip_attn:
|
||||
src_tokens = input_batch.num_tokens
|
||||
self.last_token_indices[:num_reqs] = self._accepted_last_indices(
|
||||
input_batch, num_rejected, num_reqs
|
||||
)
|
||||
hidden_states = self._run_model(
|
||||
input_batch.input_ids[:src_tokens],
|
||||
input_batch.positions[:src_tokens],
|
||||
None,
|
||||
None,
|
||||
num_tokens_across_dp,
|
||||
)
|
||||
positions_buf = input_batch.positions
|
||||
else:
|
||||
block_tables = self.block_tables
|
||||
kv_cache_config = self.kv_cache_config
|
||||
assert block_tables is not None
|
||||
assert kv_cache_config is not None
|
||||
|
||||
total_expanded = prepare_prefill_inputs(
|
||||
input_buffers=self.input_buffers,
|
||||
input_batch=input_batch,
|
||||
last_sampled=last_sampled,
|
||||
num_rejected=num_rejected,
|
||||
expanded_input_ids=self.expanded_input_ids,
|
||||
expanded_positions=self.expanded_positions,
|
||||
last_token_indices=self.last_token_indices,
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
max_model_len=self.max_model_len,
|
||||
)
|
||||
|
||||
prefill_slot_mappings = block_tables.compute_slot_mappings(
|
||||
input_batch.idx_mapping,
|
||||
self.input_buffers.query_start_loc[: num_reqs + 1],
|
||||
self.expanded_positions[:total_expanded],
|
||||
total_expanded,
|
||||
out=self.expanded_slot_mappings,
|
||||
)
|
||||
qsl_np = input_batch.query_start_loc_np
|
||||
query_start_loc_cpu_expanded = (
|
||||
torch.from_numpy(qsl_np[: num_reqs + 1]).int()
|
||||
+ torch.from_numpy(self.arange_np[: num_reqs + 1]).int()
|
||||
)
|
||||
prefill_attn_md = self._build_attn_metadata(
|
||||
batch_desc=BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.NONE,
|
||||
num_tokens=total_expanded,
|
||||
num_reqs=num_reqs,
|
||||
),
|
||||
num_reqs=num_reqs,
|
||||
query_start_loc_np=query_start_loc_cpu_expanded.numpy(),
|
||||
seq_lens_cpu_upper_bound=input_batch.seq_lens_cpu_upper_bound,
|
||||
step=0,
|
||||
slot_mappings=prefill_slot_mappings,
|
||||
)
|
||||
prefill_slot_maps_by_layer = build_slot_mappings_by_layer(
|
||||
prefill_slot_mappings, kv_cache_config
|
||||
)
|
||||
hidden_states = self._run_model(
|
||||
self.expanded_input_ids[:total_expanded],
|
||||
self.expanded_positions[:total_expanded],
|
||||
prefill_attn_md,
|
||||
prefill_slot_maps_by_layer,
|
||||
num_tokens_across_dp,
|
||||
)
|
||||
positions_buf = self.expanded_positions
|
||||
|
||||
last_indices = self.last_token_indices[:num_reqs]
|
||||
self.current_draft_step.fill_(0)
|
||||
self.draft_tokens[:num_reqs, 0] = self.sample_draft(
|
||||
hidden_states[last_indices],
|
||||
positions_buf[last_indices],
|
||||
self.idx_mapping[:num_reqs],
|
||||
self.temperature,
|
||||
self.seeds,
|
||||
self.current_draft_step,
|
||||
self.draft_logits,
|
||||
)
|
||||
|
||||
def _multi_step_decode(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
num_rejected: torch.Tensor,
|
||||
num_reqs: int,
|
||||
skip_attn: bool,
|
||||
num_tokens_across_dp: torch.Tensor | None,
|
||||
) -> None:
|
||||
if skip_attn:
|
||||
last_positions = input_batch.positions[
|
||||
self._accepted_last_indices(input_batch, num_rejected, num_reqs)
|
||||
]
|
||||
else:
|
||||
last_positions = self.expanded_positions[self.last_token_indices[:num_reqs]]
|
||||
|
||||
self.input_buffers.positions[:num_reqs].copy_(last_positions)
|
||||
# The decode loop increments seq_lens BEFORE each forward.
|
||||
# Initial seq_lens = target_seq_lens - num_rejected + 1.
|
||||
# Step 1 forward uses target_seq_lens - num_rejected + 2.
|
||||
# Step 2 forward uses target_seq_lens - num_rejected + 3.
|
||||
self.input_buffers.seq_lens[:num_reqs].copy_(
|
||||
torch.clamp(
|
||||
input_batch.seq_lens[:num_reqs] - num_rejected[:num_reqs].int() + 1,
|
||||
max=self.max_model_len,
|
||||
)
|
||||
)
|
||||
self.input_buffers.query_start_loc[: num_reqs + 1].copy_(
|
||||
self.arange_gpu[: num_reqs + 1]
|
||||
)
|
||||
|
||||
idx_mapping = input_batch.idx_mapping
|
||||
|
||||
for step in range(1, self.num_speculative_steps):
|
||||
self.input_buffers.input_ids[:num_reqs].copy_(
|
||||
self.draft_tokens[:num_reqs, step - 1].int()
|
||||
)
|
||||
torch.clamp(
|
||||
self.input_buffers.positions[:num_reqs] + 1,
|
||||
max=self.max_model_len - 1,
|
||||
out=self.input_buffers.positions[:num_reqs],
|
||||
)
|
||||
# Increment seq_lens BEFORE the forward so the attention reads from
|
||||
# the KV slot written by the previous step.
|
||||
torch.clamp(
|
||||
self.input_buffers.seq_lens[:num_reqs] + 1,
|
||||
max=self.max_model_len,
|
||||
out=self.input_buffers.seq_lens[:num_reqs],
|
||||
)
|
||||
|
||||
decode_attn_md = None
|
||||
step_slot_maps_by_layer = None
|
||||
if not skip_attn:
|
||||
block_tables = self.block_tables
|
||||
kv_cache_config = self.kv_cache_config
|
||||
assert block_tables is not None
|
||||
assert kv_cache_config is not None
|
||||
q_start = self.input_buffers.query_start_loc[: num_reqs + 1]
|
||||
positions = self.input_buffers.positions[:num_reqs]
|
||||
step_slot_mappings = block_tables.compute_slot_mappings(
|
||||
idx_mapping, q_start, positions, num_reqs
|
||||
)
|
||||
step_slot_maps_by_layer = build_slot_mappings_by_layer(
|
||||
step_slot_mappings, kv_cache_config
|
||||
)
|
||||
decode_attn_md = self._build_uniform_attn_metadata(
|
||||
batch_desc=BatchExecutionDescriptor(
|
||||
cg_mode=CUDAGraphMode.NONE,
|
||||
num_tokens=num_reqs,
|
||||
num_reqs=num_reqs,
|
||||
uniform_token_count=1,
|
||||
),
|
||||
num_reqs=num_reqs,
|
||||
num_query_per_req=1,
|
||||
seq_lens_cpu_upper_bound=input_batch.seq_lens_cpu_upper_bound,
|
||||
# Include the correction token inserted during prefill.
|
||||
step=step + 1,
|
||||
)
|
||||
hidden_states = self._run_model(
|
||||
self.input_buffers.input_ids[:num_reqs],
|
||||
self.input_buffers.positions[:num_reqs],
|
||||
decode_attn_md,
|
||||
step_slot_maps_by_layer,
|
||||
num_tokens_across_dp,
|
||||
)
|
||||
|
||||
self.current_draft_step.fill_(step)
|
||||
self.draft_tokens[:num_reqs, step] = self.sample_draft(
|
||||
hidden_states[:num_reqs],
|
||||
self.input_buffers.positions[:num_reqs],
|
||||
self.idx_mapping[:num_reqs],
|
||||
self.temperature,
|
||||
self.seeds,
|
||||
self.current_draft_step,
|
||||
self.draft_logits,
|
||||
)
|
||||
|
||||
@torch.inference_mode()
|
||||
def propose(
|
||||
self,
|
||||
input_batch: InputBatch,
|
||||
attn_metadata: dict[str, Any],
|
||||
slot_mappings: dict[str, torch.Tensor],
|
||||
last_hidden_states: torch.Tensor, # unused
|
||||
aux_hidden_states: list[torch.Tensor] | None, # unused
|
||||
num_sampled: torch.Tensor,
|
||||
num_rejected: torch.Tensor,
|
||||
last_sampled: torch.Tensor,
|
||||
next_prefill_tokens: torch.Tensor,
|
||||
temperature: torch.Tensor,
|
||||
seeds: torch.Tensor,
|
||||
dp_sync: DPSyncState | None = None,
|
||||
dummy_run: bool = False,
|
||||
skip_attn_for_dummy_run: bool = False,
|
||||
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
|
||||
is_profile: bool = False,
|
||||
) -> torch.Tensor:
|
||||
assert self.model is not None
|
||||
|
||||
num_reqs = input_batch.num_reqs
|
||||
skip_attn = dummy_run and skip_attn_for_dummy_run
|
||||
num_tokens_across_dp = (
|
||||
dp_sync.num_tokens_across_dp if dp_sync is not None else None
|
||||
)
|
||||
|
||||
# Copy per-request temperature/seeds/idx_mapping into pre-allocated
|
||||
# buffers so sample_draft can read them without extra slicing.
|
||||
self._copy_request_inputs(
|
||||
num_reqs,
|
||||
input_batch.idx_mapping,
|
||||
temperature,
|
||||
seeds,
|
||||
)
|
||||
|
||||
self._prefill(
|
||||
input_batch,
|
||||
num_rejected,
|
||||
last_sampled,
|
||||
num_reqs,
|
||||
skip_attn,
|
||||
num_tokens_across_dp,
|
||||
)
|
||||
|
||||
if self.num_speculative_steps == 1:
|
||||
return self.draft_tokens[:num_reqs, :1]
|
||||
|
||||
self._multi_step_decode(
|
||||
input_batch,
|
||||
num_rejected,
|
||||
num_reqs,
|
||||
skip_attn,
|
||||
num_tokens_across_dp,
|
||||
)
|
||||
|
||||
return self.draft_tokens[:num_reqs]
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _prepare_prefill_inputs_kernel(
|
||||
target_input_ids_ptr, # [src_tokens] int32
|
||||
target_positions_ptr, # [src_tokens] int64
|
||||
last_sampled_ptr, # [max_num_reqs] int32
|
||||
idx_mapping_ptr, # [num_reqs] int32
|
||||
out_input_ids_ptr, # [src_tokens + num_reqs] int32
|
||||
out_positions_ptr, # [src_tokens + num_reqs] int64
|
||||
last_token_indices_ptr, # [max_num_reqs] int64
|
||||
out_query_start_loc_ptr, # [max_num_reqs + 1] int32
|
||||
out_seq_lens_ptr, # [max_num_reqs] int32
|
||||
query_start_loc_ptr, # [num_reqs + 1] int32
|
||||
seq_lens_ptr, # [num_reqs] int32
|
||||
num_rejected_ptr, # [num_reqs] int32
|
||||
max_num_reqs,
|
||||
max_model_len,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
"""Per-request step-0 input preparation for the plain draft-model speculator.
|
||||
|
||||
Output layout for request i (out_start = query_start_loc[i] + i):
|
||||
[out_start, out_start + num_valid) accepted tokens
|
||||
[out_start + num_valid] correction token
|
||||
(out_start + num_valid, out_start + total_out) rejected slots
|
||||
|
||||
where num_valid = query_lens[i] - num_rejected[i]
|
||||
total_out = query_lens[i] + 1
|
||||
"""
|
||||
req_idx = tl.program_id(0)
|
||||
num_reqs = tl.num_programs(0)
|
||||
|
||||
req_state_idx = tl.load(idx_mapping_ptr + req_idx)
|
||||
|
||||
q_start = tl.load(query_start_loc_ptr + req_idx)
|
||||
q_next = tl.load(query_start_loc_ptr + req_idx + 1)
|
||||
seq_len = tl.load(seq_lens_ptr + req_idx)
|
||||
num_rejected = tl.load(num_rejected_ptr + req_idx)
|
||||
|
||||
num_valid = q_next - q_start - num_rejected
|
||||
correction_token = tl.load(last_sampled_ptr + req_state_idx).to(tl.int32)
|
||||
start_pos = tl.load(target_positions_ptr + q_start)
|
||||
out_start = q_start + req_idx
|
||||
total_out = q_next - q_start + 1
|
||||
|
||||
for i in range(0, total_out, BLOCK_SIZE):
|
||||
j = i + tl.arange(0, BLOCK_SIZE)
|
||||
in_bounds = j < total_out
|
||||
|
||||
is_valid = j < num_valid
|
||||
is_correction = j == num_valid
|
||||
src_idx = q_start + j
|
||||
token_ids = tl.load(target_input_ids_ptr + src_idx, mask=is_valid, other=0)
|
||||
positions = tl.minimum(start_pos + j, max_model_len - 1)
|
||||
token_ids = tl.where(is_correction, correction_token, token_ids)
|
||||
|
||||
out_idx = out_start + j
|
||||
tl.store(out_input_ids_ptr + out_idx, token_ids, mask=in_bounds)
|
||||
tl.store(out_positions_ptr + out_idx, positions, mask=in_bounds)
|
||||
|
||||
tl.store(last_token_indices_ptr + req_idx, out_start + num_valid)
|
||||
tl.store(out_query_start_loc_ptr + req_idx, out_start)
|
||||
# seqlen_k for the expanded prefill attention:
|
||||
# pre_existing = seq_len - query_len (draft KV before this round)
|
||||
# expanded_query_len = query_len + 1 (adds correction token)
|
||||
# seqlen_k = pre_existing + expanded_query_len = seq_len + 1
|
||||
# num_rejected does NOT change seqlen_k — the expanded query always has
|
||||
# query_len+1 slots. Rejected positions write temporary KV entries that
|
||||
# are overwritten with valid tokens in a later round.
|
||||
new_seq_len = tl.minimum(seq_len + 1, max_model_len)
|
||||
tl.store(out_seq_lens_ptr + req_idx, new_seq_len)
|
||||
|
||||
if req_idx == num_reqs - 1:
|
||||
total_expanded = out_start + total_out
|
||||
tl.store(out_query_start_loc_ptr + num_reqs, total_expanded)
|
||||
for i in range(num_reqs + 1, max_num_reqs + 1, BLOCK_SIZE):
|
||||
block = i + tl.arange(0, BLOCK_SIZE)
|
||||
mask = block <= max_num_reqs
|
||||
tl.store(out_query_start_loc_ptr + block, total_expanded, mask=mask)
|
||||
for i in range(num_reqs, max_num_reqs, BLOCK_SIZE):
|
||||
block = i + tl.arange(0, BLOCK_SIZE)
|
||||
mask = block < max_num_reqs
|
||||
tl.store(out_seq_lens_ptr + block, 0, mask=mask)
|
||||
tl.store(last_token_indices_ptr + block, 0, mask=mask)
|
||||
|
||||
|
||||
def prepare_prefill_inputs(
|
||||
input_buffers: InputBuffers,
|
||||
input_batch: InputBatch,
|
||||
last_sampled: torch.Tensor, # [max_num_reqs] int64
|
||||
num_rejected: torch.Tensor, # [num_reqs] int64
|
||||
expanded_input_ids: torch.Tensor, # [max_tokens + max_reqs] int32
|
||||
expanded_positions: torch.Tensor, # [max_tokens + max_reqs] int64
|
||||
last_token_indices: torch.Tensor, # [max_num_reqs] int64
|
||||
max_num_reqs: int,
|
||||
max_model_len: int,
|
||||
) -> int:
|
||||
"""Call _prepare_prefill_inputs_kernel and return total_expanded tokens.
|
||||
|
||||
Side-effects (kernel writes):
|
||||
- expanded_input_ids, expanded_positions
|
||||
- last_token_indices
|
||||
- input_buffers.query_start_loc (expanded: original[i] + i)
|
||||
- input_buffers.seq_lens (= target_seq_lens - num_rejected + 1)
|
||||
"""
|
||||
num_reqs = input_batch.num_reqs
|
||||
src_tokens = input_batch.num_tokens
|
||||
qsl_np = input_batch.query_start_loc_np
|
||||
query_lens = qsl_np[1 : num_reqs + 1] - qsl_np[:num_reqs]
|
||||
max_total_out = int(query_lens.max()) + 2 # +1 correction, +1 alignment
|
||||
BLOCK_SIZE = min(512, next_power_of_2(max_total_out))
|
||||
|
||||
_prepare_prefill_inputs_kernel[(num_reqs,)](
|
||||
input_batch.input_ids,
|
||||
input_batch.positions,
|
||||
last_sampled.int(),
|
||||
input_batch.idx_mapping,
|
||||
expanded_input_ids,
|
||||
expanded_positions,
|
||||
last_token_indices,
|
||||
input_buffers.query_start_loc,
|
||||
input_buffers.seq_lens,
|
||||
input_batch.query_start_loc,
|
||||
input_batch.seq_lens,
|
||||
num_rejected.int(),
|
||||
max_num_reqs,
|
||||
max_model_len,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
)
|
||||
return src_tokens + num_reqs
|
||||
@@ -190,7 +190,7 @@ class MultiModuleMTPSpeculator(DraftModelSpeculator):
|
||||
# When all requests are decoding (no true prefills), each has
|
||||
# num_speculative_steps + 1 tokens, enabling FULL graph replay.
|
||||
uniform_token_count = get_uniform_decode_token_count(
|
||||
num_reqs, num_tokens, max_query_len, input_batch.has_prefill
|
||||
num_reqs, num_tokens, max_query_len, input_batch.decode_graph_eligible
|
||||
)
|
||||
batch_desc, batch_sync = dispatch_cg_and_sync_dp(
|
||||
self.cudagraph_manager,
|
||||
|
||||
@@ -74,6 +74,76 @@ def _flatten_sampled_kernel(
|
||||
tl.store(flat_sampled_ptr + start_idx + i, token_id)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _gather_draft_sampled_kernel(
|
||||
# [num_logits]
|
||||
draft_sampled_ptr,
|
||||
# [num_logits]
|
||||
pos_ptr,
|
||||
# [num_tokens]
|
||||
input_ids_ptr,
|
||||
# [num_tokens]
|
||||
positions_ptr,
|
||||
# [num_logits]
|
||||
logits_indices_ptr,
|
||||
# [num_logits]
|
||||
expanded_idx_mapping_ptr,
|
||||
# [num_logits]
|
||||
expanded_local_pos_ptr,
|
||||
# [max_num_reqs]
|
||||
prefill_len_ptr,
|
||||
num_logits,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
):
|
||||
block = tl.program_id(0) * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
|
||||
mask = block < num_logits
|
||||
token_idx = tl.load(logits_indices_ptr + block, mask=mask)
|
||||
token_id = tl.load(input_ids_ptr + token_idx, mask=mask)
|
||||
pos = tl.load(positions_ptr + token_idx, mask=mask)
|
||||
req_state_idx = tl.load(expanded_idx_mapping_ptr + block, mask=mask)
|
||||
local_pos = tl.load(expanded_local_pos_ptr + block, mask=mask)
|
||||
prefill_len = tl.load(prefill_len_ptr + req_state_idx, mask=mask)
|
||||
# Drafts are only proposed after sampling past the prefill, so any draft
|
||||
# slots in a step starting within the prefill are placeholders (e.g. the
|
||||
# padded first step after a P/D remote KV load).
|
||||
is_placeholder = (local_pos > 0) & (pos - local_pos < prefill_len)
|
||||
token_id = tl.where(is_placeholder, -1, token_id)
|
||||
tl.store(draft_sampled_ptr + block, token_id, mask=mask)
|
||||
tl.store(pos_ptr + block, pos, mask=mask)
|
||||
|
||||
|
||||
def gather_draft_sampled(
|
||||
input_ids: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
logits_indices: torch.Tensor,
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
prefill_len: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Gather the input token and position of each logits row.
|
||||
|
||||
Draft rows of requests that have not yet sampled past their prefill are
|
||||
set to -1 so that the rejection kernels reject them.
|
||||
"""
|
||||
num_logits = logits_indices.shape[0]
|
||||
draft_sampled = input_ids.new_empty(num_logits)
|
||||
pos = positions.new_empty(num_logits)
|
||||
BLOCK_SIZE = 1024
|
||||
_gather_draft_sampled_kernel[(triton.cdiv(num_logits, BLOCK_SIZE),)](
|
||||
draft_sampled,
|
||||
pos,
|
||||
input_ids,
|
||||
positions,
|
||||
logits_indices,
|
||||
expanded_idx_mapping,
|
||||
expanded_local_pos,
|
||||
prefill_len,
|
||||
num_logits,
|
||||
BLOCK_SIZE=BLOCK_SIZE,
|
||||
)
|
||||
return draft_sampled, pos
|
||||
|
||||
|
||||
class RejectionSampler:
|
||||
def __init__(
|
||||
self,
|
||||
@@ -296,8 +366,14 @@ class RejectionSampler:
|
||||
# that num_nans is computed before applying penalties and temperature.
|
||||
num_nans = get_num_nans(logits) if self.sampler.compute_nans else None
|
||||
|
||||
draft_sampled = input_batch.input_ids[input_batch.logits_indices]
|
||||
pos = input_batch.positions[input_batch.logits_indices]
|
||||
draft_sampled, pos = gather_draft_sampled(
|
||||
input_batch.input_ids,
|
||||
input_batch.positions,
|
||||
input_batch.logits_indices,
|
||||
input_batch.expanded_idx_mapping,
|
||||
input_batch.expanded_local_pos,
|
||||
self.sampler.req_states.prefill_len.gpu,
|
||||
)
|
||||
|
||||
max_num_logprobs = self.sampler.sampling_states.max_num_logprobs(
|
||||
input_batch.idx_mapping_np
|
||||
|
||||
@@ -58,6 +58,8 @@ def _target_feeds_hc_residual(vllm_config: VllmConfig) -> bool:
|
||||
|
||||
class BaseSpeculator(ABC):
|
||||
num_query_per_req: int = 1
|
||||
# Extra query slots reserved per request outside the regular queries.
|
||||
num_extra_query_per_req: int = 0
|
||||
|
||||
@abstractmethod
|
||||
def init_cudagraph_manager(self, cudagraph_mode: CUDAGraphMode) -> None:
|
||||
@@ -302,6 +304,7 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
step: int,
|
||||
causal: bool | Mapping[int, bool] = True,
|
||||
dcp_local_seq_lens: torch.Tensor | None = None,
|
||||
slot_mappings: torch.Tensor | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
num_reqs_padded = batch_desc.num_reqs or num_reqs
|
||||
# A FULL graph replays a captured shape whose padded requests each hold
|
||||
@@ -323,7 +326,8 @@ class DraftModelSpeculator(BaseSpeculator):
|
||||
block_tables = [
|
||||
x[:num_reqs_padded] for x in self.block_tables.input_block_tables
|
||||
]
|
||||
slot_mappings = self.block_tables.slot_mappings[:, :num_tokens]
|
||||
if slot_mappings is None:
|
||||
slot_mappings = self.block_tables.slot_mappings[:, :num_tokens]
|
||||
draft_seq_lens_cpu_upper_bound = torch.zeros(
|
||||
num_reqs_padded, dtype=torch.int32, device="cpu"
|
||||
)
|
||||
|
||||
@@ -181,6 +181,11 @@ def _slice_input_batch(
|
||||
req_start:req_stop
|
||||
],
|
||||
is_prefilling_np=input_batch.is_prefilling_np[req_start:req_stop],
|
||||
prefill_runs_as_decode_np=(
|
||||
None
|
||||
if input_batch.prefill_runs_as_decode_np is None
|
||||
else input_batch.prefill_runs_as_decode_np[req_start:req_stop]
|
||||
),
|
||||
input_ids=input_batch.input_ids[tok_start:tok_stop],
|
||||
positions=input_batch.positions[tok_start:tok_stop],
|
||||
is_padding=input_batch.is_padding[tok_start:tok_stop],
|
||||
|
||||
@@ -294,7 +294,11 @@ def _warmup_kernels(
|
||||
model_runner.scheduler_config.max_num_batched_tokens
|
||||
// max(prompt_len, decode_query_len),
|
||||
)
|
||||
if max_blocks_per_req > 0:
|
||||
block_tables = getattr(model_runner, "block_tables", None)
|
||||
null_blocks = block_tables is not None and (
|
||||
block_tables.redirect_writes_to_null_block
|
||||
)
|
||||
if max_blocks_per_req > 0 and not null_blocks:
|
||||
# Reserve block 0 (null block) and ensure we have enough blocks.
|
||||
# Encoder-only models allocate no KV blocks, so this cap doesn't apply.
|
||||
num_reqs = min(
|
||||
@@ -450,4 +454,6 @@ def _warmup_kernels(
|
||||
cleanup_output.finished_req_ids = set(req_ids)
|
||||
worker_execute_model(cleanup_output)
|
||||
model_runner.kv_connector.set_disabled(False)
|
||||
if model_runner.kv_block_zeroer is not None:
|
||||
model_runner.kv_block_zeroer.zero_block_ids([0])
|
||||
torch.accelerator.synchronize()
|
||||
|
||||
@@ -4833,6 +4833,23 @@ class GPUModelRunner(
|
||||
self.input_batch.num_tokens_no_spec[i] = pos + 1
|
||||
self.input_batch.prev_req_id_to_index = prev_req_id_to_index
|
||||
|
||||
@contextmanager
|
||||
def preserve_serving_state(self):
|
||||
multi_block_table = self.input_batch.block_table
|
||||
saved = [
|
||||
(bt.block_table.gpu.clone(), bt.block_table.cpu.clone())
|
||||
for bt in multi_block_table.block_tables
|
||||
]
|
||||
multi_block_table.clear()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for bt, (saved_gpu, saved_cpu) in zip(
|
||||
multi_block_table.block_tables, saved
|
||||
):
|
||||
bt.block_table.gpu.copy_(saved_gpu)
|
||||
bt.block_table.cpu.copy_(saved_cpu)
|
||||
|
||||
def take_draft_token_ids(self) -> DraftTokenIds | None:
|
||||
if not self.num_spec_tokens or not self._draft_token_req_ids:
|
||||
return None
|
||||
|
||||
@@ -65,6 +65,7 @@ class WorkerSentinel:
|
||||
self.dp_rank,
|
||||
self.dp_size,
|
||||
backend="gloo",
|
||||
timeout=self.worker.parallel_config.cpu_distributed_timeout,
|
||||
)
|
||||
|
||||
def _clean_worker_state(self):
|
||||
|
||||
+11
-3
@@ -383,7 +383,13 @@ def select_common_block_size(
|
||||
for size in sorted(candidates, reverse=True):
|
||||
if block_size_is_supported(backends, size):
|
||||
return size
|
||||
raise ValueError(f"No common block size for {kv_manager_block_size}.")
|
||||
raise ValueError(
|
||||
f"No common block size for {kv_manager_block_size} ("
|
||||
+ "; ".join(
|
||||
f"{b.get_name()}: {b.get_supported_kernel_block_sizes()}" for b in backends
|
||||
)
|
||||
+ ")."
|
||||
)
|
||||
|
||||
|
||||
def allocate_kv_cache(
|
||||
@@ -741,10 +747,12 @@ def is_uniform_query_len(num_reqs: int, num_tokens: int, max_query_len: int) ->
|
||||
|
||||
|
||||
def get_uniform_decode_token_count(
|
||||
num_reqs: int, num_tokens: int, max_query_len: int, has_prefill: bool
|
||||
num_reqs: int, num_tokens: int, max_query_len: int, decode_graph_eligible: bool
|
||||
) -> int | None:
|
||||
"""Per-request token count of a uniform decode batch, or None."""
|
||||
if not has_prefill and is_uniform_query_len(num_reqs, num_tokens, max_query_len):
|
||||
if decode_graph_eligible and is_uniform_query_len(
|
||||
num_reqs, num_tokens, max_query_len
|
||||
):
|
||||
return max_query_len
|
||||
return None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user