Merge branch 'main' into patches
Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
@@ -506,19 +506,13 @@ class CommonAttentionMetadata:
|
||||
# but not the right per-request boundaries. Padding requests have a query
|
||||
# length of zero and are skipped by the device boundary search.
|
||||
num_mapped_tokens = int(self.query_start_loc_cpu[-1])
|
||||
from vllm.v1.attention.ops.metadata import _token_request_mapping_kernel
|
||||
from vllm.v1.attention.ops.metadata import compute_token_to_req_indices
|
||||
|
||||
num_output_tokens = max(num_mapped_tokens, num_tokens)
|
||||
assert buffer.shape[0] >= num_output_tokens
|
||||
_token_request_mapping_kernel[((num_output_tokens + 255) // 256,)](
|
||||
self.query_start_loc,
|
||||
buffer,
|
||||
self.query_start_loc.shape[0] - 1,
|
||||
num_mapped_tokens,
|
||||
num_output_tokens,
|
||||
num_warps=4,
|
||||
self._token_to_req_indices_cache = compute_token_to_req_indices(
|
||||
self.query_start_loc, buffer, num_mapped_tokens, num_output_tokens
|
||||
)
|
||||
self._token_to_req_indices_cache = buffer[:num_output_tokens]
|
||||
return self._token_to_req_indices_cache[:num_tokens]
|
||||
|
||||
# TODO(lucas): remove once we have FULL-CG spec-decode support
|
||||
@@ -609,8 +603,11 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
supports_update_block_table: bool = False
|
||||
# Whether the builder constructor requires the block-table width.
|
||||
requires_block_table_width: ClassVar[bool] = False
|
||||
# Whether all step-dependent draft decode metadata can be updated in place,
|
||||
# allowing one metadata build to be reused across autoregressive draft steps.
|
||||
# Whether update_draft_decode_metadata() can regenerate all decode metadata
|
||||
# from persistent device buffers with capture-safe ops only. Lets a
|
||||
# speculator record the refresh inside its draft decode CUDA graph, so no
|
||||
# eager build() is needed between steps or between the batches that replay
|
||||
# it, whether the graph holds one draft forward or a multi-step loop.
|
||||
supports_draft_decode_metadata_update: bool = False
|
||||
|
||||
@abstractmethod
|
||||
@@ -758,12 +755,12 @@ class AttentionMetadataBuilder(ABC, Generic[M]):
|
||||
)
|
||||
|
||||
def update_draft_decode_metadata(self, metadata: M) -> None:
|
||||
"""Update step-dependent draft decode metadata in place.
|
||||
"""Update draft decode metadata in place.
|
||||
|
||||
The fused draft loop may call this method during full CUDA graph
|
||||
capture. CUDA graph replay does not run this Python method, so
|
||||
implementations must emit capture-safe operations and keep replayed
|
||||
tensor state in persistent storage.
|
||||
Speculators can record this call inside their draft decode CUDA graphs,
|
||||
so it runs once at capture and never again in Python. Implementations
|
||||
must emit only capture-safe operations and write results into persistent
|
||||
tensors that ``metadata`` already references.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -816,8 +813,9 @@ class AttentionImplBase(ABC, Generic[T]):
|
||||
is_sparse: ClassVar[bool] = False
|
||||
|
||||
# Whether this impl provides a dense-MHA prefill path (forward_mha). Sparse
|
||||
# impls without one run the top-k MQA path for all requests.
|
||||
supports_dense_mha_prefill: ClassVar[bool] = True
|
||||
# impls without one run the top-k MQA path for all requests. Impls may
|
||||
# override it per instance, depending on the kv-cache layout.
|
||||
supports_dense_mha_prefill: bool = True
|
||||
|
||||
# Required attributes that all impls should have
|
||||
num_heads: int
|
||||
|
||||
@@ -16,6 +16,7 @@ from flashinfer import (
|
||||
BatchPrefillWithRaggedKVCacheWrapper,
|
||||
MultiLevelCascadeAttentionWrapper,
|
||||
get_seq_lens,
|
||||
nvfp4_quantize_append_paged_kv_cache_with_slot_mapping,
|
||||
)
|
||||
from flashinfer.decode import fast_decode_plan, trtllm_batch_decode_with_kv_cache
|
||||
from flashinfer.prefill import trtllm_batch_context_with_kv_cache
|
||||
@@ -106,6 +107,36 @@ logger = init_logger(__name__)
|
||||
trtllm_workspace_buffer = None
|
||||
|
||||
|
||||
def _nvfp4_kv_on_fa2() -> bool:
|
||||
return any(current_platform.is_device_capability_family(f) for f in (80, 90, 120))
|
||||
|
||||
|
||||
_KVPair = tuple[torch.Tensor, torch.Tensor]
|
||||
|
||||
|
||||
def _nvfp4_kv_views(
|
||||
kv_cache: torch.Tensor, num_kv_heads: int
|
||||
) -> tuple[_KVPair, _KVPair, str]:
|
||||
"""Views of NVFP4 pages laid out as [K data | K scale | V data | V scale]."""
|
||||
num_blocks, num_slots, block_size, full_dim = kv_cache.shape
|
||||
hnd = kv_cache.stride()[1:] == (block_size * full_dim, full_dim, 1)
|
||||
if not hnd and kv_cache.stride()[1:] != (full_dim, num_slots * full_dim, 1):
|
||||
raise ValueError(f"NVFP4 KV pages must be dense, got {kv_cache.stride()}")
|
||||
dims = (num_kv_heads, block_size) if hnd else (block_size, num_kv_heads)
|
||||
side_size = num_kv_heads * block_size * full_dim
|
||||
(k_data, k_scale), (v_data, v_scale) = (
|
||||
nvfp4_split_data_scale(
|
||||
kv_cache.as_strided(
|
||||
(num_blocks, *dims, full_dim),
|
||||
(kv_cache.stride(0), dims[1] * full_dim, full_dim, 1),
|
||||
kv_cache.storage_offset() + side * side_size,
|
||||
)
|
||||
)
|
||||
for side in range(2)
|
||||
)
|
||||
return (k_data, v_data), (k_scale, v_scale), "HND" if hnd else "NHD"
|
||||
|
||||
|
||||
def _get_trtllm_workspace_buffer():
|
||||
global trtllm_workspace_buffer
|
||||
if trtllm_workspace_buffer is None:
|
||||
@@ -498,6 +529,9 @@ class FlashInferBackend(AttentionBackend):
|
||||
@classmethod
|
||||
def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool:
|
||||
if kv_cache_dtype is not None and kv_cache_dtype.startswith("nvfp4"):
|
||||
if _nvfp4_kv_on_fa2():
|
||||
# The slot-mapping writer has no scale search.
|
||||
return kv_cache_dtype == "nvfp4"
|
||||
return (
|
||||
current_platform.is_device_capability_family(100)
|
||||
and supports_trtllm_attention(is_prefill=True)
|
||||
@@ -505,6 +539,30 @@ class FlashInferBackend(AttentionBackend):
|
||||
)
|
||||
return super().supports_kv_cache_dtype(kv_cache_dtype)
|
||||
|
||||
@classmethod
|
||||
def supports_combination(
|
||||
cls,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
kv_cache_dtype: CacheDType | None,
|
||||
block_size: int | None,
|
||||
use_mla: bool,
|
||||
has_sink: bool,
|
||||
use_sparse: bool,
|
||||
use_mm_prefix: bool,
|
||||
device_capability: DeviceCapability,
|
||||
) -> str | None:
|
||||
if (
|
||||
kv_cache_dtype is not None
|
||||
and kv_cache_dtype.startswith("nvfp4")
|
||||
and device_capability.major in (8, 9, 12)
|
||||
):
|
||||
if head_size == 64:
|
||||
return "fa2 prefill misreads an NVFP4 KV cache at head_size 64"
|
||||
if has_sink:
|
||||
return "the sink prefill wrapper cannot read an NVFP4 KV cache"
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
# https://github.com/flashinfer-ai/flashinfer/blob/3d55c71a62052c590c130897d3a3db49b14fcc34/include/flashinfer/utils.cuh#L157
|
||||
@@ -777,7 +835,16 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
# Cannot use self.kv_cache_spec.dtype here because kv_cache_spec
|
||||
# storage dtype may not be the same as the op dtype (uint8 vs fp8_e4m3)
|
||||
self.is_kvcache_nvfp4 = self.cache_dtype.startswith("nvfp4")
|
||||
if self.is_kvcache_nvfp4:
|
||||
# fa2 plans NVFP4 by its uint8 storage dtype.
|
||||
self.nvfp4_fa2 = self.is_kvcache_nvfp4 and _nvfp4_kv_on_fa2()
|
||||
self.nvfp4_trtllm = self.is_kvcache_nvfp4 and not self.nvfp4_fa2
|
||||
if self.nvfp4_fa2 and self.use_dcp:
|
||||
raise NotImplementedError(
|
||||
"The DCP prefill wrapper cannot read NVFP4 block scales."
|
||||
)
|
||||
if self.nvfp4_fa2 and self.head_dim == 64:
|
||||
raise NotImplementedError("fa2 prefill misreads NVFP4 at head_size 64.")
|
||||
if self.nvfp4_trtllm:
|
||||
if (
|
||||
force_use_trtllm_attention() is False
|
||||
or not supports_trtllm_attention(is_prefill=True)
|
||||
@@ -798,6 +865,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
else:
|
||||
self.cache_dtype = "auto"
|
||||
self.is_kvcache_nvfp4 = False
|
||||
self.nvfp4_fa2 = self.nvfp4_trtllm = False
|
||||
assert self.kv_cache_spec.dtype == self.model_config.dtype
|
||||
self.kv_cache_dtype = self.kv_cache_spec.dtype
|
||||
|
||||
@@ -810,8 +878,11 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
|
||||
# Prefer TRTLLM/XQA for decoding whenever supported. The decode kernel
|
||||
# must be selected statically for FULL cudagraph capture.
|
||||
can_use_xqa_or_trtllm_gen_decode = can_use_trtllm_attention(
|
||||
self.num_qo_heads, self.num_kv_heads, is_prefill=False
|
||||
can_use_xqa_or_trtllm_gen_decode = (
|
||||
can_use_trtllm_attention(
|
||||
self.num_qo_heads, self.num_kv_heads, is_prefill=False
|
||||
)
|
||||
and not self.nvfp4_fa2
|
||||
)
|
||||
# Page sizes >= 128 require the trtllm-gen GQA/MQA path (guaranteed by
|
||||
# get_supported_kernel_block_sizes).
|
||||
@@ -894,7 +965,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
self.window_left = self.global_hyperparameters.window_left
|
||||
self.logits_soft_cap = self.global_hyperparameters.logits_soft_cap
|
||||
self.has_sinks = self.global_hyperparameters.has_sinks
|
||||
if self.has_sinks and not FlashInferBackend.supports_sink():
|
||||
if self.has_sinks and (self.nvfp4_fa2 or not FlashInferBackend.supports_sink()):
|
||||
raise NotImplementedError(
|
||||
"FlashInfer backend currently does not support attention "
|
||||
"sinks, please use trtllm on blackwell or flash attention on "
|
||||
@@ -970,6 +1041,8 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
return FlashInferBackend.get_dtype_for_flashinfer(cache_dtype)
|
||||
return self.model_config.dtype
|
||||
if cache_dtype.startswith("nvfp4"):
|
||||
if self.nvfp4_fa2:
|
||||
return self.model_config.dtype
|
||||
return FlashInferBackend.get_dtype_for_flashinfer("fp8_e4m3")
|
||||
return self.kv_cache_spec.dtype
|
||||
|
||||
@@ -1002,7 +1075,13 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
num_qo_heads=num_qo_heads,
|
||||
num_kv_heads=spec.num_kv_heads,
|
||||
is_prefill=False,
|
||||
) or (is_xqa_arch and not _is_xqa_head_dim_supported(spec.head_size)):
|
||||
) or (
|
||||
is_xqa_arch
|
||||
and (
|
||||
spec.kv_quant_mode.is_nvfp4
|
||||
or not _is_xqa_head_dim_supported(spec.head_size)
|
||||
)
|
||||
):
|
||||
has_uniform_batch_support = False
|
||||
break
|
||||
|
||||
@@ -1230,8 +1309,8 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
)
|
||||
else:
|
||||
# NVFP4 KV cache requires the trtllm-gen backend inside
|
||||
# the wrapper; fa2/fa3 do not support nvfp4.
|
||||
backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
|
||||
# the wrapper on SM100; SM8x, SM90 and SM12x read it with fa2.
|
||||
backend = "trtllm-gen" if self.nvfp4_trtllm else "auto"
|
||||
self._prefill_wrapper = BatchPrefillWithPagedKVCacheWrapper(
|
||||
self._get_workspace_buffer(),
|
||||
get_flashinfer_layout_string(self.kv_cache_layout),
|
||||
@@ -1256,8 +1335,8 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
paged_kv_indices = None
|
||||
paged_kv_last_page_len = None
|
||||
# NVFP4 KV cache requires the trtllm-gen backend inside
|
||||
# the wrapper; fa2/fa3 do not support nvfp4.
|
||||
backend = "trtllm-gen" if self.is_kvcache_nvfp4 else "auto"
|
||||
# the wrapper on SM100; SM8x, SM90 and SM12x read it with fa2.
|
||||
backend = "trtllm-gen" if self.nvfp4_trtllm else "auto"
|
||||
decode_wrapper = BatchDecodeWithPagedKVCacheWrapper(
|
||||
self._get_workspace_buffer(),
|
||||
get_flashinfer_layout_string(self.kv_cache_layout),
|
||||
@@ -1710,7 +1789,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
# use FP8 o_data_type so the wrapper matches the
|
||||
# FP8 output buffer allocated in forward().
|
||||
o_dtype = (
|
||||
FP8_DTYPE if self.is_kvcache_nvfp4 else self.model_config.dtype
|
||||
FP8_DTYPE if self.nvfp4_trtllm else self.model_config.dtype
|
||||
)
|
||||
prefill_wrapper.plan(
|
||||
qo_indptr=qo_indptr_prefill_cpu,
|
||||
@@ -1797,9 +1876,7 @@ class FlashInferMetadataBuilder(AttentionMetadataBuilder[FlashInferMetadata]):
|
||||
# NVFP4 trtllm kernel only supports FP8 output;
|
||||
# use FP8 o_data_type so the wrapper matches the
|
||||
# FP8 output buffer allocated in forward().
|
||||
o_dtype = (
|
||||
FP8_DTYPE if self.is_kvcache_nvfp4 else self.model_config.dtype
|
||||
)
|
||||
o_dtype = FP8_DTYPE if self.nvfp4_trtllm else self.model_config.dtype
|
||||
paged_kv_indptr_cpu = self.paged_kv_indptr.cpu[: num_input_tokens + 1]
|
||||
paged_kv_last_page_len_cpu = self.paged_kv_last_page_len.cpu[
|
||||
:num_input_tokens
|
||||
@@ -1891,6 +1968,8 @@ class FlashInferImpl(AttentionImpl):
|
||||
)
|
||||
self.cache_dtype = kv_cache_dtype
|
||||
self.is_kvcache_nvfp4 = kv_cache_dtype.startswith("nvfp4")
|
||||
self.nvfp4_fa2 = self.is_kvcache_nvfp4 and _nvfp4_kv_on_fa2()
|
||||
self.nvfp4_trtllm = self.is_kvcache_nvfp4 and not self.nvfp4_fa2
|
||||
self.kv_cache_dtype = "nvfp4" if self.is_kvcache_nvfp4 else kv_cache_dtype
|
||||
self.fp4_data_dim = head_size // 2 if self.is_kvcache_nvfp4 else 0
|
||||
self.logits_soft_cap = logits_soft_cap
|
||||
@@ -1937,7 +2016,7 @@ class FlashInferImpl(AttentionImpl):
|
||||
self.o_sf_scale: float | None = None
|
||||
|
||||
# Pre-allocated FP8 output buffer for NVFP4 without fused output quant.
|
||||
if self.is_kvcache_nvfp4 and vllm_config is not None:
|
||||
if self.nvfp4_trtllm and vllm_config is not None:
|
||||
max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
self._nvfp4_fp8_out = torch.empty(
|
||||
(max_num_tokens, num_heads, head_size),
|
||||
@@ -2195,10 +2274,9 @@ class FlashInferImpl(AttentionImpl):
|
||||
canonicalize_singleton_dim_strides(k_cache.permute(*stride_order)),
|
||||
canonicalize_singleton_dim_strides(v_cache.permute(*stride_order)),
|
||||
)
|
||||
k_data, k_sf = nvfp4_split_data_scale(kv_cache_tuple[0])
|
||||
v_data, v_sf = nvfp4_split_data_scale(kv_cache_tuple[1])
|
||||
nvfp4_kv_data = (k_data, v_data)
|
||||
nvfp4_kv_block_scales = (k_sf, v_sf)
|
||||
nvfp4_kv_data, nvfp4_kv_block_scales, _ = _nvfp4_kv_views(
|
||||
kv_cache, self.num_kv_heads
|
||||
)
|
||||
else:
|
||||
kv_cache_tuple = kv_cache_permute.split(hs, dim=-1)
|
||||
|
||||
@@ -2276,7 +2354,7 @@ class FlashInferImpl(AttentionImpl):
|
||||
# Use a pre-allocated FP8 buffer and dequantize
|
||||
# afterwards.
|
||||
needs_fp8_out_prefill = (
|
||||
self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
|
||||
self.nvfp4_trtllm and output.dtype != FP8_DTYPE
|
||||
)
|
||||
if needs_fp8_out_prefill:
|
||||
out_prefill = self._nvfp4_fp8_out[:num_prefill_tokens]
|
||||
@@ -2299,7 +2377,8 @@ class FlashInferImpl(AttentionImpl):
|
||||
prefill_wrapper.run(
|
||||
prefill_query,
|
||||
kv_cache_for_fi,
|
||||
q_scale=layer._q_scale_float,
|
||||
# The fa2 NVFP4 query stays in the model dtype.
|
||||
q_scale=1.0 if self.nvfp4_fa2 else layer._q_scale_float,
|
||||
k_scale=layer._k_scale_float,
|
||||
v_scale=layer._v_scale_float,
|
||||
out=out_prefill,
|
||||
@@ -2451,7 +2530,7 @@ class FlashInferImpl(AttentionImpl):
|
||||
|
||||
# NVFP4 kernel only supports FP8 output.
|
||||
# Use a pre-allocated FP8 buffer and dequantize afterwards.
|
||||
needs_fp8_out = self.is_kvcache_nvfp4 and output.dtype != FP8_DTYPE
|
||||
needs_fp8_out = self.nvfp4_trtllm and output.dtype != FP8_DTYPE
|
||||
if needs_fp8_out:
|
||||
out_decode = self._nvfp4_fp8_out[:num_decode_tokens]
|
||||
else:
|
||||
@@ -2488,7 +2567,7 @@ class FlashInferImpl(AttentionImpl):
|
||||
decode_wrapper.run(
|
||||
decode_query,
|
||||
kv_cache_for_fi,
|
||||
q_scale=layer._q_scale_float,
|
||||
q_scale=1.0 if self.nvfp4_fa2 else layer._q_scale_float,
|
||||
k_scale=layer._k_scale_float,
|
||||
v_scale=layer._v_scale_float,
|
||||
out=out_decode,
|
||||
@@ -2668,6 +2747,19 @@ class FlashInferImpl(AttentionImpl):
|
||||
# and value[:num_actual_tokens] because the reshape_and_cache_flash
|
||||
# op uses the slot_mapping's shape to determine the number of
|
||||
# actual tokens.
|
||||
if self.nvfp4_fa2:
|
||||
data, scales, kv_layout = _nvfp4_kv_views(kv_cache, self.num_kv_heads)
|
||||
nvfp4_quantize_append_paged_kv_cache_with_slot_mapping(
|
||||
key,
|
||||
value,
|
||||
slot_mapping,
|
||||
data,
|
||||
scales,
|
||||
layer._k_scale,
|
||||
layer._v_scale,
|
||||
kv_layout=kv_layout,
|
||||
)
|
||||
return
|
||||
if self.is_kvcache_nvfp4:
|
||||
# (B, 2*H, N, full_dim) -> ((B, N, H, full_dim),
|
||||
# (B, N, H, full_dim));
|
||||
|
||||
@@ -7,6 +7,7 @@ from typing import Literal
|
||||
|
||||
import torch
|
||||
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.mamba.checkpoint import (
|
||||
MambaPrefillCheckpointBuilder,
|
||||
@@ -79,6 +80,7 @@ class GDNAttentionMetadata:
|
||||
prefill_query_start_loc: torch.Tensor | None = None
|
||||
prefill_state_indices: torch.Tensor | None = None
|
||||
prefill_has_initial_state: torch.Tensor | None = None
|
||||
aiter_prefill_metadata: object | None = None
|
||||
|
||||
# The following attributes are for triton implementation of causal_conv1d
|
||||
nums_dict: dict | None = None
|
||||
@@ -109,8 +111,11 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
_resolve_gdn_prefill_backend,
|
||||
)
|
||||
|
||||
self.gdn_prefill_backend: Literal["triton", "flashinfer", "cutedsl"]
|
||||
self.gdn_prefill_backend: Literal[
|
||||
"triton", "flashinfer", "cutedsl", "aiter_flydsl"
|
||||
]
|
||||
_, self.gdn_prefill_backend = _resolve_gdn_prefill_backend(vllm_config)
|
||||
self._check_chunk_metadata_override(type(self), self.gdn_prefill_backend)
|
||||
|
||||
if self.speculative_config:
|
||||
assert self.speculative_config.num_speculative_tokens is not None
|
||||
@@ -186,6 +191,32 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
device=device,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _check_chunk_metadata_override(
|
||||
builder_cls: type["GDNAttentionMetadataBuilder"], backend: str
|
||||
) -> None:
|
||||
"""Reject a subclass whose chunk metadata the AITER path would skip.
|
||||
|
||||
AITER brings its own varlen prefill metadata and never calls
|
||||
``_build_chunk_metadata``, so a builder that overrides it would lose
|
||||
that override without a word. No in-tree subclass can get here --
|
||||
``_resolve_gdn_prefill_backend`` only selects this backend for models
|
||||
with 128-dim GDN key and value heads, which the KDA builders are not --
|
||||
but a future one should be told rather than quietly ignored.
|
||||
"""
|
||||
if backend != "aiter_flydsl":
|
||||
return
|
||||
if (
|
||||
builder_cls._build_chunk_metadata
|
||||
is GDNAttentionMetadataBuilder._build_chunk_metadata
|
||||
):
|
||||
return
|
||||
raise RuntimeError(
|
||||
f"{builder_cls.__name__} builds its own FLA chunk metadata, which "
|
||||
"the 'aiter_flydsl' GDN prefill backend does not use. Select a "
|
||||
"different gdn_prefill_backend for this model."
|
||||
)
|
||||
|
||||
def _build_chunk_metadata(
|
||||
self,
|
||||
prefill_query_start_loc: torch.Tensor,
|
||||
@@ -260,11 +291,10 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
else:
|
||||
spec_sequence_masks_cpu = num_decode_draft_tokens_cpu >= 0
|
||||
num_spec_decodes = spec_sequence_masks_cpu.sum().item()
|
||||
if (
|
||||
num_spec_decodes == 0
|
||||
or num_decode_draft_tokens_cpu[spec_sequence_masks_cpu].sum().item()
|
||||
== 0
|
||||
):
|
||||
# A batch whose rows all drafted nothing still has to run the
|
||||
# speculative path: that is the only path that applies each row's
|
||||
# accepted-token offset to the recurrent state.
|
||||
if num_spec_decodes == 0:
|
||||
num_spec_decodes = 0
|
||||
spec_sequence_masks = None
|
||||
spec_sequence_masks_cpu = None
|
||||
@@ -432,6 +462,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
prefill_query_start_loc: torch.Tensor | None = None
|
||||
prefill_state_indices: torch.Tensor | None = None
|
||||
prefill_has_initial_state: torch.Tensor | None = None
|
||||
aiter_prefill_metadata: object | None = None
|
||||
if num_prefills > 0:
|
||||
# In a mixed non-spec batch, decodes are peeled off to the recurrent
|
||||
# kernel (decode-first front slice), so build chunk metadata from the
|
||||
@@ -453,11 +484,23 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
prefill_query_start_loc_cpu = non_spec_query_start_loc_cpu
|
||||
prefill_state_indices = non_spec_state_indices_tensor
|
||||
|
||||
chunk_indices, chunk_offsets = self._build_chunk_metadata(
|
||||
prefill_query_start_loc,
|
||||
prefill_query_start_loc_cpu,
|
||||
query_start_loc.device,
|
||||
)
|
||||
if self.gdn_prefill_backend == "aiter_flydsl":
|
||||
# AITER carries its own reusable varlen metadata and has no use
|
||||
# for FLA's chunk indices, so it replaces them rather than
|
||||
# extending what _build_chunk_metadata returns.
|
||||
assert prefill_query_start_loc_cpu is not None
|
||||
aiter_prefill_metadata = (
|
||||
rocm_aiter_ops.build_gdn_flydsl_prefill_metadata(
|
||||
torch.diff(prefill_query_start_loc_cpu).tolist(),
|
||||
cu_seqlens=prefill_query_start_loc,
|
||||
)
|
||||
)
|
||||
else:
|
||||
chunk_indices, chunk_offsets = self._build_chunk_metadata(
|
||||
prefill_query_start_loc,
|
||||
prefill_query_start_loc_cpu,
|
||||
query_start_loc.device,
|
||||
)
|
||||
|
||||
if num_prefills > 0:
|
||||
context_lens_tensor = m.compute_num_computed_tokens()
|
||||
@@ -569,6 +612,7 @@ class GDNAttentionMetadataBuilder(AttentionMetadataBuilder[GDNAttentionMetadata]
|
||||
prefill_query_start_loc=prefill_query_start_loc,
|
||||
prefill_state_indices=prefill_state_indices,
|
||||
prefill_has_initial_state=prefill_has_initial_state,
|
||||
aiter_prefill_metadata=aiter_prefill_metadata,
|
||||
spec_query_start_loc=spec_query_start_loc,
|
||||
non_spec_query_start_loc=non_spec_query_start_loc,
|
||||
spec_state_indices_tensor=spec_state_indices_tensor,
|
||||
|
||||
@@ -7,6 +7,10 @@ from typing import Any
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.model_executor.layers.mamba.checkpoint import (
|
||||
MambaPrefillCheckpointBuilder,
|
||||
MambaPrefillCheckpointMetadata,
|
||||
)
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.attention.backend import (
|
||||
AttentionBackend,
|
||||
@@ -109,6 +113,11 @@ class Mamba2AttentionMetadata(BaseMambaAttentionMetadata):
|
||||
# Chunk-related metadata (only for prefill)
|
||||
seq_idx_p: torch.Tensor | None = None
|
||||
|
||||
# Internal prefill checkpoints, one entry per prefill row. The chunk
|
||||
# index selects the varlen_states row holding the checkpoint state.
|
||||
checkpoint_chunk_idx: torch.Tensor | None = None
|
||||
checkpoint_meta: MambaPrefillCheckpointMetadata | None = None
|
||||
|
||||
|
||||
class Mamba2AttentionMetadataBuilder(
|
||||
BaseMambaAttentionMetadataBuilder[Mamba2AttentionMetadata]
|
||||
@@ -128,6 +137,9 @@ class Mamba2AttentionMetadataBuilder(
|
||||
"chunk_size needs to be set in the model config for Mamba2 models"
|
||||
)
|
||||
self.chunk_size: int = chunk_size
|
||||
self.checkpoint_builder = MambaPrefillCheckpointBuilder(
|
||||
vllm_config, kv_cache_spec
|
||||
)
|
||||
|
||||
def build(
|
||||
self,
|
||||
@@ -145,6 +157,8 @@ class Mamba2AttentionMetadataBuilder(
|
||||
seq_idx_p = None
|
||||
cu_chunk_seqlen_p = None
|
||||
last_chunk_indices_p = None
|
||||
checkpoint_chunk_idx = None
|
||||
checkpoint_meta = None
|
||||
prep_initial_states = False
|
||||
|
||||
# Compute seq_idx for prefill only
|
||||
@@ -162,12 +176,27 @@ class Mamba2AttentionMetadataBuilder(
|
||||
)
|
||||
prep_initial_states = bool((num_computed_tokens_p_cpu > 0).any())
|
||||
|
||||
cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p = (
|
||||
self._build_chunk_metadata_tensors(
|
||||
self.chunk_size,
|
||||
common,
|
||||
common_attn_metadata,
|
||||
)
|
||||
checkpoint_offsets_p = None
|
||||
first = common.num_reqs - common.num_prefills
|
||||
checkpoint = self.checkpoint_builder.build(
|
||||
common_attn_metadata,
|
||||
list(range(first, common.num_reqs)),
|
||||
)
|
||||
if checkpoint is not None:
|
||||
# The host offsets place a chunk boundary on the checkpoint.
|
||||
checkpoint_offsets_p = checkpoint.offsets
|
||||
checkpoint_meta = checkpoint
|
||||
|
||||
(
|
||||
cu_chunk_seqlen_p,
|
||||
seq_idx_p,
|
||||
last_chunk_indices_p,
|
||||
checkpoint_chunk_idx,
|
||||
) = self._build_chunk_metadata_tensors(
|
||||
self.chunk_size,
|
||||
common,
|
||||
common_attn_metadata,
|
||||
checkpoint_offsets_p,
|
||||
)
|
||||
|
||||
return replace(
|
||||
@@ -177,4 +206,22 @@ class Mamba2AttentionMetadataBuilder(
|
||||
seq_idx_p=seq_idx_p,
|
||||
cu_chunk_seqlen_p=cu_chunk_seqlen_p,
|
||||
last_chunk_indices_p=last_chunk_indices_p,
|
||||
checkpoint_chunk_idx=checkpoint_chunk_idx,
|
||||
checkpoint_meta=checkpoint_meta,
|
||||
)
|
||||
|
||||
def update_block_table(
|
||||
self,
|
||||
metadata: Mamba2AttentionMetadata,
|
||||
blk_table: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
) -> Mamba2AttentionMetadata:
|
||||
new_metadata = super().update_block_table(metadata, blk_table, slot_mapping)
|
||||
if metadata.checkpoint_meta is None:
|
||||
return new_metadata
|
||||
# Checkpoint destinations are block-table entries, so each group
|
||||
# re-gathers its own rather than writing into the source group's.
|
||||
return replace(
|
||||
new_metadata,
|
||||
checkpoint_meta=metadata.checkpoint_meta.regather_state_indices(blk_table),
|
||||
)
|
||||
|
||||
@@ -238,13 +238,14 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
num_decode_draft_tokens_cpu=num_decode_draft_tokens_cpu,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _compute_chunk_metadata(
|
||||
self,
|
||||
chunk_size: int,
|
||||
num_prefills: int,
|
||||
num_computed_tokens_p_cpu: torch.Tensor,
|
||||
query_start_loc_p_cpu: torch.Tensor,
|
||||
) -> tuple[list[int], list[int], list[int]]:
|
||||
checkpoint_offsets_p: list[int] | None = None,
|
||||
) -> tuple[list[int], list[int], list[int], list[int]]:
|
||||
"""Compute chunk-specific metadata for Mamba models.
|
||||
|
||||
The code below carefully constructs the chunks such that:
|
||||
@@ -256,20 +257,34 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
of prefix caching for mamba (wip). We need to take care
|
||||
of the interaction with chunked prefill in order to
|
||||
satisfy constraint (2).
|
||||
|
||||
`checkpoint_offsets_p[i]` forces an extra chunk end that many tokens
|
||||
into row i's query (0 = none), because the SSD scan only materializes
|
||||
states at chunk ends. Returns its chunk index per row, or -1.
|
||||
"""
|
||||
# TODO (tdoublep): This code could probably be optimized.
|
||||
cu_chunk_seqlen = []
|
||||
seq_idx = []
|
||||
last_chunk_indices = []
|
||||
checkpoint_chunk_indices = []
|
||||
seqlen_pos = 0
|
||||
|
||||
# A checkpoint splits its request into two segments so that a chunk
|
||||
# ends exactly on it; each segment then chunks by the rules below.
|
||||
segments = []
|
||||
for req_idx in range(num_prefills):
|
||||
this_num_computed = num_computed_tokens_p_cpu[req_idx].item()
|
||||
this_new_tokens = (
|
||||
computed = num_computed_tokens_p_cpu[req_idx].item()
|
||||
tokens = (
|
||||
query_start_loc_p_cpu[req_idx + 1].item()
|
||||
- query_start_loc_p_cpu[req_idx].item()
|
||||
)
|
||||
ckpt = checkpoint_offsets_p[req_idx] if checkpoint_offsets_p else 0
|
||||
if ckpt:
|
||||
segments.append((req_idx, computed, ckpt, True))
|
||||
segments.append((req_idx, computed + ckpt, tokens - ckpt, False))
|
||||
checkpoint_chunk_indices = [-1] * num_prefills
|
||||
|
||||
for req_idx, this_num_computed, this_new_tokens, is_ckpt_end in segments:
|
||||
# if computed tokens are not chunk-aligned, use the first
|
||||
# chunk to finish it off
|
||||
if this_num_computed % chunk_size != 0:
|
||||
@@ -293,11 +308,14 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
this_new_tokens -= chunk_len
|
||||
|
||||
assert this_new_tokens == 0
|
||||
last_chunk_indices.append(len(cu_chunk_seqlen) - 1)
|
||||
if is_ckpt_end:
|
||||
checkpoint_chunk_indices[req_idx] = len(cu_chunk_seqlen) - 1
|
||||
else:
|
||||
last_chunk_indices.append(len(cu_chunk_seqlen) - 1)
|
||||
|
||||
cu_chunk_seqlen.append(seqlen_pos)
|
||||
|
||||
return cu_chunk_seqlen, seq_idx, last_chunk_indices
|
||||
return cu_chunk_seqlen, seq_idx, last_chunk_indices, checkpoint_chunk_indices
|
||||
|
||||
def _prefill_cpu_metadata(
|
||||
self,
|
||||
@@ -331,9 +349,13 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
chunk_size: int,
|
||||
common: M,
|
||||
common_attn_metadata: CommonAttentionMetadata,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
checkpoint_offsets_p: list[int] | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor | None]:
|
||||
"""Compute chunk metadata and return as device tensors.
|
||||
Returns (cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p).
|
||||
Returns (cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p,
|
||||
checkpoint_chunk_idx_p). The last is None unless a row checkpoints;
|
||||
it has one entry per prefill row, holding the logical chunk that ends
|
||||
on the checkpoint, and 0 for rows that decline.
|
||||
"""
|
||||
num_prefills = common.num_prefills
|
||||
|
||||
@@ -344,11 +366,14 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
common.num_decode_tokens,
|
||||
)
|
||||
|
||||
cu_chunk_seqlen, seq_idx, last_chunk_indices = self._compute_chunk_metadata(
|
||||
chunk_size,
|
||||
num_prefills,
|
||||
num_computed_tokens_p_cpu,
|
||||
query_start_loc_p_cpu,
|
||||
cu_chunk_seqlen, seq_idx, last_chunk_indices, ckpt_idxs = (
|
||||
self._compute_chunk_metadata(
|
||||
chunk_size,
|
||||
num_prefills,
|
||||
num_computed_tokens_p_cpu,
|
||||
query_start_loc_p_cpu,
|
||||
checkpoint_offsets_p,
|
||||
)
|
||||
)
|
||||
|
||||
device = common_attn_metadata.query_start_loc.device
|
||||
@@ -361,7 +386,14 @@ class BaseMambaAttentionMetadataBuilder(AttentionMetadataBuilder[M], abc.ABC):
|
||||
last_chunk_indices_p = async_tensor_h2d(
|
||||
last_chunk_indices, dtype=torch.int32, device=device
|
||||
)
|
||||
return cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p
|
||||
ckpt_idx_p = (
|
||||
async_tensor_h2d(
|
||||
[max(idx, 0) for idx in ckpt_idxs], dtype=torch.int64, device=device
|
||||
)
|
||||
if any(idx >= 0 for idx in ckpt_idxs)
|
||||
else None
|
||||
)
|
||||
return cu_chunk_seqlen_p, seq_idx_p, last_chunk_indices_p, ckpt_idx_p
|
||||
|
||||
def _compute_common_metadata(
|
||||
self,
|
||||
|
||||
@@ -37,6 +37,8 @@ class CompressedSlotMappingKernel(
|
||||
compress_ratio: int
|
||||
triton_block_size: int
|
||||
block_size: int
|
||||
dcp_world_size: int
|
||||
cp_interleave: int
|
||||
|
||||
@staticmethod
|
||||
@triton.jit(do_not_specialize=["block_table_stride"])
|
||||
@@ -53,6 +55,8 @@ class CompressedSlotMappingKernel(
|
||||
block_table_ptr,
|
||||
block_table_stride,
|
||||
block_size,
|
||||
dcp_world_size,
|
||||
cp_interleave,
|
||||
COMPRESS_RATIO: tl.constexpr,
|
||||
PAD_ID: tl.constexpr,
|
||||
TRITON_BLOCK_SIZE: tl.constexpr,
|
||||
@@ -77,7 +81,14 @@ class CompressedSlotMappingKernel(
|
||||
slot_mapping_ptr + query_start + offset, mask=mask, other=PAD_ID
|
||||
)
|
||||
is_valid = ((pos + 1) % COMPRESS_RATIO == 0) & (slot != PAD_ID)
|
||||
pos_after_compress = pos // COMPRESS_RATIO
|
||||
# Under DCP a PAD slot also marks tokens owned by other ranks; the
|
||||
# interleave is a multiple of COMPRESS_RATIO, so a state lives
|
||||
# entirely on the rank owning its last token.
|
||||
local_pos = (
|
||||
pos // (cp_interleave * dcp_world_size) * cp_interleave
|
||||
+ pos % cp_interleave
|
||||
)
|
||||
pos_after_compress = local_pos // COMPRESS_RATIO
|
||||
|
||||
block_ids = pos_after_compress // block_size
|
||||
block_numbers = tl.load(
|
||||
@@ -97,11 +108,15 @@ class CompressedSlotMappingKernel(
|
||||
*,
|
||||
compress_ratio: int,
|
||||
block_size: int,
|
||||
dcp_world_size: int,
|
||||
cp_interleave: int,
|
||||
) -> CompileKey:
|
||||
return self.CompileKey(
|
||||
compress_ratio=compress_ratio,
|
||||
triton_block_size=self.TRITON_BLOCK_SIZE,
|
||||
block_size=triton_scalar_specialization_rep(block_size),
|
||||
dcp_world_size=triton_scalar_specialization_rep(dcp_world_size),
|
||||
cp_interleave=triton_scalar_specialization_rep(cp_interleave),
|
||||
)
|
||||
|
||||
def get_warmup_keys(self, vllm_config: Any) -> list[CompileKey]:
|
||||
@@ -115,12 +130,15 @@ class CompressedSlotMappingKernel(
|
||||
)
|
||||
if not compress_ratios:
|
||||
return []
|
||||
parallel_config = vllm_config.parallel_config
|
||||
return self._trace_dispatch(self.dispatch)(
|
||||
zip_inputs(
|
||||
*(
|
||||
dict(
|
||||
compress_ratio=ratio,
|
||||
block_size=vllm_config.cache_config.block_size // ratio,
|
||||
dcp_world_size=parallel_config.decode_context_parallel_size,
|
||||
cp_interleave=parallel_config.cp_kv_cache_interleave_size,
|
||||
)
|
||||
for ratio in compress_ratios
|
||||
)
|
||||
@@ -137,6 +155,8 @@ class CompressedSlotMappingKernel(
|
||||
block_table=int32_ptr,
|
||||
block_size=compile_key.block_size,
|
||||
compress_ratio=compile_key.compress_ratio,
|
||||
dcp_world_size=compile_key.dcp_world_size,
|
||||
cp_interleave=compile_key.cp_interleave,
|
||||
)
|
||||
|
||||
@kernel_launcher
|
||||
@@ -149,6 +169,8 @@ class CompressedSlotMappingKernel(
|
||||
block_table: torch.Tensor,
|
||||
block_size: int,
|
||||
compress_ratio: int,
|
||||
dcp_world_size: int,
|
||||
cp_interleave: int,
|
||||
) -> LaunchSpec:
|
||||
return (block_table.shape[0],), dict(
|
||||
block_table_stride=block_table.stride(0),
|
||||
@@ -167,6 +189,8 @@ def get_compressed_slot_mapping(
|
||||
block_size: int,
|
||||
compress_ratio: int,
|
||||
out: torch.Tensor | None = None,
|
||||
dcp_world_size: int = 1,
|
||||
cp_interleave: int = 1,
|
||||
) -> torch.Tensor:
|
||||
"""Slot mapping for writing the compressed states of ``num_tokens`` tokens.
|
||||
|
||||
@@ -196,6 +220,8 @@ def get_compressed_slot_mapping(
|
||||
block_table,
|
||||
block_size,
|
||||
compress_ratio,
|
||||
dcp_world_size,
|
||||
cp_interleave,
|
||||
)
|
||||
return compressed_slot_mapping
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
flat_kv_row_view,
|
||||
triton_convert_req_index_to_global_index,
|
||||
)
|
||||
from vllm.v1.attention.ops.metadata import compute_token_to_req_indices
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.vllm_flash_attn.flash_attn_interface import flash_attn_varlen_func
|
||||
|
||||
@@ -132,8 +133,18 @@ class FlashAttnMLASparseMetadataBuilder(
|
||||
self._init_reorder_batch_threshold(threshold, supports_spec_as_decode=True)
|
||||
self.supports_draft_decode_metadata_update = self.dcp_world_size == 1
|
||||
|
||||
def update_draft_decode_metadata(self, _metadata: SparseMLACommonMetadata) -> None:
|
||||
pass
|
||||
def update_draft_decode_metadata(self, metadata: SparseMLACommonMetadata) -> None:
|
||||
num_tokens = metadata.num_decode_tokens
|
||||
if num_tokens == 0:
|
||||
return
|
||||
# Everything else is a view of runner buffers; the per-token request
|
||||
# map is a builder buffer that build() filled for the captured batch.
|
||||
compute_token_to_req_indices(
|
||||
metadata.query_start_loc,
|
||||
metadata.req_id_per_token,
|
||||
num_tokens,
|
||||
num_tokens,
|
||||
)
|
||||
|
||||
|
||||
class FlashAttnMLASparseImpl(SparseMLACommonImpl[FlashAttnMLASparseMetadata]):
|
||||
|
||||
@@ -26,6 +26,7 @@ from vllm.v1.attention.backend import (
|
||||
AttentionType,
|
||||
MLAAttentionImpl,
|
||||
MultipleOf,
|
||||
max_decode_query_len,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.index_group import HiSparseMLAIndexGroup
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
@@ -34,7 +35,7 @@ from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
triton_convert_req_index_to_global_index,
|
||||
triton_filter_and_convert_dcp_index,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.model_executor.models.deepseek_v2 import Indexer
|
||||
@@ -272,7 +273,16 @@ class FlashInferMLASparseMetadataBuilder(
|
||||
class FlashInferMLASparseTRTLLMMetadataBuilder(FlashInferMLASparseMetadataBuilder):
|
||||
"""Metadata builder for the SM100 TRT-LLM sparse MLA kernel."""
|
||||
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.ALWAYS
|
||||
_cudagraph_support: ClassVar[AttentionCGSupport] = AttentionCGSupport.UNIFORM_BATCH
|
||||
|
||||
@classmethod
|
||||
def get_varlen_cudagraph_max_query_len(
|
||||
cls,
|
||||
vllm_config: VllmConfig,
|
||||
kv_cache_spec: KVCacheSpec,
|
||||
) -> int | None:
|
||||
# Decode uses device request boundaries; prefill metadata is not graph-safe.
|
||||
return max_decode_query_len(vllm_config)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, ClassVar
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
@@ -127,6 +128,9 @@ QUANTIZED_DS_MLA_CACHE_FORMATS: frozenset[str] = frozenset(
|
||||
{"fp8_ds_mla", "nvfp4_ds_mla"}
|
||||
)
|
||||
|
||||
# RoPE dims in an fp8_ds_mla row (the bf16 tail of the 656B layout).
|
||||
FP8_DS_MLA_ROPE_DIM = 64
|
||||
|
||||
|
||||
class FlashMLASparseBackend(AttentionBackend):
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
@@ -186,16 +190,16 @@ class FlashMLASparseBackend(AttentionBackend):
|
||||
) -> str | None:
|
||||
if head_size == 512:
|
||||
# GLM5Next NoPE (qk_rope_head_dim == 0, kv_lora_rank == 512) has
|
||||
# head_size 512 and is served here by the direct 512-wide bf16
|
||||
# cache on SM90. Quantized DS-MLA caches need the zero-padded
|
||||
# 576/656B envelope, which is wired up separately; plain fp8,
|
||||
# SM100 bf16, and rope-carrying 512 models must fall through to
|
||||
# head_size 512 and is served here on SM90, either by the direct
|
||||
# 512-wide bf16 cache or by the 576 fp8_ds_mla layout with a zero
|
||||
# RoPE slot (see FlashMLASparseImpl.q_head_size). Plain fp8,
|
||||
# SM100, and rope-carrying 512 models must fall through to
|
||||
# FlashInfer/TRITON.
|
||||
if (
|
||||
kv_cache_dtype in (None, "auto", "bfloat16", "float16")
|
||||
kv_cache_dtype in (None, "auto", "bfloat16", "float16", "fp8_ds_mla")
|
||||
and device_capability.major == 9
|
||||
):
|
||||
# Direct bf16 NoPE-512 is only correct for rope-free models.
|
||||
# NoPE-512 is only correct for rope-free models.
|
||||
# Precedent for reading hf_text_config in supports_combination:
|
||||
# flashinfer_mla_sparse.py.
|
||||
from vllm.config import get_current_vllm_config
|
||||
@@ -210,8 +214,8 @@ class FlashMLASparseBackend(AttentionBackend):
|
||||
)
|
||||
else:
|
||||
return (
|
||||
"FLASHMLA_SPARSE supports head_size 512 only with bf16 "
|
||||
"kv-cache on SM90 (NoPE), got "
|
||||
"FLASHMLA_SPARSE supports head_size 512 only with bf16 or "
|
||||
"fp8_ds_mla kv-cache on SM90 (NoPE), got "
|
||||
f"kv_cache_dtype={kv_cache_dtype}, "
|
||||
f"capability={device_capability}"
|
||||
)
|
||||
@@ -726,12 +730,20 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
**mla_args,
|
||||
)
|
||||
self.softmax_scale = scale
|
||||
# Prefill BF16 kernel requires 64 on Hopper, 128 on Blackwell
|
||||
self.prefill_padding = (
|
||||
128 if current_platform.is_device_capability_family(100) else 64
|
||||
)
|
||||
# Prefill BF16 kernel requires 64 heads on Hopper and Blackwell.
|
||||
self.prefill_padding = 64
|
||||
self.fp8_decode_padded_heads = self._compute_fp8_decode_padded_heads(num_heads)
|
||||
|
||||
# The kernels read queries as wide as the cache rows. A NoPE model on
|
||||
# fp8_ds_mla keeps the DeepSeek 576 layout: the cache writer zero-fills
|
||||
# the RoPE slot and forward_mqa zero-pads q_pe to match (q_pe . 0 = 0).
|
||||
self.q_head_size = head_size
|
||||
if kv_cache_dtype == "fp8_ds_mla" and self.qk_rope_head_dim == 0:
|
||||
self.q_head_size = self.kv_lora_rank + FP8_DS_MLA_ROPE_DIM
|
||||
# Dense-MHA prefill would gather the cache into a
|
||||
# kv_lora_rank-wide workspace, too narrow for the 576 rows.
|
||||
self.supports_dense_mha_prefill = False
|
||||
|
||||
vllm_config = get_current_vllm_config()
|
||||
max_tokens = vllm_config.scheduler_config.max_num_batched_tokens
|
||||
q_concat_heads = num_heads
|
||||
@@ -741,7 +753,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
// self.prefill_padding
|
||||
* self.prefill_padding
|
||||
)
|
||||
q_concat_shape = (max_tokens, q_concat_heads, head_size)
|
||||
q_concat_shape = (max_tokens, q_concat_heads, self.q_head_size)
|
||||
if is_quantized_kv_cache(kv_cache_dtype):
|
||||
assert kv_cache_dtype in QUANTIZED_DS_MLA_CACHE_FORMATS, (
|
||||
"FlashMLA Sparse Attention backend only supports the "
|
||||
@@ -777,11 +789,11 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
# PCP+DCP upconverts this rank's KV shard, then all-gathers the
|
||||
# shards into a workspace of the full prefill size.
|
||||
shard_rows //= parallel_config.decode_context_parallel_size
|
||||
self.prefill_workspace_shape = (shard_rows, head_size)
|
||||
self.prefill_workspace_shape = (shard_rows, self.q_head_size)
|
||||
self.workspace_specs.append((self.prefill_workspace_shape, torch.bfloat16))
|
||||
if self.pcp_dcp_kv_gather:
|
||||
self.workspace_specs.append(
|
||||
((prefill_workspace_size, head_size), torch.bfloat16)
|
||||
((prefill_workspace_size, self.q_head_size), torch.bfloat16)
|
||||
)
|
||||
prefill_query_heads = num_heads
|
||||
if self.pcp_dcp_kv_gather and self.dcp_world_size > self.pcp_world_size:
|
||||
@@ -792,7 +804,7 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
self.workspace_specs.extend(
|
||||
(shape, torch.bfloat16)
|
||||
for shape in (
|
||||
(max_tokens, padded_prefill_query_heads, head_size),
|
||||
(max_tokens, padded_prefill_query_heads, self.q_head_size),
|
||||
(max_tokens, padded_prefill_query_heads, self.kv_lora_rank),
|
||||
(max_tokens, prefill_query_heads, self.kv_lora_rank),
|
||||
)
|
||||
@@ -1309,9 +1321,9 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
-1, 1, kv_c_and_k_pe_cache.shape[-1]
|
||||
)
|
||||
|
||||
# NOTE(Chen): kernel requires num_local_head to be a multiple of
|
||||
# 64 on hopper and 128 on blackwell. Pad from q's head count, not
|
||||
# self.num_heads: under DCP the heads are all-gathered before this.
|
||||
# NOTE(Chen): kernel requires num_local_head to be a multiple of 64.
|
||||
# Pad from q's head count, not self.num_heads: under DCP the heads are
|
||||
# all-gathered before this.
|
||||
if actual_num_heads is None:
|
||||
actual_num_heads = q.shape[1]
|
||||
padded_num_heads = (
|
||||
@@ -1370,11 +1382,16 @@ class FlashMLASparseImpl(SparseMLACommonImpl[FlashMLASparseMetadata]):
|
||||
if q_pe.size(-1) == 0:
|
||||
# NoPE (GLM5Next): concat_mla_q requires rope_dim == 64,
|
||||
# copy directly into the head-padded buffer instead.
|
||||
q[:, : ql_nope.shape[1]].copy_(ql_nope)
|
||||
q[:, : ql_nope.shape[1], : self.kv_lora_rank].copy_(ql_nope)
|
||||
if self.q_head_size > self.kv_lora_rank:
|
||||
q[..., self.kv_lora_rank :].zero_()
|
||||
else:
|
||||
ops.concat_mla_q(ql_nope, q_pe, q)
|
||||
else:
|
||||
actual_num_heads = q.shape[1]
|
||||
if q.shape[-1] < self.q_head_size:
|
||||
# DCP gathers the unpadded NoPE query.
|
||||
q = F.pad(q, (0, self.q_head_size - q.shape[-1]))
|
||||
|
||||
num_actual_toks = q.shape[0]
|
||||
|
||||
|
||||
@@ -233,7 +233,7 @@ class HiSparseMLAIndexGroup(SparseMLAIndexGroup):
|
||||
cache = self.cache(layer_index)
|
||||
num_tokens = logical_topk_indices.shape[0]
|
||||
req_id_per_token = attn_metadata.req_id_per_token[:num_tokens]
|
||||
if num_tokens > self.physical_topk_indices.shape[0]:
|
||||
if num_tokens > cache.runtime.max_swap_rows:
|
||||
# Prefill-sized batches do not fit the decode residency workspace.
|
||||
# Non-resident prefills are staged before reaching this path.
|
||||
assert cache.all_context_pages_resident
|
||||
|
||||
@@ -554,7 +554,15 @@ class BuildPrefillChunkMetadataKernel(
|
||||
# Cover Triton's divisible, exact-one, and generic i32 classes.
|
||||
query_slice_start=(0, 1, 2),
|
||||
query_slice_stop=(1, 2 * max_tokens - 1, 2 * max_tokens),
|
||||
DCP_INTERLEAVE=dcp_interleave,
|
||||
# Compressed indexers localize in units of compressed states.
|
||||
DCP_INTERLEAVE=list(
|
||||
dict.fromkeys(
|
||||
dcp_interleave // ratio
|
||||
for ratio in compress_ratios
|
||||
if dcp_interleave % ratio == 0
|
||||
)
|
||||
)
|
||||
or [dcp_interleave],
|
||||
BLOCK_SIZE=self.BLOCK_SIZE,
|
||||
COMPRESS_RATIO=list(compress_ratios),
|
||||
# PCP's global cumulative lengths are the second row of one packed
|
||||
@@ -670,6 +678,7 @@ class DeepseekV32IndexerMetadata:
|
||||
decode: DeepSeekV32IndexerDecodeMetadata | None = None
|
||||
prefill: DeepseekV32IndexerPrefillMetadata | None = None
|
||||
positions: torch.Tensor | None = None
|
||||
block_table: torch.Tensor | None = None
|
||||
|
||||
|
||||
@triton.jit(do_not_specialize=["num_reqs", "num_actual_tokens", "num_tokens"])
|
||||
@@ -693,11 +702,15 @@ def _kpool_tail_slot_mapping_kernel(
|
||||
end = tl.load(query_start_loc_ptr + pid + 1)
|
||||
end = tl.where(pid == num_reqs - 1, num_actual_tokens, end)
|
||||
own_block = tl.load(block_table_ptr + pid * block_table_stride).to(tl.int64)
|
||||
# Every scheduled request owns a tail block; the runners give dummy and
|
||||
# padding requests the null block, which must never be written.
|
||||
has_block = own_block != 0
|
||||
for i in range(start, end, BLOCK):
|
||||
offs = i + tl.arange(0, BLOCK)
|
||||
mask = offs < end
|
||||
pos = tl.load(positions_ptr + offs, mask=mask, other=0).to(tl.int64)
|
||||
tl.store(out_ptr + offs, own_block * kpool + pos % kpool, mask=mask)
|
||||
slot = tl.where(has_block, own_block * kpool + pos % kpool, -1)
|
||||
tl.store(out_ptr + offs, slot, mask=mask)
|
||||
else:
|
||||
offs = num_actual_tokens + (pid - num_reqs) * BLOCK + tl.arange(0, BLOCK)
|
||||
mask = offs < num_tokens
|
||||
@@ -750,7 +763,8 @@ def compute_kpool_tail_slot_mapping(
|
||||
req = req.clamp_(min=0, max=num_reqs - 1)
|
||||
own_block = block_table[:num_reqs, 0].index_select(0, req).to(torch.int64)
|
||||
pos = positions[:num_actual_tokens].to(torch.int64)
|
||||
out[:num_actual_tokens] = own_block * kpool + torch.remainder(pos, kpool)
|
||||
slots = own_block * kpool + torch.remainder(pos, kpool)
|
||||
out[:num_actual_tokens] = torch.where(own_block != 0, slots, -1)
|
||||
return out
|
||||
|
||||
|
||||
@@ -1010,11 +1024,31 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
(self.num_sms + 1, 2), dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
if self.dcp_world_size > 1 and self.compress_ratio > 1:
|
||||
raise NotImplementedError(
|
||||
"DCP is not supported with sparse indexer KV compression "
|
||||
f"(compress_ratio={self.compress_ratio})."
|
||||
# Each compressed state must live on a single rank, so the DCP
|
||||
# interleave has to cover whole states.
|
||||
if (
|
||||
self.dcp_world_size > 1
|
||||
and self.compress_ratio > 1
|
||||
and (
|
||||
(
|
||||
isinstance(self.kv_cache_spec, MLAAttentionSpec)
|
||||
and self.kv_cache_spec.model_version == "deepseek_v4"
|
||||
)
|
||||
or self.cp_kv_cache_interleave_size % self.compress_ratio != 0
|
||||
)
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"DCP with sparse indexer KV compression "
|
||||
f"(compress_ratio={self.compress_ratio}) requires "
|
||||
"--cp-kv-cache-interleave-size to be a multiple of it; "
|
||||
"DeepSeek-V4 is not supported."
|
||||
)
|
||||
# DCP interleave in units of compressed states.
|
||||
self.compressed_cp_interleave_size = (
|
||||
self.cp_kv_cache_interleave_size // self.compress_ratio
|
||||
if self.dcp_world_size > 1 and self.compress_ratio > 1
|
||||
else self.cp_kv_cache_interleave_size
|
||||
)
|
||||
|
||||
# Pre-allocate buffers for CUDA graph compatibility when
|
||||
if self.compress_ratio > 1:
|
||||
@@ -1348,6 +1382,8 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
self.kv_cache_spec.num_states,
|
||||
self.compress_ratio,
|
||||
out=self.compressed_slot_mapping_buffer,
|
||||
dcp_world_size=self.dcp_world_size,
|
||||
cp_interleave=self.cp_kv_cache_interleave_size,
|
||||
)
|
||||
if self.pcp_world_size > 1:
|
||||
compressed_slot_mapping = get_pcp_group().all_gather(
|
||||
@@ -1467,7 +1503,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
skip_kv_gather=query_slice.start > 0,
|
||||
dcp_rank=self.dcp_rank,
|
||||
dcp_world_size=self.dcp_world_size,
|
||||
cp_kv_cache_interleave_size=self.cp_kv_cache_interleave_size,
|
||||
cp_kv_cache_interleave_size=self.compressed_cp_interleave_size,
|
||||
pcp_plan=pcp_plan,
|
||||
)
|
||||
# Skip when total_seq_lens is 0 (i.e., no compressed token).
|
||||
@@ -1683,6 +1719,7 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
num_prefill_tokens=num_prefill_tokens,
|
||||
prefill=prefill_metadata,
|
||||
decode=decode_metadata,
|
||||
block_table=common_attn_metadata.block_table_tensor,
|
||||
)
|
||||
|
||||
return attn_metadata
|
||||
@@ -1698,8 +1735,28 @@ class DeepseekV32IndexerMetadataBuilder(AttentionMetadataBuilder):
|
||||
assert metadata.num_prefills == 0
|
||||
assert metadata.num_decodes == metadata.num_decode_tokens
|
||||
assert decode.seq_lens.numel() == metadata.num_decode_tokens
|
||||
assert metadata.block_table is not None
|
||||
assert self.dcp_world_size == 1
|
||||
|
||||
# One query token per request, so the per-token decode block table is
|
||||
# the request block table (at the indexer kernel's page size). build()
|
||||
# may copy it into a builder buffer, so re-derive it for this batch.
|
||||
block_table = metadata.block_table[: metadata.num_decode_tokens]
|
||||
kernel_block_size = self.kernel_block_size
|
||||
if (
|
||||
self.compress_ratio > 1
|
||||
and kernel_block_size is not None
|
||||
and self.kv_cache_spec.block_size != kernel_block_size
|
||||
and self.kv_cache_spec.block_size % kernel_block_size == 0
|
||||
):
|
||||
factor = self.kv_cache_spec.block_size // kernel_block_size
|
||||
block_table = block_table[:, ::factor] // factor
|
||||
decode.block_table.copy_(block_table)
|
||||
if decode.indices is not None:
|
||||
decode.indices.copy_(self.arange_buffer[: metadata.num_decode_tokens])
|
||||
if decode.per_req_decode_lens is not None:
|
||||
decode.per_req_decode_lens.fill_(1)
|
||||
|
||||
if self.compress_ratio > 1:
|
||||
get_compressed_slot_mapping(
|
||||
metadata.num_decode_tokens,
|
||||
|
||||
@@ -31,7 +31,10 @@ class AiterFlashAttnPrefillBackend(MLAPrefillBackend):
|
||||
return "ROCM_AITER_FA"
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
def supports_compute_capability(
|
||||
cls,
|
||||
device_capability: "DeviceCapability | None",
|
||||
) -> bool:
|
||||
if not current_platform.is_rocm():
|
||||
return False
|
||||
from vllm.platforms.rocm import on_mi3xx
|
||||
|
||||
@@ -49,7 +49,10 @@ class MLAPrefillBackend(ABC):
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
def supports_compute_capability(
|
||||
cls,
|
||||
device_capability: "DeviceCapability | None",
|
||||
) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
@@ -90,16 +93,19 @@ class MLAPrefillBackend(ABC):
|
||||
@classmethod
|
||||
def validate_configuration(
|
||||
cls,
|
||||
device_capability: "DeviceCapability",
|
||||
device_capability: "DeviceCapability | None",
|
||||
selector_config: "MLAPrefillSelectorConfig",
|
||||
) -> list[str]:
|
||||
invalid_reasons: list[str] = []
|
||||
|
||||
if not cls.supports_compute_capability(device_capability):
|
||||
invalid_reasons.append(
|
||||
f"compute capability {device_capability.major}."
|
||||
f"{device_capability.minor} not supported"
|
||||
)
|
||||
if device_capability is None:
|
||||
invalid_reasons.append("device capability not available")
|
||||
else:
|
||||
invalid_reasons.append(
|
||||
f"compute capability {device_capability.major}."
|
||||
f"{device_capability.minor} not supported"
|
||||
)
|
||||
|
||||
if not cls.supports_dtype(selector_config.dtype):
|
||||
invalid_reasons.append(f"dtype {selector_config.dtype} not supported")
|
||||
|
||||
@@ -51,8 +51,11 @@ class FlashInferPrefillBackend(MLAPrefillBackend):
|
||||
return "FLASHINFER"
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
return device_capability.major == 10
|
||||
def supports_compute_capability(
|
||||
cls,
|
||||
device_capability: "DeviceCapability | None",
|
||||
) -> bool:
|
||||
return device_capability is not None and device_capability.major == 10
|
||||
|
||||
@classmethod
|
||||
def is_available(cls) -> bool:
|
||||
|
||||
@@ -10,11 +10,14 @@ from collections.abc import Callable
|
||||
from enum import Enum, EnumMeta
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLAPrefillBackend
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class _MLAPrefillBackendEnumMeta(EnumMeta):
|
||||
"""Metaclass for MLAPrefillBackendEnum to provide better error messages."""
|
||||
@@ -61,6 +64,37 @@ class MLAPrefillBackendEnum(Enum, metaclass=_MLAPrefillBackendEnumMeta):
|
||||
# set to None to avoid alias with other backend, whose value is an empty string
|
||||
CUSTOM = None
|
||||
|
||||
@classmethod
|
||||
def register(cls, name: str, value: str) -> "MLAPrefillBackendEnum":
|
||||
"""Dynamically register a new MLA prefill backend enum member.
|
||||
|
||||
Args:
|
||||
name: The name for the new enum member
|
||||
value: The fully qualified class path string
|
||||
|
||||
Returns:
|
||||
The newly created enum member
|
||||
|
||||
"""
|
||||
if name in cls._member_map_:
|
||||
raise ValueError(
|
||||
f"MLA prefill backend {name} already exists in {cls.__name__}. "
|
||||
f"Use register_mla_prefill_backend("
|
||||
f"{cls.__name__}.{name}, '{value}') to override."
|
||||
)
|
||||
if not name.isidentifier() or hasattr(cls, name):
|
||||
raise ValueError(f"Invalid or reserved backend name: {name}")
|
||||
|
||||
member = object.__new__(cls)
|
||||
member._name_ = name
|
||||
member._value_ = value
|
||||
setattr(cls, name, member)
|
||||
cls._member_map_[name] = member
|
||||
cls._value2member_map_[value] = member
|
||||
cls._member_names_.append(name)
|
||||
logger.info("Registered new MLA prefill backend: %s -> %s", name, value)
|
||||
return member
|
||||
|
||||
def get_path(self) -> str:
|
||||
"""Get the class path for this backend (respects overrides).
|
||||
|
||||
@@ -107,13 +141,15 @@ _MLA_PREFILL_OVERRIDES: dict[MLAPrefillBackendEnum, str] = {}
|
||||
|
||||
|
||||
def register_mla_prefill_backend(
|
||||
backend: MLAPrefillBackendEnum,
|
||||
backend: MLAPrefillBackendEnum | str,
|
||||
class_path: str | None = None,
|
||||
) -> Callable[[type], type]:
|
||||
"""Register or override an MLA prefill backend implementation.
|
||||
|
||||
Args:
|
||||
backend: The MLAPrefillBackendEnum member to register.
|
||||
backend: The MLAPrefillBackendEnum member to register,
|
||||
or a string name for a new custom backend
|
||||
(e.g., "CUSTOM_MLA_PREFILL").
|
||||
class_path: Optional class path. If not provided and used as
|
||||
decorator, will be auto-generated from the class.
|
||||
|
||||
@@ -131,13 +167,27 @@ def register_mla_prefill_backend(
|
||||
class MyCustomPrefillBackend(MLAPrefillBackend):
|
||||
...
|
||||
|
||||
# Register a new custom MLA prefill backend with a dynamic enum name
|
||||
@register_mla_prefill_backend("CUSTOM_MLA_PREFILL")
|
||||
class CustomMLAPrefillBackend(MLAPrefillBackend):
|
||||
...
|
||||
|
||||
# Direct registration
|
||||
register_mla_prefill_backend(
|
||||
MLAPrefillBackendEnum.CUSTOM,
|
||||
"my.module.MyCustomPrefillBackend"
|
||||
)
|
||||
|
||||
# Direct registration with string name
|
||||
register_mla_prefill_backend(
|
||||
"CUSTOM_MLA_PREFILL",
|
||||
"custom.attention.mla_prefill.CustomMLAPrefillBackend"
|
||||
)
|
||||
|
||||
"""
|
||||
# Handle dynamic enum creation for string backend names
|
||||
if isinstance(backend, str):
|
||||
backend = MLAPrefillBackendEnum.register(backend, class_path or "")
|
||||
|
||||
def decorator(cls: type) -> type:
|
||||
_MLA_PREFILL_OVERRIDES[backend] = f"{cls.__module__}.{cls.__qualname__}"
|
||||
|
||||
@@ -12,9 +12,7 @@ from typing import TYPE_CHECKING, NamedTuple
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
from vllm.v1.attention.backends.mla.prefill.base import MLADimensions
|
||||
from vllm.v1.attention.backends.mla.prefill.registry import MLAPrefillBackendEnum
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
@@ -45,54 +43,8 @@ class MLAPrefillSelectorConfig(NamedTuple):
|
||||
)
|
||||
|
||||
|
||||
def _get_mla_prefill_backend_priorities(
|
||||
device_capability: DeviceCapability,
|
||||
mla_dimensions: MLADimensions,
|
||||
) -> list[MLAPrefillBackendEnum]:
|
||||
"""Get MLA prefill backend priorities based on device capability.
|
||||
|
||||
Args:
|
||||
device_capability: The device's compute capability.
|
||||
mla_dimensions: The model's MLA head dimensions.
|
||||
|
||||
Returns:
|
||||
List of backends in priority order (highest priority first).
|
||||
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_rocm():
|
||||
return [
|
||||
MLAPrefillBackendEnum.ROCM_AITER_FA,
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
]
|
||||
|
||||
if device_capability.major == 10: # Blackwell
|
||||
if mla_dimensions == MLADimensions(
|
||||
qk_nope_head_dim=192,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=256,
|
||||
):
|
||||
return [
|
||||
MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
MLAPrefillBackendEnum.FLASHINFER,
|
||||
MLAPrefillBackendEnum.TOKENSPEED_MLA,
|
||||
]
|
||||
return [
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
MLAPrefillBackendEnum.TRTLLM_RAGGED,
|
||||
MLAPrefillBackendEnum.FLASHINFER,
|
||||
MLAPrefillBackendEnum.TOKENSPEED_MLA,
|
||||
]
|
||||
else: # Hopper (SM90) and older
|
||||
return [
|
||||
MLAPrefillBackendEnum.FLASH_ATTN,
|
||||
]
|
||||
|
||||
|
||||
def get_mla_prefill_backend(
|
||||
vllm_config: "VllmConfig",
|
||||
vllm_config: "VllmConfig | None",
|
||||
) -> "type[MLAPrefillBackend]":
|
||||
"""Select the MLA prefill backend based on configuration and device.
|
||||
|
||||
@@ -101,7 +53,8 @@ def get_mla_prefill_backend(
|
||||
priority-based selection.
|
||||
|
||||
Args:
|
||||
vllm_config: The vLLM configuration.
|
||||
vllm_config: The vLLM configuration. May be None before model
|
||||
resolution, in which case defaults are used.
|
||||
|
||||
Returns:
|
||||
The selected prefill backend class.
|
||||
@@ -109,30 +62,7 @@ def get_mla_prefill_backend(
|
||||
"""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if current_platform.is_cpu():
|
||||
# CPUs have no compute capability, so the capability-driven priority
|
||||
# path below does not apply. Prefer an accelerator-specific CPU backend
|
||||
# when its kernels are present, else the generic SDPA one.
|
||||
for backend_enum in (MLAPrefillBackendEnum.ZEN_CPU, MLAPrefillBackendEnum.CPU):
|
||||
try:
|
||||
cpu_backend_cls = backend_enum.get_class()
|
||||
except ImportError:
|
||||
continue
|
||||
if cpu_backend_cls.is_available():
|
||||
logger.info_once("Using %s MLA prefill backend.", backend_enum.name)
|
||||
return cpu_backend_cls
|
||||
raise ValueError("No valid CPU MLA prefill backend found.")
|
||||
|
||||
device_capability = current_platform.get_device_capability()
|
||||
if device_capability is None:
|
||||
logger.info_once(
|
||||
"Device capability not available, using FlashAttention MLA prefill backend."
|
||||
)
|
||||
return MLAPrefillBackendEnum.FLASH_ATTN.get_class()
|
||||
|
||||
attention_config = vllm_config.attention_config
|
||||
|
||||
model_config = vllm_config.model_config
|
||||
model_config = vllm_config.model_config if vllm_config is not None else None
|
||||
if model_config is None:
|
||||
selector_config = MLAPrefillSelectorConfig(dtype=torch.get_default_dtype())
|
||||
else:
|
||||
@@ -146,11 +76,21 @@ def get_mla_prefill_backend(
|
||||
),
|
||||
)
|
||||
|
||||
if attention_config.mla_prefill_backend is not None:
|
||||
if current_platform.is_cpu():
|
||||
# CPUs have a single fixed MLA prefill backend, so explicit backend
|
||||
# configuration does not apply; always auto-select via the platform.
|
||||
return _auto_select_mla_prefill_backend(selector_config)
|
||||
|
||||
attention_config = vllm_config.attention_config if vllm_config is not None else None
|
||||
if (
|
||||
attention_config is not None
|
||||
and attention_config.mla_prefill_backend is not None
|
||||
):
|
||||
selected_backend = attention_config.mla_prefill_backend
|
||||
backend_cls: type[MLAPrefillBackend] | None = None
|
||||
try:
|
||||
backend_cls = selected_backend.get_class()
|
||||
device_capability = current_platform.get_device_capability()
|
||||
invalid_reasons = backend_cls.validate_configuration(
|
||||
device_capability, selector_config
|
||||
)
|
||||
@@ -166,63 +106,27 @@ def get_mla_prefill_backend(
|
||||
logger.info_once("Using %s MLA prefill backend.", selected_backend.name)
|
||||
return backend_cls
|
||||
|
||||
return _auto_select_mla_prefill_backend(
|
||||
device_capability,
|
||||
selector_config,
|
||||
)
|
||||
return _auto_select_mla_prefill_backend(selector_config)
|
||||
|
||||
|
||||
@cache
|
||||
def _auto_select_mla_prefill_backend(
|
||||
device_capability: DeviceCapability,
|
||||
selector_config: MLAPrefillSelectorConfig,
|
||||
) -> "type[MLAPrefillBackend]":
|
||||
"""Auto-select the best available MLA prefill backend.
|
||||
|
||||
Args:
|
||||
device_capability: The device's compute capability.
|
||||
selector_config: Hashable configuration for backend selection.
|
||||
|
||||
Returns:
|
||||
The selected prefill backend class.
|
||||
|
||||
Raises:
|
||||
ValueError: If the platform has no valid MLA prefill backend.
|
||||
|
||||
"""
|
||||
priorities = _get_mla_prefill_backend_priorities(
|
||||
device_capability,
|
||||
selector_config.mla_dimensions,
|
||||
)
|
||||
all_invalid_reasons: dict[str, list[str]] = {}
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
for backend_enum in priorities:
|
||||
backend_cls: type[MLAPrefillBackend] | None = None
|
||||
try:
|
||||
backend_cls = backend_enum.get_class()
|
||||
invalid_reasons = backend_cls.validate_configuration(
|
||||
device_capability, selector_config
|
||||
)
|
||||
except ImportError:
|
||||
invalid_reasons = ["ImportError"]
|
||||
if not invalid_reasons:
|
||||
assert backend_cls is not None
|
||||
logger.info_once("Using %s MLA prefill backend.", backend_enum.name)
|
||||
return backend_cls
|
||||
all_invalid_reasons[backend_enum.name] = invalid_reasons
|
||||
|
||||
reasons_str = (
|
||||
"{"
|
||||
+ ", ".join(
|
||||
f"{name}: [{', '.join(reasons)}]"
|
||||
for name, reasons in all_invalid_reasons.items()
|
||||
)
|
||||
+ "}"
|
||||
)
|
||||
config_str = repr(selector_config)
|
||||
logger.debug_once(
|
||||
"Some MLA prefill backends are not valid with %s. Reasons: %s.",
|
||||
config_str,
|
||||
reasons_str,
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
f"No valid MLA prefill backend found with {config_str}. Reasons: {reasons_str}."
|
||||
)
|
||||
selected_backend = current_platform.get_mla_prefill_backend_cls(selector_config)
|
||||
logger.info_once("Using %s MLA prefill backend.", selected_backend.get_name())
|
||||
return selected_backend
|
||||
|
||||
@@ -35,8 +35,11 @@ class TokenspeedMLAPrefillBackend(MLAPrefillBackend):
|
||||
return "TOKENSPEED_MLA"
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
return device_capability.major == 10
|
||||
def supports_compute_capability(
|
||||
cls,
|
||||
device_capability: "DeviceCapability | None",
|
||||
) -> bool:
|
||||
return device_capability is not None and device_capability.major == 10
|
||||
|
||||
_INSTALL_HINT = (
|
||||
"tokenspeed_mla package is not installed. "
|
||||
|
||||
@@ -43,8 +43,11 @@ class TrtllmRaggedPrefillBackend(MLAPrefillBackend):
|
||||
return "TRTLLM_RAGGED"
|
||||
|
||||
@classmethod
|
||||
def supports_compute_capability(cls, device_capability: "DeviceCapability") -> bool:
|
||||
return device_capability.major == 10
|
||||
def supports_compute_capability(
|
||||
cls,
|
||||
device_capability: "DeviceCapability | None",
|
||||
) -> bool:
|
||||
return device_capability is not None and device_capability.major == 10
|
||||
|
||||
@classmethod
|
||||
def is_available(cls) -> bool:
|
||||
|
||||
@@ -601,13 +601,14 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
parallel_config.decode_context_parallel_size,
|
||||
parallel_config.cp_kv_cache_interleave_size,
|
||||
)
|
||||
verify_route = envs.VLLM_ROCM_AITER_MLA_DCP_VERIFY.lower()
|
||||
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"
|
||||
and verify_route != "segmented"
|
||||
)
|
||||
super().__init__(
|
||||
kv_cache_spec,
|
||||
@@ -627,14 +628,20 @@ class AiterMLAMetadataBuilder(MLACommonMetadataBuilder[AiterMLAMetadata]):
|
||||
self._asm_dcp_verify_heads = _asm_dcp_verify_heads(
|
||||
self.num_heads * self.dcp_world_size
|
||||
)
|
||||
if not self._asm_dcp_verify_heads:
|
||||
if self._asm_dcp_verify_heads:
|
||||
self._asm_dcp_verify = True
|
||||
elif verify_route == "asm" or not supports_segmented_dcp_verify:
|
||||
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."
|
||||
f"VLLM_ROCM_AITER_MLA_DCP_VERIFY={verify_route}, but the "
|
||||
"round-robin asm decode has no kernel for "
|
||||
f"{self.num_heads * self.dcp_world_size} DCP-gathered heads "
|
||||
f"(native counts: {_NATIVE_CPRR_HEADS}). "
|
||||
+ (
|
||||
"Set VLLM_ROCM_AITER_MLA_DCP_VERIFY=segmented."
|
||||
if supports_segmented_dcp_verify
|
||||
else "This AITER build also lacks segmented MLA decode."
|
||||
)
|
||||
)
|
||||
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:
|
||||
|
||||
@@ -37,7 +37,9 @@ from vllm.v1.attention.backends.mla.rocm_aiter_mla import (
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
|
||||
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
|
||||
rocm_sparse_attn_decode_bf16,
|
||||
rocm_sparse_attn_prefill,
|
||||
rocm_sparse_decode_bf16_num_splits,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheLayout
|
||||
from vllm.v1.worker.workspace import current_workspace_manager
|
||||
@@ -904,20 +906,45 @@ class ROCMAiterMLASparseImpl(
|
||||
self.sinks.reshape(1, self.num_heads, 1),
|
||||
q.shape[1],
|
||||
).reshape(-1)
|
||||
rocm_sparse_attn_prefill(
|
||||
q=q,
|
||||
kv=kv_c_and_k_pe_cache.view(-1, 1, q.shape[-1]),
|
||||
indices=None,
|
||||
topk_length=None,
|
||||
scale=self.scale,
|
||||
head_dim=q.shape[-1],
|
||||
nope_head_dim=self.kv_lora_rank,
|
||||
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
|
||||
attn_sink=triton_sinks,
|
||||
output=output,
|
||||
ragged_indices=attn_metadata.paged_kv_indices,
|
||||
ragged_indptr=attn_metadata.paged_kv_indptr,
|
||||
kv = kv_c_and_k_pe_cache.view(-1, 1, q.shape[-1])
|
||||
decode_num_splits = (
|
||||
rocm_sparse_decode_bf16_num_splits(
|
||||
num_tokens,
|
||||
q.shape[1],
|
||||
min(attn_metadata.max_seq_len, attn_metadata.topk_tokens),
|
||||
)
|
||||
if attn_metadata.num_decode_tokens == num_tokens
|
||||
else 1
|
||||
)
|
||||
if decode_num_splits > 1:
|
||||
rocm_sparse_attn_decode_bf16(
|
||||
q=q,
|
||||
kv=kv,
|
||||
scale=self.scale,
|
||||
head_dim=q.shape[-1],
|
||||
nope_head_dim=self.kv_lora_rank,
|
||||
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
|
||||
attn_sink=triton_sinks,
|
||||
output=output,
|
||||
ragged_indices=attn_metadata.paged_kv_indices,
|
||||
ragged_indptr=attn_metadata.paged_kv_indptr,
|
||||
num_splits=decode_num_splits,
|
||||
)
|
||||
else:
|
||||
rocm_sparse_attn_prefill(
|
||||
q=q,
|
||||
kv=kv,
|
||||
indices=None,
|
||||
topk_length=None,
|
||||
scale=self.scale,
|
||||
head_dim=q.shape[-1],
|
||||
nope_head_dim=self.kv_lora_rank,
|
||||
rope_head_dim=q.shape[-1] - self.kv_lora_rank,
|
||||
attn_sink=triton_sinks,
|
||||
output=output,
|
||||
ragged_indices=attn_metadata.paged_kv_indices,
|
||||
ragged_indptr=attn_metadata.paged_kv_indptr,
|
||||
)
|
||||
output = AiterMLAHelper.get_mla_unpadded_o(self.num_heads, output)
|
||||
return output, None
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ from vllm.v1.attention.backends.mla.compressor_utils import (
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import split_decodes_and_prefills
|
||||
from vllm.v1.attention.ops.flashmla import FlashMLASchedMeta, get_mla_metadata
|
||||
from vllm.v1.attention.ops.metadata import compute_token_to_req_indices
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
KVCacheSpec,
|
||||
MLAAttentionSpec,
|
||||
@@ -829,7 +830,8 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
self,
|
||||
metadata: DeepseekSparseSWAMetadata,
|
||||
) -> None:
|
||||
if metadata.num_decode_tokens == 0:
|
||||
num_tokens = metadata.num_decode_tokens
|
||||
if num_tokens == 0:
|
||||
return
|
||||
assert metadata.query_start_loc is not None
|
||||
assert metadata.seq_lens is not None
|
||||
@@ -839,6 +841,17 @@ class DeepseekSparseSWAMetadataBuilder(AttentionMetadataBuilder):
|
||||
assert metadata.decode_swa_lens is not None
|
||||
assert metadata.replay_start is not None
|
||||
|
||||
# Recompute the validity mask and token->request map from the device
|
||||
# buffers. Their padding differs from the dummy batch the graph was
|
||||
# captured with.
|
||||
torch.ge(metadata.slot_mapping, 0, out=metadata.is_valid_token)
|
||||
compute_token_to_req_indices(
|
||||
metadata.query_start_loc,
|
||||
metadata.token_to_req_indices,
|
||||
num_tokens,
|
||||
num_tokens,
|
||||
)
|
||||
|
||||
_COMPUTE_SWA_INDICES_AND_LENS_KERNEL(
|
||||
metadata.decode_swa_indices,
|
||||
metadata.decode_swa_lens,
|
||||
|
||||
@@ -53,6 +53,9 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
"vllm.v1.attention.backends.triton_flash_attn.TritonFlashAttentionBackend"
|
||||
)
|
||||
ROCM_ATTN = "vllm.v1.attention.backends.rocm_attn.RocmAttentionBackend"
|
||||
ROCM_SEGMENTED_ATTN = (
|
||||
"vllm.v1.attention.backends.rocm_segmented_attn.RocmSegmentedAttentionBackend"
|
||||
)
|
||||
ROCM_AITER_MLA = "vllm.v1.attention.backends.mla.rocm_aiter_mla.AiterMLABackend"
|
||||
ROCM_AITER_TRITON_MLA = (
|
||||
"vllm.v1.attention.backends.mla.aiter_triton_mla.AiterTritonMLABackend"
|
||||
@@ -149,10 +152,43 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
CPU_MLA = "vllm.v1.attention.backends.mla.cpu_mla.CPUMLABackend"
|
||||
AMX_MLA = "vllm.v1.attention.backends.mla.amx_mla.AMXMLABackend"
|
||||
TURBOQUANT = "vllm.v1.attention.backends.turboquant_attn.TurboQuantAttentionBackend"
|
||||
ULTRAQUANT = "vllm.v1.attention.backends.ultraquant_attn.UltraQuantAttentionBackend"
|
||||
# Placeholder for third-party/custom backends - must be registered before use
|
||||
# set to None to avoid alias with other backend, whose value is an empty string
|
||||
CUSTOM = None
|
||||
|
||||
@classmethod
|
||||
def register(cls, name: str, value: str) -> "AttentionBackendEnum":
|
||||
"""Dynamically register a new backend enum member.
|
||||
|
||||
Args:
|
||||
name: The name for the new enum member
|
||||
value: The fully qualified class path string
|
||||
|
||||
Returns:
|
||||
The newly created enum member
|
||||
|
||||
"""
|
||||
if name in cls._member_map_:
|
||||
raise ValueError(
|
||||
f"Backend {name} already exists in {cls.__name__}. "
|
||||
f"Use register_backend({cls.__name__}.{name}, '{value}') "
|
||||
f"to override."
|
||||
)
|
||||
if not name.isidentifier() or hasattr(cls, name):
|
||||
raise ValueError(f"Invalid or reserved backend name: {name}")
|
||||
|
||||
# Create new enum member dynamically
|
||||
member = object.__new__(cls)
|
||||
member._name_ = name
|
||||
member._value_ = value
|
||||
setattr(cls, name, member)
|
||||
cls._member_map_[name] = member
|
||||
cls._value2member_map_[value] = member
|
||||
cls._member_names_.append(name)
|
||||
logger.info("Registered new attention backend: %s -> %s", name, value)
|
||||
return member
|
||||
|
||||
def get_path(self, include_classname: bool = True) -> str:
|
||||
"""Get the class path for this backend (respects overrides).
|
||||
|
||||
@@ -210,6 +246,37 @@ class MambaAttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
|
||||
backend.get_class()
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def register(cls, name: str, value: str) -> "MambaAttentionBackendEnum":
|
||||
"""Dynamically register a new mamba backend enum member.
|
||||
|
||||
Args:
|
||||
name: The name for the new enum member
|
||||
value: The fully qualified class path string
|
||||
|
||||
Returns:
|
||||
The newly created enum member
|
||||
|
||||
"""
|
||||
if name in cls._member_map_:
|
||||
raise ValueError(
|
||||
f"Backend {name} already exists in {cls.__name__}. "
|
||||
f"Use register_backend({cls.__name__}.{name}, '{value}') "
|
||||
f"to override."
|
||||
)
|
||||
if not name.isidentifier() or hasattr(cls, name):
|
||||
raise ValueError(f"Invalid or reserved backend name: {name}")
|
||||
|
||||
member = object.__new__(cls)
|
||||
member._name_ = name
|
||||
member._value_ = value
|
||||
setattr(cls, name, member)
|
||||
cls._member_map_[name] = member
|
||||
cls._value2member_map_[value] = member
|
||||
cls._member_names_.append(name)
|
||||
logger.info("Registered new attention backend: %s -> %s", name, value)
|
||||
return member
|
||||
|
||||
MAMBA1 = "vllm.v1.attention.backends.mamba1_attn.Mamba1AttentionBackend"
|
||||
MAMBA2 = "vllm.v1.attention.backends.mamba2_attn.Mamba2AttentionBackend"
|
||||
SHORT_CONV = "vllm.v1.attention.backends.short_conv_attn.ShortConvAttentionBackend"
|
||||
@@ -271,14 +338,15 @@ _MAMBA_ATTN_OVERRIDES: dict[MambaAttentionBackendEnum, str] = {}
|
||||
|
||||
|
||||
def register_backend(
|
||||
backend: AttentionBackendEnum | MambaAttentionBackendEnum,
|
||||
backend: AttentionBackendEnum | MambaAttentionBackendEnum | str,
|
||||
class_path: str | None = None,
|
||||
is_mamba: bool = False,
|
||||
) -> Callable[[type], type]:
|
||||
"""Register or override a backend implementation.
|
||||
|
||||
Args:
|
||||
backend: The AttentionBackendEnum member to register
|
||||
backend: The AttentionBackendEnum/MambaAttentionBackendEnum member to register,
|
||||
or a string name for a new custom backend (e.g., "CUSTOM_MLA").
|
||||
class_path: Optional class path. If not provided and used as
|
||||
decorator, will be auto-generated from the class.
|
||||
is_mamba: Whether the backend is a Mamba attention backend.
|
||||
@@ -302,13 +370,30 @@ def register_backend(
|
||||
class MyCustomBackend:
|
||||
...
|
||||
|
||||
# Register a new custom attention backend with a dynamic enum name
|
||||
@register_backend("CUSTOM_MLA")
|
||||
class CustomMLABackend:
|
||||
...
|
||||
|
||||
# Direct registration
|
||||
register_backend(
|
||||
AttentionBackendEnum.CUSTOM,
|
||||
"my.module.MyCustomBackend"
|
||||
)
|
||||
|
||||
# Direct registration with string name
|
||||
register_backend(
|
||||
"CUSTOM_MLA",
|
||||
"custom.attention.mla_v1.CustomMLAABackend"
|
||||
)
|
||||
|
||||
"""
|
||||
# Handle dynamic enum creation for string backend names
|
||||
if isinstance(backend, str):
|
||||
if is_mamba:
|
||||
backend = MambaAttentionBackendEnum.register(backend, class_path or "")
|
||||
else:
|
||||
backend = AttentionBackendEnum.register(backend, class_path or "")
|
||||
|
||||
def decorator(cls: type) -> type:
|
||||
if is_mamba:
|
||||
|
||||
@@ -184,8 +184,11 @@ class RocmAiterUnifiedAttentionImpl(RocmAttentionImpl):
|
||||
)
|
||||
from aiter.ops.triton.unified_attention import unified_attention
|
||||
|
||||
from vllm.platforms.rocm import on_gfx11
|
||||
|
||||
self.unified_attention = unified_attention
|
||||
self.supports_quant_query_input = True
|
||||
# RDNA3 has no low precision MMA, preserve query precision
|
||||
self.supports_quant_query_input = not on_gfx11()
|
||||
|
||||
def _split_kv_cache(
|
||||
self, kv_cache: torch.Tensor
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""ROCm attention backend for token-major segmented Triton attention."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config import VllmConfig, get_current_vllm_config
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.torch_utils import is_quantized_kv_cache
|
||||
from vllm.v1.attention.backend import AttentionLayer, AttentionType
|
||||
from vllm.v1.attention.backends.rocm_attn import (
|
||||
RocmAttentionBackend,
|
||||
RocmAttentionImpl,
|
||||
RocmAttentionMetadata,
|
||||
RocmAttentionMetadataBuilder,
|
||||
)
|
||||
from vllm.v1.attention.backends.utils import get_num_attention_heads_from_layers
|
||||
from vllm.v1.attention.ops.segmented_attention import (
|
||||
get_segmented_attention_workspace,
|
||||
segmented_attention,
|
||||
segmented_attention_workspace_size,
|
||||
)
|
||||
from vllm.v1.attention.ops.triton_reshape_and_cache_flash import (
|
||||
triton_reshape_and_cache_flash,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.platforms.interface import DeviceCapability
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def is_rdna() -> bool:
|
||||
if not current_platform.is_rocm():
|
||||
return False
|
||||
from vllm.platforms.rocm import on_gfx1x
|
||||
|
||||
return on_gfx1x()
|
||||
|
||||
|
||||
class RocmSegmentedAttentionMetadataBuilder(RocmAttentionMetadataBuilder):
|
||||
def __init__(
|
||||
self,
|
||||
kv_cache_spec: AttentionSpec,
|
||||
layer_names: list[str],
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
):
|
||||
super().__init__(kv_cache_spec, layer_names, vllm_config, device)
|
||||
model_config = vllm_config.model_config
|
||||
self.num_heads_q = get_num_attention_heads_from_layers(
|
||||
vllm_config, layer_names
|
||||
) or model_config.get_num_attention_heads(vllm_config.parallel_config)
|
||||
self.num_heads_kv = kv_cache_spec.num_kv_heads
|
||||
self.headdim = kv_cache_spec.head_size
|
||||
|
||||
|
||||
class RocmSegmentedAttentionBackend(RocmAttentionBackend):
|
||||
"""Explicit token-major ROCm backend optimized for segmented prefill."""
|
||||
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [
|
||||
torch.float16,
|
||||
torch.bfloat16,
|
||||
]
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"float16",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "ROCM_SEGMENTED_ATTN"
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["RocmSegmentedAttentionImpl"]:
|
||||
return RocmSegmentedAttentionImpl
|
||||
|
||||
@staticmethod
|
||||
def get_builder_cls() -> type["RocmSegmentedAttentionMetadataBuilder"]:
|
||||
return RocmSegmentedAttentionMetadataBuilder
|
||||
|
||||
@classmethod
|
||||
def get_supported_head_sizes(cls) -> list[int]:
|
||||
return [64, 128, 256]
|
||||
|
||||
@classmethod
|
||||
def supports_attn_type(cls, attn_type: str) -> bool:
|
||||
return attn_type == AttentionType.DECODER
|
||||
|
||||
@classmethod
|
||||
def supports_non_causal(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_sliding_window(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def supports_mm_prefix(cls) -> bool:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def supports_combination(
|
||||
cls,
|
||||
head_size: int,
|
||||
dtype: torch.dtype,
|
||||
kv_cache_dtype: CacheDType | None,
|
||||
block_size: int | None,
|
||||
use_mla: bool,
|
||||
has_sink: bool,
|
||||
use_sparse: bool,
|
||||
use_mm_prefix: bool,
|
||||
device_capability: "DeviceCapability",
|
||||
) -> str | None:
|
||||
del (
|
||||
head_size,
|
||||
dtype,
|
||||
block_size,
|
||||
use_mla,
|
||||
has_sink,
|
||||
use_sparse,
|
||||
use_mm_prefix,
|
||||
device_capability,
|
||||
)
|
||||
if not is_rdna():
|
||||
return "ROCM_SEGMENTED_ATTN requires AMD RDNA GPUs on ROCm"
|
||||
|
||||
from vllm.platforms.rocm import on_gfx12x
|
||||
|
||||
if kv_cache_dtype in ("fp8", "fp8_e4m3") and not on_gfx12x():
|
||||
return "FP8 segmented attention requires gfx12"
|
||||
return None
|
||||
|
||||
|
||||
class RocmSegmentedAttentionImpl(RocmAttentionImpl):
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
scale: float,
|
||||
num_kv_heads: int,
|
||||
alibi_slopes: list[float] | None,
|
||||
sliding_window: int | None,
|
||||
kv_cache_dtype: str,
|
||||
logits_soft_cap: float | None = None,
|
||||
attn_type: AttentionType = AttentionType.DECODER,
|
||||
kv_sharing_target_layer_name: int | None = None,
|
||||
sinks: torch.Tensor | None = None,
|
||||
) -> None:
|
||||
if not is_rdna():
|
||||
raise ValueError("ROCM_SEGMENTED_ATTN requires AMD RDNA GPUs on ROCm")
|
||||
|
||||
super().__init__(
|
||||
num_heads,
|
||||
head_size,
|
||||
scale,
|
||||
num_kv_heads,
|
||||
alibi_slopes,
|
||||
sliding_window,
|
||||
kv_cache_dtype,
|
||||
logits_soft_cap,
|
||||
attn_type,
|
||||
kv_sharing_target_layer_name,
|
||||
sinks,
|
||||
)
|
||||
from vllm.platforms.rocm import on_gfx1x, on_gfx12x
|
||||
|
||||
fp8 = kv_cache_dtype in ("fp8", "fp8_e4m3")
|
||||
arch_supported = on_gfx12x() if fp8 else on_gfx1x()
|
||||
gqa_ratio_supported = (
|
||||
num_kv_heads > 0
|
||||
and num_heads % num_kv_heads == 0
|
||||
and 1 <= self.num_queries_per_kv <= 16
|
||||
)
|
||||
if not (
|
||||
arch_supported
|
||||
and attn_type == AttentionType.DECODER
|
||||
and head_size in (64, 128, 256)
|
||||
and gqa_ratio_supported
|
||||
and kv_cache_dtype in ("auto", "float16", "bfloat16", "fp8", "fp8_e4m3")
|
||||
and alibi_slopes is None
|
||||
):
|
||||
raise ValueError(
|
||||
"ROCM_SEGMENTED_ATTN requires decoder attention on gfx1x "
|
||||
"(gfx12 for FP8), head size 64, 128 or 256, GQA ratio 1-16, and "
|
||||
"does not support ALiBi."
|
||||
)
|
||||
# Startup tuning and target/draft compilation must share a Triton cache.
|
||||
cache_dir = os.environ.setdefault(
|
||||
"TRITON_CACHE_DIR",
|
||||
str(Path(envs.VLLM_CACHE_ROOT) / "rocm_segmented_attention" / "triton"),
|
||||
)
|
||||
Path(cache_dir).mkdir(parents=True, exist_ok=True)
|
||||
logger.info_once("Using token-major ROCm segmented Triton attention")
|
||||
self._segmented_attention_warmed_up = False
|
||||
self._segmented_attention_config: VllmConfig | None = None
|
||||
|
||||
def process_weights_after_loading(self, act_dtype: torch.dtype):
|
||||
super().process_weights_after_loading(act_dtype)
|
||||
config = get_current_vllm_config()
|
||||
self._segmented_attention_config = config
|
||||
|
||||
def _autotune_enabled(self) -> bool:
|
||||
config = self._segmented_attention_config
|
||||
return (
|
||||
config is not None
|
||||
and config.kernel_config.enable_rocm_segmented_attn_autotune
|
||||
)
|
||||
|
||||
def _get_workspace(self, device):
|
||||
config = self._segmented_attention_config
|
||||
assert config is not None
|
||||
sizes = segmented_attention_workspace_size(
|
||||
config.scheduler_config.max_num_seqs,
|
||||
self.num_heads,
|
||||
self.num_kv_heads,
|
||||
self.head_size,
|
||||
config.model_config.max_model_len,
|
||||
max_tokens=config.scheduler_config.max_num_batched_tokens,
|
||||
fp8=self.kv_cache_dtype in ("fp8", "fp8_e4m3"),
|
||||
autotune=self._autotune_enabled(),
|
||||
)
|
||||
return get_segmented_attention_workspace(device, sizes)
|
||||
|
||||
def _split_kv_cache(
|
||||
self,
|
||||
kv_cache: torch.Tensor,
|
||||
num_kv_heads: int | None = None,
|
||||
head_size: int | None = None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
num_kv_heads = num_kv_heads or self.num_kv_heads
|
||||
head_size = head_size or self.head_size
|
||||
return (
|
||||
kv_cache[:, 0].unflatten(-1, (num_kv_heads, head_size)),
|
||||
kv_cache[:, 1].unflatten(-1, (num_kv_heads, head_size)),
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
layer: torch.nn.Module,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
attn_metadata: RocmAttentionMetadata,
|
||||
output: torch.Tensor,
|
||||
output_scale: torch.Tensor | None = None,
|
||||
output_block_scale: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
if output_block_scale is not None:
|
||||
raise NotImplementedError(
|
||||
"fused block_scale output quantization is not supported"
|
||||
)
|
||||
# Profile runs allocate the same fixed scratch used during graph replay.
|
||||
workspace = self._get_workspace(query.device)
|
||||
if attn_metadata is None:
|
||||
return output.fill_(0)
|
||||
assert not attn_metadata.use_cascade
|
||||
|
||||
num_actual_tokens = attn_metadata.num_actual_tokens
|
||||
key_cache, value_cache = self._split_kv_cache(kv_cache)
|
||||
if is_quantized_kv_cache(self.kv_cache_dtype):
|
||||
key_cache = key_cache.view(self.fp8_dtype)
|
||||
value_cache = value_cache.view(self.fp8_dtype)
|
||||
if query.dtype == self.fp8_dtype and layer._q_scale_float != 1.0:
|
||||
raise NotImplementedError(
|
||||
"A non-1.0 q_scale with an FP8 query is not supported"
|
||||
)
|
||||
|
||||
segmented_attention(
|
||||
query=query[:num_actual_tokens],
|
||||
key=key[:num_actual_tokens],
|
||||
value=value[:num_actual_tokens],
|
||||
output=output[:num_actual_tokens],
|
||||
kv_cache_dtype=self.kv_cache_dtype,
|
||||
key_cache=key_cache,
|
||||
value_cache=value_cache,
|
||||
block_table=attn_metadata.block_table,
|
||||
query_start_loc=attn_metadata.query_start_loc,
|
||||
seq_lens=attn_metadata.seq_lens,
|
||||
max_seq_len=attn_metadata.max_seq_len,
|
||||
max_query_len=attn_metadata.max_query_len,
|
||||
k_scale=layer._k_scale,
|
||||
v_scale=layer._v_scale,
|
||||
sm_scale=self.scale,
|
||||
sliding_window=self.sliding_window[0],
|
||||
output_scale=output_scale,
|
||||
sinks=self.sinks,
|
||||
causal=attn_metadata.causal,
|
||||
softcap=self.logits_soft_cap,
|
||||
workspace=workspace,
|
||||
use_tuned_config=self._autotune_enabled(),
|
||||
)
|
||||
return output
|
||||
|
||||
def do_kv_cache_update(
|
||||
self,
|
||||
layer: AttentionLayer,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
slot_mapping: torch.Tensor,
|
||||
):
|
||||
key_cache, value_cache = self._split_kv_cache(kv_cache)
|
||||
if is_quantized_kv_cache(self.kv_cache_dtype):
|
||||
key_cache = key_cache.view(self.fp8_dtype)
|
||||
value_cache = value_cache.view(self.fp8_dtype)
|
||||
triton_reshape_and_cache_flash(
|
||||
key,
|
||||
value,
|
||||
key_cache,
|
||||
value_cache,
|
||||
slot_mapping,
|
||||
self.kv_cache_dtype,
|
||||
layer._k_scale,
|
||||
layer._v_scale,
|
||||
)
|
||||
|
||||
def do_rope_and_kv_cache_update(
|
||||
self,
|
||||
layer: AttentionLayer,
|
||||
query: torch.Tensor,
|
||||
key: torch.Tensor,
|
||||
value: torch.Tensor,
|
||||
positions: torch.Tensor,
|
||||
cos_sin_cache: torch.Tensor,
|
||||
is_neox: bool,
|
||||
kv_cache: torch.Tensor,
|
||||
layer_slot_mapping: torch.Tensor,
|
||||
):
|
||||
key_cache, value_cache = self._split_kv_cache(
|
||||
kv_cache,
|
||||
layer.num_kv_heads, # type: ignore[attr-defined]
|
||||
layer.head_size, # type: ignore[attr-defined]
|
||||
)
|
||||
is_fp8_kv_cache = is_quantized_kv_cache(self.kv_cache_dtype)
|
||||
if is_fp8_kv_cache:
|
||||
key_cache = key_cache.view(self.fp8_dtype)
|
||||
value_cache = value_cache.view(self.fp8_dtype)
|
||||
|
||||
rocm_aiter_ops.triton_rope_and_cache(
|
||||
query,
|
||||
key,
|
||||
value,
|
||||
positions,
|
||||
cos_sin_cache,
|
||||
is_neox,
|
||||
key_cache,
|
||||
value_cache,
|
||||
layer_slot_mapping,
|
||||
layer._k_scale,
|
||||
layer._v_scale,
|
||||
True,
|
||||
is_fp8_kv_cache,
|
||||
)
|
||||
@@ -70,10 +70,11 @@ class TritonAttentionDiffKVBackend(TritonAttentionBackend):
|
||||
# V head dim — set per layer via ``set_head_size_v`` before instantiation.
|
||||
head_size_v: int = 128
|
||||
|
||||
# No FP8 / int8 KV cache for the DiffKV path yet; require fp16/bf16/fp32.
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
|
||||
"auto",
|
||||
"bfloat16",
|
||||
"fp8",
|
||||
"fp8_e4m3",
|
||||
]
|
||||
|
||||
@classmethod
|
||||
@@ -110,16 +111,15 @@ class TritonAttentionDiffKVImpl(TritonAttentionImpl):
|
||||
|
||||
def __init__(self, *args, **kwargs) -> None:
|
||||
super().__init__(*args, **kwargs)
|
||||
if is_quantized_kv_cache(self.kv_cache_dtype):
|
||||
if (
|
||||
is_quantized_kv_cache(self.kv_cache_dtype)
|
||||
and self.kv_cache_dtype
|
||||
not in TritonAttentionDiffKVBackend.supported_kv_cache_dtypes
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"TritonAttentionDiffKVBackend does not yet support quantized "
|
||||
"TritonAttentionDiffKVBackend supports only fp8/fp8_e4m3 quantized "
|
||||
f"KV cache (got kv_cache_dtype={self.kv_cache_dtype!r})."
|
||||
)
|
||||
if self._is_per_token_head_quant:
|
||||
raise NotImplementedError(
|
||||
"TritonAttentionDiffKVBackend does not support per-token-head "
|
||||
"quantization."
|
||||
)
|
||||
if self.chunk_lookback > -1:
|
||||
raise NotImplementedError(
|
||||
"TritonAttentionDiffKVBackend does not support chunked "
|
||||
@@ -191,6 +191,9 @@ class TritonAttentionDiffKVImpl(TritonAttentionImpl):
|
||||
|
||||
# Triton DiffKV kernels consume (B, N, H, D) cache views.
|
||||
kv_cache = kv_cache.transpose(1, 2)
|
||||
quantized = is_quantized_kv_cache(self.kv_cache_dtype)
|
||||
if quantized:
|
||||
kv_cache = kv_cache.view(self.fp8_dtype)
|
||||
key_cache = kv_cache[..., :head_size_qk]
|
||||
value_cache = kv_cache[..., head_size_qk : head_size_qk + head_size_v]
|
||||
|
||||
@@ -202,6 +205,11 @@ class TritonAttentionDiffKVImpl(TritonAttentionImpl):
|
||||
cu_seqlens_q=attn_metadata.query_start_loc,
|
||||
seqused_k=attn_metadata.seq_lens,
|
||||
softmax_scale=self.scale,
|
||||
q_descale=(
|
||||
layer._q_scale if quantized and query.dtype == self.fp8_dtype else None
|
||||
),
|
||||
k_descale=layer._k_scale if quantized else None,
|
||||
v_descale=layer._v_scale if quantized else None,
|
||||
causal=True,
|
||||
alibi_slopes=self.alibi_slopes,
|
||||
use_alibi_sqrt=self.use_alibi_sqrt,
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""UltraQuant 4-bit KV-cache attention backend.
|
||||
|
||||
UltraQuant is a 4-bit KV-cache format (FP4 E2M1 codes + UE8M0 power-of-two
|
||||
per-group-32 scales) with Hadamard-rotated keys. It reuses the TurboQuant
|
||||
attention scaffolding (forward orchestration, metadata, cache-layout addressing,
|
||||
CUDA-graph pre-warm) by subclassing, and overrides only the format-specific
|
||||
seams:
|
||||
|
||||
* store -> ultraquant_store (rotate K, pack FP4 + UE8M0 scales)
|
||||
* decode -> FlyDSL D=256 scaled-MFMA kernel, Triton unified fallback
|
||||
* continuation -> small chunk: Triton unified; large chunk: dequant + FA
|
||||
|
||||
``UltraQuantAttentionBackend`` is a standalone backend with its own identity
|
||||
(``ULTRAQUANT``) and dtype (``ultraquant_4bit``); the TurboQuant backend/impl
|
||||
carry no UltraQuant knowledge.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import math
|
||||
from dataclasses import replace
|
||||
from typing import Any, ClassVar
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.attention.backend import AttentionType
|
||||
from vllm.v1.attention.backends.fa_utils import get_flash_attn_version
|
||||
from vllm.v1.attention.backends.turboquant_attn import (
|
||||
_CONTINUATION_DECODE_THRESHOLD,
|
||||
_HAS_FLASH_ATTN,
|
||||
TurboQuantAttentionBackend,
|
||||
TurboQuantAttentionImpl,
|
||||
TurboQuantMetadata,
|
||||
_build_hadamard,
|
||||
)
|
||||
from vllm.v1.attention.ops.flydsl_ultraquant_decode import (
|
||||
flydsl_ultraquant_decode_attention,
|
||||
is_ultraquant_flydsl_available,
|
||||
ultraquant_flydsl_decode_eligible,
|
||||
)
|
||||
from vllm.v1.attention.ops.ultraquant.format import slot_size
|
||||
from vllm.v1.attention.ops.ultraquant.triton_unified_attention import (
|
||||
ultraquant_unified_attention,
|
||||
)
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec
|
||||
from vllm.v1.worker.workspace import (
|
||||
current_workspace_manager,
|
||||
is_workspace_manager_initialized,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# CK FlashAttention on ROCm has no compiled kernel above head_dim 256 and no
|
||||
# sinks argument; those cases route through the Triton unified kernel instead.
|
||||
_CK_MAX_HEAD_DIM = 256
|
||||
|
||||
|
||||
class UltraQuantAttentionBackend(TurboQuantAttentionBackend):
|
||||
"""Standalone backend for the ``ultraquant_4bit`` KV-cache dtype.
|
||||
|
||||
Subclasses :class:`TurboQuantAttentionBackend` for the shared metadata and
|
||||
cache-layout plumbing, and overrides identity, spec, impl, block size, and
|
||||
capabilities so no UltraQuant knowledge lives in the TurboQuant backend.
|
||||
"""
|
||||
|
||||
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = ["ultraquant_4bit"]
|
||||
# FlyDSL D=256 decode loads query as bf16; fp16 is not supported. Selection
|
||||
# reads this from the backend class, not from the impl.
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
|
||||
@classmethod
|
||||
def customize_spec(cls, spec: AttentionSpec) -> AttentionSpec:
|
||||
"""UltraQuant packs K+V into one 4-bit FP4/UE8M0 slot per head."""
|
||||
if spec.state_content_bytes is not None or not spec.kv_quant_mode.is_ultraquant:
|
||||
return spec
|
||||
return replace(spec, state_content_bytes=slot_size(spec.head_size))
|
||||
|
||||
@staticmethod
|
||||
def get_name() -> str:
|
||||
return "ULTRAQUANT"
|
||||
|
||||
@classmethod
|
||||
def get_preferred_block_size(cls, default_block_size: int) -> int:
|
||||
# FlyDSL D=256 decode geometry requires a 64-token KV block; pin it so
|
||||
# the KV-cache manager pages stay dense and splittable into kernel blocks.
|
||||
return 64
|
||||
|
||||
@staticmethod
|
||||
def get_impl_cls() -> type["UltraQuantAttentionImpl"]:
|
||||
return UltraQuantAttentionImpl
|
||||
|
||||
@classmethod
|
||||
def supports_kv_cache_dtype(cls, kv_cache_dtype: CacheDType | None) -> bool:
|
||||
return kv_cache_dtype == "ultraquant_4bit"
|
||||
|
||||
@classmethod
|
||||
def supports_sink(cls) -> bool:
|
||||
# Decode and continuation prefill route sinks to the Triton unified
|
||||
# kernel, but first-chunk prefill goes through flash_attn_varlen, which
|
||||
# takes no sinks argument. Until that path is covered, reject sink
|
||||
# models at selection rather than returning silently wrong output.
|
||||
return False
|
||||
|
||||
|
||||
class UltraQuantAttentionImpl(TurboQuantAttentionImpl):
|
||||
"""UltraQuant 4-bit KV-cache attention (FP4 E2M1 + UE8M0, rotated K).
|
||||
|
||||
Overrides the init, on-device setup, store, decode, and prefill/continuation
|
||||
seams of :class:`TurboQuantAttentionImpl`; the shared ``forward`` /
|
||||
``do_kv_cache_update`` orchestration and metadata handling are inherited.
|
||||
"""
|
||||
|
||||
# FlyDSL D=256 decode loads query as bf16; fp16 is not supported.
|
||||
supported_dtypes: ClassVar[list[torch.dtype]] = [torch.bfloat16]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
num_heads: int,
|
||||
head_size: int,
|
||||
scale: float,
|
||||
num_kv_heads: int | None = None,
|
||||
alibi_slopes: list[float] | None = None,
|
||||
sliding_window: int | None = None,
|
||||
kv_cache_dtype: str = "auto",
|
||||
logits_soft_cap: float | None = None,
|
||||
attn_type: str = AttentionType.DECODER,
|
||||
kv_sharing_target_layer_name: str | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
self.num_heads = num_heads
|
||||
self.head_size = head_size
|
||||
self.scale = scale
|
||||
self.num_kv_heads = num_kv_heads if num_kv_heads is not None else num_heads
|
||||
self.num_kv_groups = num_heads // self.num_kv_heads
|
||||
self.kv_cache_dtype = kv_cache_dtype
|
||||
|
||||
self.fa_version = get_flash_attn_version(head_size=head_size)
|
||||
|
||||
vllm_config = get_current_vllm_config()
|
||||
self.max_num_kv_splits = (
|
||||
vllm_config.attention_config.tq_max_kv_splits_for_cuda_graph
|
||||
)
|
||||
self.sliding_window = sliding_window
|
||||
self.sinks = kwargs.get("sinks")
|
||||
self._max_model_len = vllm_config.model_config.max_model_len
|
||||
|
||||
self._use_ultraquant_flydsl = is_ultraquant_flydsl_available()
|
||||
# FlyDSL decode eligibility is static per layer config; compute once.
|
||||
self._flydsl_decode_eligible = ultraquant_flydsl_decode_eligible(
|
||||
head_size=self.head_size,
|
||||
num_kv_groups=self.num_kv_groups,
|
||||
has_sinks=self.sinks is not None,
|
||||
sliding_window=self.sliding_window,
|
||||
flydsl_loaded=self._use_ultraquant_flydsl,
|
||||
)
|
||||
|
||||
def _ensure_on_device(self, layer, device):
|
||||
"""Build the shared Hadamard rotation and pre-warm FlyDSL buffers.
|
||||
|
||||
UltraQuant needs no Lloyd-Max centroids, but the inherited forward reads
|
||||
``layer._tq_centroids``, so an empty tensor is kept on the layer.
|
||||
"""
|
||||
if self._use_ultraquant_flydsl:
|
||||
# CUDA-graph capture safety for the FlyDSL decode path on ROCm:
|
||||
# pre-allocate index buffers and grow the workspace to its max size
|
||||
# before capture so replay never lands on stale addresses.
|
||||
_max_len = self._max_model_len
|
||||
_already_ok = (
|
||||
hasattr(self, "_arange_cache")
|
||||
and self._arange_cache.device.type == str(device).split(":")[0]
|
||||
and self._arange_cache.shape[0] >= _max_len + 2
|
||||
)
|
||||
if not _already_ok:
|
||||
self._arange_cache = torch.arange(
|
||||
0, _max_len + 2, device=device, dtype=torch.int32
|
||||
)
|
||||
if not hasattr(self, "_cu_2") or self._cu_2.device != torch.device(device):
|
||||
self._cu_2 = torch.zeros(2, device=device, dtype=torch.int32)
|
||||
if (
|
||||
is_workspace_manager_initialized()
|
||||
and not current_workspace_manager().is_locked()
|
||||
):
|
||||
B_max = self._max_capture_batch_size()
|
||||
D = self.head_size
|
||||
Hq = self.num_heads
|
||||
S = self.max_num_kv_splits
|
||||
_pre_warm_bytes = (
|
||||
B_max * Hq * (S * (D + 1) + D) * 4 # fp32 mid_o + fp32 lse
|
||||
+ B_max * Hq * D * 2 # query-dtype output (bf16 = 2 B)
|
||||
+ 512 # alignment padding
|
||||
)
|
||||
with contextlib.suppress(AssertionError):
|
||||
current_workspace_manager().get_simultaneous(
|
||||
((_pre_warm_bytes,), torch.uint8)
|
||||
)
|
||||
|
||||
if not hasattr(layer, "_tq_cached"):
|
||||
D = self.head_size
|
||||
# Pure Hadamard: orthonormal + symmetric (H = H^T), enabling
|
||||
# in-kernel butterfly fusion and trivial inverse for continuation.
|
||||
H = _build_hadamard(D, str(device))
|
||||
layer._tq_PiT = H
|
||||
layer._tq_Pi = H
|
||||
layer._tq_Pi_half = H.to(torch.float16)
|
||||
# Inherited TurboQuantAttentionImpl.forward reads _tq_centroids
|
||||
# unconditionally; UltraQuant has no centroid table, so an empty
|
||||
# tensor satisfies the read.
|
||||
layer._tq_centroids = torch.empty(0, device=device, dtype=torch.float32)
|
||||
layer._tq_cached = True
|
||||
|
||||
def _store_kv(
|
||||
self,
|
||||
key: torch.Tensor, # (N, Hk, D)
|
||||
value: torch.Tensor, # (N, Hk, D)
|
||||
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
|
||||
slot_mapping: torch.Tensor,
|
||||
layer: Any,
|
||||
):
|
||||
"""Rotate K by the Hadamard and pack K+V into FP4/UE8M0 slots."""
|
||||
from vllm.v1.attention.ops.ultraquant.triton_store import ultraquant_store
|
||||
|
||||
ultraquant_store(
|
||||
key,
|
||||
value,
|
||||
kv_cache,
|
||||
slot_mapping,
|
||||
PiT=layer._tq_PiT,
|
||||
)
|
||||
|
||||
def _decode_attention(
|
||||
self,
|
||||
query: torch.Tensor, # (B, Hq, D)
|
||||
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
|
||||
attn_metadata: TurboQuantMetadata,
|
||||
Pi: torch.Tensor,
|
||||
centroids: torch.Tensor,
|
||||
PiT: torch.Tensor | None = None,
|
||||
layer: torch.nn.Module | None = None,
|
||||
) -> torch.Tensor:
|
||||
# Acquire shared decode scratch from the WorkspaceManager (UltraQuant
|
||||
# only needs the output buffer; the mid_o/lse slots keep the triple
|
||||
# allocation identical to the base decode for buffer reuse).
|
||||
B = query.shape[0]
|
||||
D = self.head_size
|
||||
S = self.max_num_kv_splits
|
||||
Hq = self.num_heads
|
||||
output_buf = None
|
||||
if is_workspace_manager_initialized():
|
||||
_mid_o, output_buf, _lse = current_workspace_manager().get_simultaneous(
|
||||
((B, Hq, S, D + 1), torch.float32),
|
||||
((B, Hq, D), query.dtype),
|
||||
((B, Hq), torch.float32),
|
||||
)
|
||||
|
||||
if self._flydsl_decode_eligible:
|
||||
return flydsl_ultraquant_decode_attention(
|
||||
query=query,
|
||||
kv_cache=kv_cache,
|
||||
block_table=attn_metadata.block_table,
|
||||
seq_lens=attn_metadata.seq_lens,
|
||||
scale=self.scale,
|
||||
PiT=PiT,
|
||||
max_seq_len=attn_metadata.max_seq_len,
|
||||
output_buf=output_buf,
|
||||
buf_holder=layer,
|
||||
max_num_kv_splits=self.max_num_kv_splits,
|
||||
sinks=self.sinks,
|
||||
)
|
||||
|
||||
logger.info_once(
|
||||
"UltraQuant FlyDSL is ineligible for head_size=%s, GQA=%s, "
|
||||
"sinks=%s, sliding_window=%s; using Triton fallback.",
|
||||
self.head_size,
|
||||
self.num_kv_groups,
|
||||
self.sinks is not None,
|
||||
self.sliding_window,
|
||||
)
|
||||
return ultraquant_unified_attention(
|
||||
query=query,
|
||||
kv_cache=kv_cache,
|
||||
block_table=attn_metadata.block_table,
|
||||
seq_lens=attn_metadata.seq_lens,
|
||||
query_start_loc=attn_metadata.query_start_loc,
|
||||
scale=self.scale,
|
||||
PiT=PiT,
|
||||
output=output_buf,
|
||||
max_query_len=1,
|
||||
max_seq_len=attn_metadata.max_seq_len,
|
||||
sinks=self.sinks,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
|
||||
def _prefill_attention(
|
||||
self,
|
||||
query: torch.Tensor, # (N, Hq, D)
|
||||
key: torch.Tensor, # (N, Hk, D)
|
||||
value: torch.Tensor, # (N, Hk, D)
|
||||
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
|
||||
attn_metadata: TurboQuantMetadata,
|
||||
Pi: torch.Tensor,
|
||||
centroids: torch.Tensor,
|
||||
PiT: torch.Tensor | None = None,
|
||||
layer: Any = None,
|
||||
) -> torch.Tensor:
|
||||
N, Hq, D = query.shape
|
||||
|
||||
# Fast path: flash_attn for first-chunk prefills (all K/V in batch).
|
||||
# CK cannot serve head dims above 256, so those fall through to the
|
||||
# per-request unified-attention path below.
|
||||
if (
|
||||
_HAS_FLASH_ATTN
|
||||
and attn_metadata.max_query_len == attn_metadata.max_seq_len
|
||||
and D <= _CK_MAX_HEAD_DIM
|
||||
):
|
||||
return self._flash_attn_varlen(
|
||||
q=query,
|
||||
k=key,
|
||||
v=value,
|
||||
cu_seqlens_q=attn_metadata.query_start_loc,
|
||||
cu_seqlens_k=attn_metadata.query_start_loc,
|
||||
max_seqlen_q=attn_metadata.max_query_len,
|
||||
max_seqlen_k=attn_metadata.max_query_len,
|
||||
)
|
||||
|
||||
# Continuation or no flash_attn: per-request attention.
|
||||
Hk = key.shape[1]
|
||||
use_gqa = Hk < Hq
|
||||
query_start_loc = attn_metadata.query_start_loc
|
||||
num_reqs = query_start_loc.shape[0] - 1
|
||||
|
||||
output = torch.zeros(N, Hq, D, device=query.device, dtype=query.dtype)
|
||||
|
||||
if attn_metadata.query_start_loc_cpu is not None:
|
||||
qsl = attn_metadata.query_start_loc_cpu.tolist()
|
||||
else:
|
||||
qsl = query_start_loc.tolist()
|
||||
if attn_metadata.seq_lens_cpu is not None:
|
||||
seq_lens_list = attn_metadata.seq_lens_cpu.tolist()
|
||||
else:
|
||||
seq_lens_list = attn_metadata.seq_lens.tolist()
|
||||
|
||||
if not hasattr(self, "_cu_2"):
|
||||
self._cu_2 = torch.zeros(2, device=query.device, dtype=torch.int32)
|
||||
_max_seq = attn_metadata.max_seq_len
|
||||
_ac: torch.Tensor | None = getattr(self, "_arange_cache", None)
|
||||
if _ac is None or _ac.shape[0] <= _max_seq:
|
||||
_ac = torch.arange(
|
||||
0, _max_seq + 1, device=query.device, dtype=attn_metadata.seq_lens.dtype
|
||||
)
|
||||
self._arange_cache = _ac
|
||||
_arange_cache: torch.Tensor = _ac
|
||||
|
||||
for i in range(num_reqs):
|
||||
q_start = qsl[i]
|
||||
q_end = qsl[i + 1]
|
||||
q_len = q_end - q_start
|
||||
if q_len <= 0:
|
||||
continue
|
||||
|
||||
seq_len = seq_lens_list[i]
|
||||
q_seq = query[q_start:q_end] # (q_len, Hq, D)
|
||||
k_seq = key[q_start:q_end] # (q_len, Hk, D)
|
||||
v_seq = value[q_start:q_end] # (q_len, Hk, D)
|
||||
|
||||
if q_len == seq_len:
|
||||
# First-chunk prefill: all K/V are in the current batch.
|
||||
if D > _CK_MAX_HEAD_DIM:
|
||||
# Head dims CK cannot handle (Gemma 4 global layers,
|
||||
# D=512). This kernel is generic over head size.
|
||||
from vllm.v1.attention.ops.triton_unified_attention import (
|
||||
unified_attention,
|
||||
)
|
||||
|
||||
out = torch.empty_like(q_seq)
|
||||
cu_single = torch.tensor(
|
||||
[0, q_len], dtype=torch.int32, device=query.device
|
||||
)
|
||||
seq_lens_single = torch.tensor(
|
||||
[q_len], dtype=torch.int32, device=query.device
|
||||
)
|
||||
block_table_single = torch.zeros(
|
||||
(1, 1), dtype=torch.int32, device=query.device
|
||||
)
|
||||
unified_attention(
|
||||
q=q_seq,
|
||||
k=k_seq.unsqueeze(0),
|
||||
v=v_seq.unsqueeze(0),
|
||||
out=out,
|
||||
cu_seqlens_q=cu_single,
|
||||
max_seqlen_q=q_len,
|
||||
seqused_k=seq_lens_single,
|
||||
max_seqlen_k=q_len,
|
||||
softmax_scale=self.scale,
|
||||
causal=True,
|
||||
window_size=(-1, -1),
|
||||
block_table=block_table_single,
|
||||
softcap=0.0,
|
||||
q_descale=None,
|
||||
k_descale=None,
|
||||
v_descale=None,
|
||||
sinks=None,
|
||||
)
|
||||
elif _HAS_FLASH_ATTN:
|
||||
self._cu_2[1:2] = q_len
|
||||
cu = self._cu_2
|
||||
out = self._flash_attn_varlen(
|
||||
q=q_seq,
|
||||
k=k_seq,
|
||||
v=v_seq,
|
||||
cu_seqlens_q=cu,
|
||||
cu_seqlens_k=cu,
|
||||
max_seqlen_q=q_len,
|
||||
max_seqlen_k=q_len,
|
||||
)
|
||||
else:
|
||||
q_t = q_seq.transpose(0, 1).contiguous()
|
||||
k_t = k_seq.transpose(0, 1).contiguous()
|
||||
v_t = v_seq.transpose(0, 1).contiguous()
|
||||
out = F.scaled_dot_product_attention(
|
||||
q_t,
|
||||
k_t,
|
||||
v_t,
|
||||
is_causal=True,
|
||||
scale=self.scale,
|
||||
enable_gqa=use_gqa,
|
||||
).transpose(0, 1)
|
||||
output[q_start:q_end] = out.to(query.dtype)
|
||||
else:
|
||||
# Continuation chunk: prefix already stored (Hadamard-rotated
|
||||
# FP4) by do_kv_cache_update. Small chunks reuse the Triton
|
||||
# unified decode-shaped kernel; large chunks dequant the prefix
|
||||
# once and run a dense flash-attention prefill.
|
||||
cached_len = seq_len - q_len
|
||||
if q_len <= _CONTINUATION_DECODE_THRESHOLD:
|
||||
synth_seq_lens = _arange_cache[cached_len + 1 : seq_len + 1]
|
||||
synth_bt = attn_metadata.block_table[i : i + 1].expand(q_len, -1)
|
||||
out = ultraquant_unified_attention(
|
||||
query=q_seq,
|
||||
kv_cache=kv_cache,
|
||||
block_table=synth_bt,
|
||||
seq_lens=synth_seq_lens,
|
||||
query_start_loc=_arange_cache[: q_len + 1],
|
||||
scale=self.scale,
|
||||
PiT=PiT,
|
||||
max_query_len=1,
|
||||
max_seq_len=seq_len,
|
||||
sinks=self.sinks,
|
||||
sliding_window=self.sliding_window,
|
||||
)
|
||||
else:
|
||||
out = self._ultraquant_continuation_prefill(
|
||||
layer=layer,
|
||||
query=q_seq,
|
||||
key_chunk=k_seq,
|
||||
val_chunk=v_seq,
|
||||
kv_cache=kv_cache,
|
||||
block_table=attn_metadata.block_table[i : i + 1],
|
||||
cached_len=cached_len,
|
||||
seq_len=seq_len,
|
||||
PiT=PiT,
|
||||
)
|
||||
output[q_start:q_end] = out.to(query.dtype)
|
||||
|
||||
return output
|
||||
|
||||
def _ultraquant_continuation_prefill(
|
||||
self,
|
||||
*,
|
||||
layer: Any,
|
||||
query: torch.Tensor, # (q_len, Hq, D) unrotated
|
||||
key_chunk: torch.Tensor, # (q_len, Hk, D) unrotated
|
||||
val_chunk: torch.Tensor, # (q_len, Hk, D)
|
||||
kv_cache: torch.Tensor, # (num_blocks, block_size, Hk, slot_size)
|
||||
block_table: torch.Tensor, # (1, max_num_blocks)
|
||||
cached_len: int,
|
||||
seq_len: int,
|
||||
PiT: torch.Tensor, # (D, D) fp32 Hadamard
|
||||
) -> torch.Tensor:
|
||||
"""Large continuation chunk: dequant the cached prefix, then flash_attn.
|
||||
|
||||
The cache stores K already Hadamard-rotated, so only the current chunk's
|
||||
K and the queries need rotating. Hadamard is symmetric orthonormal, so
|
||||
rotating both sides leaves the attention scores unchanged.
|
||||
"""
|
||||
from vllm.v1.attention.ops.ultraquant.triton_dequant import (
|
||||
ultraquant_full_dequant_kv,
|
||||
)
|
||||
|
||||
q_len, Hq, D = query.shape
|
||||
Hk = key_chunk.shape[1]
|
||||
device = query.device
|
||||
qdtype = query.dtype
|
||||
block_size = kv_cache.shape[1]
|
||||
alloc_len = math.ceil(cached_len / block_size) * block_size
|
||||
|
||||
# Dequant target, shared across layers by the workspace manager so long
|
||||
# context does not pay one allocation per layer.
|
||||
buf_shape = (1, Hk, alloc_len, D)
|
||||
k_buf, v_buf = current_workspace_manager().get_simultaneous(
|
||||
(buf_shape, qdtype),
|
||||
(buf_shape, qdtype),
|
||||
)
|
||||
ultraquant_full_dequant_kv(
|
||||
kv_cache=kv_cache,
|
||||
block_table=block_table,
|
||||
k_out=k_buf,
|
||||
v_out=v_buf,
|
||||
alloc_len=alloc_len,
|
||||
)
|
||||
|
||||
# Layer-cached prefix+chunk concatenation, grown once to worst case.
|
||||
cap = block_table.shape[1] * block_size
|
||||
k_full_buf = getattr(layer, "_uq_kfull_buf", None)
|
||||
if (
|
||||
k_full_buf is None
|
||||
or k_full_buf.shape[0] < cap
|
||||
or k_full_buf.dtype != qdtype
|
||||
):
|
||||
k_full_buf = torch.empty(cap, Hk, D, dtype=qdtype, device=device)
|
||||
layer._uq_kfull_buf = k_full_buf
|
||||
v_full_buf = getattr(layer, "_uq_vfull_buf", None)
|
||||
if (
|
||||
v_full_buf is None
|
||||
or v_full_buf.shape[0] < cap
|
||||
or v_full_buf.dtype != qdtype
|
||||
):
|
||||
v_full_buf = torch.empty(cap, Hk, D, dtype=qdtype, device=device)
|
||||
layer._uq_vfull_buf = v_full_buf
|
||||
k_full = k_full_buf[:seq_len]
|
||||
v_full = v_full_buf[:seq_len]
|
||||
|
||||
k_full[:cached_len] = k_buf[0, :, :cached_len, :].transpose(0, 1)
|
||||
v_full[:cached_len] = v_buf[0, :, :cached_len, :].transpose(0, 1)
|
||||
k_full[cached_len:] = (key_chunk.to(torch.float32) @ PiT).to(qdtype)
|
||||
v_full[cached_len:] = val_chunk
|
||||
q_rot = (query.to(torch.float32) @ PiT).to(qdtype)
|
||||
|
||||
# Unequal q/k lengths with causal=True gives lower-right alignment:
|
||||
# query i (absolute position cached_len + i) sees keys 0..cached_len+i.
|
||||
#
|
||||
# FA2 on ROCm has no sinks parameter, and CK cannot serve head dims
|
||||
# above 256, so those cases route through the Triton unified kernel.
|
||||
# Q/K are already in Hadamard-rotated space (q_rot, k_full) so the dot
|
||||
# products match the original-space attention scores.
|
||||
if self.sinks is not None or D > _CK_MAX_HEAD_DIM:
|
||||
from vllm.v1.attention.ops.triton_unified_attention import (
|
||||
unified_attention,
|
||||
)
|
||||
|
||||
out = torch.empty_like(q_rot)
|
||||
cu_q = torch.tensor([0, q_len], dtype=torch.int32, device=device)
|
||||
seqused_k = torch.tensor([seq_len], dtype=torch.int32, device=device)
|
||||
block_table_single = torch.zeros((1, 1), dtype=torch.int32, device=device)
|
||||
window = (
|
||||
(self.sliding_window - 1, 0)
|
||||
if self.sliding_window and self.sliding_window > 0
|
||||
else (-1, -1)
|
||||
)
|
||||
unified_attention(
|
||||
q=q_rot,
|
||||
k=k_full.unsqueeze(0),
|
||||
v=v_full.unsqueeze(0),
|
||||
out=out,
|
||||
cu_seqlens_q=cu_q,
|
||||
max_seqlen_q=q_len,
|
||||
seqused_k=seqused_k,
|
||||
max_seqlen_k=seq_len,
|
||||
softmax_scale=self.scale,
|
||||
causal=True,
|
||||
window_size=window,
|
||||
block_table=block_table_single,
|
||||
softcap=0.0,
|
||||
q_descale=None,
|
||||
k_descale=None,
|
||||
v_descale=None,
|
||||
sinks=self.sinks,
|
||||
)
|
||||
return out.to(qdtype)
|
||||
if _HAS_FLASH_ATTN:
|
||||
cu_q = torch.tensor([0, q_len], dtype=torch.int32, device=device)
|
||||
cu_k = torch.tensor([0, seq_len], dtype=torch.int32, device=device)
|
||||
return self._flash_attn_varlen(
|
||||
q=q_rot,
|
||||
k=k_full,
|
||||
v=v_full,
|
||||
cu_seqlens_q=cu_q,
|
||||
cu_seqlens_k=cu_k,
|
||||
max_seqlen_q=q_len,
|
||||
max_seqlen_k=seq_len,
|
||||
)
|
||||
q_t = q_rot.transpose(0, 1).unsqueeze(0)
|
||||
k_t = k_full.transpose(0, 1).unsqueeze(0)
|
||||
v_t = v_full.transpose(0, 1).unsqueeze(0)
|
||||
if Hq > Hk:
|
||||
k_t = k_t.expand(1, Hq, -1, -1)
|
||||
v_t = v_t.expand(1, Hq, -1, -1)
|
||||
return (
|
||||
F.scaled_dot_product_attention(
|
||||
q_t, k_t, v_t, is_causal=True, scale=self.scale
|
||||
)
|
||||
.squeeze(0)
|
||||
.transpose(0, 1)
|
||||
.to(qdtype)
|
||||
)
|
||||
@@ -307,8 +307,12 @@ def resolve_kv_cache_layout(
|
||||
f"none is in every supported set: {supported_layouts}."
|
||||
)
|
||||
|
||||
# Self-addressed per-request rings (e.g. the kpool tail) are replicated
|
||||
# state like Mamba and don't need a separate draft group.
|
||||
dcp_sharding = {
|
||||
spec.dcp_sharded for spec in kv_cache_specs if isinstance(spec, AttentionSpec)
|
||||
spec.dcp_sharded
|
||||
for spec in kv_cache_specs
|
||||
if isinstance(spec, AttentionSpec) and spec.uses_slot_mapping
|
||||
}
|
||||
page_sizes = {spec.page_size_bytes for spec in kv_cache_specs}
|
||||
if len(dcp_sharding) > 1 and len(page_sizes) > 1:
|
||||
|
||||
@@ -0,0 +1,983 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
# UltraQuant D=256 decode (FlyDSL) — gfx950 / CDNA4
|
||||
#
|
||||
# Production path only: scaled FP4×E4M3 QK MFMA, native V CVT, HW V-transpose,
|
||||
# Q hoist, strided tile-groups, and in-kernel Walsh-Hadamard for GQA 6/8/16.
|
||||
#
|
||||
# AoS slot (D=256, group_size=32 → 8 groups, 272 B):
|
||||
# [0:128) K FP4 codes; [128:136) K UE8M0; [136:264) V FP4; [264:272) V UE8M0
|
||||
# QK MFMA: A=K, B=Q → C[token, query]; PV MFMA: A=V_T, B=P → C[head_dim, query]
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import flydsl.compiler as flyc
|
||||
import flydsl.expr as fx
|
||||
from aiter.ops.flydsl.kernels import buffer_ops, vector
|
||||
from flydsl._mlir import ir
|
||||
from flydsl._mlir.dialects import scf as _scf
|
||||
from flydsl.expr import (
|
||||
arith,
|
||||
gpu,
|
||||
rocdl,
|
||||
)
|
||||
from flydsl.expr.primitive import const_expr, range_constexpr
|
||||
from flydsl.expr.typing import T
|
||||
from flydsl.runtime.device import get_rocm_arch as get_hip_arch
|
||||
from flydsl.utils.smem_allocator import SmemAllocator, SmemPtr
|
||||
|
||||
|
||||
def _vector_insert(value, dest, *, static_position):
|
||||
"""Insert a DSL scalar using FlyDSL 0.3's raw vector dialect binding."""
|
||||
return vector.insert(
|
||||
vector.as_ir_value(value),
|
||||
vector.as_ir_value(dest),
|
||||
dynamic_position=[],
|
||||
static_position=static_position,
|
||||
)
|
||||
|
||||
|
||||
# === Constants (256-wide-head ultraquant decode profile) =======================
|
||||
HEAD_SIZE = 256
|
||||
KV_BLOCK_SIZE = 16 # default; overridable via build(kv_block_size=...)
|
||||
TILE_SIZE = 16 # MFMA tile = 16 tokens
|
||||
N_CENTROIDS = 16 # FP4 E2M1 value table (16 entries indexed by nibble)
|
||||
QUERY_GROUP_SIZE = 16 # default for tests; overridable via build(...)
|
||||
WARP_SIZE = 64
|
||||
BLOCK_THREADS = WARP_SIZE
|
||||
KV_COMPUTE_BLOCK = 256 # 16 K-tiles × 16 tokens
|
||||
|
||||
# ultraquant AoS slot layout (per (slot, head), D=256, group_size=32 => 8 groups)
|
||||
FP8_GROUP_SIZE = 32
|
||||
N_GROUPS = HEAD_SIZE // FP8_GROUP_SIZE # 8 UE8M0 scale bytes per head
|
||||
KEY_CODE_BYTES = HEAD_SIZE // 2 # 128
|
||||
VAL_CODE_BYTES = HEAD_SIZE // 2 # 128
|
||||
K_SCALES_OFFSET = KEY_CODE_BYTES # 128
|
||||
V_CODES_OFFSET = KEY_CODE_BYTES + N_GROUPS # 136
|
||||
V_SCALES_OFFSET = V_CODES_OFFSET + VAL_CODE_BYTES # 264
|
||||
SLOT_CONTENT_BYTES = V_SCALES_OFFSET + N_GROUPS # 272
|
||||
|
||||
# MFMA
|
||||
MFMA_N = 16
|
||||
PV_N_CHUNKS = HEAD_SIZE // MFMA_N # 16 for HEAD_SIZE=256
|
||||
|
||||
# --- Per-lane data-movement geometry (generalized from the 128 kernel) ------
|
||||
# The K/V dequant lane assignment splits each token's packed code bytes across
|
||||
# the 4 ``chunk_in_tok`` sub-lanes (lane % 4). Each lane processes
|
||||
# ``KEY_CODE_BYTES // 4`` code bytes = 32 B at 256. buffer_load maxes at 16 B
|
||||
# (dwordx4) so a lane issues ``HALVES``=2 loads; each 16-B half covers exactly
|
||||
# one UE8M0 group of 32 head-dims.
|
||||
# HEAD_SIZE=128: LANE_CODE_BYTES=16, HALVES=1, SUBCHUNK_HDIMS=32
|
||||
# HEAD_SIZE=256: LANE_CODE_BYTES=32, HALVES=2, SUBCHUNK_HDIMS=64
|
||||
LANE_CODE_BYTES = KEY_CODE_BYTES // 4 # 32 code bytes per lane per K-tile
|
||||
HALVES = LANE_CODE_BYTES // 16 # 2 for HEAD_SIZE=256
|
||||
HALF_HDIMS = 32 # head-dims per half (= one group)
|
||||
SUBCHUNK_HDIMS = HEAD_SIZE // 4 # head-dims per chunk_in_tok sub-lane (64)
|
||||
# Q row-major LDS load geometry (STEP B): each lane loads 8 bf16 (=4 i32),
|
||||
# so a row spans ``HEAD_SIZE // 8`` column-groups.
|
||||
Q_GROUPS_PER_ROW = HEAD_SIZE // 8 # 32 for 256
|
||||
Q_ROW_SHIFT = Q_GROUPS_PER_ROW.bit_length() - 1 # 5 for 256
|
||||
Q_COL_MASK = Q_GROUPS_PER_ROW - 1 # 31 for 256
|
||||
|
||||
# LDS regions
|
||||
CENTROID_LDS_BYTES = N_CENTROIDS * 4 # 64
|
||||
|
||||
# KV LDS rows are padded by 16 B to reduce bank conflicts while preserving
|
||||
# ds_read/ds_write_b128 alignment.
|
||||
KV_ROW_PAD_ELEMS = 8
|
||||
assert KV_ROW_PAD_ELEMS % 8 == 0, "KV row pad must be a multiple of 8 bf16 (16 B)"
|
||||
KV_ROW_ELEMS = HEAD_SIZE + KV_ROW_PAD_ELEMS # 264 @ pad 8
|
||||
KV_ROW_BYTES = KV_ROW_ELEMS * 2 # 528
|
||||
KFP4_ROW_PAD_I32 = 4
|
||||
assert KFP4_ROW_PAD_I32 % 4 == 0, "FP4-K row pad must be a multiple of 4 i32 (16 B)"
|
||||
KFP4_ROW_I32 = HEAD_SIZE // 8 + KFP4_ROW_PAD_I32
|
||||
KV_TILE_LDS_BYTES_PADDED = TILE_SIZE * KV_ROW_BYTES # 8448 (V dominates)
|
||||
SCALE_LDS_BYTES = TILE_SIZE * N_GROUPS * 4 # 16*8*4 = 512 for 256
|
||||
|
||||
LOG2E = 1.4426950408889634
|
||||
NEG_INF_VAL = float("-inf")
|
||||
|
||||
|
||||
def _vsplat_mul(vec, scalar):
|
||||
s = scalar.ir_value() if hasattr(scalar, "ir_value") else scalar
|
||||
return vec * vector.broadcast(T.f32x4, s)
|
||||
|
||||
|
||||
allocator = None
|
||||
|
||||
|
||||
def build_ultraquant_decode_hd256_module(
|
||||
num_seqs: int,
|
||||
num_kv_heads: int,
|
||||
num_partitions: int,
|
||||
padded_slot: int,
|
||||
max_blocks_per_seq: int = 512,
|
||||
softmax_scale: float | None = None,
|
||||
query_group_size: int = QUERY_GROUP_SIZE,
|
||||
kv_block_size: int = KV_BLOCK_SIZE,
|
||||
tile_groups_per_partition: int = 1,
|
||||
fuse_qrot: bool = True,
|
||||
stride_q_seq: int | None = None,
|
||||
stride_q_head: int | None = None,
|
||||
):
|
||||
"""Build the production UltraQuant D=256 decode kernel.
|
||||
|
||||
``padded_slot`` is the per-(token, head) slot stride in bytes
|
||||
(``kv_cache.shape[3]``, >= 272). Cache layout is
|
||||
``[num_blocks, block_size, num_kv_heads, padded_slot]`` uint8 AoS.
|
||||
|
||||
QK is always scaled FP4×E4M3 MFMA; V always uses native CVT + HW
|
||||
transpose; tile-groups are always strided. ``fuse_qrot`` selects the
|
||||
in-kernel WHT when the query layout is eligible.
|
||||
"""
|
||||
# QG=6 (Qwen3.6 full-attention layers) reuses the 8-row WHT lane map with
|
||||
# two inactive rows masked. STEP C may read rows QG..15 from adjacent LDS,
|
||||
# but those MFMA rows are discarded by the `mfma_row < QG` output gate.
|
||||
assert query_group_size in (6, 8, 16), (
|
||||
f"query_group_size must be 6, 8 or 16; got {query_group_size}"
|
||||
)
|
||||
# head_dim=256 hybrid models (Qwen3.6/3.8) force a larger mamba-aligned KV
|
||||
# block; the tiled inner loop (_TILES_PER_BLOCK = kv_block_size // TILE_SIZE)
|
||||
# handles any multiple of TILE_SIZE, so accept 16/32/64/128/256.
|
||||
assert kv_block_size in (16, 32, 64, 128, 256), (
|
||||
f"kv_block_size must be 16/32/64/128/256; got {kv_block_size}"
|
||||
)
|
||||
assert kv_block_size % TILE_SIZE == 0
|
||||
assert int(tile_groups_per_partition) >= 1
|
||||
|
||||
TGPP = int(tile_groups_per_partition)
|
||||
# Partition p owns tile-groups p, p+P, p+2P, ... This keeps the graph-fixed
|
||||
# grid wide for short sequences; the reducer is agnostic to the mapping.
|
||||
NUM_PARTS_C = int(num_partitions)
|
||||
MFMA_SCALED_K = 128
|
||||
MFMA_ISSUES = HEAD_SIZE // MFMA_SCALED_K # 2 for HEAD_SIZE=256
|
||||
GRPS_PER_ISSUE = MFMA_SCALED_K // FP8_GROUP_SIZE # 4
|
||||
|
||||
QG = int(query_group_size)
|
||||
QG_LOAD_ITERS = (QG * Q_GROUPS_PER_ROW) // WARP_SIZE # 8@QG16, 4@QG8, 3@QG6
|
||||
|
||||
_BLOCK_THREADS = WARP_SIZE
|
||||
|
||||
# Fuse Q rotation (q_rot = Q @ PiT) into this kernel as an in-register WHT.
|
||||
# The 8-row lane map masks its two inactive rows for GQA-6.
|
||||
_FUSE_QROT = bool(fuse_qrot)
|
||||
|
||||
# --- Cache policy on the KV code stream ----------------------------------
|
||||
# KV codes are read EXACTLY ONCE per decode (81.6 MB at B=4/seq=75k) and
|
||||
# never reused, so caching them only evicts Q / block-table / scale lines
|
||||
# that ARE reused. gfx9 buffer aux bits: bit0=sc0, bit1=nt, bit4=sc1.
|
||||
# 0 = default (what we ship today: no hint at all)
|
||||
# 2 = nt (non-temporal: stream, do not pollute)
|
||||
# 18 = nt|sc1 (also bypass the far cache level)
|
||||
_KV_AUX = 0
|
||||
|
||||
# --- Occupancy: size the Q LDS to the ACTUAL query group -------------------
|
||||
# STEP B only writes rows [0, QG) and STEP C/F only read those rows. For
|
||||
# QG=8 the upper 4 KB is allocated-but-never-touched, so shrinking it to
|
||||
# QG*HEAD_SIZE*2 is bitwise identical and frees LDS/workgroup (17 KB -> 13 KB
|
||||
# at QG=8), lifting waves/CU (~3 -> ~5) since the kernel is LDS-occupancy
|
||||
# bound. The launcher pads segm pools to QG=16 regardless, so this is purely
|
||||
# an in-kernel LDS footprint reduction.
|
||||
_Q_LDS_BYTES = QG * HEAD_SIZE * 2
|
||||
|
||||
_BS = int(kv_block_size)
|
||||
_TILES_PER_BLOCK = _BS // TILE_SIZE
|
||||
_PADDED_SLOT = int(padded_slot)
|
||||
assert _PADDED_SLOT >= SLOT_CONTENT_BYTES, (
|
||||
f"padded_slot={_PADDED_SLOT} < {SLOT_CONTENT_BYTES} (ultraquant D=256 content)"
|
||||
)
|
||||
assert _PADDED_SLOT % 4 == 0, f"padded_slot={_PADDED_SLOT} must be 4-byte aligned"
|
||||
|
||||
arch = get_hip_arch()
|
||||
|
||||
if softmax_scale is None:
|
||||
softmax_scale = 1.0 / (HEAD_SIZE**0.5)
|
||||
_qk_scale = float(softmax_scale)
|
||||
|
||||
# --- Strides ---
|
||||
_Hq = num_kv_heads * QG
|
||||
# Defaults describe the pooled [B, Hq, D] q_rot buffer. When the rotation is
|
||||
# fused in (STEP B'), Q is read straight from the model's query tensor,
|
||||
# which is a SPLIT OF THE FUSED QKV PROJECTION -- so its row stride is
|
||||
# (Hq + 2*Hk)*D, not Hq*D. Those strides are constant for a given model and
|
||||
# TP rank, so the caller passes them in and they bake in like any other
|
||||
# compile-time constant (they are part of the kernel cache key).
|
||||
_stride_q_seq = int(stride_q_seq) if stride_q_seq is not None else _Hq * HEAD_SIZE
|
||||
_stride_q_head = int(stride_q_head) if stride_q_head is not None else HEAD_SIZE
|
||||
_stride_bt_seq = max_blocks_per_seq
|
||||
|
||||
# ultraquant AoS cache: [num_blocks, block_size, num_kv_heads, padded_slot].
|
||||
_stride_cache_head = _PADDED_SLOT
|
||||
_stride_cache_pos = num_kv_heads * _PADDED_SLOT
|
||||
_stride_cache_block = _BS * _stride_cache_pos
|
||||
|
||||
_stride_out_part = QG * HEAD_SIZE
|
||||
_stride_out_head = num_partitions * QG * HEAD_SIZE
|
||||
_stride_out_seq = num_kv_heads * num_partitions * QG * HEAD_SIZE
|
||||
_stride_es_seq = num_kv_heads * num_partitions * QG
|
||||
_stride_ml_seq = _stride_es_seq
|
||||
|
||||
# --- LDS layout ---
|
||||
# `allocator` is intentionally a BUILD-LOCAL captured by the kernel closure
|
||||
# (a freevar), NOT a module global. The @flyc.jit drift guard
|
||||
# (_check_globals_drift) snapshots every module global referenced by the JIT
|
||||
# launcher's dependency tree (which includes this kernel) and ABORTS if one
|
||||
# changes between compiles. When more than one partition variant is
|
||||
# JIT-resident at once (e.g. a ragged/adaptive batch mixes num_partitions
|
||||
# 256 and 512, or fixed cap=512 yields 294@75k and 512@131k), each build
|
||||
# created a fresh SmemAllocator; as a reassigned MODULE GLOBAL that tripped
|
||||
# "global 'allocator' changed since first compile" and crashed the worker.
|
||||
# Keeping it local + a per-variant symbol name lets the variants coexist.
|
||||
# The build-local is handed to the launcher via a module attribute set AFTER
|
||||
# the kernel is built (see end of function); that assignment is safe because
|
||||
# no @flyc.jit function references the module global anymore.
|
||||
allocator = SmemAllocator(
|
||||
None,
|
||||
arch=arch,
|
||||
global_sym_name=(f"ultraquant_hd256_smem_p{int(num_partitions)}"),
|
||||
)
|
||||
centroid_off = 0
|
||||
allocator.ptr = CENTROID_LDS_BYTES
|
||||
q_off = allocator.ptr
|
||||
allocator.ptr += _Q_LDS_BYTES
|
||||
kv_off = allocator.ptr
|
||||
allocator.ptr += KV_TILE_LDS_BYTES_PADDED
|
||||
scale_off = allocator.ptr
|
||||
allocator.ptr += SCALE_LDS_BYTES
|
||||
|
||||
@flyc.kernel
|
||||
def ultraquant_decode_hd256_kernel(
|
||||
out_ptr: fx.Tensor,
|
||||
exp_sums_ptr: fx.Tensor,
|
||||
max_logits_ptr: fx.Tensor,
|
||||
query_ptr: fx.Tensor,
|
||||
kv_cache_ptr: fx.Tensor,
|
||||
centroids_ptr: fx.Tensor,
|
||||
block_tables_ptr: fx.Tensor,
|
||||
seq_lens_ptr: fx.Tensor,
|
||||
):
|
||||
# ---- IDs ---------------------------------------------------------
|
||||
tid = gpu.thread_idx.x
|
||||
seq = gpu.block_idx.x
|
||||
kv_h = gpu.block_idx.y
|
||||
part = gpu.block_idx.z
|
||||
lane = tid # 0..63
|
||||
mfma_row = lane & fx.Int32(15)
|
||||
mfma_col_grp = lane >> fx.Int32(4) # 0..3, K-group dim
|
||||
|
||||
# ---- Buffer resources -------------------------------------------
|
||||
q_rsrc = buffer_ops.create_buffer_resource(query_ptr, max_size=True)
|
||||
bt_rsrc = buffer_ops.create_buffer_resource(block_tables_ptr, max_size=True)
|
||||
sl_rsrc = buffer_ops.create_buffer_resource(seq_lens_ptr, max_size=True)
|
||||
cent_rsrc = buffer_ops.create_buffer_resource(centroids_ptr, max_size=True)
|
||||
out_rsrc = buffer_ops.create_buffer_resource(out_ptr, max_size=True)
|
||||
es_rsrc = buffer_ops.create_buffer_resource(exp_sums_ptr, max_size=True)
|
||||
ml_rsrc = buffer_ops.create_buffer_resource(max_logits_ptr, max_size=True)
|
||||
|
||||
# ---- LDS pointers -----------------------------------------------
|
||||
base = allocator.get_base()
|
||||
cent_lds = SmemPtr(base, centroid_off, T.f32, shape=(N_CENTROIDS,))
|
||||
q_lds_i32 = SmemPtr(base, q_off, T.i32, shape=(_Q_LDS_BYTES // 4,)).get()
|
||||
q_lds_i64 = SmemPtr(base, q_off, T.i64, shape=(_Q_LDS_BYTES // 8,)).get()
|
||||
# KV / scale views span ALL warps' private regions (W*stride); the
|
||||
# per-warp base offset is folded into the element indices below via
|
||||
# _kvi*/_sci (a literal 0 for W=1, so the single-warp path is unchanged).
|
||||
kv_lds_i32 = SmemPtr(
|
||||
base, kv_off, T.i32, shape=(KV_TILE_LDS_BYTES_PADDED // 4,)
|
||||
).get()
|
||||
kv_lds_i64 = SmemPtr(
|
||||
base, kv_off, T.i64, shape=(KV_TILE_LDS_BYTES_PADDED // 8,)
|
||||
).get()
|
||||
scale_lds_i32 = SmemPtr(base, scale_off, T.i32, shape=(TILE_SIZE * N_GROUPS,))
|
||||
|
||||
def _kvi32(e):
|
||||
return e
|
||||
|
||||
def _kvi64(e):
|
||||
return e
|
||||
|
||||
def _sci(e):
|
||||
return e
|
||||
|
||||
# ---- Constants ---------------------------------------------------
|
||||
c_sq = fx.Int32(_stride_q_seq)
|
||||
c_qh = fx.Int32(_stride_q_head)
|
||||
c_qg = fx.Int32(QG)
|
||||
c_bt = fx.Int32(_stride_bt_seq)
|
||||
c_stride_pos = fx.Int32(_stride_cache_pos)
|
||||
c_stride_head = fx.Int32(_stride_cache_head)
|
||||
c_kscale_off = fx.Int32(K_SCALES_OFFSET) # 128
|
||||
c_vcode_off = fx.Int32(V_CODES_OFFSET) # 136
|
||||
c_vscale_off = fx.Int32(V_SCALES_OFFSET) # 264
|
||||
c_w = fx.Int32(WARP_SIZE)
|
||||
|
||||
NEG_INF = arith.constant(NEG_INF_VAL, type=T.f32)
|
||||
ZERO_F = fx.Float32(0.0)
|
||||
ONE_F = fx.Float32(1.0)
|
||||
LOG2E_C = arith.constant(LOG2E, type=T.f32)
|
||||
QK_SCALE = arith.constant(_qk_scale, type=T.f32)
|
||||
|
||||
def _ival(v):
|
||||
return v.ir_value() if hasattr(v, "ir_value") else v
|
||||
|
||||
c_zero_i32 = arith.constant(0, type=T.i32)
|
||||
|
||||
def _f32x8_to_fp8_i64(f):
|
||||
# 8 f32 -> 8 E4M3 bytes packed as i64 (MFMA fp8 operand).
|
||||
w0 = rocdl.cvt_pk_fp8_f32(T.i32, f[0], f[1], c_zero_i32, 0)
|
||||
w0 = rocdl.cvt_pk_fp8_f32(T.i32, f[2], f[3], w0, 1)
|
||||
w1 = rocdl.cvt_pk_fp8_f32(T.i32, f[4], f[5], c_zero_i32, 0)
|
||||
w1 = rocdl.cvt_pk_fp8_f32(T.i32, f[6], f[7], w1, 1)
|
||||
pv = vector.from_elements(T.vec(2, T.i32), [w0, w1])
|
||||
return vector.extract(
|
||||
vector.bitcast(T.vec(1, T.i64), pv), static_position=[0]
|
||||
)
|
||||
|
||||
def _bf16x8_to_fp8_i64(v_bf16):
|
||||
f = [
|
||||
arith.extf(T.f32, vector.extract(v_bf16, static_position=[i]))
|
||||
for i in range(8)
|
||||
]
|
||||
return _f32x8_to_fp8_i64(f)
|
||||
|
||||
# ===== STEP A: Load centroids → LDS (cooperative, race-safe) =====
|
||||
c_idx_safe = lane & fx.Int32(N_CENTROIDS - 1)
|
||||
c_val = buffer_ops.buffer_load(cent_rsrc, c_idx_safe, vec_width=1, dtype=T.f32)
|
||||
cent_lds.store(c_val, [arith.index_cast(T.index, c_idx_safe)])
|
||||
gpu.barrier()
|
||||
|
||||
# ===== STEP B': in-kernel Q rotation (fused WHT) ==================
|
||||
# The shipped path needs a SEPARATE prologue kernel to compute
|
||||
# q_rot = Q @ PiT. That kernel is ~7 us at B=4 -- essentially ALL fixed
|
||||
# per-dispatch cost (measured: 2.1M MACs, and sweeping its grid 4x moves
|
||||
# it 0%). PiT is the orthonormal Sylvester Hadamard with a column
|
||||
# permutation folded in on the host, so Q @ PiT is a WALSH-HADAMARD
|
||||
# TRANSFORM: 8 butterfly stages (2048 add/sub per row) instead of a
|
||||
# 256x256 matmul (65536 MACs) -- 32x less work, cheap enough to redo
|
||||
# redundantly in every partition and delete the dispatch entirely.
|
||||
#
|
||||
# Verified offline: butterfly vs matmul differs by <=1.8e-6 in fp32, and
|
||||
# after the E4M3 haircut the two agree EXACTLY (0/2048 elements differ),
|
||||
# because e4m3 keeps only 3 mantissa bits. So this is bit-exact, not an
|
||||
# approximation.
|
||||
#
|
||||
# Lane map: lane L owns row r = L>>3 and the 32 CONSECUTIVE head-dims
|
||||
# d = (L&7)*32 + t. That puts butterfly stages 0..4 (strides 1..16)
|
||||
# entirely inside one lane's registers, and leaves only stages 5..7
|
||||
# (strides 32/64/128 == chunk XOR 1/2/4) needing a cross-lane exchange.
|
||||
if const_expr(_FUSE_QROT):
|
||||
_wrow = lane >> fx.Int32(3) # 0..7 row within the group
|
||||
_wchk = lane & fx.Int32(7) # 0..7 32-dim chunk
|
||||
# inv(qperm) is a pure bit permutation of the head-dim index:
|
||||
# dest = (d & 0x8F) | ((d>>2)&0x10) | ((d<<1)&0x60)
|
||||
# which splits additively into a compile-time part in t and a
|
||||
# per-lane part in the chunk index (verified exhaustively):
|
||||
# ct(t) = (t & 0x0F) | ((t & 0x10) << 1)
|
||||
# rt(c) = ((c&2)<<3) | ((c&1)<<6) | ((c&4)<<5)
|
||||
_perm_base = (
|
||||
((_wchk & fx.Int32(2)) << fx.Int32(3))
|
||||
| ((_wchk & fx.Int32(1)) << fx.Int32(6))
|
||||
| ((_wchk & fx.Int32(4)) << fx.Int32(5))
|
||||
)
|
||||
_inv_sqrtD = arith.constant(1.0 / math.sqrt(HEAD_SIZE), type=T.f32)
|
||||
for _qit in range_constexpr((QG + 7) // 8):
|
||||
_qrow = _wrow + fx.Int32(_qit * 8)
|
||||
if _qrow < fx.Int32(QG):
|
||||
_qb = (
|
||||
seq * c_sq + (kv_h * c_qg + _qrow) * c_qh + _wchk * fx.Int32(32)
|
||||
)
|
||||
# ---- load this lane's 32 raw-Q head-dims (4 x dwordx4) ----
|
||||
_v = []
|
||||
for _j in range_constexpr(4):
|
||||
_raw = buffer_ops.buffer_load(
|
||||
q_rsrc,
|
||||
(_qb + fx.Int32(_j * 8)) // fx.Int32(2),
|
||||
vec_width=4,
|
||||
dtype=T.i32,
|
||||
)
|
||||
_rb = vector.bitcast(T.vec(8, T.bf16), _raw)
|
||||
for _e in range_constexpr(8):
|
||||
_v.append(
|
||||
arith.extf(
|
||||
T.f32, vector.extract(_rb, static_position=[_e])
|
||||
)
|
||||
)
|
||||
# ---- stages 0..4: in-register, no LDS, no cross-lane ----
|
||||
for _s in range_constexpr(5):
|
||||
_st = 1 << _s
|
||||
_nx = list(_v)
|
||||
for _g in range_constexpr(32 // (2 * _st)):
|
||||
for _k in range_constexpr(_st):
|
||||
_i0 = _g * 2 * _st + _k
|
||||
_i1 = _i0 + _st
|
||||
_a, _b = _v[_i0], _v[_i1]
|
||||
_nx[_i0] = _a + _b
|
||||
_nx[_i1] = _a - _b
|
||||
_v = _nx
|
||||
# ---- stages 5..7: chunk XOR 1/2/4 via ds_swizzle ----
|
||||
# ds_swizzle_b32 offset (bit15=0, 32-lane groups):
|
||||
# [4:0]=and_mask [9:5]=or_mask [14:10]=xor_mask
|
||||
# pure XOR k -> and_mask=0x1F, or_mask=0, xor_mask=k. The
|
||||
# partner is always within the same 32-lane group (k<=4).
|
||||
for _s in range_constexpr(3):
|
||||
_k = 1 << _s
|
||||
_swz = arith.constant((_k << 10) | 0x1F, type=T.i32)
|
||||
# High half of the pair computes (partner - mine), the low
|
||||
# half (mine + partner). Fold that into a single sign
|
||||
# computed ONCE per stage, so each element costs one
|
||||
# multiply-add rather than a branch or a per-element select.
|
||||
_chk_bit = _wchk & fx.Int32(_k)
|
||||
_is_hi = arith.cmpi(
|
||||
arith.CmpIPredicate.ne,
|
||||
_chk_bit.ir_value()
|
||||
if hasattr(_chk_bit, "ir_value")
|
||||
else _chk_bit,
|
||||
fx.Int32(0).ir_value(),
|
||||
)
|
||||
_sf = arith.select(
|
||||
_is_hi,
|
||||
arith.constant(-1.0, type=T.f32),
|
||||
arith.constant(1.0, type=T.f32),
|
||||
)
|
||||
_nx = []
|
||||
for _t in range_constexpr(32):
|
||||
_mi = arith.bitcast(T.i32, _v[_t])
|
||||
_pt = arith.bitcast(
|
||||
T.f32, rocdl.ds_swizzle(T.i32, _mi, _swz)
|
||||
)
|
||||
_nx.append(_v[_t] * _sf + _pt)
|
||||
_v = _nx
|
||||
# ---- 1/sqrt(D) normalization + E4M3 haircut -> bf16 ----
|
||||
# cvt_pk_fp8_f32 is the SAME instruction the QK operand build
|
||||
# uses, so this reproduces the host haircut exactly. E4M3 is a
|
||||
# subset of bf16, so the bf16 store below is lossless and every
|
||||
# downstream consumer stays byte-identical.
|
||||
_hc = []
|
||||
for _p in range_constexpr(16):
|
||||
_w = rocdl.cvt_pk_fp8_f32(
|
||||
T.i32,
|
||||
_v[2 * _p] * _inv_sqrtD,
|
||||
_v[2 * _p + 1] * _inv_sqrtD,
|
||||
fx.Int32(0),
|
||||
0,
|
||||
)
|
||||
_u = rocdl.cvt_pk_f32_fp8(T.vec(2, T.f32), _w, 0)
|
||||
_hc.append(
|
||||
arith.truncf(
|
||||
T.bf16, vector.extract(_u, static_position=[0])
|
||||
)
|
||||
)
|
||||
_hc.append(
|
||||
arith.truncf(
|
||||
T.bf16, vector.extract(_u, static_position=[1])
|
||||
)
|
||||
)
|
||||
# ---- permuted store ----
|
||||
# ct(t) maps t=0..15 -> 0..15 and t=16..31 -> 32..47, i.e. TWO
|
||||
# contiguous 16-element runs, so the scatter is still 4 aligned
|
||||
# 16-byte vector stores rather than 32 scalar writes.
|
||||
_qrow_elem = _qrow * fx.Int32(HEAD_SIZE)
|
||||
for _half in range_constexpr(2):
|
||||
for _q4 in range_constexpr(2):
|
||||
_elems = [_hc[_half * 16 + _q4 * 8 + _e] for _e in range(8)]
|
||||
_vec = vector.from_elements(T.vec(8, T.bf16), _elems)
|
||||
_dst = (
|
||||
_qrow_elem + _perm_base + fx.Int32(_half * 32 + _q4 * 8)
|
||||
)
|
||||
vector.store(
|
||||
vector.bitcast(T.vec(4, T.i32), _vec),
|
||||
q_lds_i32,
|
||||
[arith.index_cast(T.index, _dst // fx.Int32(2))],
|
||||
)
|
||||
gpu.barrier()
|
||||
|
||||
# ===== STEP B: Load pre-rotated q_rot → row-major Q LDS ==========
|
||||
for c in range_constexpr(0 if _FUSE_QROT else QG_LOAD_ITERS):
|
||||
row_chunk = lane + fx.Int32(c * WARP_SIZE)
|
||||
row = row_chunk >> fx.Int32(Q_ROW_SHIFT) # 0..QG-1
|
||||
col_b = row_chunk & fx.Int32(Q_COL_MASK) # 0..Q_GROUPS_PER_ROW-1
|
||||
col_elem = col_b * fx.Int32(8) # bf16 elem
|
||||
q_off_elem = seq * c_sq + (kv_h * c_qg + row) * c_qh + col_elem
|
||||
q_v = buffer_ops.buffer_load(
|
||||
q_rsrc,
|
||||
q_off_elem // fx.Int32(2),
|
||||
vec_width=4,
|
||||
dtype=T.i32,
|
||||
)
|
||||
q_lds_byte = row * fx.Int32(HEAD_SIZE * 2) + col_elem * fx.Int32(2)
|
||||
vector.store(
|
||||
q_v,
|
||||
q_lds_i32,
|
||||
[arith.index_cast(T.index, q_lds_byte // fx.Int32(4))],
|
||||
)
|
||||
gpu.barrier()
|
||||
|
||||
# Scaled-MFMA Q operands (loop-invariant): one per MFMA issue.
|
||||
q_op_hoisted = []
|
||||
for h in range_constexpr(MFMA_ISSUES):
|
||||
_q_hoist_words = []
|
||||
for j in range_constexpr(4):
|
||||
_q_hoist_idx = (
|
||||
mfma_row * fx.Int32(HEAD_SIZE * 2 // 8)
|
||||
+ (fx.Int32(h * GRPS_PER_ISSUE) + mfma_col_grp) * fx.Int32(8)
|
||||
+ fx.Int32(j * 2)
|
||||
)
|
||||
_q_hoist_v = vector.load_op(
|
||||
T.vec(2, T.i64),
|
||||
q_lds_i64,
|
||||
[arith.index_cast(T.index, _q_hoist_idx)],
|
||||
)
|
||||
_q_hoist_words.append(
|
||||
_bf16x8_to_fp8_i64(vector.bitcast(T.vec(8, T.bf16), _q_hoist_v))
|
||||
)
|
||||
q_op_hoisted.append(
|
||||
vector.bitcast(
|
||||
T.vec(8, T.i32),
|
||||
vector.from_elements(T.vec(4, T.i64), _q_hoist_words),
|
||||
)
|
||||
)
|
||||
|
||||
# ===== STEP D: Online softmax + PV state =========================
|
||||
running_max = NEG_INF
|
||||
running_sum = ZERO_F
|
||||
zero_v4 = arith.constant_vector(0.0, T.f32x4)
|
||||
acc_pv = [zero_v4 for _ in range(PV_N_CHUNKS)]
|
||||
|
||||
# ===== STEP E: Sequence-len + partition base ====================
|
||||
seq_len = buffer_ops.buffer_load(sl_rsrc, seq, vec_width=1, dtype=T.i32)
|
||||
|
||||
# Per-K-tile dequant lane assignment: lane t -> token = t/4,
|
||||
# chunk_in_tok = t%4 (each chunk = SUBCHUNK_HDIMS=64 head-dims = 2 groups).
|
||||
tok_in_tile = lane >> fx.Int32(2)
|
||||
chunk_in_tok = lane & fx.Int32(3)
|
||||
# Both UE8M0 group bytes for this lane's chunk (groups 2c, 2c+1) live in
|
||||
# the SAME 4-byte scale word at offset (chunk_in_tok>>1)*4 within the
|
||||
# 8-byte scale region. Load once; extract per-half below.
|
||||
c_scale_word_off = (chunk_in_tok >> fx.Int32(1)) * fx.Int32(4)
|
||||
|
||||
# ===== STEP F: K-tile loop =======================================
|
||||
c_kcb = fx.Int32(KV_COMPUTE_BLOCK)
|
||||
c_tgpp = fx.Int32(TGPP)
|
||||
c_zero_i32 = fx.Int32(0)
|
||||
c_one_i32 = fx.Int32(1)
|
||||
c_nparts = fx.Int32(NUM_PARTS_C)
|
||||
total_tgs = (seq_len + c_kcb - c_one_i32) // c_kcb
|
||||
avail = total_tgs - part
|
||||
in_range = avail > c_zero_i32
|
||||
trip_raw = (avail + c_nparts - c_one_i32) // c_nparts
|
||||
trip_clamped = (trip_raw > c_tgpp).select(c_tgpp, trip_raw)
|
||||
trip_or_zero = in_range.select(trip_clamped, c_zero_i32)
|
||||
c_zero_idx = arith.constant(0, index=True)
|
||||
c_one_idx = arith.constant(1, index=True)
|
||||
trip_idx = arith.index_cast(
|
||||
T.index,
|
||||
trip_or_zero.ir_value()
|
||||
if hasattr(trip_or_zero, "ir_value")
|
||||
else trip_or_zero,
|
||||
)
|
||||
_init_iter = [
|
||||
_ival(running_max),
|
||||
_ival(running_sum),
|
||||
*[_ival(p) for p in acc_pv],
|
||||
]
|
||||
_for_op = _scf.ForOp(
|
||||
c_zero_idx,
|
||||
trip_idx,
|
||||
c_one_idx,
|
||||
_init_iter,
|
||||
)
|
||||
_for_ip = ir.InsertionPoint(_for_op.body)
|
||||
_for_ip.__enter__()
|
||||
try:
|
||||
tg_idx = _for_op.induction_variable
|
||||
tg_i32 = fx.Int32(arith.index_cast(T.i32, tg_idx))
|
||||
partition_start = (part + tg_i32 * c_nparts) * c_kcb
|
||||
bt_seq_base = seq * c_bt + (partition_start // fx.Int32(_BS))
|
||||
running_max = _for_op.inner_iter_args[0]
|
||||
running_sum = _for_op.inner_iter_args[1]
|
||||
acc_pv = list(_for_op.inner_iter_args[2:])
|
||||
|
||||
# ==== SOFTWARE PREFETCH =====================================
|
||||
# Emit ONLY the HBM buffer_loads for one tile (K codes, V codes,
|
||||
# K/V UE8M0 scale words) and return the loaded register values.
|
||||
# Emitting tile N+1's loads BEFORE tile N's dequant+MFMA lets the
|
||||
# vmem fetches overlap compute: the compiler's s_waitcnt for these
|
||||
# values lands at their first use one iteration later, hiding HBM
|
||||
# latency (the decode kernel is ~85% HBM-stalled at low batch).
|
||||
# This is bit-identical to the pre-prefetch path -- only the
|
||||
# *emission order* of independent loads changes, never any
|
||||
# arithmetic. All addressing locals (slot_base_byte, blk_rsrc,
|
||||
# ...) are consumed only inside this closure; the dequant below
|
||||
# needs just the four returned register values.
|
||||
def _emit_tile_loads(n_tile):
|
||||
# n_tile is a compile-time int on the single-warp path and a
|
||||
# runtime fx.Int32 on the multi-warp path (each warp strides the
|
||||
# 16 tiles). Compute the block/tile/slot geometry accordingly.
|
||||
if const_expr(isinstance(n_tile, int)):
|
||||
block_in_part = fx.Int32(n_tile // _TILES_PER_BLOCK)
|
||||
tile_in_block = n_tile % _TILES_PER_BLOCK
|
||||
tile_start_tok = partition_start + fx.Int32(n_tile * TILE_SIZE)
|
||||
slot = fx.Int32(tile_in_block * TILE_SIZE) + tok_in_tile
|
||||
else:
|
||||
block_in_part = n_tile // fx.Int32(_TILES_PER_BLOCK)
|
||||
tile_in_block = n_tile - block_in_part * fx.Int32(_TILES_PER_BLOCK)
|
||||
tile_start_tok = partition_start + n_tile * fx.Int32(TILE_SIZE)
|
||||
slot = tile_in_block * fx.Int32(TILE_SIZE) + tok_in_tile
|
||||
tile_in_seq = tile_start_tok < seq_len
|
||||
bt_off = bt_seq_base + block_in_part
|
||||
bt_off_safe = tile_in_seq.select(bt_off, seq * c_bt)
|
||||
phys_block = buffer_ops.buffer_load(
|
||||
bt_rsrc,
|
||||
bt_off_safe,
|
||||
vec_width=1,
|
||||
dtype=T.i32,
|
||||
)
|
||||
# A buffer descriptor addresses with a 32-bit voffset, so
|
||||
# ``phys_block * c_block`` wraps once the cache view exceeds
|
||||
# 4 GiB. Fold the block base into the descriptor's 64-bit
|
||||
# base pointer and keep only in-block offsets below.
|
||||
blk_off_i64 = arith.extui(T.i64, phys_block) * fx.Int64(
|
||||
_stride_cache_block
|
||||
)
|
||||
blk_rsrc = buffer_ops.create_buffer_resource(
|
||||
kv_cache_ptr,
|
||||
max_size=True,
|
||||
base_byte_offset=blk_off_i64,
|
||||
)
|
||||
block_base = fx.Int32(0)
|
||||
|
||||
slot_base_byte = block_base + slot * c_stride_pos + kv_h * c_stride_head
|
||||
# K codes: LANE_CODE_BYTES (=32) at slot_base + chunk*32, in
|
||||
# HALVES x 16-byte buffer_loads.
|
||||
k_byte0 = slot_base_byte + chunk_in_tok * fx.Int32(LANE_CODE_BYTES)
|
||||
_kpl = []
|
||||
for hf in range_constexpr(HALVES):
|
||||
_kpl.append(
|
||||
buffer_ops.buffer_load(
|
||||
blk_rsrc,
|
||||
(k_byte0 + fx.Int32(hf * 16)) // fx.Int32(4),
|
||||
vec_width=4,
|
||||
dtype=T.i32,
|
||||
cache_modifier=_KV_AUX,
|
||||
)
|
||||
)
|
||||
|
||||
# ---- V codes + K/V scale HBM loads ------------------------
|
||||
v_byte0 = (
|
||||
slot_base_byte
|
||||
+ c_vcode_off
|
||||
+ chunk_in_tok * fx.Int32(LANE_CODE_BYTES)
|
||||
)
|
||||
_vpl = []
|
||||
for hf in range_constexpr(HALVES):
|
||||
_vpl.append(
|
||||
buffer_ops.buffer_load(
|
||||
blk_rsrc,
|
||||
(v_byte0 + fx.Int32(hf * 16)) // fx.Int32(4),
|
||||
vec_width=4,
|
||||
dtype=T.i32,
|
||||
cache_modifier=_KV_AUX,
|
||||
)
|
||||
)
|
||||
# UE8M0 group scale words (one 4-byte word covers this lane's
|
||||
# two groups). scale = 2^(byte-127) = bitcast_f32(byte<<23);
|
||||
# byte==0 -> +0.0 (zero sentinel).
|
||||
_ksw = buffer_ops.buffer_load(
|
||||
blk_rsrc,
|
||||
(slot_base_byte + c_kscale_off + c_scale_word_off) // fx.Int32(4),
|
||||
vec_width=1,
|
||||
dtype=T.i32,
|
||||
)
|
||||
_vsw = buffer_ops.buffer_load(
|
||||
blk_rsrc,
|
||||
(slot_base_byte + c_vscale_off + c_scale_word_off) // fx.Int32(4),
|
||||
vec_width=1,
|
||||
dtype=T.i32,
|
||||
)
|
||||
return (_kpl, _vpl, _ksw, _vsw)
|
||||
|
||||
# Depth-1 software prefetch: emit the next tile's HBM loads before
|
||||
# consuming the current tile without changing arithmetic order.
|
||||
_PF_DEPTH = 1
|
||||
# Prime the pipeline with the first _PF_DEPTH tiles' loads.
|
||||
_pf_queue = []
|
||||
for _pi in range_constexpr(min(_PF_DEPTH, 16)):
|
||||
_pf_queue.append(_emit_tile_loads(_pi))
|
||||
_tile_range = range_constexpr(16)
|
||||
for _jt in _tile_range:
|
||||
n_tile = _jt
|
||||
_ntile_tok = fx.Int32(n_tile * TILE_SIZE)
|
||||
(k_packed_list, v_packed_list, kscale_word, vscale_word) = (
|
||||
_pf_queue.pop(0)
|
||||
)
|
||||
_pf_nxt = n_tile + _PF_DEPTH
|
||||
if const_expr(_pf_nxt < 16):
|
||||
_pf_queue.append(_emit_tile_loads(_pf_nxt))
|
||||
# Store raw FP4 codes (natural contiguous order,
|
||||
# 16 B = 32 nibbles per UE8M0 group) straight to KV LDS as
|
||||
# the scaled-MFMA A operand — no dequant here.
|
||||
for hf in range_constexpr(HALVES):
|
||||
grp = chunk_in_tok * fx.Int32(2) + fx.Int32(hf)
|
||||
grp_shift = (grp & fx.Int32(3)) * fx.Int32(8)
|
||||
kscale_byte = (kscale_word >> grp_shift) & fx.Int32(0xFF)
|
||||
k_packed = k_packed_list[hf]
|
||||
vector.store(
|
||||
k_packed,
|
||||
kv_lds_i32,
|
||||
[
|
||||
arith.index_cast(
|
||||
T.index,
|
||||
_kvi32(
|
||||
tok_in_tile * fx.Int32(KFP4_ROW_I32)
|
||||
+ grp * fx.Int32(4)
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
scale_lds_i32.store(
|
||||
kscale_byte,
|
||||
[
|
||||
arith.index_cast(
|
||||
T.index,
|
||||
_sci(tok_in_tile * fx.Int32(N_GROUPS) + grp),
|
||||
)
|
||||
],
|
||||
)
|
||||
gpu.barrier()
|
||||
# QK: MFMA_ISSUES native scaled MFMAs over K=128,
|
||||
# chained through the accumulator.
|
||||
# A = K raw FP4 codes (vec4 i32 = 16 B) per (token, group)
|
||||
# B = Q E4M3 (vec8 i32 = 32 B) for the same group
|
||||
# scaleA = per-(token,group) UE8M0 byte at op_sel byte 0
|
||||
# scaleB = 0x7F identity (Q carries no scale)
|
||||
BLGP_E2M1 = 4 # A operand type code = fp4 e2m1
|
||||
CBSZ_E4M3 = 0 # B operand type code = fp8 e4m3
|
||||
IDENT = fx.Int32(0x7F)
|
||||
qk_acc = zero_v4
|
||||
for h in range_constexpr(MFMA_ISSUES):
|
||||
grp = fx.Int32(h * GRPS_PER_ISSUE) + mfma_col_grp
|
||||
k_op = vector.load_op(
|
||||
T.vec(4, T.i32),
|
||||
kv_lds_i32,
|
||||
[
|
||||
arith.index_cast(
|
||||
T.index,
|
||||
_kvi32(
|
||||
mfma_row * fx.Int32(KFP4_ROW_I32)
|
||||
+ grp * fx.Int32(4)
|
||||
),
|
||||
)
|
||||
],
|
||||
)
|
||||
q_op = q_op_hoisted[h]
|
||||
scbyte = fx.Int32(
|
||||
scale_lds_i32.load(
|
||||
[
|
||||
arith.index_cast(
|
||||
T.index,
|
||||
_sci(mfma_row * fx.Int32(N_GROUPS) + grp),
|
||||
)
|
||||
]
|
||||
)
|
||||
)
|
||||
kscale = fx.Int32(0x7F7F7F00) | scbyte
|
||||
qk_acc = rocdl.mfma_scale_f32_16x16x128_f8f6f4(
|
||||
T.vec(4, T.f32),
|
||||
[
|
||||
k_op,
|
||||
q_op,
|
||||
qk_acc,
|
||||
BLGP_E2M1,
|
||||
CBSZ_E4M3,
|
||||
0,
|
||||
kscale,
|
||||
0,
|
||||
IDENT,
|
||||
],
|
||||
)
|
||||
|
||||
# Scale + mask out-of-context tokens.
|
||||
qk_acc = _vsplat_mul(qk_acc, QK_SCALE)
|
||||
for elem in range_constexpr(4):
|
||||
kv_tok = (
|
||||
partition_start
|
||||
+ _ntile_tok
|
||||
+ mfma_col_grp * fx.Int32(4)
|
||||
+ fx.Int32(elem)
|
||||
)
|
||||
in_b = kv_tok < seq_len
|
||||
v = vector.extract(qk_acc, static_position=[elem])
|
||||
qk_acc = _vector_insert(
|
||||
in_b.select(v, NEG_INF),
|
||||
qk_acc,
|
||||
static_position=[elem],
|
||||
)
|
||||
|
||||
# FA2 online softmax: per-query-row reduce.
|
||||
local_max = vector.reduction(T.f32, "maxnumf", qk_acc)
|
||||
r1 = local_max.shuffle_xor(fx.Int32(16), c_w)
|
||||
local_max = local_max.maximumf(r1)
|
||||
r2 = local_max.shuffle_xor(fx.Int32(32), c_w)
|
||||
tile_max = local_max.maximumf(r2)
|
||||
|
||||
new_max = running_max.maximumf(tile_max)
|
||||
max_diff = running_max - new_max
|
||||
safe_diff = (running_max > NEG_INF).select(max_diff, ZERO_F)
|
||||
scale = (safe_diff * LOG2E_C).exp2(fastmath=arith.FastMathFlags.fast)
|
||||
running_sum = running_sum * scale
|
||||
for h in range_constexpr(PV_N_CHUNKS):
|
||||
acc_pv[h] = _vsplat_mul(acc_pv[h], scale)
|
||||
running_max = new_max
|
||||
|
||||
tile_sum = ZERO_F
|
||||
for elem in range_constexpr(4):
|
||||
s = vector.extract(qk_acc, static_position=[elem])
|
||||
d = s - new_max
|
||||
d = (new_max > NEG_INF).select(d, NEG_INF)
|
||||
p = (d * LOG2E_C).exp2(fastmath=arith.FastMathFlags.fast)
|
||||
tile_sum = tile_sum + p
|
||||
qk_acc = _vector_insert(p, qk_acc, static_position=[elem])
|
||||
|
||||
ts1 = tile_sum.shuffle_xor(fx.Int32(16), c_w)
|
||||
tile_sum = tile_sum + ts1
|
||||
ts2 = tile_sum.shuffle_xor(fx.Int32(32), c_w)
|
||||
tile_sum = tile_sum + ts2
|
||||
running_sum = running_sum + tile_sum
|
||||
# V dequant → LDS [token][head_dim] (ROW-MAJOR, no transpose)
|
||||
# written as ds_write_b128 (vec(2,i64)); read back via the
|
||||
# ds_read_tr16_b64 HW transpose in the PV block below.
|
||||
v_lds_elem_base = tok_in_tile * fx.Int32(
|
||||
KV_ROW_ELEMS
|
||||
) + chunk_in_tok * fx.Int32(SUBCHUNK_HDIMS)
|
||||
for hf in range_constexpr(HALVES):
|
||||
v_packed = v_packed_list[hf]
|
||||
half_hd = fx.Int32(hf * HALF_HDIMS)
|
||||
grp_shift = (
|
||||
(chunk_in_tok * fx.Int32(2) + fx.Int32(hf)) & fx.Int32(3)
|
||||
) * fx.Int32(8)
|
||||
vscale_byte = (vscale_word >> grp_shift) & fx.Int32(0xFF)
|
||||
vscale_f32 = arith.bitcast(
|
||||
T.f32, _ival(vscale_byte << fx.Int32(23))
|
||||
)
|
||||
for w in range_constexpr(4):
|
||||
word_i32 = vector.extract(v_packed, static_position=[w])
|
||||
# Native CDNA4 scaled convert: 2-wide
|
||||
# cvt_scalef32_pk_bf16_fp4. srcSel s picks byte s
|
||||
# of the word (nibbles 2s, 2s+1) → 2 bf16 with the
|
||||
# UE8M0 group scale fused. 4 cvt calls/word.
|
||||
bf16_elems = []
|
||||
for s in range_constexpr(4):
|
||||
v2 = rocdl.cvt_scalef32_pk_bf16_fp4(
|
||||
T.vec(2, T.bf16),
|
||||
_ival(word_i32),
|
||||
_ival(vscale_f32),
|
||||
int(s),
|
||||
)
|
||||
bf16_elems.append(vector.extract(v2, static_position=[0]))
|
||||
bf16_elems.append(vector.extract(v2, static_position=[1]))
|
||||
v_bf16 = vector.from_elements(T.vec(8, T.bf16), bf16_elems)
|
||||
v_i64 = vector.bitcast(T.vec(2, T.i64), v_bf16)
|
||||
v_lds_i64_idx = (
|
||||
v_lds_elem_base + half_hd + fx.Int32(w * 8)
|
||||
) // fx.Int32(4)
|
||||
vector.store(
|
||||
v_i64,
|
||||
kv_lds_i64,
|
||||
[arith.index_cast(T.index, _kvi64(v_lds_i64_idx))],
|
||||
)
|
||||
# HW V transpose cross-lane LDS fence (see 128 kernel).
|
||||
rocdl.sched_barrier(0)
|
||||
rocdl.s_waitcnt(0xC07F)
|
||||
gpu.barrier()
|
||||
|
||||
# ---- PV MFMA: A=V[head_dim, token], B=P (=qk_acc bf16) -----
|
||||
p_bf16 = arith.trunc_f(T.vec(4, T.bf16), qk_acc)
|
||||
p_op = vector.bitcast(T.vec(4, T.i16), p_bf16)
|
||||
# HW-transpose PV: V_lds row-major V[token][head_dim].
|
||||
token_idx = lane >> fx.Int32(2)
|
||||
hd_sub = (lane & fx.Int32(3)) * fx.Int32(4)
|
||||
v_lane_byte = (
|
||||
fx.Int32(kv_off)
|
||||
+ token_idx * fx.Int32(KV_ROW_BYTES)
|
||||
+ hd_sub * fx.Int32(2)
|
||||
)
|
||||
for h in range_constexpr(PV_N_CHUNKS):
|
||||
v_byte_off = v_lane_byte + fx.Int32(h * 32)
|
||||
v_byte_i64 = fx.Int64(v_byte_off)
|
||||
v_ptr = buffer_ops.create_llvm_ptr(
|
||||
v_byte_i64,
|
||||
address_space=3,
|
||||
)
|
||||
v_op_raw = rocdl.ds_read_tr16_b64(
|
||||
T.vec(4, T.i16),
|
||||
v_ptr,
|
||||
).result
|
||||
acc_pv[h] = rocdl.mfma_f32_16x16x16bf16_1k(
|
||||
T.f32x4, [v_op_raw, p_op, acc_pv[h], 0, 0, 0]
|
||||
)
|
||||
|
||||
_scf.YieldOp(
|
||||
[
|
||||
_ival(running_max),
|
||||
_ival(running_sum),
|
||||
*[_ival(p) for p in acc_pv],
|
||||
]
|
||||
)
|
||||
finally:
|
||||
_for_ip.__exit__(None, None, None)
|
||||
running_max = _for_op.results[0]
|
||||
running_sum = _for_op.results[1]
|
||||
acc_pv = list(_for_op.results[2:])
|
||||
|
||||
# ===== STEP G: Output ===========================================
|
||||
safe_sum = (running_sum > ZERO_F).select(running_sum, ONE_F)
|
||||
rcp = ONE_F / safe_sum
|
||||
|
||||
c_os = fx.Int32(_stride_out_seq)
|
||||
c_oh = fx.Int32(_stride_out_head)
|
||||
c_op_ = fx.Int32(_stride_out_part)
|
||||
out_base = seq * c_os + kv_h * c_oh + part * c_op_
|
||||
|
||||
valid_row_pred = arith.cmpi(
|
||||
arith.CmpIPredicate.ult,
|
||||
mfma_row.ir_value() if hasattr(mfma_row, "ir_value") else mfma_row,
|
||||
arith.constant(QG, type=T.i32),
|
||||
)
|
||||
_if = _scf.IfOp(valid_row_pred)
|
||||
with ir.InsertionPoint(_if.then_block):
|
||||
for h in range_constexpr(PV_N_CHUNKS):
|
||||
pv_norm = _vsplat_mul(acc_pv[h], rcp)
|
||||
pv_bf16 = arith.trunc_f(T.vec(4, T.bf16), pv_norm)
|
||||
pv_i32x2 = vector.bitcast(T.vec(2, T.i32), pv_bf16)
|
||||
head_dim_start = fx.Int32(h * 16) + mfma_col_grp * fx.Int32(4)
|
||||
out_off_elem = (
|
||||
out_base + mfma_row * fx.Int32(HEAD_SIZE) + head_dim_start
|
||||
)
|
||||
buffer_ops.buffer_store(
|
||||
pv_i32x2,
|
||||
out_rsrc,
|
||||
out_off_elem * fx.Int32(2),
|
||||
offset_is_bytes=True,
|
||||
)
|
||||
|
||||
c_npq = fx.Int32(num_partitions * QG)
|
||||
ml_off = (
|
||||
seq * fx.Int32(_stride_ml_seq) + kv_h * c_npq + part * c_qg + mfma_row
|
||||
)
|
||||
es_off = (
|
||||
seq * fx.Int32(_stride_es_seq) + kv_h * c_npq + part * c_qg + mfma_row
|
||||
)
|
||||
buffer_ops.buffer_store(running_max, ml_rsrc, ml_off)
|
||||
buffer_ops.buffer_store(running_sum, es_rsrc, es_off)
|
||||
_scf.YieldOp([])
|
||||
|
||||
# Hand the build-local allocator to the launcher. `_get_kernel` reads
|
||||
# `kmod.allocator` immediately after this returns (before the next build can
|
||||
# run), so each launcher captures its own variant's allocator. This does NOT
|
||||
# reintroduce the drift bug: the kernel above closes over the LOCAL
|
||||
# `allocator`, so no @flyc.jit function references module-global `allocator`
|
||||
# and it is never snapshotted by _check_globals_drift.
|
||||
globals()["allocator"] = allocator
|
||||
return ultraquant_decode_hd256_kernel
|
||||
@@ -0,0 +1,834 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FlyDSL launcher for the optimized UltraQuant 4-bit D=256 decode kernel.
|
||||
|
||||
The production kernel uses scaled FP4×E4M3 QK MFMA, native V conversion,
|
||||
query hoisting, in-kernel Walsh-Hadamard rotation for GQA-6/8/16, and strided
|
||||
tile-group scheduling. These choices are fixed and are not environment-tunable.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.triton_utils import triton
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_FLYDSL_AVAILABLE: bool | None = None
|
||||
_ULTRAQUANT_MOD: Any = None
|
||||
_FLYC: Any = None
|
||||
_FX: Any = None
|
||||
_TYPING_T: Any = None
|
||||
_CC: Any = None
|
||||
_IR: Any = None
|
||||
|
||||
|
||||
def is_ultraquant_flydsl_available() -> bool:
|
||||
"""Return whether the gfx950 UltraQuant FlyDSL kernel can be loaded."""
|
||||
global _FLYDSL_AVAILABLE, _ULTRAQUANT_MOD
|
||||
global _FLYC, _FX, _TYPING_T, _CC, _IR
|
||||
if _FLYDSL_AVAILABLE is not None:
|
||||
return _FLYDSL_AVAILABLE
|
||||
try:
|
||||
from vllm.platforms.rocm import on_gfx950
|
||||
|
||||
if not on_gfx950():
|
||||
_FLYDSL_AVAILABLE = False
|
||||
return False
|
||||
|
||||
import flydsl.compiler as flyc
|
||||
import flydsl.expr as fx
|
||||
from flydsl._mlir import ir
|
||||
from flydsl.compiler.kernel_function import CompilationContext
|
||||
from flydsl.expr.typing import T
|
||||
|
||||
from vllm.v1.attention.ops.flydsl_kernels import (
|
||||
ultraquant_decode_hd256 as ultraquant_mod,
|
||||
)
|
||||
|
||||
_FLYC = flyc
|
||||
_FX = fx
|
||||
_TYPING_T = T
|
||||
_CC = CompilationContext
|
||||
_IR = ir
|
||||
_ULTRAQUANT_MOD = ultraquant_mod
|
||||
_FLYDSL_AVAILABLE = True
|
||||
logger.info_once("FlyDSL UltraQuant D=256 decode is available")
|
||||
except Exception as ex: # noqa: BLE001
|
||||
_FLYDSL_AVAILABLE = False
|
||||
logger.warning_once(
|
||||
"FlyDSL UltraQuant decode is unavailable (%s); using Triton fallback.",
|
||||
ex,
|
||||
)
|
||||
return _FLYDSL_AVAILABLE
|
||||
|
||||
|
||||
_ULTRAQUANT_FLYDSL_GQA = (6, 8, 16)
|
||||
|
||||
|
||||
def ultraquant_flydsl_decode_eligible(
|
||||
*,
|
||||
head_size: int,
|
||||
num_kv_groups: int,
|
||||
has_sinks: bool,
|
||||
sliding_window: int | None,
|
||||
flydsl_loaded: bool,
|
||||
) -> bool:
|
||||
"""Return whether decode should use the gfx950 FlyDSL kernel.
|
||||
|
||||
Production FlyDSL covers D=256 and GQA in {6, 8, 16}. Sinks and sliding
|
||||
window fall back to unified Triton. ``flydsl_loaded`` is the process-level
|
||||
compiler/hardware probe so this policy can be unit-tested without a GPU.
|
||||
"""
|
||||
return (
|
||||
flydsl_loaded
|
||||
and head_size == 256
|
||||
and num_kv_groups in _ULTRAQUANT_FLYDSL_GQA
|
||||
and not has_sinks
|
||||
and not (sliding_window and sliding_window > 0)
|
||||
)
|
||||
|
||||
|
||||
# -- Kernel module cache -------------------------------------------------------
|
||||
# Compiling a FlyDSL kernel is expensive; cache by the constexprs that
|
||||
# parameterize stride math: num_kv_heads, num_partitions, max_blocks_per_seq,
|
||||
# scale, query_group_size, kv_block_size, padded_slot, hw_v_transpose,
|
||||
# tile_groups_per_partition.
|
||||
_KERN_CACHE: dict[tuple, Any] = {}
|
||||
|
||||
_LOG_INVOKED_ONCE: bool = False
|
||||
|
||||
# Per-device cached FP4 E2M1 value table (used as the kernel "centroids" LUT).
|
||||
_FP4_LUT_CACHE: dict[tuple[str, torch.dtype], torch.Tensor] = {}
|
||||
|
||||
|
||||
def _fp4_value_lut(device: torch.device) -> torch.Tensor:
|
||||
"""Return the fixed 16-entry FP4 E2M1 value table as fp32 [16] on device.
|
||||
|
||||
Indexed by the stored 4-bit E2M1 code, so ``lut[nibble]`` is the dequant
|
||||
value directly (matches ``format.FP4_BITS_TO_VALUE``).
|
||||
"""
|
||||
from vllm.v1.attention.ops.ultraquant.format import FP4_BITS_TO_VALUE
|
||||
|
||||
key = (str(device), torch.float32)
|
||||
t = _FP4_LUT_CACHE.get(key)
|
||||
if t is None:
|
||||
t = torch.tensor(
|
||||
FP4_BITS_TO_VALUE, dtype=torch.float32, device=device
|
||||
).contiguous()
|
||||
_FP4_LUT_CACHE[key] = t
|
||||
return t
|
||||
|
||||
# Per-device cached qperm head-dim permutation for scaled QK MFMA.
|
||||
|
||||
|
||||
# qperm[phys] = the natural head-dim placed at physical operand position phys.
|
||||
# It realigns the fixed FP4xFP8 scaled-MFMA contraction so that, with K fed
|
||||
# native-contiguous, Q's columns pair correctly. Folded into PiT on the host
|
||||
# (PiT[:, qperm]) so the Q rotation matmul emits already-permuted q_rot at zero
|
||||
# extra runtime cost. Derived + validated in tmp_qk_scaled_mfma.py (contigK).
|
||||
_QPERM_CACHE: dict[str, torch.Tensor] = {}
|
||||
|
||||
|
||||
def _kmap_phys(group: int, s: int) -> int:
|
||||
# Physical operand position of group's element s for the K=128 fp4/fp8
|
||||
# scaled MFMA (matches tmp_qk_scaled_mfma.py::_kmap).
|
||||
return 32 * (s >> 4) + 64 * (group % 2) + 16 * (group // 2) + (s & 15)
|
||||
|
||||
|
||||
def _qperm_index(
|
||||
device: torch.device, D: int = 128, group_size: int = 32
|
||||
) -> torch.Tensor:
|
||||
# _kmap_phys describes ONE K=128 contraction (4 groups of 32). A head dim
|
||||
# wider than 128 is covered by ceil(D/128) back-to-back MFMA issues, each
|
||||
# contracting its own independent 128-wide slice, so the same map repeats
|
||||
# per slice: qperm = [qperm128, qperm128 + 128, ...]. Applying _kmap_phys
|
||||
# with group >= 4 instead yields positions outside the slice and is not a
|
||||
# permutation at all.
|
||||
key = f"{device}:{D}:{group_size}"
|
||||
t = _QPERM_CACHE.get(key)
|
||||
if t is None:
|
||||
k_per_mfma = 128
|
||||
assert D % k_per_mfma == 0, (
|
||||
f"scaled QK MFMA needs D to be a multiple of {k_per_mfma}, got {D}"
|
||||
)
|
||||
groups_per_mfma = k_per_mfma // group_size
|
||||
qperm = [0] * D
|
||||
for half in range(D // k_per_mfma):
|
||||
base = half * k_per_mfma
|
||||
for g in range(groups_per_mfma):
|
||||
for s in range(group_size):
|
||||
qperm[base + _kmap_phys(g, s)] = base + g * group_size + s
|
||||
assert sorted(qperm) == list(range(D)), "qperm is not a permutation"
|
||||
t = torch.tensor(qperm, dtype=torch.long, device=device).contiguous()
|
||||
_QPERM_CACHE[key] = t
|
||||
return t
|
||||
|
||||
|
||||
def _detect_max_capture_B() -> int:
|
||||
try:
|
||||
from vllm.config import get_current_vllm_config
|
||||
|
||||
cfg = get_current_vllm_config()
|
||||
candidates: list[int] = []
|
||||
sizes = cfg.compilation_config.cudagraph_capture_sizes
|
||||
if sizes:
|
||||
candidates.append(int(max(sizes)))
|
||||
sched = getattr(cfg, "scheduler_config", None)
|
||||
if sched is not None and getattr(sched, "max_num_seqs", None):
|
||||
candidates.append(int(sched.max_num_seqs))
|
||||
if candidates:
|
||||
return max(candidates)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return 512
|
||||
|
||||
|
||||
class _SegmBufPool:
|
||||
"""Single-bucket buffer pool for segm_out/segm_max/segm_sum/output + the
|
||||
pooled Q-rotation intermediates. Identical to the TQ pool except that
|
||||
ultraquant needs an extra ``q_fp8`` (float8_e4m3fn) slot for the Q precision
|
||||
haircut (``q_rot_fp32 -> fp8_e4m3 -> bf16``) so that no fresh allocation
|
||||
lands in the HIP graph memory pool post-capture.
|
||||
"""
|
||||
|
||||
__slots__ = ("_bufs", "_max_B")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._bufs: dict[tuple, dict[str, torch.Tensor]] = {}
|
||||
self._max_B: int | None = None
|
||||
|
||||
def get(
|
||||
self,
|
||||
B: int,
|
||||
Hk: int,
|
||||
Hq: int,
|
||||
num_partitions: int,
|
||||
QG: int,
|
||||
D: int,
|
||||
device: torch.device,
|
||||
q_dtype: torch.dtype,
|
||||
) -> dict[str, torch.Tensor]:
|
||||
if self._max_B is None:
|
||||
self._max_B = _detect_max_capture_B()
|
||||
B_bucket = max(self._max_B, int(B))
|
||||
key = (
|
||||
int(Hk),
|
||||
int(Hq),
|
||||
int(num_partitions),
|
||||
int(QG),
|
||||
int(D),
|
||||
str(device),
|
||||
q_dtype,
|
||||
)
|
||||
bufs = self._bufs.get(key)
|
||||
if bufs is None or bufs["segm_out"].shape[0] < B_bucket:
|
||||
if bufs is not None and bufs["segm_out"].shape[0] < B_bucket:
|
||||
# First-time grow: warn so user knows cudagraphs may be
|
||||
# invalidated. This should only happen during warmup or in
|
||||
# always-eager configs (a batch larger than any captured
|
||||
# cudagraph size).
|
||||
logger.warning_once(
|
||||
"FlyDSL UltraQuant buffer pool growing from %d "
|
||||
"to %d (B=%d). If this happens AFTER cudagraph warmup the "
|
||||
"captured graphs hold stale pointers and will GPU-fault.",
|
||||
bufs["segm_out"].shape[0],
|
||||
B_bucket,
|
||||
B,
|
||||
)
|
||||
bufs = {
|
||||
"segm_out": torch.empty(
|
||||
(B_bucket, Hk, num_partitions, QG, D),
|
||||
dtype=torch.bfloat16,
|
||||
device=device,
|
||||
),
|
||||
"segm_max": torch.empty(
|
||||
(B_bucket, Hk, num_partitions, QG),
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
),
|
||||
"segm_sum": torch.empty(
|
||||
(B_bucket, Hk, num_partitions, QG),
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
),
|
||||
"output": torch.empty(
|
||||
(B_bucket, Hq, D),
|
||||
dtype=q_dtype,
|
||||
device=device,
|
||||
),
|
||||
"q_rot": torch.empty(
|
||||
(B_bucket, Hq, D),
|
||||
dtype=q_dtype,
|
||||
device=device,
|
||||
),
|
||||
"q_float": torch.empty(
|
||||
(B_bucket, Hq, D),
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
),
|
||||
"q_rot_fp32": torch.empty(
|
||||
(B_bucket, Hq, D),
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
),
|
||||
# ultraquant-specific: E4M3 haircut intermediate (pooled so the
|
||||
# cast does not allocate a fresh tensor post-capture).
|
||||
"q_fp8": torch.empty(
|
||||
(B_bucket, Hq, D),
|
||||
dtype=torch.float8_e4m3fn,
|
||||
device=device,
|
||||
),
|
||||
}
|
||||
self._bufs[key] = bufs
|
||||
self._max_B = B_bucket
|
||||
logger.info_once(
|
||||
"FlyDSL UltraQuant buffer pool allocated "
|
||||
"shape=(Hk=%d, Hq=%d, P=%d, QG=%d, D=%d, dtype=%s) "
|
||||
"B_bucket=%d. VRAM = %.1f MiB / shape.",
|
||||
Hk,
|
||||
Hq,
|
||||
num_partitions,
|
||||
QG,
|
||||
D,
|
||||
q_dtype,
|
||||
B_bucket,
|
||||
sum(t.numel() * t.element_size() for t in bufs.values()) / (1 << 20),
|
||||
)
|
||||
return {
|
||||
"segm_out": bufs["segm_out"][:B],
|
||||
"segm_max": bufs["segm_max"][:B],
|
||||
"segm_sum": bufs["segm_sum"][:B],
|
||||
"output": bufs["output"][:B],
|
||||
"q_rot": bufs["q_rot"][:B],
|
||||
"q_float": bufs["q_float"][:B],
|
||||
"q_rot_fp32": bufs["q_rot_fp32"][:B],
|
||||
"q_fp8": bufs["q_fp8"][:B],
|
||||
}
|
||||
|
||||
|
||||
_SEGM_POOL = _SegmBufPool()
|
||||
|
||||
_GET_KERNEL_STATS = {"hits": 0, "misses": 0, "build_total_s": 0.0}
|
||||
|
||||
|
||||
def _get_kernel(
|
||||
num_kv_heads: int,
|
||||
num_partitions: int,
|
||||
max_blocks_per_seq: int,
|
||||
scale: float,
|
||||
query_group_size: int,
|
||||
kv_block_size: int,
|
||||
padded_slot: int,
|
||||
fuse_qrot: bool,
|
||||
num_seqs_hint: int,
|
||||
tile_groups_per_partition: int,
|
||||
stride_q_seq: int,
|
||||
stride_q_head: int,
|
||||
):
|
||||
key = (
|
||||
num_kv_heads,
|
||||
num_partitions,
|
||||
max_blocks_per_seq,
|
||||
round(scale, 8),
|
||||
query_group_size,
|
||||
kv_block_size,
|
||||
padded_slot,
|
||||
fuse_qrot,
|
||||
tile_groups_per_partition,
|
||||
stride_q_seq,
|
||||
stride_q_head,
|
||||
)
|
||||
cached = _KERN_CACHE.get(key)
|
||||
if cached is not None:
|
||||
_GET_KERNEL_STATS["hits"] += 1
|
||||
return cached
|
||||
|
||||
assert is_ultraquant_flydsl_available()
|
||||
import time
|
||||
|
||||
build_start = time.perf_counter()
|
||||
kmod = _ULTRAQUANT_MOD
|
||||
assert kmod is not None
|
||||
kfn = kmod.build_ultraquant_decode_hd256_module(
|
||||
num_seqs=num_seqs_hint,
|
||||
num_kv_heads=num_kv_heads,
|
||||
num_partitions=num_partitions,
|
||||
padded_slot=padded_slot,
|
||||
max_blocks_per_seq=max_blocks_per_seq,
|
||||
softmax_scale=scale,
|
||||
query_group_size=query_group_size,
|
||||
kv_block_size=kv_block_size,
|
||||
tile_groups_per_partition=tile_groups_per_partition,
|
||||
fuse_qrot=fuse_qrot,
|
||||
stride_q_seq=stride_q_seq,
|
||||
stride_q_head=stride_q_head,
|
||||
)
|
||||
allocator = kmod.allocator
|
||||
flyc = _FLYC
|
||||
fx = _FX
|
||||
T = _TYPING_T
|
||||
CompilationContext = _CC
|
||||
ir_mod = _IR
|
||||
|
||||
@flyc.jit
|
||||
def _launch(
|
||||
out,
|
||||
es,
|
||||
ml,
|
||||
q,
|
||||
kvc,
|
||||
cents,
|
||||
bt,
|
||||
sl,
|
||||
gx: fx.Int32, # type: ignore[name-defined]
|
||||
gy: fx.Int32, # type: ignore[name-defined]
|
||||
gz: fx.Int32, # type: ignore[name-defined]
|
||||
stream: fx.Stream, # type: ignore[name-defined]
|
||||
):
|
||||
allocator.finalized = False
|
||||
ctx = CompilationContext.get_current()
|
||||
with ir_mod.InsertionPoint(ctx.gpu_module_body):
|
||||
allocator.finalize()
|
||||
from flydsl.expr import arith
|
||||
|
||||
grid_x = arith.index_cast(T.index, gx.ir_value())
|
||||
grid_y = arith.index_cast(T.index, gy.ir_value())
|
||||
grid_z = arith.index_cast(T.index, gz.ir_value())
|
||||
kfn(out, es, ml, q, kvc, cents, bt, sl).launch(
|
||||
grid=(grid_x, grid_y, grid_z),
|
||||
block=(kmod.BLOCK_THREADS, 1, 1),
|
||||
stream=stream,
|
||||
)
|
||||
|
||||
_KERN_CACHE[key] = _launch
|
||||
build_time = time.perf_counter() - build_start
|
||||
_GET_KERNEL_STATS["misses"] += 1
|
||||
_GET_KERNEL_STATS["build_total_s"] += build_time
|
||||
logger.info(
|
||||
"Built FlyDSL UltraQuant kernel #%d in %.2fs (total %.1fs), key=%s",
|
||||
_GET_KERNEL_STATS["misses"],
|
||||
build_time,
|
||||
_GET_KERNEL_STATS["build_total_s"],
|
||||
key,
|
||||
)
|
||||
return _launch
|
||||
|
||||
|
||||
# -- Partition reducer ---------------------------------------------------------
|
||||
from vllm.triton_utils import tl # noqa: E402
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _reduce_partitions(
|
||||
output_ptr, # [N, Hq, D] in OUT_DTYPE
|
||||
segm_out_ptr, # [N, Hk, P, QG, D] bf16
|
||||
segm_max_ptr, # [N, Hk, P, QG] fp32
|
||||
segm_sum_ptr, # [N, Hk, P, QG] fp32
|
||||
out_stride_n: tl.int64,
|
||||
out_stride_h: tl.int64,
|
||||
NUM_KV_HEADS: tl.constexpr,
|
||||
QG: tl.constexpr,
|
||||
NUM_PARTS: tl.constexpr,
|
||||
HEAD_SIZE: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
n = tl.program_id(0)
|
||||
hq = tl.program_id(1)
|
||||
kv_h = hq // QG
|
||||
qg = hq % QG
|
||||
# Splitting the head-dim across programs is what gives this kernel enough
|
||||
# parallelism to use the GPU: the reduction runs over PARTITIONS, so every
|
||||
# head-dim column is independent. A (B, Hq) grid is only 32 workgroups at
|
||||
# B=4 -- ~12% of a 256-CU part -- which is why it moved 8.4 MB at just
|
||||
# ~995 GB/s. The partition reduction itself is untouched (same values, same
|
||||
# order), so the result is bit-identical; only the columns each program
|
||||
# owns change. The [P] max/sum vectors get re-read per D-block, which is
|
||||
# 4 KB of duplicated traffic against a 262 KB tile.
|
||||
|
||||
msum_base = n * (NUM_KV_HEADS * NUM_PARTS * QG) + kv_h * (NUM_PARTS * QG) + qg
|
||||
so_base = (
|
||||
n * (NUM_KV_HEADS * NUM_PARTS * QG * HEAD_SIZE)
|
||||
+ kv_h * (NUM_PARTS * QG * HEAD_SIZE)
|
||||
+ qg * HEAD_SIZE
|
||||
)
|
||||
|
||||
p_off = tl.arange(0, NUM_PARTS)
|
||||
d_off = tl.program_id(2) * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
|
||||
m_idx = msum_base + p_off * QG
|
||||
seg_max = tl.load(segm_max_ptr + m_idx)
|
||||
seg_sum = tl.load(segm_sum_ptr + m_idx)
|
||||
|
||||
valid = seg_max > float("-inf")
|
||||
overall_max = tl.max(tl.where(valid, seg_max, float("-inf")))
|
||||
|
||||
rescale = tl.where(valid, tl.exp(seg_max - overall_max), 0.0)
|
||||
seg_sum_rescaled = seg_sum * rescale
|
||||
overall_sum = tl.sum(seg_sum_rescaled)
|
||||
|
||||
so_idx = so_base + p_off[:, None] * (QG * HEAD_SIZE) + d_off[None, :]
|
||||
seg_out = tl.load(segm_out_ptr + so_idx).to(tl.float32)
|
||||
weighted = seg_out * seg_sum_rescaled[:, None]
|
||||
acc_sum = tl.sum(weighted, axis=0)
|
||||
acc = tl.where(overall_sum > 0.0, acc_sum / overall_sum, 0.0)
|
||||
|
||||
out_off = n * out_stride_n + hq * out_stride_h + d_off
|
||||
tl.store(output_ptr + out_off, acc.to(output_ptr.dtype.element_ty))
|
||||
|
||||
|
||||
# -- Fused Q rotation + E4M3 haircut (Triton) ---------------------------------
|
||||
# Replaces the 4-op torch prologue (copy bf16->fp32, mm by PiT, copy fp32->e4m3,
|
||||
# copy e4m3->bf16) with ONE kernel. The win is kernel COUNT, not bytes: each of
|
||||
# those small ops costs ~2-4us of fixed GPU-side cost here largely independent of
|
||||
# element count (verified: sweeping the pool's B_bucket 512->1, i.e. 512x fewer
|
||||
# elements in the copies, moved the floor 0%). Under CUDA graphs the host launch
|
||||
# cost is already gone, so only per-kernel GPU cost remains and collapsing 4
|
||||
# kernels into 1 is the lever that is left.
|
||||
@triton.jit
|
||||
def _fused_q_rot_haircut(
|
||||
q_ptr, # [B, Hq, D] query dtype (bf16/fp16), strided
|
||||
pit_ptr, # [D, D] fp32 contiguous (already qperm-permuted)
|
||||
out_ptr, # [B_bucket, Hq, D] out dtype, contiguous
|
||||
M, # B * Hq (runtime)
|
||||
q_stride_n: tl.int64,
|
||||
q_stride_h: tl.int64,
|
||||
HQ: tl.constexpr,
|
||||
D: tl.constexpr,
|
||||
HAIRCUT: tl.constexpr, # round through E4M3 (fp8-consuming QK MFMA paths)
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_d = tl.program_id(1)
|
||||
m_off = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
m_mask = m_off < M
|
||||
n = m_off // HQ
|
||||
h = m_off % HQ
|
||||
|
||||
# Splitting the OUTPUT columns across programs (not just the rows) is what
|
||||
# gives this kernel parallelism at small batch: M = B*Hq is only 8 at B=1,
|
||||
# so a row-only grid launches ONE workgroup and serializes the whole
|
||||
# 256x256 rotation on a single CU. The K reduction is untouched by the
|
||||
# split, so the result stays bit-identical.
|
||||
d_off = pid_d * BLOCK_D + tl.arange(0, BLOCK_D)
|
||||
acc = tl.zeros([BLOCK_M, BLOCK_D], dtype=tl.float32)
|
||||
for k0 in range(0, D, BLOCK_K):
|
||||
k_off = k0 + tl.arange(0, BLOCK_K)
|
||||
q_idx = n[:, None] * q_stride_n + h[:, None] * q_stride_h + k_off[None, :]
|
||||
q_blk = tl.load(q_ptr + q_idx, mask=m_mask[:, None], other=0.0)
|
||||
p_blk = tl.load(pit_ptr + k_off[:, None] * D + d_off[None, :])
|
||||
acc = tl.dot(q_blk.to(tl.float32), p_blk, acc)
|
||||
|
||||
if HAIRCUT:
|
||||
# fp32 -> E4M3 -> fp32. Mirrors the torch path's
|
||||
# q_rot_fp32 -> float8_e4m3fn -> bf16 round trip (e4m3 is a subset of
|
||||
# bf16, so the second hop is exact and folds away here).
|
||||
acc = acc.to(tl.float8e4nv).to(tl.float32)
|
||||
|
||||
out_idx = m_off[:, None] * D + d_off[None, :]
|
||||
tl.store(out_ptr + out_idx, acc.to(out_ptr.dtype.element_ty), mask=m_mask[:, None])
|
||||
|
||||
|
||||
# Prologue Q-rotation fusion (fallback for non-hd256 / in-kernel-WHT-off paths).
|
||||
# Cleared the accuracy ladder (offline parity -> autoregressive drift -> paired
|
||||
# GSM8K); pinned ON as part of the validated production config.
|
||||
_FUSE_Q_ROT = True
|
||||
|
||||
# Stronger form: do the rotation INSIDE the decode kernel as a Walsh-Hadamard
|
||||
# butterfly and drop the prologue dispatch entirely. The prologue is ~7us at
|
||||
# B=4 and that is almost all fixed per-dispatch cost (sweeping its grid 4x moves
|
||||
# it 0%), so deleting the launch -- not optimizing it -- is the win.
|
||||
# Default ON: verified bit-exact (torch.equal) against the prologue path across
|
||||
# B={1,2,3,4,8,16} x seq={4k,8k,16k,32k,50021,75k}, including non-power-of-2
|
||||
# batch and seq.
|
||||
_FUSE_QROT_INKERNEL = True
|
||||
|
||||
|
||||
def _run_fused_q_rot(query, PiT_used, out, B, Hq, D, haircut):
|
||||
"""Launch the fused prologue. ``out`` is the pooled [B_bucket, Hq, D] buf."""
|
||||
M = B * Hq
|
||||
BLOCK_M = 16
|
||||
BLOCK_K = 32
|
||||
BLOCK_D = 64
|
||||
grid = (triton.cdiv(M, BLOCK_M), triton.cdiv(D, BLOCK_D))
|
||||
_fused_q_rot_haircut[grid](
|
||||
query,
|
||||
PiT_used,
|
||||
out,
|
||||
M,
|
||||
query.stride(0),
|
||||
query.stride(1),
|
||||
HQ=int(Hq),
|
||||
D=int(D),
|
||||
HAIRCUT=bool(haircut),
|
||||
BLOCK_M=BLOCK_M,
|
||||
BLOCK_K=BLOCK_K,
|
||||
BLOCK_D=BLOCK_D,
|
||||
)
|
||||
|
||||
|
||||
# -- Public launcher ----------------------------------------------------------
|
||||
def flydsl_ultraquant_decode_attention(
|
||||
query: torch.Tensor,
|
||||
kv_cache: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
seq_lens: torch.Tensor,
|
||||
scale: float,
|
||||
PiT: torch.Tensor | None = None,
|
||||
max_seq_len: int = 0,
|
||||
output_buf: torch.Tensor | None = None,
|
||||
buf_holder: Any = None,
|
||||
max_num_kv_splits: int = 32,
|
||||
sinks: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Launch the optimized FlyDSL UltraQuant D=256 decode."""
|
||||
if not is_ultraquant_flydsl_available():
|
||||
raise RuntimeError(
|
||||
"FlyDSL UltraQuant decode requires gfx950 and importable FlyDSL."
|
||||
)
|
||||
if sinks is not None:
|
||||
raise NotImplementedError("FlyDSL UltraQuant decode does not support sinks")
|
||||
|
||||
B, Hq, D = query.shape
|
||||
Hk = kv_cache.shape[2]
|
||||
block_size = kv_cache.shape[1]
|
||||
padded_slot = int(kv_cache.shape[3])
|
||||
QG = Hq // Hk
|
||||
assert D == 256, f"UltraQuant FlyDSL requires head_dim=256, got {D}"
|
||||
assert block_size in (16, 32, 64, 128, 256), (
|
||||
f"UltraQuant FlyDSL supports kv_block_size 16/32/64/128/256, got {block_size}"
|
||||
)
|
||||
assert QG in _ULTRAQUANT_FLYDSL_GQA, (
|
||||
f"UltraQuant FlyDSL supports GQA factor "
|
||||
f"{', '.join(map(str, _ULTRAQUANT_FLYDSL_GQA))}, got {QG}"
|
||||
)
|
||||
|
||||
device = query.device
|
||||
|
||||
# ---- PiT (Hadamard) — cache the contiguous fp32 form on the layer -----
|
||||
PiT_f32: torch.Tensor
|
||||
if buf_holder is not None:
|
||||
PiT_f32 = getattr(buf_holder, "_ultraquant_PiT_f32", None)
|
||||
if PiT_f32 is None:
|
||||
assert PiT is not None, (
|
||||
"UltraQuant launcher requires PiT (the Hadamard rotation)"
|
||||
)
|
||||
PiT_f32 = PiT if PiT.dtype == torch.float32 else PiT.to(torch.float32)
|
||||
if not PiT_f32.is_contiguous():
|
||||
PiT_f32 = PiT_f32.contiguous()
|
||||
buf_holder._ultraquant_PiT_f32 = PiT_f32
|
||||
else:
|
||||
assert PiT is not None, (
|
||||
"UltraQuant launcher requires PiT (the Hadamard rotation)"
|
||||
)
|
||||
PiT_f32 = PiT if PiT.dtype == torch.float32 else PiT.to(torch.float32)
|
||||
if not PiT_f32.is_contiguous():
|
||||
PiT_f32 = PiT_f32.contiguous()
|
||||
|
||||
centroids_c = _fp4_value_lut(device)
|
||||
|
||||
# ---- Partition count (FA2 split-KV) -----------------------------------
|
||||
kv_compute_block = _ULTRAQUANT_MOD.KV_COMPUTE_BLOCK
|
||||
worst_case_max_seq_len = int(block_table.shape[1]) * int(block_size)
|
||||
if max_seq_len <= 0:
|
||||
max_seq_len = worst_case_max_seq_len
|
||||
sizing_max_seq_len = worst_case_max_seq_len
|
||||
|
||||
# Split-KV parallelism cap. The old default (32) silently serialized long
|
||||
# contexts: once required_num_partitions exceeds the cap, TGPP grows and each
|
||||
# workgroup walks MORE tile-groups instead of the grid getting wider. The
|
||||
# decode kernel is latency-bound at ~1-2 waves/CU (grid = B*Hk*P workgroups
|
||||
# of a single wavefront), so that serialization dominated long-context decode.
|
||||
# Raising the cap to 256 keeps TGPP ~1 and measured (B=16, rocprof, per step
|
||||
# decode+reduce+store): 16k 82.7->40.0us, 32k 152.0->55.1us, 64k 339.4->95.7us,
|
||||
# 131k 671.3->179.0us (2.1x - 3.8x, growing with context). 512 regresses
|
||||
# because _reduce_partitions cost grows with partition count.
|
||||
# Cost: the segm pool scales with P (~8x vs P=32).
|
||||
# BATCH-ADAPTIVE split-KV cap (low-concurrency occupancy fix).
|
||||
# rocprof (B=4, 75k): the decode kernel is occupancy/latency-bound, not
|
||||
# compute-bound -- OccupancyPercent 5.8%, MfmaUtil 4.5%, VALUBusy 14.5%
|
||||
# (stalled ~85% on HBM), VALUUtilization 90% (no divergence). The grid is
|
||||
# B*Hk*num_partitions single-wavefront workgroups; at B=4/Hk=1/P=256 that's
|
||||
# only 1024 wg = 4/CU, too few to hide memory latency. Splitting MORE at low
|
||||
# batch adds resident wavefronts and cuts ITL; at high batch the grid is
|
||||
# already full so extra partitions only inflate _reduce_partitions + empty-
|
||||
# partition overhead. Measured end-to-end (graphs on, TP=8, uniform 75k,
|
||||
# median ITL vs kv8): cap512 vs cap256 -> C4 +9.0%->+4.9%, C8 +6.6%->+2.5%
|
||||
# (better), C16 +2.8%->+4.3% (worse). So use 512 at low batch, 256 at high.
|
||||
# This is only SAFE because the build-local-allocator fix in
|
||||
# ultraquant_decode_hd256.py lets the two num_partitions variants (256 & 512)
|
||||
# coexist across CUDA-graph batch buckets without the @flyc.jit
|
||||
# "global 'allocator' changed since first compile" drift crash.
|
||||
MAX_PARTITIONS = 512 if B <= 8 else 256
|
||||
required_num_partitions = (
|
||||
sizing_max_seq_len + kv_compute_block - 1
|
||||
) // kv_compute_block
|
||||
parallelism_floor = min(MAX_PARTITIONS, max(1, max_num_kv_splits))
|
||||
num_partitions_actual = max(
|
||||
parallelism_floor,
|
||||
min(MAX_PARTITIONS, required_num_partitions),
|
||||
)
|
||||
# Cap partitions by how much work there actually IS to split. Nothing above
|
||||
# forces a partition to hold a useful number of tokens -- max_num_kv_splits
|
||||
# sets a parallelism FLOOR -- so a short context gets split into partitions
|
||||
# of a handful of tokens each, where every partition is almost entirely
|
||||
# fixed cost (and each one still writes a full QG x D partial for the
|
||||
# reduce to read back). Measured sweet spot is ~130-147 tokens/partition,
|
||||
# roughly flat in between; next_power_of_2 below rounds this target up, so
|
||||
# the effective range lands at ~96-192 tokens. At B=4 this is worth 27.9 ->
|
||||
# 24.4 us at seq=2048 and 27.0 -> 24.8 us at seq=16384, and is inert once
|
||||
# the context is long enough to want every partition (seq >= ~64k).
|
||||
_tok_per_part = 192
|
||||
if _tok_per_part > 0:
|
||||
_useful_parts = max(
|
||||
1, (int(sizing_max_seq_len) + _tok_per_part - 1) // _tok_per_part
|
||||
)
|
||||
num_partitions_actual = min(num_partitions_actual, _useful_parts)
|
||||
num_partitions = max(2, triton.next_power_of_2(num_partitions_actual))
|
||||
_tgpp_required = max(
|
||||
1,
|
||||
(required_num_partitions + num_partitions - 1) // num_partitions,
|
||||
)
|
||||
tile_groups_per_partition = int(triton.next_power_of_2(_tgpp_required))
|
||||
|
||||
# ---- Pooled buffers ---------------------------------------------------
|
||||
pool_bufs = _SEGM_POOL.get(
|
||||
B,
|
||||
Hk,
|
||||
Hq,
|
||||
num_partitions,
|
||||
QG,
|
||||
D,
|
||||
device,
|
||||
query.dtype,
|
||||
)
|
||||
segm_out = pool_bufs["segm_out"]
|
||||
segm_max = pool_bufs["segm_max"]
|
||||
segm_sum = pool_bufs["segm_sum"]
|
||||
if output_buf is None:
|
||||
output = pool_bufs["output"]
|
||||
else:
|
||||
output = output_buf[:B] if output_buf.shape[0] != B else output_buf
|
||||
|
||||
# Fold the scaled-MFMA head-dim permutation into PiT's columns so the
|
||||
# WHT / prologue produces native operand order. Always apply the E4M3
|
||||
# haircut: scaled QK consumes Q as E4M3.
|
||||
PiT_used = PiT_f32
|
||||
qperm_idx = _qperm_index(device, D=D)
|
||||
if buf_holder is not None:
|
||||
PiT_used = getattr(buf_holder, "_ultraquant_PiT_perm_f32", None)
|
||||
if PiT_used is None:
|
||||
PiT_used = PiT_f32.index_select(1, qperm_idx).contiguous()
|
||||
buf_holder._ultraquant_PiT_perm_f32 = PiT_used
|
||||
else:
|
||||
PiT_used = PiT_f32.index_select(1, qperm_idx).contiguous()
|
||||
_q_float = pool_bufs["q_float"]
|
||||
_q_rot_f32 = pool_bufs["q_rot_fp32"]
|
||||
_q_fp8 = pool_bufs["q_fp8"]
|
||||
_q_rot_out = pool_bufs["q_rot"]
|
||||
|
||||
_inkernel_qrot = (
|
||||
_FUSE_QROT_INKERNEL
|
||||
and int(D) == 256
|
||||
and QG in _ULTRAQUANT_FLYDSL_GQA
|
||||
and query.dim() == 3
|
||||
and query.stride(2) == 1
|
||||
and query.stride(1) == int(D)
|
||||
)
|
||||
if _inkernel_qrot:
|
||||
q_for_kernel = query
|
||||
# The fused kernel indexes the head-dim contiguously; fall back if not.
|
||||
elif _FUSE_Q_ROT and query.stride(-1) == 1:
|
||||
# One kernel for the whole prologue instead of four ops.
|
||||
_run_fused_q_rot(query, PiT_used, _q_rot_out, B, Hq, D, haircut=True)
|
||||
else:
|
||||
_q_float.copy_(query)
|
||||
torch.mm(
|
||||
_q_float.view(B * Hq, D),
|
||||
PiT_used,
|
||||
out=_q_rot_f32.view(B * Hq, D),
|
||||
)
|
||||
_q_fp8.copy_(_q_rot_f32) # fp32 -> e4m3
|
||||
_q_rot_out.copy_(_q_fp8) # e4m3 -> bf16
|
||||
if not _inkernel_qrot:
|
||||
q_for_kernel = _q_rot_out
|
||||
|
||||
# ---- FlyDSL kernel launch --------------------------------------------
|
||||
max_bps = int(block_table.shape[1])
|
||||
launch = _get_kernel(
|
||||
Hk,
|
||||
num_partitions,
|
||||
max_bps,
|
||||
scale,
|
||||
QG,
|
||||
block_size,
|
||||
padded_slot,
|
||||
fuse_qrot=_inkernel_qrot,
|
||||
num_seqs_hint=int(B),
|
||||
tile_groups_per_partition=int(tile_groups_per_partition),
|
||||
stride_q_seq=int(q_for_kernel.stride(0)),
|
||||
stride_q_head=int(q_for_kernel.stride(1)),
|
||||
)
|
||||
global _LOG_INVOKED_ONCE
|
||||
if not _LOG_INVOKED_ONCE:
|
||||
_LOG_INVOKED_ONCE = True
|
||||
logger.info(
|
||||
"FlyDSL UltraQuant launcher invoked: B=%d Hk=%d Hq=%d D=%d QG=%d "
|
||||
"num_partitions=%d (actual=%d, cap=%d) TGPP=%d max_bps=%d "
|
||||
"block_size=%d padded_slot=%d max_seq_len=%d "
|
||||
"(coverage=%d tokens, worst_case=%d tokens)",
|
||||
B,
|
||||
Hk,
|
||||
Hq,
|
||||
D,
|
||||
QG,
|
||||
num_partitions,
|
||||
num_partitions_actual,
|
||||
MAX_PARTITIONS,
|
||||
tile_groups_per_partition,
|
||||
max_bps,
|
||||
int(block_size),
|
||||
padded_slot,
|
||||
int(max_seq_len),
|
||||
num_partitions * tile_groups_per_partition * kv_compute_block,
|
||||
worst_case_max_seq_len,
|
||||
)
|
||||
launch(
|
||||
segm_out,
|
||||
segm_sum,
|
||||
segm_max,
|
||||
q_for_kernel,
|
||||
kv_cache,
|
||||
centroids_c,
|
||||
block_table,
|
||||
seq_lens,
|
||||
B,
|
||||
Hk,
|
||||
num_partitions,
|
||||
torch.cuda.current_stream(),
|
||||
)
|
||||
|
||||
# ---- Reduce partitions -> [B, Hq, D] ---------------------------------
|
||||
# 64 splits the head-dim 4 ways, taking the grid from 32 to 128 workgroups.
|
||||
# Bit-identical by construction (the partition reduction is per-column).
|
||||
_red_block_d = min(int(D), 64)
|
||||
_reduce_partitions[(B, Hq, triton.cdiv(int(D), _red_block_d))](
|
||||
output_ptr=output,
|
||||
segm_out_ptr=segm_out,
|
||||
segm_max_ptr=segm_max,
|
||||
segm_sum_ptr=segm_sum,
|
||||
out_stride_n=output.stride(0),
|
||||
out_stride_h=output.stride(1),
|
||||
NUM_KV_HEADS=Hk,
|
||||
QG=QG,
|
||||
NUM_PARTS=num_partitions,
|
||||
HEAD_SIZE=D,
|
||||
BLOCK_D=_red_block_d,
|
||||
)
|
||||
return output
|
||||
@@ -139,8 +139,19 @@ def merge_attn_states(
|
||||
return headdim % 4 == 0
|
||||
return headdim % 8 == 0
|
||||
|
||||
# CDNA3 and newer (gfx942, gfx950, gfx1250). gfx90a is CDNA2 and
|
||||
# stays on the Triton merge.
|
||||
def supported_platform() -> bool:
|
||||
if current_platform.is_cuda():
|
||||
return True
|
||||
if current_platform.is_rocm():
|
||||
from vllm.platforms.rocm import get_cdna_version
|
||||
|
||||
return get_cdna_version() >= 3
|
||||
return False
|
||||
|
||||
if (
|
||||
current_platform.is_cuda()
|
||||
supported_platform()
|
||||
and supported_dtypes(prefix_output)
|
||||
and supported_headdim(prefix_output)
|
||||
):
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Device-side request mapping and sparse indexer metadata."""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
|
||||
|
||||
@@ -27,6 +29,28 @@ def _token_request_mapping_kernel(
|
||||
tl.store(output + token, tl.where(token < num_mapped, req, 0), token < num_tokens)
|
||||
|
||||
|
||||
def compute_token_to_req_indices(
|
||||
query_start_loc: torch.Tensor,
|
||||
out: torch.Tensor,
|
||||
num_mapped_tokens: int,
|
||||
num_tokens: int,
|
||||
) -> torch.Tensor:
|
||||
"""Map each of the first ``num_tokens`` tokens to its request index.
|
||||
|
||||
Reads only the device ``query_start_loc``, so it is safe to record in a
|
||||
CUDA graph. Tokens at or past ``num_mapped_tokens`` are mapped to 0.
|
||||
"""
|
||||
_token_request_mapping_kernel[((num_tokens + 255) // 256,)](
|
||||
query_start_loc,
|
||||
out,
|
||||
query_start_loc.shape[0] - 1,
|
||||
num_mapped_tokens,
|
||||
num_tokens,
|
||||
num_warps=4,
|
||||
)
|
||||
return out[:num_tokens]
|
||||
|
||||
|
||||
@triton.jit(
|
||||
do_not_specialize=[
|
||||
"num_reqs",
|
||||
|
||||
@@ -707,6 +707,14 @@ def paged_mqa_logits_module():
|
||||
return None
|
||||
|
||||
|
||||
def _per_sequence_context_lens(context_lens: torch.Tensor) -> torch.Tensor:
|
||||
# AITER takes one length per sequence: the last column of a (B, next_n) table.
|
||||
# TODO: remove once AITER accepts (B, next_n) context_lens (ROCm/aiter#6153).
|
||||
if context_lens.dim() == 2 and context_lens.shape[1] > 1:
|
||||
return context_lens[:, -1].contiguous()
|
||||
return context_lens
|
||||
|
||||
|
||||
def rocm_fp8_paged_mqa_logits(
|
||||
q_fp8: torch.Tensor,
|
||||
kv_cache_fp8: torch.Tensor,
|
||||
@@ -726,8 +734,8 @@ def rocm_fp8_paged_mqa_logits(
|
||||
kv_cache_fp8: Paged KV-cache in packed FP8+scale layout with shape
|
||||
[num_blocks, block_size, 1, D+4], dtype `torch.uint8`.
|
||||
weights: Tensor of shape [B * next_n, H], dtype `torch.float32`.
|
||||
context_lens: Tensor of shape [B], dtype int32; effective context length
|
||||
for each batch element.
|
||||
context_lens: Tensor of shape [B] or [B, next_n], dtype int32; effective
|
||||
context length for each batch element, or for each of its Q rows.
|
||||
block_tables: Tensor of shape [B, max_blocks], dtype int32; maps logical
|
||||
block indices to physical blocks in the paged cache.
|
||||
schedule_metadata: Returned by `get_paged_mqa_logits_metadata`;
|
||||
@@ -779,7 +787,7 @@ def rocm_fp8_paged_mqa_logits(
|
||||
kv_cache_fp8,
|
||||
weights,
|
||||
out_logits,
|
||||
context_lens,
|
||||
_per_sequence_context_lens(context_lens),
|
||||
block_tables,
|
||||
max_model_len,
|
||||
ChunkK=256,
|
||||
@@ -801,7 +809,7 @@ def rocm_fp8_paged_mqa_logits(
|
||||
kv_cache_fp8,
|
||||
weights,
|
||||
out_qk,
|
||||
context_lens,
|
||||
_per_sequence_context_lens(context_lens),
|
||||
block_tables,
|
||||
max_model_len,
|
||||
ChunkQ=heads,
|
||||
@@ -2208,6 +2216,119 @@ def _sparse_attn_prefill_ragged_kernel(
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _sparse_attn_decode_ragged_bf16_partial_kernel(
|
||||
q_ptr,
|
||||
kv_ptr,
|
||||
kv_indices_ptr,
|
||||
kv_indptr_ptr,
|
||||
part_m_ptr,
|
||||
part_l_ptr,
|
||||
part_acc_ptr,
|
||||
q_stride_t,
|
||||
q_stride_h,
|
||||
q_stride_d,
|
||||
kv_stride_n,
|
||||
kv_stride_d,
|
||||
pm_stride0,
|
||||
pm_stride_s,
|
||||
pa_stride0,
|
||||
pa_stride_s,
|
||||
pa_stride_h,
|
||||
num_heads,
|
||||
head_dim,
|
||||
num_kv,
|
||||
scale,
|
||||
BLOCK_H: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
BLOCK_K: tl.constexpr,
|
||||
NUM_SPLITS: tl.constexpr,
|
||||
):
|
||||
query_idx = tl.program_id(0)
|
||||
split_id = tl.program_id(1)
|
||||
pid_h = tl.program_id(2)
|
||||
|
||||
head_offsets = pid_h * BLOCK_H + tl.arange(0, BLOCK_H)
|
||||
dim_offsets = tl.arange(0, BLOCK_D)
|
||||
head_mask = head_offsets < num_heads
|
||||
dim_mask = dim_offsets < head_dim
|
||||
|
||||
q = tl.load(
|
||||
q_ptr
|
||||
+ query_idx * q_stride_t
|
||||
+ head_offsets[:, None] * q_stride_h
|
||||
+ dim_offsets[None, :] * q_stride_d,
|
||||
mask=head_mask[:, None] & dim_mask[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
|
||||
neg_large = -3.4028234663852886e38
|
||||
m_i = tl.full((BLOCK_H,), neg_large, dtype=tl.float32)
|
||||
l_i = tl.zeros((BLOCK_H,), dtype=tl.float32)
|
||||
acc = tl.zeros((BLOCK_H, BLOCK_D), dtype=tl.float32)
|
||||
|
||||
kv_start = tl.load(kv_indptr_ptr + query_idx)
|
||||
kv_end = tl.load(kv_indptr_ptr + query_idx + 1)
|
||||
kv_len = kv_end - kv_start
|
||||
chunk = (kv_len + NUM_SPLITS - 1) // NUM_SPLITS
|
||||
kv_lo = split_id * chunk
|
||||
kv_hi = tl.minimum(kv_lo + chunk, kv_len)
|
||||
|
||||
k_offsets = tl.arange(0, BLOCK_K)
|
||||
slot = tl.load(
|
||||
kv_indices_ptr + kv_start + kv_lo + k_offsets,
|
||||
mask=kv_lo + k_offsets < kv_hi,
|
||||
other=-1,
|
||||
)
|
||||
for k_start in tl.range(kv_lo, kv_hi, BLOCK_K):
|
||||
k_pos = k_start + k_offsets
|
||||
in_range = k_pos < kv_hi
|
||||
valid = in_range & (slot >= 0) & (slot < num_kv)
|
||||
safe_slot = tl.where(valid, slot, 0)
|
||||
|
||||
kv = tl.load(
|
||||
kv_ptr
|
||||
+ _sparse_kv_row_offset(safe_slot[:, None], kv_stride_n)
|
||||
+ dim_offsets[None, :] * kv_stride_d,
|
||||
mask=valid[:, None] & dim_mask[None, :],
|
||||
other=0.0,
|
||||
)
|
||||
|
||||
next_k_pos = k_start + BLOCK_K + k_offsets
|
||||
slot = tl.load(
|
||||
kv_indices_ptr + kv_start + next_k_pos, mask=next_k_pos < kv_hi, other=-1
|
||||
)
|
||||
|
||||
scores = tl.dot(q, tl.trans(kv)) * scale
|
||||
scores = tl.where(head_mask[:, None] & valid[None, :], scores, neg_large)
|
||||
|
||||
m_block = tl.max(scores, axis=1)
|
||||
m_new = tl.maximum(m_i, m_block)
|
||||
alpha = tl.exp(m_i - m_new)
|
||||
p = tl.exp(scores - m_new[:, None])
|
||||
p = tl.where(head_mask[:, None] & valid[None, :], p, 0.0)
|
||||
l_new = l_i * alpha + tl.sum(p, axis=1)
|
||||
|
||||
acc = acc * alpha[:, None] + tl.dot(p.to(kv.dtype), kv)
|
||||
m_i = m_new
|
||||
l_i = l_new
|
||||
|
||||
# Every launched slot is written; empty splits store the (neg_large, 0.0)
|
||||
# sentinel the reduce combines to nothing.
|
||||
pm_base = query_idx * pm_stride0 + split_id * pm_stride_s + head_offsets
|
||||
tl.store(part_m_ptr + pm_base, m_i, mask=head_mask)
|
||||
tl.store(part_l_ptr + pm_base, l_i, mask=head_mask)
|
||||
tl.store(
|
||||
part_acc_ptr
|
||||
+ query_idx * pa_stride0
|
||||
+ split_id * pa_stride_s
|
||||
+ head_offsets[:, None] * pa_stride_h
|
||||
+ dim_offsets[None, :],
|
||||
acc,
|
||||
mask=head_mask[:, None] & dim_mask[None, :],
|
||||
)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _decode_e8m0_scales_triton(encoded_scales):
|
||||
scale_bits = encoded_scales.to(tl.int32) << 23
|
||||
@@ -3664,6 +3785,182 @@ def _decode_gfx950_num_splits(
|
||||
return num_splits
|
||||
|
||||
|
||||
# Empirically single-pass bf16 decode is faster than split-K below this number of
|
||||
# selected slots per query, so we do not split.
|
||||
_SPARSE_DECODE_BF16_MIN_SPLIT_LEN = 512
|
||||
_SPARSE_DECODE_BF16_BLOCK_H = 16
|
||||
_SPARSE_DECODE_BF16_BLOCK_K = 32
|
||||
|
||||
|
||||
def rocm_sparse_decode_bf16_num_splits(
|
||||
num_queries: int, num_heads: int, sparse_len: int
|
||||
) -> int:
|
||||
"""Number or kv splits in splitK for the sparse bf16 decode, or 1 for single-pass.
|
||||
|
||||
Args:
|
||||
num_queries: Decode rows in the batch.
|
||||
num_heads: Query heads per row.
|
||||
sparse_len: Longest selected KV run any decode row can walk.
|
||||
|
||||
Returns:
|
||||
The split count, or 1 when the caller should use the single-pass kernel.
|
||||
|
||||
"""
|
||||
if sparse_len < _SPARSE_DECODE_BF16_MIN_SPLIT_LEN:
|
||||
return 1
|
||||
block_k = _SPARSE_DECODE_BF16_BLOCK_K
|
||||
heads_blocks = triton.cdiv(num_heads, _SPARSE_DECODE_BF16_BLOCK_H)
|
||||
select = _decode_gfx950_num_splits if _ON_GFX950 else _decode_num_splits
|
||||
num_splits = select(num_queries, heads_blocks, sparse_len, 0.0, block_k)
|
||||
# Number of splits cannot exceed the available k tiles
|
||||
return max(1, min(num_splits, math.ceil(sparse_len / block_k)))
|
||||
|
||||
|
||||
def _rocm_sparse_attn_decode_ragged_bf16_triton(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
indices: torch.Tensor,
|
||||
indptr: torch.Tensor,
|
||||
scale: float,
|
||||
attn_sink: torch.Tensor | None,
|
||||
nope_head_dim: int,
|
||||
rope_head_dim: int,
|
||||
num_splits: int,
|
||||
out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Split-K decode over an bf16 ragged KV cache.
|
||||
|
||||
Partitions each query's selected tokens across different workgroups and combines
|
||||
the partials through reduction.
|
||||
|
||||
Args:
|
||||
q: Queries laid out as ``[sq, h, d]``.
|
||||
kv: Unquantized KV rows laid out as ``[skv, d]``.
|
||||
indices: Flattened per-query KV slots.
|
||||
indptr: Segment offsets into ``indices``, ``[sq + 1]``.
|
||||
scale: Softmax scale.
|
||||
attn_sink: Optional per-head sink logits.
|
||||
nope_head_dim: NoPE width of ``d``.
|
||||
rope_head_dim: RoPE width of ``d``.
|
||||
num_splits: Number of KV splits per query.
|
||||
out: Optional destination with ``d`` trailing elements.
|
||||
|
||||
Returns:
|
||||
The attention output, ``out`` when provided.
|
||||
|
||||
"""
|
||||
assert q.ndim == 3, f"expected q=[sq,h,d], got {q.shape}"
|
||||
assert kv.ndim == 2, f"expected kv=[skv,d], got {kv.shape}"
|
||||
assert indices.ndim == 1, f"expected indices=[nnz], got {indices.shape}"
|
||||
assert indptr.ndim == 1, f"expected indptr=[sq+1], got {indptr.shape}"
|
||||
assert not q.is_cpu and not kv.is_cpu and not indices.is_cpu and not indptr.is_cpu
|
||||
|
||||
indices = _as_int32_contiguous_1d(indices)
|
||||
indptr = _as_int32_contiguous_1d(indptr)
|
||||
has_attn_sink = attn_sink is not None
|
||||
if attn_sink is None:
|
||||
attn_sink = torch.empty(1, device=q.device, dtype=torch.float32)
|
||||
else:
|
||||
attn_sink = attn_sink.contiguous()
|
||||
|
||||
num_queries, num_heads, head_dim = q.shape
|
||||
assert indptr.numel() == num_queries + 1, (
|
||||
f"expected indptr shape [{num_queries + 1}], got {indptr.shape}"
|
||||
)
|
||||
_validate_sparse_dims(
|
||||
head_dim,
|
||||
nope_head_dim,
|
||||
rope_head_dim,
|
||||
"_rocm_sparse_attn_decode_ragged_bf16_triton",
|
||||
)
|
||||
if out is None:
|
||||
out = torch.empty_like(q)
|
||||
assert out.shape[-1] == head_dim, (
|
||||
f"expected out trailing dim {head_dim}, got {out.shape[-1]}"
|
||||
)
|
||||
|
||||
block_h = _SPARSE_DECODE_BF16_BLOCK_H
|
||||
block_d = triton.next_power_of_2(head_dim)
|
||||
block_k = _SPARSE_DECODE_BF16_BLOCK_K
|
||||
heads_blocks = triton.cdiv(num_heads, block_h)
|
||||
comb_dim = nope_head_dim + rope_head_dim
|
||||
|
||||
part_m = torch.empty(
|
||||
(num_queries, num_splits, num_heads), dtype=torch.float32, device=q.device
|
||||
)
|
||||
part_l = torch.empty_like(part_m)
|
||||
part_acc = torch.empty(
|
||||
(num_queries, num_splits, num_heads, comb_dim),
|
||||
dtype=torch.float32,
|
||||
device=q.device,
|
||||
)
|
||||
|
||||
_sparse_attn_decode_ragged_bf16_partial_kernel[
|
||||
(num_queries, num_splits, heads_blocks)
|
||||
](
|
||||
q,
|
||||
kv,
|
||||
indices,
|
||||
indptr,
|
||||
part_m,
|
||||
part_l,
|
||||
part_acc,
|
||||
q.stride(0),
|
||||
q.stride(1),
|
||||
q.stride(2),
|
||||
kv.stride(0),
|
||||
kv.stride(1),
|
||||
part_m.stride(0),
|
||||
part_m.stride(1),
|
||||
part_acc.stride(0),
|
||||
part_acc.stride(1),
|
||||
part_acc.stride(2),
|
||||
num_heads,
|
||||
head_dim,
|
||||
kv.shape[0],
|
||||
float(scale),
|
||||
BLOCK_H=block_h,
|
||||
BLOCK_D=block_d,
|
||||
BLOCK_K=block_k,
|
||||
NUM_SPLITS=num_splits,
|
||||
num_warps=4,
|
||||
)
|
||||
|
||||
_sparse_attn_decode_reduce_kernel[(num_queries, num_heads)](
|
||||
part_m,
|
||||
part_l,
|
||||
part_acc,
|
||||
attn_sink,
|
||||
out,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
out.stride(0),
|
||||
out.stride(1),
|
||||
0,
|
||||
head_dim // 32,
|
||||
part_m.stride(0),
|
||||
part_m.stride(1),
|
||||
part_acc.stride(0),
|
||||
part_acc.stride(1),
|
||||
part_acc.stride(2),
|
||||
0,
|
||||
num_heads,
|
||||
HAS_ATTN_SINK=has_attn_sink,
|
||||
ADAPTIVE_SPLITS=False,
|
||||
COMB_DIM=comb_dim,
|
||||
BLOCK_H=1,
|
||||
NUM_SPLITS=num_splits,
|
||||
SPLITS_PAD=triton.next_power_of_2(num_splits),
|
||||
FUSE_INV_ROPE=False,
|
||||
NOPE=nope_head_dim,
|
||||
HALF=rope_head_dim // 2,
|
||||
QUANT_OUT=False,
|
||||
num_warps=4,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _rocm_sparse_attn_decode_ragged_triton(
|
||||
q: torch.Tensor,
|
||||
main_cache: torch.Tensor,
|
||||
@@ -4143,6 +4440,72 @@ def rocm_sparse_attn_prefill(
|
||||
)
|
||||
|
||||
|
||||
def rocm_sparse_attn_decode_bf16(
|
||||
q: torch.Tensor,
|
||||
kv: torch.Tensor,
|
||||
scale: float,
|
||||
head_dim: int,
|
||||
nope_head_dim: int,
|
||||
rope_head_dim: int,
|
||||
attn_sink: torch.Tensor | None,
|
||||
output: torch.Tensor,
|
||||
ragged_indices: torch.Tensor,
|
||||
ragged_indptr: torch.Tensor,
|
||||
num_splits: int,
|
||||
) -> None:
|
||||
"""Run split-K sparse attention over decode rows using an unquantized KV cache.
|
||||
|
||||
Args:
|
||||
q: Decode queries laid out as ``[sq, h, d]``.
|
||||
kv: KV cache laid out as ``[skv, 1, d]``.
|
||||
scale: Softmax scale.
|
||||
head_dim: Post-absorption head width.
|
||||
nope_head_dim: NoPE width of ``head_dim``.
|
||||
rope_head_dim: RoPE width of ``head_dim``.
|
||||
attn_sink: Optional per-head sink logits.
|
||||
output: Destination, written in place.
|
||||
ragged_indices: Flattened per-query KV slots.
|
||||
ragged_indptr: Segment offsets into ``ragged_indices``, ``[sq + 1]``.
|
||||
num_splits: KV splits per query, from
|
||||
:func:`rocm_sparse_decode_bf16_num_splits`.
|
||||
|
||||
"""
|
||||
assert kv.ndim == 3 and kv.shape[1] == 1, (
|
||||
f"ROCm Triton sparse decode expects kv=[skv,1,d], got {kv.shape}"
|
||||
)
|
||||
_validate_sparse_dims(
|
||||
head_dim,
|
||||
nope_head_dim,
|
||||
rope_head_dim,
|
||||
"rocm_sparse_attn_decode_bf16",
|
||||
)
|
||||
num_queries, num_heads = q.shape[0], q.shape[1]
|
||||
direct = output.shape[-1] == head_dim
|
||||
out = (
|
||||
output
|
||||
if direct
|
||||
else torch.empty(
|
||||
(num_queries, num_heads, head_dim),
|
||||
dtype=output.dtype,
|
||||
device=output.device,
|
||||
)
|
||||
)
|
||||
_rocm_sparse_attn_decode_ragged_bf16_triton(
|
||||
q=q,
|
||||
kv=kv.squeeze(1),
|
||||
indices=ragged_indices,
|
||||
indptr=ragged_indptr,
|
||||
scale=scale,
|
||||
attn_sink=None if attn_sink is None else attn_sink[: q.shape[1]],
|
||||
nope_head_dim=nope_head_dim,
|
||||
rope_head_dim=rope_head_dim,
|
||||
num_splits=num_splits,
|
||||
out=out,
|
||||
)
|
||||
if not direct:
|
||||
output.copy_(out[..., : output.shape[-1]])
|
||||
|
||||
|
||||
def rocm_sparse_attn_decode(
|
||||
q: torch.Tensor,
|
||||
kv_cache: torch.Tensor | None,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -243,9 +243,10 @@ def context_attention_fwd(
|
||||
b_seq_len: [b]
|
||||
out: [b * s, head, head_dim]
|
||||
"""
|
||||
BLOCK = get_block_size(q.dtype)
|
||||
|
||||
Lq, Lk, _ = q.shape[-1], k.shape[-1], v.shape[-1]
|
||||
BLOCK = get_block_size(q.dtype)
|
||||
if Lk >= 512:
|
||||
BLOCK = min(BLOCK, 32)
|
||||
|
||||
sm_scale = 1.0 / (Lq**0.5) if softmax_scale is None else softmax_scale
|
||||
# rescale with 1/ln(2) for triton exp2
|
||||
|
||||
@@ -586,7 +586,15 @@ def kernel_unified_attention(
|
||||
P_v = (P * v_token_head_scales[None, :]).to(V.dtype)
|
||||
acc += tl.dot(P_v, V)
|
||||
else:
|
||||
acc += tl.dot(P.to(V.dtype), V)
|
||||
# Keep softmax weights representable when the P @ V dot uses FP8
|
||||
# tensor cores. Undo the power-of-two scale after the dot.
|
||||
if V.dtype == tl.float8e4nv:
|
||||
p_scale = 256.0
|
||||
elif V.dtype.is_fp8():
|
||||
p_scale = 128.0
|
||||
else:
|
||||
p_scale = 1.0
|
||||
acc += tl.dot((P * p_scale).to(V.dtype), V) / p_scale
|
||||
|
||||
# ---- Epilogue ---------------------------------------------------------
|
||||
if IS_3D:
|
||||
|
||||
@@ -60,6 +60,9 @@ def kernel_unified_attention_diffkv(
|
||||
query_ptr,
|
||||
key_cache_ptr, # view of packed cache: [..., :head_size_qk]
|
||||
value_cache_ptr, # view of packed cache: [..., head_size_qk:hqk+hv]
|
||||
q_descale_ptr,
|
||||
k_descale_ptr,
|
||||
v_descale_ptr,
|
||||
sink_ptr,
|
||||
block_tables_ptr,
|
||||
seq_lens_ptr,
|
||||
@@ -83,6 +86,8 @@ def kernel_unified_attention_diffkv(
|
||||
USE_ALIBI_SQRT: tl.constexpr,
|
||||
USE_SOFTCAP: tl.constexpr,
|
||||
USE_SINKS: tl.constexpr,
|
||||
USE_Q_SCALE: tl.constexpr,
|
||||
USE_KV_SCALES: tl.constexpr,
|
||||
SLIDING_WINDOW: tl.constexpr,
|
||||
# Strides for both cache views (they share the same packed buffer, so
|
||||
# dims 0/1/2 strides match; only the per-head extent differs).
|
||||
@@ -154,6 +159,12 @@ def kernel_unified_attention_diffkv(
|
||||
other=0.0,
|
||||
)
|
||||
|
||||
if USE_Q_SCALE:
|
||||
scale *= tl.load(q_descale_ptr)
|
||||
if USE_KV_SCALES:
|
||||
scale *= tl.load(k_descale_ptr)
|
||||
v_descale = tl.load(v_descale_ptr)
|
||||
|
||||
block_table_offset = seq_idx * block_table_stride
|
||||
|
||||
M = init_softmax_M(
|
||||
@@ -262,6 +273,9 @@ def kernel_unified_attention_diffkv(
|
||||
acc += tl.dot(P.to(V.dtype), V)
|
||||
|
||||
# ---- Epilogue --------------------------------------------------------
|
||||
if USE_KV_SCALES:
|
||||
acc *= v_descale
|
||||
|
||||
if IS_3D:
|
||||
# Store per-segment partials; finalized by reduce_segments_diffkv.
|
||||
segm_output_offset = (
|
||||
@@ -403,6 +417,9 @@ def unified_attention_diffkv(
|
||||
softmax_segm_output: torch.Tensor | None = None,
|
||||
softmax_segm_max: torch.Tensor | None = None,
|
||||
softmax_segm_expsum: torch.Tensor | None = None,
|
||||
k_descale: torch.Tensor | None = None,
|
||||
v_descale: torch.Tensor | None = None,
|
||||
q_descale: torch.Tensor | None = None,
|
||||
):
|
||||
assert causal, "Only causal attention is supported"
|
||||
|
||||
@@ -470,6 +487,9 @@ def unified_attention_diffkv(
|
||||
query_ptr=q,
|
||||
key_cache_ptr=k,
|
||||
value_cache_ptr=v,
|
||||
q_descale_ptr=q_descale,
|
||||
k_descale_ptr=k_descale,
|
||||
v_descale_ptr=v_descale,
|
||||
sink_ptr=sinks,
|
||||
block_tables_ptr=block_table,
|
||||
seq_lens_ptr=seqused_k,
|
||||
@@ -493,6 +513,8 @@ def unified_attention_diffkv(
|
||||
USE_ALIBI_SQRT=use_alibi_sqrt,
|
||||
USE_SOFTCAP=(softcap > 0),
|
||||
USE_SINKS=(sinks is not None),
|
||||
USE_Q_SCALE=q_descale is not None,
|
||||
USE_KV_SCALES=k_descale is not None,
|
||||
SLIDING_WINDOW=sliding_window_val,
|
||||
stride_k_cache_0=k.stride(0),
|
||||
stride_k_cache_1=k.stride(1),
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""UltraQuant 4-bit KV cache: FP4 E2M1 codes + UE8M0 group-of-32 scales.
|
||||
|
||||
Production decode uses the FlyDSL D=256 kernel on gfx950, with Triton
|
||||
unified attention as the fallback. Slot size is ``slot_size(head_dim)``
|
||||
(272 B at D=256). Format helpers live in ``format``; import them from
|
||||
there, not this package root.
|
||||
"""
|
||||
|
||||
__all__ = ["ultraquant_store"]
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
if name == "ultraquant_store":
|
||||
from vllm.v1.attention.ops.ultraquant.triton_store import ultraquant_store
|
||||
|
||||
return ultraquant_store
|
||||
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
||||
@@ -0,0 +1,218 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""FP4 codepoint + UE8M0 scale constants for the UltraQuant KV cache.
|
||||
|
||||
K/V codes are FP4 E2M1. Per-group scales are UE8M0 (one byte, a power of
|
||||
two): ``s = 2^round(log2(c · absmax))`` with ``c = 0.156``. Decode
|
||||
consumes Q as FP8 E4M3 so scaled F8F6F4 MFMA can run natively on CDNA4.
|
||||
|
||||
AoS slot layout (group_size=32), per (token, head):
|
||||
bytes [0 .. D/2) : K codes (FP4 nibbles, 2/byte)
|
||||
bytes [D/2 .. D/2 + Gk) : K scales (UE8M0, 1 byte × Gk groups)
|
||||
bytes [D/2 + Gk .. D + Gk) : V codes
|
||||
bytes [D + Gk .. D + 2*Gk) : V scales
|
||||
D=256 → Gk=8 → 272 B/slot. D=128 → Gk=4 → 136 B/slot.
|
||||
|
||||
No per-token norm-fold. No V rotation. K is Hadamard-rotated at store.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
# ── 15 unique FP4 E2M1 levels, sorted ascending ────
|
||||
FP4_LEVELS_SORTED: tuple[float, ...] = (
|
||||
-6.0,
|
||||
-4.0,
|
||||
-3.0,
|
||||
-2.0,
|
||||
-1.5,
|
||||
-1.0,
|
||||
-0.5,
|
||||
0.0,
|
||||
0.5,
|
||||
1.0,
|
||||
1.5,
|
||||
2.0,
|
||||
3.0,
|
||||
4.0,
|
||||
6.0,
|
||||
)
|
||||
assert len(FP4_LEVELS_SORTED) == 15
|
||||
|
||||
# Midpoints between consecutive sorted levels (14 boundaries).
|
||||
MIDPOINTS_SORTED: tuple[float, ...] = tuple(
|
||||
(FP4_LEVELS_SORTED[i] + FP4_LEVELS_SORTED[i + 1]) / 2.0
|
||||
for i in range(len(FP4_LEVELS_SORTED) - 1)
|
||||
)
|
||||
assert len(MIDPOINTS_SORTED) == 14
|
||||
|
||||
# FP4 E2M1 bit-pattern decode (16 entries indexed by 4-bit code).
|
||||
# Sign bit (MSB) | 2 exp bits | 1 mantissa bit (LSB).
|
||||
FP4_BITS_TO_VALUE: tuple[float, ...] = (
|
||||
0.0,
|
||||
0.5,
|
||||
1.0,
|
||||
1.5,
|
||||
2.0,
|
||||
3.0,
|
||||
4.0,
|
||||
6.0,
|
||||
-0.0,
|
||||
-0.5,
|
||||
-1.0,
|
||||
-1.5,
|
||||
-2.0,
|
||||
-3.0,
|
||||
-4.0,
|
||||
-6.0,
|
||||
)
|
||||
assert len(FP4_BITS_TO_VALUE) == 16
|
||||
|
||||
# Sorted index → FP4 E2M1 bit pattern (uint4).
|
||||
SORTED_TO_BITS: tuple[int, ...] = (
|
||||
0b1111,
|
||||
0b1110,
|
||||
0b1101,
|
||||
0b1100,
|
||||
0b1011,
|
||||
0b1010,
|
||||
0b1001,
|
||||
0b0000,
|
||||
0b0001,
|
||||
0b0010,
|
||||
0b0011,
|
||||
0b0100,
|
||||
0b0101,
|
||||
0b0110,
|
||||
0b0111,
|
||||
)
|
||||
assert len(SORTED_TO_BITS) == 15
|
||||
for _i, _bits in enumerate(SORTED_TO_BITS):
|
||||
_v = FP4_BITS_TO_VALUE[_bits]
|
||||
_v = 0.0 if _v == 0.0 else _v
|
||||
assert _v == FP4_LEVELS_SORTED[_i]
|
||||
|
||||
# ── Format constants ──────────────────────────────────────────────────────
|
||||
GROUP_SIZE: int = 32
|
||||
"""Elements per group; one E8M0 scale per group. Fixed at 32 because the
|
||||
AMD scaled F8F6F4 MFMA instruction also consumes one E8M0 scale per 32
|
||||
elements along K. Other group sizes would force a fallback to plain MFMA
|
||||
+ accumulator-side scale multiply (no hardware fast-path)."""
|
||||
|
||||
FP4_MAX: float = 6.0
|
||||
"""Largest representable FP4 magnitude."""
|
||||
|
||||
DEFAULT_CONSTANT_C: float = 0.156
|
||||
"""MSE-optimal scale constant; ``s_raw = c * absmax``, then UE8M0-snapped."""
|
||||
|
||||
|
||||
def get_constant_c() -> float:
|
||||
"""Return the fixed UltraQuant scale constant."""
|
||||
return DEFAULT_CONSTANT_C
|
||||
|
||||
|
||||
def get_group_size() -> int:
|
||||
"""Return the fixed group size required by scaled MFMA."""
|
||||
return GROUP_SIZE
|
||||
|
||||
|
||||
# ── Scale encoding ────────────────────────────────────────────────────────
|
||||
# Per-group scale `s = pow2_round(c · absmax)` stored as the E8M0 byte;
|
||||
# codebook is the raw FP4 grid {0, ±0.5, ..., ±6}; dequant = code · s.
|
||||
|
||||
|
||||
# ── UE8M0 helpers ──────────────────────────────────────────────────────────
|
||||
# E8M0 = 8 exponent bits, 0 mantissa bits, no sign. The byte value `e`
|
||||
# represents `2^(e - 127)` for e in [1, 254]. e=0 and e=255 are reserved
|
||||
# (zero and NaN respectively in the OCP spec). We use e=0 as our zero
|
||||
# sentinel for sink-zero groups.
|
||||
|
||||
UE8M0_BIAS: int = 127
|
||||
|
||||
# fp32 minimum positive normal = 2^-126 ≈ 1.175e-38. Anything smaller
|
||||
# clamps to the zero sentinel.
|
||||
_UE8M0_MIN_EXP: int = -126
|
||||
_UE8M0_MAX_EXP: int = 127
|
||||
|
||||
|
||||
def ue8m0_encode(s: float) -> int:
|
||||
"""Snap a positive fp32 scale `s` to the nearest power of 2 and
|
||||
encode as a UE8M0 byte. `s <= 0` encodes as 0 (zero sentinel)."""
|
||||
if s <= 0.0 or not math.isfinite(s):
|
||||
return 0
|
||||
exp = int(round(math.log2(s)))
|
||||
if exp < _UE8M0_MIN_EXP:
|
||||
return 0
|
||||
if exp > _UE8M0_MAX_EXP:
|
||||
exp = _UE8M0_MAX_EXP
|
||||
return exp + UE8M0_BIAS
|
||||
|
||||
|
||||
def ue8m0_decode(byte: int) -> float:
|
||||
"""Decode a UE8M0 byte back to fp32. 0 → 0.0 (zero sentinel)."""
|
||||
if byte == 0:
|
||||
return 0.0
|
||||
return 2.0 ** (byte - UE8M0_BIAS)
|
||||
|
||||
|
||||
# ── Per-slot AoS byte layout ──────────────────────────────────────────────
|
||||
# Per slot, per head (group_size=GS=32, Gk = D/GS):
|
||||
# bytes [0 .. D/2) : K codes (2 nibbles/byte)
|
||||
# bytes [D/2 .. D/2 + Gk) : K scales (E8M0, 1 byte each)
|
||||
# bytes [D/2 + Gk .. D + Gk) : V codes
|
||||
# bytes [D + Gk .. D + 2*Gk) : V scales (E8M0, 1 byte each)
|
||||
# D=256 → 272 B/slot. D=128 → 136 B/slot.
|
||||
|
||||
|
||||
def k_codes_bytes(head_dim: int) -> int:
|
||||
"""Bytes for one head's packed K codes."""
|
||||
if head_dim % 2 != 0:
|
||||
raise ValueError(f"head_dim must be even, got {head_dim}")
|
||||
return head_dim // 2
|
||||
|
||||
|
||||
def n_groups(head_dim: int, group_size: int | None = None) -> int:
|
||||
gs = group_size if group_size is not None else get_group_size()
|
||||
if head_dim % gs != 0:
|
||||
raise ValueError(f"head_dim={head_dim} must be a multiple of group_size={gs}")
|
||||
return head_dim // gs
|
||||
|
||||
|
||||
def k_scales_bytes(head_dim: int, group_size: int | None = None) -> int:
|
||||
"""Bytes for one head's K scales (one E8M0 byte per group)."""
|
||||
return n_groups(head_dim, group_size)
|
||||
|
||||
|
||||
def v_codes_bytes(head_dim: int) -> int:
|
||||
return k_codes_bytes(head_dim)
|
||||
|
||||
|
||||
def v_scales_bytes(head_dim: int, group_size: int | None = None) -> int:
|
||||
return k_scales_bytes(head_dim, group_size)
|
||||
|
||||
|
||||
def slot_size(head_dim: int, group_size: int | None = None) -> int:
|
||||
"""Bytes per (token, head) slot."""
|
||||
return (
|
||||
k_codes_bytes(head_dim)
|
||||
+ k_scales_bytes(head_dim, group_size)
|
||||
+ v_codes_bytes(head_dim)
|
||||
+ v_scales_bytes(head_dim, group_size)
|
||||
)
|
||||
|
||||
|
||||
def k_codes_offset(head_dim: int, group_size: int | None = None) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def k_scales_offset(head_dim: int, group_size: int | None = None) -> int:
|
||||
return k_codes_bytes(head_dim)
|
||||
|
||||
|
||||
def v_codes_offset(head_dim: int, group_size: int | None = None) -> int:
|
||||
return k_codes_bytes(head_dim) + k_scales_bytes(head_dim, group_size)
|
||||
|
||||
|
||||
def v_scales_offset(head_dim: int, group_size: int | None = None) -> int:
|
||||
return v_codes_offset(head_dim, group_size) + v_codes_bytes(head_dim)
|
||||
@@ -0,0 +1,349 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""PyTorch reference for the UltraQuant KV cache format.
|
||||
|
||||
Scale is UE8M0 (power of two): after ``s = c * absmax`` snap
|
||||
``s = 2^round(log2(s))`` and store one byte. Q is Hadamard-rotated then
|
||||
cast to FP8 E4M3 before the QK matmul, matching the kernel launcher.
|
||||
|
||||
Same FP4 E2M1 grid. ``c = 0.156``. No per-token L2 norm. No V rotation.
|
||||
K is rotated at encode; Q arrives pre-rotated at decode.
|
||||
|
||||
This module is the bit-comparison ground truth for the kernels.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.v1.attention.ops.ultraquant.format import (
|
||||
FP4_LEVELS_SORTED,
|
||||
GROUP_SIZE,
|
||||
MIDPOINTS_SORTED,
|
||||
SORTED_TO_BITS,
|
||||
UE8M0_BIAS,
|
||||
get_constant_c,
|
||||
)
|
||||
|
||||
_LEVELS_CACHE: dict[tuple[torch.device, torch.dtype], torch.Tensor] = {}
|
||||
_MIDPOINTS_CACHE: dict[tuple[torch.device, torch.dtype], torch.Tensor] = {}
|
||||
_SORTED_TO_BITS_CACHE: dict[torch.device, torch.Tensor] = {}
|
||||
|
||||
|
||||
def _get_levels(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
||||
key = (device, dtype)
|
||||
t = _LEVELS_CACHE.get(key)
|
||||
if t is None:
|
||||
t = torch.tensor(FP4_LEVELS_SORTED, device=device, dtype=dtype)
|
||||
_LEVELS_CACHE[key] = t
|
||||
return t
|
||||
|
||||
|
||||
def _get_midpoints(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
||||
key = (device, dtype)
|
||||
t = _MIDPOINTS_CACHE.get(key)
|
||||
if t is None:
|
||||
t = torch.tensor(MIDPOINTS_SORTED, device=device, dtype=dtype)
|
||||
_MIDPOINTS_CACHE[key] = t
|
||||
return t
|
||||
|
||||
|
||||
def _get_sorted_to_bits(device: torch.device) -> torch.Tensor:
|
||||
t = _SORTED_TO_BITS_CACHE.get(device)
|
||||
if t is None:
|
||||
t = torch.tensor(SORTED_TO_BITS, device=device, dtype=torch.uint8)
|
||||
_SORTED_TO_BITS_CACHE[device] = t
|
||||
return t
|
||||
|
||||
|
||||
_HADAMARD_CACHE: dict[tuple[int, torch.device, torch.dtype], torch.Tensor] = {}
|
||||
|
||||
|
||||
def hadamard_matrix(
|
||||
dim: int, device: torch.device, dtype: torch.dtype = torch.float32
|
||||
) -> torch.Tensor:
|
||||
"""Sylvester Hadamard, normalised so H @ H.T = I."""
|
||||
if dim <= 0 or (dim & (dim - 1)) != 0:
|
||||
raise ValueError(f"hadamard_matrix requires power-of-two dim, got {dim}")
|
||||
key = (dim, device, dtype)
|
||||
cached = _HADAMARD_CACHE.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
H = torch.tensor([[1.0]], dtype=torch.float64)
|
||||
while H.shape[0] < dim:
|
||||
H = torch.cat([torch.cat([H, H], dim=1), torch.cat([H, -H], dim=1)], dim=0)
|
||||
H = (H / (dim**0.5)).to(device=device, dtype=dtype).contiguous()
|
||||
_HADAMARD_CACHE[key] = H
|
||||
return H
|
||||
|
||||
|
||||
# ── Core quantization primitives ───────────────────────────────────────────
|
||||
def _snap_to_sorted_idx(
|
||||
x_norm: torch.Tensor, *, dtype: torch.dtype = torch.float32
|
||||
) -> torch.Tensor:
|
||||
"""Snap normalised values to nearest FP4 level, returning sorted index
|
||||
in [0, 14]. Same semantic as `torch.bucketize` against midpoints
|
||||
(reproduced by 14 `tl.where` in the kernel)."""
|
||||
boundaries = _get_midpoints(x_norm.device, dtype)
|
||||
x = x_norm.to(dtype)
|
||||
# ROCm's bucketize uses int32 element indexing and raises
|
||||
# hipErrorInvalidConfiguration once numel >= 2**31 (e.g. a [B, Hk, N, D]
|
||||
# K tensor at B=128, N=16384, Hk=8, D=128 is exactly 2**31). Chunk the
|
||||
# flattened input so each call stays under the limit (bit-identical output).
|
||||
_INT32_LIMIT = 2**31
|
||||
if x.numel() < _INT32_LIMIT:
|
||||
return torch.bucketize(x, boundaries)
|
||||
flat = x.reshape(-1)
|
||||
out = torch.empty_like(flat, dtype=torch.long)
|
||||
chunk = _INT32_LIMIT // 2
|
||||
for i in range(0, flat.numel(), chunk):
|
||||
out[i : i + chunk] = torch.bucketize(flat[i : i + chunk], boundaries)
|
||||
return out.reshape(x.shape)
|
||||
|
||||
|
||||
def _pack_nibbles_last_dim(codes: torch.Tensor) -> torch.Tensor:
|
||||
if codes.shape[-1] % 2 != 0:
|
||||
raise ValueError(f"pack_nibbles last dim must be even, got {codes.shape[-1]}")
|
||||
lo = codes[..., 0::2] & 0xF
|
||||
hi = codes[..., 1::2] & 0xF
|
||||
return (lo | (hi << 4)).to(torch.uint8)
|
||||
|
||||
|
||||
def _unpack_nibbles_last_dim(packed: torch.Tensor, out_dim: int) -> torch.Tensor:
|
||||
if out_dim != 2 * packed.shape[-1]:
|
||||
packed_dim = packed.shape[-1]
|
||||
raise ValueError(
|
||||
f"unpack_nibbles: out_dim={out_dim} must be 2*packed.last={2 * packed_dim}"
|
||||
)
|
||||
p = packed.to(torch.int32)
|
||||
lo = (p & 0xF).to(torch.uint8)
|
||||
hi = ((p >> 4) & 0xF).to(torch.uint8)
|
||||
out_shape = packed.shape[:-1] + (out_dim,)
|
||||
out = torch.empty(out_shape, dtype=torch.uint8, device=packed.device)
|
||||
out[..., 0::2] = lo
|
||||
out[..., 1::2] = hi
|
||||
return out
|
||||
|
||||
|
||||
def _ue8m0_snap_tensor(
|
||||
s_raw: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
"""Snap a positive-scale tensor `s_raw` to a power of two and return
|
||||
``(s_snapped_fp32, byte_uint8)``.
|
||||
|
||||
Matches the kernel: zero / non-finite inputs map to byte=0 / value=0.0.
|
||||
Round-half-up via ``floor(log2(s) + 0.5)``, matching Triton's
|
||||
``tl.floor(... + 0.5)`` idiom.
|
||||
"""
|
||||
is_zero = (s_raw <= 0) | ~torch.isfinite(s_raw)
|
||||
s_safe = torch.where(is_zero, torch.ones_like(s_raw), s_raw)
|
||||
log2_s = torch.log2(s_safe)
|
||||
exp = torch.floor(log2_s + 0.5).to(torch.int32)
|
||||
# Clamp to UE8M0's representable exponent range (signed pre-bias).
|
||||
exp = torch.clamp(exp, min=-126, max=127)
|
||||
byte = (exp + UE8M0_BIAS).to(torch.int32)
|
||||
byte = torch.where(is_zero, torch.zeros_like(byte), byte).to(torch.uint8)
|
||||
s_snapped = torch.where(
|
||||
is_zero, torch.zeros_like(s_raw), torch.exp2(exp.to(torch.float32))
|
||||
)
|
||||
return s_snapped, byte
|
||||
|
||||
|
||||
@dataclass
|
||||
class UltraQuantEncoded:
|
||||
"""Encoded ultraquant representation of one tensor along its last axis.
|
||||
|
||||
Shapes assume input shape `[..., D]`:
|
||||
- codes_packed: `[..., D // 2]` uint8 — 2 FP4 nibbles per byte
|
||||
- scale_bytes: `[..., D // GROUP_SIZE]` uint8 — E8M0 byte per group
|
||||
Dequant is ``code · 2^(byte - 127)`` (`c` is folded into the byte).
|
||||
"""
|
||||
|
||||
codes_packed: torch.Tensor # uint8, [..., D//2]
|
||||
scale_bytes: torch.Tensor # uint8, [..., D//GROUP_SIZE]
|
||||
|
||||
@property
|
||||
def scales_fp32(self) -> torch.Tensor:
|
||||
"""Decode the E8M0 bytes back to fp32 (for dequant / inspection)."""
|
||||
b = self.scale_bytes.to(torch.int32)
|
||||
exp = b - UE8M0_BIAS
|
||||
is_zero = b == 0
|
||||
s = torch.where(
|
||||
is_zero,
|
||||
torch.zeros_like(b, dtype=torch.float32),
|
||||
torch.exp2(exp.to(torch.float32)),
|
||||
)
|
||||
return s
|
||||
|
||||
|
||||
def ultraquant_encode(
|
||||
x: torch.Tensor,
|
||||
*,
|
||||
rotate: bool = True,
|
||||
constant_c: float | None = None,
|
||||
) -> UltraQuantEncoded:
|
||||
"""Encode `x` (shape [..., D]) to FP4 codes + E8M0 per-group-of-32 scales.
|
||||
|
||||
Steps:
|
||||
1. Optional Hadamard rotation: `x_rot = x @ H.T`
|
||||
2. Reshape to `[..., G, GROUP_SIZE]`.
|
||||
3. `absmax = max(|x_rot|)` per group.
|
||||
4. `s_raw = c · absmax`; `s_snapped = 2^round(log2(s_raw))`.
|
||||
Zero-amax groups encode byte=0.
|
||||
5. `sorted_idx = bucketize(x_g / s_snapped, midpoints)` ∈ [0, 14].
|
||||
6. Remap sorted_idx → FP4 E2M1 bit pattern via SORTED_TO_BITS.
|
||||
7. Pack pairs of 4-bit codes into bytes.
|
||||
"""
|
||||
if x.shape[-1] % GROUP_SIZE != 0:
|
||||
raise ValueError(
|
||||
f"ultraquant_encode: last dim {x.shape[-1]} must be a multiple of "
|
||||
f"GROUP_SIZE={GROUP_SIZE}"
|
||||
)
|
||||
D = x.shape[-1]
|
||||
G = D // GROUP_SIZE
|
||||
c = constant_c if constant_c is not None else get_constant_c()
|
||||
|
||||
x_f32 = x.to(torch.float32)
|
||||
if rotate:
|
||||
H = hadamard_matrix(D, x.device, torch.float32)
|
||||
x_rot = x_f32 @ H.T
|
||||
else:
|
||||
x_rot = x_f32
|
||||
|
||||
x_g = x_rot.reshape(*x.shape[:-1], G, GROUP_SIZE)
|
||||
absmax = x_g.abs().amax(dim=-1, keepdim=True) # [..., G, 1]
|
||||
s_raw = absmax * c
|
||||
s_snapped, scale_bytes = _ue8m0_snap_tensor(s_raw.squeeze(-1))
|
||||
s_snapped = s_snapped.unsqueeze(-1) # [..., G, 1]
|
||||
s_for_div = torch.where(s_snapped == 0, torch.ones_like(s_snapped), s_snapped)
|
||||
|
||||
sorted_idx = _snap_to_sorted_idx(x_g / s_for_div)
|
||||
sorted_idx = torch.where(
|
||||
(s_snapped == 0).expand_as(sorted_idx),
|
||||
torch.full_like(sorted_idx, 7), # sorted idx 7 → +0.0
|
||||
sorted_idx,
|
||||
)
|
||||
|
||||
sorted_to_bits = _get_sorted_to_bits(x.device)
|
||||
fp4_bits = sorted_to_bits[sorted_idx] # [..., G, GS]
|
||||
fp4_bits_flat = fp4_bits.reshape(*x.shape[:-1], D)
|
||||
codes_packed = _pack_nibbles_last_dim(fp4_bits_flat) # [..., D//2]
|
||||
|
||||
return UltraQuantEncoded(
|
||||
codes_packed=codes_packed,
|
||||
scale_bytes=scale_bytes,
|
||||
)
|
||||
|
||||
|
||||
def ultraquant_dequant(
|
||||
encoded: UltraQuantEncoded,
|
||||
head_dim: int,
|
||||
) -> torch.Tensor:
|
||||
"""Decode `encoded` to fp32 (no inverse rotation — result in the
|
||||
rotated basis if rotation was applied at encode).
|
||||
|
||||
Dequant is ``code · 2^(byte - 127)`` (`c` is already folded into the byte).
|
||||
"""
|
||||
G = head_dim // GROUP_SIZE
|
||||
codes = _unpack_nibbles_last_dim(encoded.codes_packed, head_dim)
|
||||
bits_to_val = torch.tensor(
|
||||
[
|
||||
0.0,
|
||||
0.5,
|
||||
1.0,
|
||||
1.5,
|
||||
2.0,
|
||||
3.0,
|
||||
4.0,
|
||||
6.0,
|
||||
-0.0,
|
||||
-0.5,
|
||||
-1.0,
|
||||
-1.5,
|
||||
-2.0,
|
||||
-3.0,
|
||||
-4.0,
|
||||
-6.0,
|
||||
],
|
||||
device=encoded.codes_packed.device,
|
||||
dtype=torch.float32,
|
||||
)
|
||||
decoded = bits_to_val[codes.to(torch.long)] # [..., D] fp32
|
||||
decoded_g = decoded.reshape(*decoded.shape[:-1], G, GROUP_SIZE)
|
||||
scales = encoded.scales_fp32.unsqueeze(-1) # [..., G, 1]
|
||||
return (decoded_g * scales).reshape(*decoded.shape[:-1], head_dim)
|
||||
|
||||
|
||||
def ultraquant_encode_decode(
|
||||
x: torch.Tensor,
|
||||
*,
|
||||
rotate: bool = True,
|
||||
constant_c: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""Full encode→decode round-trip in the rotated basis. Returns fp32."""
|
||||
enc = ultraquant_encode(
|
||||
x,
|
||||
rotate=rotate,
|
||||
constant_c=constant_c,
|
||||
)
|
||||
return ultraquant_dequant(enc, x.shape[-1])
|
||||
|
||||
|
||||
# ── Reference attention against the ultraquant encoded cache ──────────────────
|
||||
def reference_ultraquant_attention(
|
||||
query: torch.Tensor, # [B, Hq, D] bf16 — RAW (will be rotated + cast to FP8 here)
|
||||
key: torch.Tensor, # [B, N, Hk, D] bf16
|
||||
value: torch.Tensor, # [B, N, Hk, D] bf16
|
||||
*,
|
||||
scale: float,
|
||||
sinks: torch.Tensor | None = None,
|
||||
constant_c: float | None = None,
|
||||
) -> torch.Tensor:
|
||||
"""End-to-end reference attention with ultraquant K/V encode→decode in
|
||||
the rotated basis. Q is Hadamard-rotated AND cast through FP8 E4M3
|
||||
(scale = 1) before the QK matmul — mirrors what the launcher does.
|
||||
|
||||
Output shape: [B, Hq, D] in query.dtype.
|
||||
"""
|
||||
B, Hq, D = query.shape
|
||||
B2, N, Hk, D2 = key.shape
|
||||
assert B == B2 and D == D2, (B, B2, D, D2)
|
||||
assert value.shape == key.shape
|
||||
assert Hq % Hk == 0, f"Hq={Hq} must be a multiple of Hk={Hk}"
|
||||
g = Hq // Hk
|
||||
|
||||
H = hadamard_matrix(D, query.device, torch.float32)
|
||||
q_rot = query.to(torch.float32) @ H.T
|
||||
# Round-trip Q through FP8 E4M3 with scale=1 — same precision haircut
|
||||
# as the launcher (`q_rot.to(torch.float8_e4m3fn)`).
|
||||
q_fp8 = q_rot.to(torch.float8_e4m3fn)
|
||||
q_for_matmul = q_fp8.to(torch.float32)
|
||||
|
||||
k_recon_rot = ultraquant_encode_decode(
|
||||
key.transpose(1, 2).contiguous(),
|
||||
rotate=True,
|
||||
constant_c=constant_c,
|
||||
)
|
||||
v_recon = ultraquant_encode_decode(
|
||||
value.transpose(1, 2).contiguous(),
|
||||
rotate=False,
|
||||
constant_c=constant_c,
|
||||
)
|
||||
|
||||
k_recon_rot = k_recon_rot.unsqueeze(2).expand(B, Hk, g, N, D).reshape(B, Hq, N, D)
|
||||
v_recon = v_recon.unsqueeze(2).expand(B, Hk, g, N, D).reshape(B, Hq, N, D)
|
||||
|
||||
qk = torch.einsum("bhd,bhnd->bhn", q_for_matmul, k_recon_rot) * scale # [B, Hq, N]
|
||||
|
||||
if sinks is not None:
|
||||
sink_log = sinks.to(torch.float32).reshape(1, Hq, 1).expand(B, Hq, 1)
|
||||
qk_full = torch.cat([qk, sink_log], dim=-1)
|
||||
p_full = torch.softmax(qk_full, dim=-1)
|
||||
p = p_full[..., :N]
|
||||
else:
|
||||
p = torch.softmax(qk, dim=-1)
|
||||
|
||||
out = torch.einsum("bhn,bhnd->bhd", p, v_recon)
|
||||
return out.to(query.dtype)
|
||||
@@ -0,0 +1,190 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Full KV dequant for the UltraQuant cache format.
|
||||
|
||||
Used by continuation prefill: when a chunk brings many new query tokens on
|
||||
top of a long cached prefix, dequanting the prefix once and running a dense
|
||||
prefill kernel beats replaying the decode kernel per query token.
|
||||
|
||||
Reads FP4 codes plus UE8M0 group scales and writes K (Hadamard-rotated, as
|
||||
stored) and V (raw) into pre-allocated fp16/bf16 buffers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.ops.ultraquant.format import (
|
||||
FP4_BITS_TO_VALUE,
|
||||
UE8M0_BIAS,
|
||||
get_group_size,
|
||||
k_scales_offset,
|
||||
n_groups,
|
||||
v_codes_offset,
|
||||
v_scales_offset,
|
||||
)
|
||||
from vllm.v1.attention.ops.ultraquant.triton_store import _kv_cache_flat
|
||||
|
||||
_FP4_DECODE_CACHE: dict[tuple[torch.device, torch.dtype], torch.Tensor] = {}
|
||||
|
||||
|
||||
def _get_fp4_decode_table(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
||||
"""16-entry FP4 E2M1 bit-pattern -> value table (cached per device)."""
|
||||
key = (device, dtype)
|
||||
t = _FP4_DECODE_CACHE.get(key)
|
||||
if t is None:
|
||||
t = torch.tensor(FP4_BITS_TO_VALUE, device=device, dtype=dtype).contiguous()
|
||||
_FP4_DECODE_CACHE[key] = t
|
||||
return t
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _ultraquant_full_dequant_kv(
|
||||
KV_cache_ptr, # uint8 view, flat
|
||||
Block_table_ptr, # [B, max_num_blocks] int32
|
||||
Fp4_decode_ptr, # [16] FP4 bit pattern -> value
|
||||
K_out_ptr,
|
||||
V_out_ptr,
|
||||
stride_ko_b: tl.int64,
|
||||
stride_ko_h: tl.int64,
|
||||
stride_ko_s: tl.int64,
|
||||
stride_vo_b: tl.int64,
|
||||
stride_vo_h: tl.int64,
|
||||
stride_vo_s: tl.int64,
|
||||
stride_cache_block: tl.int64,
|
||||
stride_cache_pos: tl.int64,
|
||||
stride_cache_head: tl.int64,
|
||||
stride_bt_b: tl.int64,
|
||||
HEAD_DIM: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
NUM_KV_HEADS: tl.constexpr,
|
||||
K_SCALES_OFFSET: tl.constexpr,
|
||||
V_CODES_OFFSET: tl.constexpr,
|
||||
V_SCALES_OFFSET: tl.constexpr,
|
||||
GROUP_SIZE_C: tl.constexpr,
|
||||
N_GROUPS_C: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
OUT_BF16: tl.constexpr,
|
||||
UE8M0_BIAS_C: tl.constexpr,
|
||||
):
|
||||
pos = tl.program_id(0)
|
||||
bh = tl.program_id(1)
|
||||
bid = bh // NUM_KV_HEADS
|
||||
hid = bh % NUM_KV_HEADS
|
||||
|
||||
page_idx = pos // BLOCK_SIZE
|
||||
page_off = pos % BLOCK_SIZE
|
||||
block_num = tl.load(Block_table_ptr + bid * stride_bt_b + page_idx).to(tl.int64)
|
||||
slot_base = (
|
||||
block_num * stride_cache_block
|
||||
+ page_off * stride_cache_pos
|
||||
+ tl.cast(hid, tl.int64) * stride_cache_head
|
||||
)
|
||||
|
||||
d_offs = tl.arange(0, BLOCK_D)
|
||||
d_mask = d_offs < HEAD_DIM
|
||||
byte_idx = (d_offs // 2).to(tl.int32)
|
||||
nibble_shift = ((d_offs % 2) * 4).to(tl.int32)
|
||||
g_offs = tl.arange(0, N_GROUPS_C)
|
||||
|
||||
out_dtype = tl.bfloat16 if OUT_BF16 else tl.float16
|
||||
|
||||
# K side: codes are packed nibbles, one UE8M0 byte per group of 32.
|
||||
k_byte_raw = tl.load(KV_cache_ptr + slot_base + byte_idx, mask=d_mask, other=0).to(
|
||||
tl.int32
|
||||
)
|
||||
k_codes = (k_byte_raw >> nibble_shift) & 0xF
|
||||
k_dec = tl.load(Fp4_decode_ptr + k_codes).to(tl.float32)
|
||||
k_dec = tl.where(d_mask, k_dec, 0.0)
|
||||
|
||||
# UE8M0 scale: value = 2^(byte - bias); byte == 0 encodes exact zero.
|
||||
k_scale_bytes = tl.load(KV_cache_ptr + slot_base + K_SCALES_OFFSET + g_offs).to(
|
||||
tl.int32
|
||||
)
|
||||
k_scales = tl.where(
|
||||
k_scale_bytes == 0,
|
||||
0.0,
|
||||
tl.exp2(tl.cast(k_scale_bytes - UE8M0_BIAS_C, tl.float32)),
|
||||
)
|
||||
|
||||
k_g = tl.reshape(k_dec, [N_GROUPS_C, GROUP_SIZE_C])
|
||||
k_recon = tl.reshape(k_g * k_scales[:, None], [BLOCK_D])
|
||||
k_recon = tl.where(d_mask, k_recon, 0.0)
|
||||
|
||||
ko_base = bid * stride_ko_b + hid * stride_ko_h + pos * stride_ko_s
|
||||
tl.store(K_out_ptr + ko_base + d_offs, k_recon.to(out_dtype), mask=d_mask)
|
||||
|
||||
# V side mirrors K but is stored unrotated.
|
||||
v_byte_raw = tl.load(
|
||||
KV_cache_ptr + slot_base + V_CODES_OFFSET + byte_idx,
|
||||
mask=d_mask,
|
||||
other=0,
|
||||
).to(tl.int32)
|
||||
v_codes = (v_byte_raw >> nibble_shift) & 0xF
|
||||
v_dec = tl.load(Fp4_decode_ptr + v_codes).to(tl.float32)
|
||||
v_dec = tl.where(d_mask, v_dec, 0.0)
|
||||
|
||||
v_scale_bytes = tl.load(KV_cache_ptr + slot_base + V_SCALES_OFFSET + g_offs).to(
|
||||
tl.int32
|
||||
)
|
||||
v_scales = tl.where(
|
||||
v_scale_bytes == 0,
|
||||
0.0,
|
||||
tl.exp2(tl.cast(v_scale_bytes - UE8M0_BIAS_C, tl.float32)),
|
||||
)
|
||||
|
||||
v_g = tl.reshape(v_dec, [N_GROUPS_C, GROUP_SIZE_C])
|
||||
v_recon = tl.reshape(v_g * v_scales[:, None], [BLOCK_D])
|
||||
v_recon = tl.where(d_mask, v_recon, 0.0)
|
||||
|
||||
vo_base = bid * stride_vo_b + hid * stride_vo_h + pos * stride_vo_s
|
||||
tl.store(V_out_ptr + vo_base + d_offs, v_recon.to(out_dtype), mask=d_mask)
|
||||
|
||||
|
||||
def ultraquant_full_dequant_kv(
|
||||
kv_cache: torch.Tensor,
|
||||
block_table: torch.Tensor,
|
||||
k_out: torch.Tensor,
|
||||
v_out: torch.Tensor,
|
||||
alloc_len: int,
|
||||
) -> None:
|
||||
"""Dequant ``alloc_len`` cached positions into ``k_out`` / ``v_out``.
|
||||
|
||||
``k_out`` / ``v_out`` are ``[B, Hk, alloc_len, D]`` in fp16 or bf16.
|
||||
"""
|
||||
B = block_table.shape[0]
|
||||
Hk = kv_cache.shape[2]
|
||||
D = k_out.shape[3]
|
||||
block_size = kv_cache.shape[1]
|
||||
|
||||
gs = get_group_size()
|
||||
_ultraquant_full_dequant_kv[(alloc_len, B * Hk)](
|
||||
_kv_cache_flat(kv_cache),
|
||||
block_table,
|
||||
_get_fp4_decode_table(kv_cache.device, k_out.dtype),
|
||||
k_out,
|
||||
v_out,
|
||||
k_out.stride(0),
|
||||
k_out.stride(1),
|
||||
k_out.stride(2),
|
||||
v_out.stride(0),
|
||||
v_out.stride(1),
|
||||
v_out.stride(2),
|
||||
kv_cache.stride(0),
|
||||
kv_cache.stride(1),
|
||||
kv_cache.stride(2),
|
||||
block_table.stride(0),
|
||||
HEAD_DIM=D,
|
||||
BLOCK_SIZE=block_size,
|
||||
NUM_KV_HEADS=Hk,
|
||||
K_SCALES_OFFSET=k_scales_offset(D, gs),
|
||||
V_CODES_OFFSET=v_codes_offset(D, gs),
|
||||
V_SCALES_OFFSET=v_scales_offset(D, gs),
|
||||
GROUP_SIZE_C=gs,
|
||||
N_GROUPS_C=n_groups(D, gs),
|
||||
BLOCK_D=triton.next_power_of_2(D),
|
||||
OUT_BF16=1 if k_out.dtype == torch.bfloat16 else 0,
|
||||
UE8M0_BIAS_C=UE8M0_BIAS,
|
||||
num_warps=4,
|
||||
)
|
||||
@@ -0,0 +1,351 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Triton store kernel for the ultraquant KV cache format.
|
||||
|
||||
Per-token, per-head, per-group-of-32 the kernel computes:
|
||||
|
||||
s_raw = c * absmax(group) # c = 0.156 by default
|
||||
s = 2^round(log2(s_raw)) # UE8M0 snap (power of 2)
|
||||
code = quantize_to_fp4(group / s) # OCP E2M1, 4 bits/elt
|
||||
|
||||
and stores ``code`` as packed nibbles + ``s`` as a single UE8M0 byte per
|
||||
group. The output layout matches ``format.py`` (272 B/slot for D=256).
|
||||
|
||||
K is Hadamard-rotated in-register; V is not. There is no per-token L2
|
||||
norm. The UE8M0 snap makes ``s`` a power of two so scaled F8F6F4 MFMA
|
||||
can consume it on the read side.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.attention.ops.ultraquant.format import (
|
||||
MIDPOINTS_SORTED,
|
||||
SORTED_TO_BITS,
|
||||
UE8M0_BIAS,
|
||||
get_constant_c,
|
||||
get_group_size,
|
||||
k_scales_offset,
|
||||
n_groups,
|
||||
slot_size,
|
||||
v_codes_offset,
|
||||
v_scales_offset,
|
||||
)
|
||||
|
||||
|
||||
def _kv_cache_flat(kv_cache: torch.Tensor) -> torch.Tensor:
|
||||
"""1-D uint8 view of the raw KV allocation (handles padded layouts)."""
|
||||
if kv_cache.is_contiguous():
|
||||
return kv_cache.reshape(-1)
|
||||
n = kv_cache.untyped_storage().nbytes() // kv_cache.element_size()
|
||||
return torch.empty(0, dtype=kv_cache.dtype, device=kv_cache.device).set_(
|
||||
kv_cache.untyped_storage(), 0, (n,)
|
||||
)
|
||||
|
||||
|
||||
_SUPPORTED_DTYPES = {torch.float16, torch.bfloat16}
|
||||
|
||||
# Built lazily on first launch so importing this module does not require triton.
|
||||
_MIDPOINTS_C: Any = None
|
||||
|
||||
|
||||
def _ensure_const_tables() -> None:
|
||||
global _MIDPOINTS_C
|
||||
if _MIDPOINTS_C is None:
|
||||
_MIDPOINTS_C = tl.constexpr(tuple(float(m) for m in MIDPOINTS_SORTED))
|
||||
|
||||
|
||||
# ── Cached per-device constant tensors ─────────────────────────────────────
|
||||
_MIDPOINTS_CACHE: dict[torch.device, torch.Tensor] = {}
|
||||
_SORTED_TO_BITS_CACHE: dict[torch.device, torch.Tensor] = {}
|
||||
_PIT_CACHE: dict[tuple[int, torch.device, torch.dtype], torch.Tensor] = {}
|
||||
|
||||
|
||||
def _get_midpoints_tensor(device: torch.device) -> torch.Tensor:
|
||||
t = _MIDPOINTS_CACHE.get(device)
|
||||
if t is None:
|
||||
t = torch.tensor(MIDPOINTS_SORTED, device=device, dtype=torch.float32)
|
||||
_MIDPOINTS_CACHE[device] = t
|
||||
return t
|
||||
|
||||
|
||||
def _get_sorted_to_bits_tensor(device: torch.device) -> torch.Tensor:
|
||||
t = _SORTED_TO_BITS_CACHE.get(device)
|
||||
if t is None:
|
||||
t = torch.tensor(SORTED_TO_BITS, device=device, dtype=torch.int32)
|
||||
_SORTED_TO_BITS_CACHE[device] = t
|
||||
return t
|
||||
|
||||
|
||||
def _get_hadamard(
|
||||
dim: int, device: torch.device, dtype: torch.dtype = torch.float32
|
||||
) -> torch.Tensor:
|
||||
"""Sylvester Hadamard in fp32 (cached, normalised)."""
|
||||
key = (dim, device, dtype)
|
||||
cached = _PIT_CACHE.get(key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
if dim <= 0 or (dim & (dim - 1)) != 0:
|
||||
raise ValueError(f"ultraquant store requires power-of-two dim, got {dim}")
|
||||
H = torch.tensor([[1.0]], dtype=torch.float64)
|
||||
while H.shape[0] < dim:
|
||||
H = torch.cat([torch.cat([H, H], dim=1), torch.cat([H, -H], dim=1)], dim=0)
|
||||
H = (H / (dim**0.5)).to(device=device, dtype=dtype).contiguous()
|
||||
_PIT_CACHE[key] = H
|
||||
return H
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Triton kernel
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _ultraquant_store_kernel(
|
||||
Key_ptr, # [N*H, D] in raw dtype (bf16 or fp16)
|
||||
Value_ptr, # [N*H, D] in raw dtype
|
||||
KV_cache_ptr, # raw uint8 view, flat
|
||||
Slot_mapping_ptr, # [N] int64
|
||||
Midpoints_ptr, # [14] fp32
|
||||
SortedToBits_ptr, # [15] int32
|
||||
# Cache strides (in bytes)
|
||||
stride_cache_block: tl.constexpr,
|
||||
stride_cache_pos: tl.constexpr,
|
||||
stride_cache_head: tl.constexpr,
|
||||
# Dimensions
|
||||
HEAD_DIM: tl.constexpr,
|
||||
H: tl.constexpr,
|
||||
BLOCK_SIZE: tl.constexpr,
|
||||
BLOCK_D: tl.constexpr,
|
||||
LOG2_D: tl.constexpr,
|
||||
# Layout
|
||||
GROUP_SIZE_C: tl.constexpr,
|
||||
N_GROUPS_C: tl.constexpr,
|
||||
K_SCALES_OFFSET: tl.constexpr,
|
||||
V_CODES_OFFSET: tl.constexpr,
|
||||
V_SCALES_OFFSET: tl.constexpr,
|
||||
FP4_C: tl.constexpr,
|
||||
UE8M0_BIAS_C: tl.constexpr,
|
||||
# When 1, the FP4 midpoints and the sorted->bits remap are materialised as
|
||||
# immediates instead of being read from `Midpoints_ptr`/`SortedToBits_ptr`.
|
||||
# That removes 28 scalar global loads and two 256-lane divergent gathers
|
||||
# from the critical path of a kernel whose runtime is pure latency (flat at
|
||||
# ~22 us from batch 1 to batch 64). Numerically identical: the immediates
|
||||
# are the same fp32 values, and the remap formula is exact (asserted in
|
||||
# `format`, verified for all 15 entries).
|
||||
CONST_TABLES: tl.constexpr = 1,
|
||||
):
|
||||
pid = tl.program_id(0)
|
||||
token_idx = pid // H
|
||||
head_idx = pid % H
|
||||
|
||||
slot = tl.load(Slot_mapping_ptr + token_idx)
|
||||
if slot < 0:
|
||||
return
|
||||
blk = slot // BLOCK_SIZE
|
||||
off = slot % BLOCK_SIZE
|
||||
slot_base = (
|
||||
blk * stride_cache_block + off * stride_cache_pos + head_idx * stride_cache_head
|
||||
).to(tl.int64)
|
||||
k_code_base = slot_base
|
||||
k_scale_base = slot_base + K_SCALES_OFFSET
|
||||
v_code_base = slot_base + V_CODES_OFFSET
|
||||
v_scale_base = slot_base + V_SCALES_OFFSET
|
||||
|
||||
base = pid * HEAD_DIM
|
||||
d_offs = tl.arange(0, BLOCK_D)
|
||||
d_mask = d_offs < HEAD_DIM
|
||||
shifts_4 = tl.arange(0, 2) * 4 # 0, 4 for nibble packing
|
||||
g_offs = tl.arange(0, N_GROUPS_C)
|
||||
|
||||
# ── K side ─────────────────────────────────────────────────────────
|
||||
# 1. Load + Hadamard-rotate K via WHT butterfly.
|
||||
k_raw = tl.load(Key_ptr + base + d_offs, mask=d_mask, other=0.0).to(tl.float32)
|
||||
k_rot = tl.where(d_mask, k_raw, 0.0)
|
||||
|
||||
INV_SQRT2: tl.constexpr = 0.7071067811865476
|
||||
for _stage in tl.static_range(LOG2_D):
|
||||
_bmask = 1 << _stage
|
||||
_pidx = (d_offs ^ _bmask).to(tl.int32)
|
||||
_pval = tl.gather(k_rot, _pidx, 0)
|
||||
_sign = tl.where((d_offs & _bmask) == 0, 1.0, -1.0).to(tl.float32)
|
||||
k_rot = (_sign * k_rot + _pval) * INV_SQRT2
|
||||
k_rot = tl.where(d_mask, k_rot, 0.0)
|
||||
|
||||
# 2. Per-group absmax.
|
||||
k_g = tl.reshape(k_rot, [N_GROUPS_C, GROUP_SIZE_C])
|
||||
k_absmax = tl.max(tl.abs(k_g), axis=1) # [N_GROUPS]
|
||||
k_is_zero = k_absmax == 0.0
|
||||
|
||||
# 3. UE8M0 snap: s_raw = c * absmax; exp = round(log2(s_raw));
|
||||
# divisor = 2^exp (c folded in). Zero groups write byte=0.
|
||||
k_s_raw = k_absmax * tl.cast(FP4_C, tl.float32)
|
||||
k_s_safe = tl.where(k_is_zero, 1.0, k_s_raw)
|
||||
k_log2 = tl.log2(k_s_safe)
|
||||
k_exp = tl.cast(tl.floor(k_log2 + 0.5), tl.int32) # round-half-up
|
||||
k_s_snapped = tl.exp2(tl.cast(k_exp, tl.float32))
|
||||
k_s_div = tl.where(k_is_zero, 1.0, k_s_snapped)
|
||||
|
||||
# 4. Normalize + snap to sorted FP4 idx via 14 sequential tl.where (`>` for
|
||||
# bucketize(right=False) parity with the reference).
|
||||
k_norm = k_g / k_s_div[:, None]
|
||||
k_sorted = tl.zeros([N_GROUPS_C, GROUP_SIZE_C], dtype=tl.int32)
|
||||
for i in tl.static_range(14):
|
||||
mid = _MIDPOINTS_C.value[i] if CONST_TABLES else tl.load(Midpoints_ptr + i)
|
||||
k_sorted += tl.where(k_norm > mid, 1, 0)
|
||||
k_sorted = tl.where(k_is_zero[:, None], 7, k_sorted)
|
||||
|
||||
# 5. Remap sorted idx → FP4 E2M1 bit pattern.
|
||||
if CONST_TABLES:
|
||||
k_bits = tl.where(k_sorted < 7, 15 - k_sorted, k_sorted - 7)
|
||||
else:
|
||||
k_bits = tl.load(SortedToBits_ptr + k_sorted)
|
||||
|
||||
# 6. Pack pairs of 4-bit codes into uint8 bytes.
|
||||
k_bits_flat = tl.reshape(k_bits, [HEAD_DIM])
|
||||
k_pairs = tl.reshape(k_bits_flat, [HEAD_DIM // 2, 2])
|
||||
k_packed = tl.sum((k_pairs & 0xF) << shifts_4[None, :], axis=1).to(tl.uint8)
|
||||
k_code_addrs = k_code_base + tl.arange(0, HEAD_DIM // 2)
|
||||
tl.store(KV_cache_ptr + k_code_addrs, k_packed)
|
||||
|
||||
# 7. Store K scales as E8M0 bytes (one per group). Zero-amax groups
|
||||
# write byte=0 (zero sentinel).
|
||||
k_byte = tl.where(k_is_zero, 0, k_exp + UE8M0_BIAS_C)
|
||||
k_byte = tl.where((k_byte < 0) | (k_byte > 255), 0, k_byte).to(tl.uint8)
|
||||
k_scale_addrs = k_scale_base + g_offs
|
||||
tl.store(KV_cache_ptr + k_scale_addrs, k_byte)
|
||||
|
||||
# ── V side (mirror K but skip rotation) ────────────────────────────
|
||||
v_raw = tl.load(Value_ptr + base + d_offs, mask=d_mask, other=0.0).to(tl.float32)
|
||||
v_raw = tl.where(d_mask, v_raw, 0.0)
|
||||
|
||||
v_g = tl.reshape(v_raw, [N_GROUPS_C, GROUP_SIZE_C])
|
||||
v_absmax = tl.max(tl.abs(v_g), axis=1)
|
||||
v_is_zero = v_absmax == 0.0
|
||||
|
||||
v_s_raw = v_absmax * tl.cast(FP4_C, tl.float32)
|
||||
v_s_safe = tl.where(v_is_zero, 1.0, v_s_raw)
|
||||
v_log2 = tl.log2(v_s_safe)
|
||||
v_exp = tl.cast(tl.floor(v_log2 + 0.5), tl.int32)
|
||||
v_s_snapped = tl.exp2(tl.cast(v_exp, tl.float32))
|
||||
v_s_div = tl.where(v_is_zero, 1.0, v_s_snapped)
|
||||
|
||||
v_norm = v_g / v_s_div[:, None]
|
||||
v_sorted = tl.zeros([N_GROUPS_C, GROUP_SIZE_C], dtype=tl.int32)
|
||||
for i in tl.static_range(14):
|
||||
mid = _MIDPOINTS_C.value[i] if CONST_TABLES else tl.load(Midpoints_ptr + i)
|
||||
v_sorted += tl.where(v_norm > mid, 1, 0)
|
||||
v_sorted = tl.where(v_is_zero[:, None], 7, v_sorted)
|
||||
|
||||
if CONST_TABLES:
|
||||
v_bits = tl.where(v_sorted < 7, 15 - v_sorted, v_sorted - 7)
|
||||
else:
|
||||
v_bits = tl.load(SortedToBits_ptr + v_sorted)
|
||||
v_bits_flat = tl.reshape(v_bits, [HEAD_DIM])
|
||||
v_pairs = tl.reshape(v_bits_flat, [HEAD_DIM // 2, 2])
|
||||
v_packed = tl.sum((v_pairs & 0xF) << shifts_4[None, :], axis=1).to(tl.uint8)
|
||||
v_code_addrs = v_code_base + tl.arange(0, HEAD_DIM // 2)
|
||||
tl.store(KV_cache_ptr + v_code_addrs, v_packed)
|
||||
|
||||
v_byte = tl.where(v_is_zero, 0, v_exp + UE8M0_BIAS_C)
|
||||
v_byte = tl.where((v_byte < 0) | (v_byte > 255), 0, v_byte).to(tl.uint8)
|
||||
v_scale_addrs = v_scale_base + g_offs
|
||||
tl.store(KV_cache_ptr + v_scale_addrs, v_byte)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Launcher
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
def ultraquant_store(
|
||||
key: torch.Tensor, # [N, H, D] bf16 or fp16
|
||||
value: torch.Tensor, # [N, H, D] bf16 or fp16
|
||||
kv_cache: torch.Tensor, # [num_blocks, block_size, Hk, slot_size_aligned] uint8
|
||||
slot_mapping: torch.Tensor, # [N] int64
|
||||
*,
|
||||
PiT: torch.Tensor | None = None, # unused; kept for call-site compatibility
|
||||
constant_c: float | None = None,
|
||||
) -> None:
|
||||
"""Launch the ultraquant store kernel. Writes K/V into `kv_cache`
|
||||
in-place at the slots specified by `slot_mapping`."""
|
||||
if key.dtype not in _SUPPORTED_DTYPES:
|
||||
raise ValueError(
|
||||
f"ultraquant_store: key.dtype must be one of "
|
||||
f"{_SUPPORTED_DTYPES}, got {key.dtype}"
|
||||
)
|
||||
if value.dtype != key.dtype:
|
||||
raise ValueError(
|
||||
f"ultraquant_store: key/value dtype mismatch ({key.dtype} vs {value.dtype})"
|
||||
)
|
||||
if slot_mapping.dtype != torch.int64:
|
||||
slot_mapping = slot_mapping.to(torch.int64)
|
||||
|
||||
N, H, D = key.shape
|
||||
NH = N * H
|
||||
block_size = kv_cache.shape[1]
|
||||
num_kv_heads = kv_cache.shape[2]
|
||||
padded_slot = kv_cache.shape[3]
|
||||
|
||||
expected_slot = slot_size(D)
|
||||
if padded_slot < expected_slot:
|
||||
raise ValueError(
|
||||
f"ultraquant_store: kv_cache slot {padded_slot} < expected "
|
||||
f"{expected_slot} for head_dim={D}"
|
||||
)
|
||||
if num_kv_heads != H:
|
||||
raise ValueError(
|
||||
f"ultraquant_store: kv_cache num_kv_heads {num_kv_heads} != key heads {H}"
|
||||
)
|
||||
|
||||
midpoints = _get_midpoints_tensor(key.device)
|
||||
sorted_to_bits = _get_sorted_to_bits_tensor(key.device)
|
||||
|
||||
k_flat = key.reshape(NH, D).contiguous()
|
||||
v_flat = value.reshape(NH, D).contiguous()
|
||||
|
||||
gs = get_group_size()
|
||||
BLOCK_D = triton.next_power_of_2(D)
|
||||
N_GROUPS_C = n_groups(D, gs)
|
||||
K_SCALES_OFFSET = k_scales_offset(D, gs)
|
||||
V_CODES_OFFSET = v_codes_offset(D, gs)
|
||||
V_SCALES_OFFSET = v_scales_offset(D, gs)
|
||||
|
||||
stride_block = kv_cache.stride(0)
|
||||
stride_pos = kv_cache.stride(1)
|
||||
stride_head = kv_cache.stride(2)
|
||||
|
||||
c = constant_c if constant_c is not None else get_constant_c()
|
||||
|
||||
_ensure_const_tables()
|
||||
grid = (NH,)
|
||||
_ultraquant_store_kernel[grid](
|
||||
k_flat,
|
||||
v_flat,
|
||||
_kv_cache_flat(kv_cache),
|
||||
slot_mapping,
|
||||
midpoints,
|
||||
sorted_to_bits,
|
||||
stride_cache_block=stride_block,
|
||||
stride_cache_pos=stride_pos,
|
||||
stride_cache_head=stride_head,
|
||||
HEAD_DIM=D,
|
||||
H=H,
|
||||
BLOCK_SIZE=block_size,
|
||||
BLOCK_D=BLOCK_D,
|
||||
LOG2_D=int(D).bit_length() - 1,
|
||||
GROUP_SIZE_C=gs,
|
||||
N_GROUPS_C=N_GROUPS_C,
|
||||
K_SCALES_OFFSET=K_SCALES_OFFSET,
|
||||
V_CODES_OFFSET=V_CODES_OFFSET,
|
||||
V_SCALES_OFFSET=V_SCALES_OFFSET,
|
||||
FP4_C=c,
|
||||
UE8M0_BIAS_C=UE8M0_BIAS,
|
||||
CONST_TABLES=1,
|
||||
num_warps=4,
|
||||
num_stages=1,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -479,8 +479,8 @@ class BlockPool:
|
||||
kv_cache_group_id: KV cache group that owns the partial entry.
|
||||
block_size: Cache block size for the owning group. The partial
|
||||
entry hash itself is always the prefix-chain hash at
|
||||
``num_tokens``; ``block_size`` is used to assert that the
|
||||
entry is partial within the owning cache block.
|
||||
``num_tokens``; ``block_size`` must be a multiple of the hash
|
||||
block size.
|
||||
replace_existing_hashes: Whether the block contents were replaced
|
||||
and all existing cache entries must be removed before the new
|
||||
entry is registered.
|
||||
@@ -494,9 +494,6 @@ class BlockPool:
|
||||
return None
|
||||
|
||||
assert block_size % self.hash_block_size == 0
|
||||
assert replace_existing_hashes or (
|
||||
block_size > self.hash_block_size and num_tokens % block_size != 0
|
||||
)
|
||||
block_hash = self._get_partial_block_hash(request, num_tokens)
|
||||
num_hash_blocks = num_tokens // self.hash_block_size
|
||||
block_hash_with_group_id = make_block_hash_with_group_id(
|
||||
@@ -829,7 +826,7 @@ class BlockPool:
|
||||
|
||||
def reset_prefix_cache(self) -> bool:
|
||||
"""Reset prefix cache. This function may be used in RLHF
|
||||
flows to invalid prefix caching after the weights are updated,
|
||||
flows to invalidate prefix caching after the weights are updated,
|
||||
or used for resetting prefix caching status for benchmarking.
|
||||
|
||||
Returns:
|
||||
|
||||
@@ -4,13 +4,14 @@ from abc import ABC, abstractmethod
|
||||
from collections.abc import Sequence
|
||||
from typing import NamedTuple
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv, round_down
|
||||
from vllm.v1.core.block_pool import BlockPool
|
||||
from vllm.v1.core.kv_cache_metrics import KVCacheMetricsCollector
|
||||
from vllm.v1.core.kv_cache_utils import (
|
||||
BlockHash,
|
||||
KVCacheBlock,
|
||||
eagle_proof_margin,
|
||||
partial_hash_hits_enabled,
|
||||
)
|
||||
from vllm.v1.core.single_type_kv_cache_manager import (
|
||||
CrossAttentionManager,
|
||||
@@ -28,8 +29,6 @@ from vllm.v1.kv_cache_interface import (
|
||||
)
|
||||
from vllm.v1.request import Request
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _validate_prefix_cache_retention_interval(
|
||||
retention_interval: int | None,
|
||||
@@ -341,6 +340,14 @@ class KVCacheCoordinator(ABC):
|
||||
extension = request.num_prompt_tokens // block * block
|
||||
return tuple(sorted({max(resend - block, 0), max(extension - block, 0)}))
|
||||
|
||||
def get_num_cacheable_tokens(
|
||||
self, num_computed_tokens: int, kv_cache_group_id: int
|
||||
) -> int:
|
||||
"""Return the prefix eligible for hashing in this group."""
|
||||
# Only cache tokens with finalized KV. The last num_reprefillable_tokens
|
||||
# tokens can be re-prefilled during multi-module MTP.
|
||||
return max(0, num_computed_tokens - self.num_reprefillable_tokens)
|
||||
|
||||
def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
|
||||
"""Cache the blocks for the request.
|
||||
|
||||
@@ -352,17 +359,12 @@ class KVCacheCoordinator(ABC):
|
||||
|
||||
"""
|
||||
boundaries = self.get_replay_boundaries(request)
|
||||
for manager in self.single_type_managers:
|
||||
for group_id, manager in enumerate(self.single_type_managers):
|
||||
if not manager.enable_caching:
|
||||
continue
|
||||
# Only cache tokens with finalized KV. The last num_reprefillable_tokens
|
||||
# tokens can be re-prefilled during multi-module MTP.
|
||||
num_tokens_to_cache = max(
|
||||
0, num_computed_tokens - self.num_reprefillable_tokens
|
||||
)
|
||||
manager.cache_blocks(
|
||||
request,
|
||||
num_tokens_to_cache,
|
||||
self.get_num_cacheable_tokens(num_computed_tokens, group_id),
|
||||
retention_interval=self.retention_interval,
|
||||
replay_boundaries=boundaries,
|
||||
)
|
||||
@@ -692,37 +694,15 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
# managers in every group. TP needs hashing finer than the Mamba block;
|
||||
# DCP accepts equality because it scales the effective full-attention
|
||||
# block instead.
|
||||
has_partial_mamba_group = any(
|
||||
isinstance(g.kv_cache_spec, MambaSpec)
|
||||
and g.kv_cache_spec.mamba_cache_mode == "align"
|
||||
and (
|
||||
(dcp_world_size == 1 and g.kv_cache_spec.block_size > hash_block_size)
|
||||
or (
|
||||
dcp_world_size > 1 and g.kv_cache_spec.block_size >= hash_block_size
|
||||
)
|
||||
)
|
||||
for g in kv_cache_config.kv_cache_groups
|
||||
)
|
||||
self.enable_partial_hash_hits = (
|
||||
allow_partial_hash_hits and has_partial_mamba_group
|
||||
allow_partial_hash_hits
|
||||
and partial_hash_hits_enabled(
|
||||
kv_cache_config.kv_cache_groups,
|
||||
hash_block_size,
|
||||
dcp_world_size,
|
||||
[type(manager) for manager in self.single_type_managers],
|
||||
)
|
||||
)
|
||||
if self.enable_partial_hash_hits:
|
||||
unsupported_partial_hit_managers = {
|
||||
type(manager).__name__
|
||||
for manager, group in zip(
|
||||
self.single_type_managers, kv_cache_config.kv_cache_groups
|
||||
)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
and not manager.supports_fine_grained_hash_lookup
|
||||
and manager.block_size != hash_block_size
|
||||
}
|
||||
if unsupported_partial_hit_managers:
|
||||
self.enable_partial_hash_hits = False
|
||||
logger.warning_once(
|
||||
"Disabling fine-grained prefix-cache hits because these KV "
|
||||
"cache managers require block-aligned lookups: %s.",
|
||||
", ".join(sorted(unsupported_partial_hit_managers)),
|
||||
)
|
||||
cache_hit_alignment_tokens = self._cache_hit_alignment_tokens
|
||||
for manager in self.single_type_managers:
|
||||
manager.cache_hit_alignment_tokens = cache_hit_alignment_tokens
|
||||
@@ -809,39 +789,22 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
return num_tokens
|
||||
return round_down(num_tokens, self.scheduler_block_size)
|
||||
|
||||
def cache_blocks(self, request: Request, num_computed_tokens: int) -> None:
|
||||
def get_num_cacheable_tokens(
|
||||
self, num_computed_tokens: int, kv_cache_group_id: int
|
||||
) -> int:
|
||||
cached_num_computed_tokens = self._align_cacheable(num_computed_tokens)
|
||||
boundaries = self.get_replay_boundaries(request)
|
||||
for manager in self.single_type_managers:
|
||||
if not manager.enable_caching:
|
||||
continue
|
||||
num_tokens_to_cache = cached_num_computed_tokens
|
||||
# EAGLE groups match one block past each aligned boundary and drop
|
||||
# it, so make that lookahead block eligible to be cached.
|
||||
if manager.use_eagle and cached_num_computed_tokens > 0:
|
||||
# Only cache tokens with finalized KV. The last
|
||||
# num_reprefillable_tokens tokens can be re-prefilled during
|
||||
# multi-module MTP.
|
||||
num_finalized_computed_tokens = max(
|
||||
0, num_computed_tokens - self.num_reprefillable_tokens
|
||||
)
|
||||
cached_num_finalized_computed_tokens = self._align_cacheable(
|
||||
num_finalized_computed_tokens
|
||||
)
|
||||
num_tokens_to_cache = min(
|
||||
num_finalized_computed_tokens,
|
||||
cached_num_finalized_computed_tokens + manager.block_size,
|
||||
)
|
||||
# The manager already knows the fine hit granularity
|
||||
# (``scheduler_block_size``); retention is passed separately so it
|
||||
# can keep both the coarse segment tails and the fine replay
|
||||
# boundary (which needs the fine value).
|
||||
manager.cache_blocks(
|
||||
request,
|
||||
num_tokens_to_cache,
|
||||
retention_interval=self.retention_interval,
|
||||
replay_boundaries=boundaries,
|
||||
manager = self.single_type_managers[kv_cache_group_id]
|
||||
# EAGLE matches one block past the aligned boundary, then drops it.
|
||||
if manager.use_eagle and cached_num_computed_tokens > 0:
|
||||
num_finalized_computed_tokens = max(
|
||||
0, num_computed_tokens - self.num_reprefillable_tokens
|
||||
)
|
||||
return min(
|
||||
num_finalized_computed_tokens,
|
||||
self._align_cacheable(num_finalized_computed_tokens)
|
||||
+ manager.block_size,
|
||||
)
|
||||
return cached_num_computed_tokens
|
||||
|
||||
def find_longest_cache_hit(
|
||||
self,
|
||||
@@ -913,15 +876,15 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
# mamba: its finder never drops (draft models have no mamba
|
||||
# layers), so the hit would grow past the candidate.
|
||||
if drop_eagle_block and not isinstance(spec, MambaSpec):
|
||||
eagle_margin = (
|
||||
self.hash_block_size
|
||||
if self.enable_partial_hash_hits
|
||||
and manager_cls.supports_fine_grained_hash_lookup
|
||||
and group_block_size > self.hash_block_size
|
||||
else group_block_size
|
||||
eagle_margin = eagle_proof_margin(
|
||||
group_block_size,
|
||||
self.hash_block_size,
|
||||
self.enable_partial_hash_hits
|
||||
and manager_cls.supports_fine_grained_hash_lookup,
|
||||
)
|
||||
_max_length = min(
|
||||
curr_hit_length + eagle_margin, max_cache_hit_length
|
||||
curr_hit_length + eagle_margin,
|
||||
len(block_hashes) * self.hash_block_size,
|
||||
)
|
||||
hit_blocks, _new_hit_length = manager_cls.find_longest_cache_hit(
|
||||
block_hashes=block_hashes,
|
||||
@@ -997,9 +960,21 @@ class HybridKVCacheCoordinator(KVCacheCoordinator):
|
||||
|
||||
for spec, group_ids, manager_cls, use_eagle in self.attention_groups:
|
||||
manager = self.single_type_managers[group_ids[0]]
|
||||
lookup_length = max_cache_hit_length
|
||||
if use_eagle and not isinstance(spec, MambaSpec):
|
||||
eagle_margin = eagle_proof_margin(
|
||||
manager.block_size,
|
||||
self.hash_block_size,
|
||||
self.enable_partial_hash_hits
|
||||
and manager_cls.supports_fine_grained_hash_lookup,
|
||||
)
|
||||
lookup_length = min(
|
||||
max_cache_hit_length + eagle_margin,
|
||||
len(block_hashes) * self.hash_block_size,
|
||||
)
|
||||
blocks, group_hit = manager_cls.find_longest_cache_hit(
|
||||
block_hashes=block_hashes,
|
||||
max_length=max_cache_hit_length,
|
||||
max_length=lookup_length,
|
||||
kv_cache_group_ids=group_ids,
|
||||
block_pool=manager.block_pool,
|
||||
kv_cache_spec=spec,
|
||||
|
||||
+125
-36
@@ -53,6 +53,7 @@ from vllm.v1.utils import tensor_data
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.core.block_pool import BlockPool
|
||||
from vllm.v1.core.single_type_kv_cache_manager import SingleTypeKVCacheManager
|
||||
|
||||
|
||||
# BlockHash represents the hash of a single KV-cache block used for
|
||||
@@ -303,19 +304,17 @@ class FreeKVCacheBlockQueue:
|
||||
The first free block.
|
||||
|
||||
"""
|
||||
if (
|
||||
self.fake_free_list_head.next_free_block is self.fake_free_list_tail
|
||||
or self.fake_free_list_head.next_free_block is None
|
||||
):
|
||||
head = self.fake_free_list_head
|
||||
first_block = head.next_free_block
|
||||
if first_block is self.fake_free_list_tail or first_block is None:
|
||||
assert self.num_free_blocks == 0, (
|
||||
f"num_free_blocks ({self.num_free_blocks}) is out of sync "
|
||||
"with the free list."
|
||||
)
|
||||
raise ValueError("No free blocks available")
|
||||
|
||||
first_block: KVCacheBlock = self.fake_free_list_head.next_free_block
|
||||
|
||||
if first_block.next_free_block is None:
|
||||
next_block = first_block.next_free_block
|
||||
if next_block is None:
|
||||
# This should not happen if the block is from the free list.
|
||||
# It indicates a bug in the caller's logic.
|
||||
raise RuntimeError(
|
||||
@@ -325,8 +324,8 @@ class FreeKVCacheBlockQueue:
|
||||
|
||||
# Connect fake_head and the next block of first_block (i.e. second block
|
||||
# or fake tail).
|
||||
self.fake_free_list_head.next_free_block = first_block.next_free_block
|
||||
first_block.next_free_block.prev_free_block = self.fake_free_list_head
|
||||
head.next_free_block = next_block
|
||||
next_block.prev_free_block = head
|
||||
|
||||
# Remove the block from the linked list.
|
||||
first_block.prev_free_block = first_block.next_free_block = None
|
||||
@@ -350,6 +349,16 @@ class FreeKVCacheBlockQueue:
|
||||
self.num_free_blocks -= n
|
||||
|
||||
curr_block = self.fake_free_list_head.next_free_block
|
||||
if n == 1:
|
||||
assert curr_block is not None
|
||||
next_block = curr_block.next_free_block
|
||||
curr_block.prev_free_block = None
|
||||
curr_block.next_free_block = None
|
||||
if next_block is not None:
|
||||
self.fake_free_list_head.next_free_block = next_block
|
||||
next_block.prev_free_block = self.fake_free_list_head
|
||||
return [curr_block]
|
||||
|
||||
# Pop n blocks from the head of the list
|
||||
ret = []
|
||||
for _ in range(n):
|
||||
@@ -375,15 +384,17 @@ class FreeKVCacheBlockQueue:
|
||||
block: The block to remove.
|
||||
|
||||
"""
|
||||
if block.prev_free_block is None or block.next_free_block is None:
|
||||
prev_block = block.prev_free_block
|
||||
next_block = block.next_free_block
|
||||
if prev_block is None or next_block is None:
|
||||
# This should not happen if the block is from the free list.
|
||||
# It indicates a bug in the caller's logic.
|
||||
raise RuntimeError(f"remove() called on an invalid block: {block}")
|
||||
|
||||
# Link the previous block to the next block.
|
||||
block.prev_free_block.next_free_block = block.next_free_block
|
||||
prev_block.next_free_block = next_block
|
||||
# Link the next block to the previous block.
|
||||
block.next_free_block.prev_free_block = block.prev_free_block
|
||||
next_block.prev_free_block = prev_block
|
||||
|
||||
# Remove the block from the linked list.
|
||||
block.prev_free_block = block.next_free_block = None
|
||||
@@ -397,19 +408,19 @@ class FreeKVCacheBlockQueue:
|
||||
block: The block to append.
|
||||
|
||||
"""
|
||||
if self.fake_free_list_tail.prev_free_block is None:
|
||||
tail = self.fake_free_list_tail
|
||||
last_block = tail.prev_free_block
|
||||
if last_block is None:
|
||||
raise RuntimeError(
|
||||
"prev_free_block of fake_free_list_tail should always exist"
|
||||
)
|
||||
last_block: KVCacheBlock = self.fake_free_list_tail.prev_free_block
|
||||
|
||||
# Connect the new block after the last block.
|
||||
last_block.next_free_block = block
|
||||
block.prev_free_block = last_block
|
||||
|
||||
# Connect the fake tail after the new block.
|
||||
block.next_free_block = self.fake_free_list_tail
|
||||
self.fake_free_list_tail.prev_free_block = block
|
||||
block.next_free_block = tail
|
||||
tail.prev_free_block = block
|
||||
|
||||
self.num_free_blocks += 1
|
||||
|
||||
@@ -441,10 +452,11 @@ class FreeKVCacheBlockQueue:
|
||||
blocks: The blocks to append.
|
||||
|
||||
"""
|
||||
if len(blocks) == 0:
|
||||
if not blocks:
|
||||
return
|
||||
|
||||
last_block = self.fake_free_list_tail.prev_free_block
|
||||
tail = self.fake_free_list_tail
|
||||
last_block = tail.prev_free_block
|
||||
assert last_block is not None, (
|
||||
"prev_free_block of fake_free_list_tail should always exist"
|
||||
)
|
||||
@@ -455,8 +467,8 @@ class FreeKVCacheBlockQueue:
|
||||
last_block = block
|
||||
|
||||
# Connect the last block of <blocks> to the fake tail
|
||||
last_block.next_free_block = self.fake_free_list_tail
|
||||
self.fake_free_list_tail.prev_free_block = last_block
|
||||
last_block.next_free_block = tail
|
||||
tail.prev_free_block = last_block
|
||||
|
||||
self.num_free_blocks += len(blocks)
|
||||
|
||||
@@ -736,6 +748,60 @@ def resolve_dcp_kv_cache_spec(spec: KVCacheSpec, dcp_world_size: int) -> KVCache
|
||||
return replace(spec, block_size=block_size)
|
||||
|
||||
|
||||
def partial_hash_hits_enabled(
|
||||
kv_cache_groups: Sequence[KVCacheGroupSpec],
|
||||
hash_block_size: int,
|
||||
dcp_world_size: int = 1,
|
||||
manager_classes: Sequence[type["SingleTypeKVCacheManager"]] | None = None,
|
||||
) -> bool:
|
||||
"""Whether aligned Mamba states support sub-block prefix-cache hits.
|
||||
|
||||
If ``manager_classes`` (one per group) is given, also require every other
|
||||
prefix-cacheable group to support fine-grained lookups.
|
||||
"""
|
||||
if not any(
|
||||
isinstance(spec, MambaSpec)
|
||||
and spec.mamba_cache_mode == "align"
|
||||
and (
|
||||
(dcp_world_size == 1 and spec.block_size > hash_block_size)
|
||||
or (dcp_world_size > 1 and spec.block_size >= hash_block_size)
|
||||
)
|
||||
for group in kv_cache_groups
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
):
|
||||
return False
|
||||
if manager_classes is None:
|
||||
return True
|
||||
unsupported_managers = {
|
||||
manager_cls.__name__
|
||||
for group, manager_cls in zip(kv_cache_groups, manager_classes)
|
||||
if group.kv_cache_spec.prefix_cacheable
|
||||
and not manager_cls.supports_fine_grained_hash_lookup
|
||||
and resolve_dcp_kv_block_size(group.kv_cache_spec, dcp_world_size)
|
||||
!= hash_block_size
|
||||
}
|
||||
if unsupported_managers:
|
||||
logger.warning_once(
|
||||
"Disabling fine-grained prefix-cache hits because these KV "
|
||||
"cache managers require block-aligned lookups: %s.",
|
||||
", ".join(sorted(unsupported_managers)),
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def eagle_proof_margin(
|
||||
block_size: int, hash_block_size: int, fine_grained_lookup: bool
|
||||
) -> int:
|
||||
"""Tokens an EAGLE group matches past a cache hit before dropping them.
|
||||
|
||||
Fine-grained lookups drop one hash unit; others drop one cache block.
|
||||
"""
|
||||
if fine_grained_lookup and block_size > hash_block_size:
|
||||
return hash_block_size
|
||||
return block_size
|
||||
|
||||
|
||||
def resolve_kv_cache_block_sizes(
|
||||
kv_cache_config: KVCacheConfig,
|
||||
vllm_config: VllmConfig,
|
||||
@@ -764,8 +830,7 @@ def resolve_kv_cache_block_sizes(
|
||||
if groups and not groups[0].kv_cache_spec.dcp_sharded:
|
||||
dcp = 1
|
||||
bs = cache_config.block_size * dcp
|
||||
# The Mamba prefill checkpoint builder reads prefix_match_unit directly,
|
||||
# so a value dropped here puts its checkpoints off the scheduler's grid.
|
||||
# Reject a prefix_match_unit that would otherwise be silently ignored.
|
||||
if (
|
||||
cache_config.prefix_match_unit not in (None, bs)
|
||||
and len(groups) == 1
|
||||
@@ -786,8 +851,8 @@ def resolve_kv_cache_block_sizes(
|
||||
]
|
||||
scheduler_block_size = math.lcm(*group_block_sizes)
|
||||
|
||||
logger.info("kv cache group sizes %s", group_block_sizes)
|
||||
logger.info("kv lcm block sizes %s", scheduler_block_size)
|
||||
logger.info_once("kv cache group sizes %s", tuple(group_block_sizes))
|
||||
logger.info_once("kv lcm block sizes %s", scheduler_block_size)
|
||||
|
||||
# Block hashes are only consumed by prefix caching and KV connectors
|
||||
# (P/D, offloading); when neither is active, keep hash_block_size equal
|
||||
@@ -828,18 +893,10 @@ def resolve_kv_cache_block_sizes(
|
||||
and isinstance(spec.tokens_per_state, int)
|
||||
and spec.tokens_per_state > 1
|
||||
}
|
||||
has_partial_mamba_group = any(
|
||||
isinstance(spec, MambaSpec)
|
||||
and spec.mamba_cache_mode == "align"
|
||||
and (
|
||||
(dcp == 1 and block_size > hash_block_size)
|
||||
or (dcp > 1 and block_size >= hash_block_size)
|
||||
)
|
||||
for group, block_size in zip(groups, group_block_sizes)
|
||||
for spec in iter_layer_specs(group.kv_cache_spec)
|
||||
)
|
||||
cache_hit_alignment = (
|
||||
hash_block_size if has_partial_mamba_group else scheduler_block_size
|
||||
hash_block_size
|
||||
if partial_hash_hits_enabled(groups, hash_block_size, dcp)
|
||||
else scheduler_block_size
|
||||
)
|
||||
if any(cache_hit_alignment % alignment for alignment in prefix_alignments):
|
||||
raise ValueError(
|
||||
@@ -850,6 +907,38 @@ def resolve_kv_cache_block_sizes(
|
||||
return scheduler_block_size, hash_block_size
|
||||
|
||||
|
||||
def resolve_cache_hit_alignment_tokens(
|
||||
kv_cache_config: KVCacheConfig,
|
||||
vllm_config: VllmConfig,
|
||||
scheduler_block_size: int,
|
||||
hash_block_size: int,
|
||||
) -> int:
|
||||
"""Token granularity at which prefix-cache hits land.
|
||||
|
||||
Mirrors the alignment the hybrid KV cache coordinator pushes to its
|
||||
managers: fine-grained hits land on ``hash_block_size``, all others on
|
||||
``scheduler_block_size``.
|
||||
"""
|
||||
groups = kv_cache_config.kv_cache_groups
|
||||
if not vllm_config.cache_config.enable_prefix_caching or len(groups) <= 1:
|
||||
return scheduler_block_size
|
||||
manager_classes = []
|
||||
for group in groups:
|
||||
manager_cls = KVCacheSpecRegistry.get_manager_class(
|
||||
group.kv_cache_spec, group.role
|
||||
)
|
||||
assert manager_cls is not None
|
||||
manager_classes.append(manager_cls)
|
||||
if partial_hash_hits_enabled(
|
||||
groups,
|
||||
hash_block_size,
|
||||
vllm_config.parallel_config.decode_context_parallel_size,
|
||||
manager_classes,
|
||||
):
|
||||
return hash_block_size
|
||||
return scheduler_block_size
|
||||
|
||||
|
||||
def get_request_block_hasher(
|
||||
hash_block_size: int,
|
||||
caching_hash_fn: Callable[[Any], bytes],
|
||||
|
||||
@@ -26,7 +26,7 @@ class PauseState(enum.IntEnum):
|
||||
|
||||
- UNPAUSED: Normal operation
|
||||
- PAUSE_NEW: No new requests are scheduled, requests already in
|
||||
running state are scheduled.
|
||||
running state or holding KV blocks are scheduled.
|
||||
- PAUSE_ALL: No requests are scheduled
|
||||
"""
|
||||
|
||||
|
||||
+135
-67
@@ -147,9 +147,15 @@ class Scheduler(SchedulerInterface):
|
||||
self.kv_events_config is not None
|
||||
and self.kv_events_config.enable_kv_cache_events
|
||||
)
|
||||
# Diffusion models may not sample any tokens for a denoising step.
|
||||
# Pooling and diffusion models do not append a sampled token after
|
||||
# prefill, so they should not reserve one context slot while scheduling.
|
||||
self.num_sampled_tokens_per_step = (
|
||||
1 if not vllm_config.model_config.is_diffusion else 0
|
||||
0
|
||||
if (
|
||||
vllm_config.model_config.runner_type == "pooling"
|
||||
or vllm_config.model_config.is_diffusion
|
||||
)
|
||||
else 1
|
||||
)
|
||||
|
||||
# Create KVConnector for the Scheduler. Note that each Worker
|
||||
@@ -284,10 +290,14 @@ class Scheduler(SchedulerInterface):
|
||||
# DSV41 SWA bounded replay: groups that declare a replay window are rebuilt
|
||||
# after a prefix hit by recomputing its trailing tokens. One window
|
||||
# for all such groups, so the rewind matches every group's allocation.
|
||||
replay_windows = {
|
||||
group.kv_cache_spec.prefix_replay_tokens
|
||||
for group in kv_cache_config.kv_cache_groups
|
||||
self.prefix_replay_group_ids = tuple(
|
||||
group_id
|
||||
for group_id, group in enumerate(kv_cache_config.kv_cache_groups)
|
||||
if group.kv_cache_spec.prefix_replay_tokens > 0
|
||||
)
|
||||
replay_windows = {
|
||||
kv_cache_config.kv_cache_groups[group_id].kv_cache_spec.prefix_replay_tokens
|
||||
for group_id in self.prefix_replay_group_ids
|
||||
}
|
||||
assert len(replay_windows) <= 1, (
|
||||
f"Prefix replay windows should agree: {sorted(replay_windows)}"
|
||||
@@ -371,9 +381,8 @@ class Scheduler(SchedulerInterface):
|
||||
or group.kv_cache_spec.num_prefill_checkpoint_blocks > 0
|
||||
for group in kv_cache_config.kv_cache_groups
|
||||
)
|
||||
# A finer prefix_match_unit is configured: a mamba partial tail entry
|
||||
# can only be registered by a step ending exactly at the prompt's last
|
||||
# hash boundary, so the split adds that stop.
|
||||
# Fine-grained hits reuse the prompt's hash-aligned Mamba checkpoint.
|
||||
# Split there only if the backend cannot save it within the final chunk.
|
||||
self.mamba_partial_cache_hit = (
|
||||
self.need_mamba_block_aligned_split
|
||||
and self.hash_block_size < self.block_size
|
||||
@@ -450,14 +459,19 @@ class Scheduler(SchedulerInterface):
|
||||
# The last block-aligned position whose state can be cached. With
|
||||
# Eagle, FullAttn prunes the last matching block, so back off one
|
||||
# block to avoid a Mamba cache miss.
|
||||
last_cache_position = request.num_tokens - request.num_tokens % block_size
|
||||
if self.use_eagle_block_drop:
|
||||
last_cache_position = max(last_cache_position - block_size, 0)
|
||||
ckpt_block_size = (
|
||||
self.hash_block_size if self.mamba_partial_cache_hit else self.block_size
|
||||
)
|
||||
last_cache_position = get_mamba_prefill_checkpoint_position(
|
||||
request.num_tokens,
|
||||
block_size,
|
||||
self.use_eagle_block_drop,
|
||||
)
|
||||
|
||||
end = start + num_new_tokens
|
||||
checkpoint_position = get_mamba_prefill_checkpoint_position(
|
||||
prefill_end,
|
||||
self.hash_block_size,
|
||||
ckpt_block_size,
|
||||
drop_eagle_block=self.use_eagle_block_drop,
|
||||
)
|
||||
use_internal_checkpoint = (
|
||||
@@ -490,18 +504,14 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
next_block_boundary = (start // block_size + 1) * block_size
|
||||
tail_boundary = (
|
||||
request.num_prompt_tokens // self.hash_block_size * self.hash_block_size
|
||||
get_mamba_prefill_checkpoint_position(
|
||||
request.num_prompt_tokens,
|
||||
self.hash_block_size,
|
||||
self.use_eagle_block_drop,
|
||||
)
|
||||
if self.mamba_partial_cache_hit and not use_internal_checkpoint
|
||||
else 0
|
||||
)
|
||||
if tail_boundary and self.use_eagle_block_drop:
|
||||
# Eagle matches one hash unit past the candidate and drops it, so
|
||||
# nothing proves the prompt's own last hash boundary. Materialize
|
||||
# the state one unit lower, where the hit can actually land. Keyed on
|
||||
# the block-drop bit, not plain use_eagle: this shift exists only to
|
||||
# compensate for the drop, and the Mamba manager's matching gate
|
||||
# reads the same bit (the coordinator is handed use_eagle_block_drop).
|
||||
tail_boundary = max(tail_boundary - self.hash_block_size, 0)
|
||||
junction = request.shared_prefix_boundary
|
||||
# Block-floored: a sub-block junction's state is not separately cacheable.
|
||||
block_floored = start + (junction - start) // block_size * block_size
|
||||
@@ -522,8 +532,7 @@ class Scheduler(SchedulerInterface):
|
||||
else 0,
|
||||
# Never run past the last cacheable block boundary mid-chunk.
|
||||
last_cache_position,
|
||||
# Fine-grained hits: the prompt's partial-tail entry can only be
|
||||
# registered by a chunk ending exactly at its last hash boundary.
|
||||
# Stop at the prompt checkpoint unless the backend saves it internally.
|
||||
tail_boundary
|
||||
if last_cache_position < tail_boundary < request.num_prompt_tokens
|
||||
else 0,
|
||||
@@ -709,6 +718,7 @@ class Scheduler(SchedulerInterface):
|
||||
# Schedule encoder inputs.
|
||||
encoder_inputs_to_schedule = None
|
||||
external_load_encoder_input: list[int] = []
|
||||
duplicate_encoder_inputs: list[int] = []
|
||||
new_encoder_compute_budget = encoder_compute_budget
|
||||
if request.has_encoder_inputs:
|
||||
(
|
||||
@@ -716,6 +726,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_new_tokens,
|
||||
new_encoder_compute_budget,
|
||||
external_load_encoder_input,
|
||||
duplicate_encoder_inputs,
|
||||
) = self._try_schedule_encoder_inputs(
|
||||
request,
|
||||
request.num_computed_tokens,
|
||||
@@ -856,17 +867,13 @@ class Scheduler(SchedulerInterface):
|
||||
# Encoder-related.
|
||||
if encoder_inputs_to_schedule:
|
||||
scheduled_encoder_inputs[request_id] = encoder_inputs_to_schedule
|
||||
# Allocate the encoder cache.
|
||||
for i in encoder_inputs_to_schedule:
|
||||
self.encoder_cache_manager.allocate(request, i)
|
||||
if self.ec_connector is not None:
|
||||
self.ec_connector.update_state_after_alloc(request, i)
|
||||
encoder_compute_budget = new_encoder_compute_budget
|
||||
if external_load_encoder_input:
|
||||
for i in external_load_encoder_input:
|
||||
self.encoder_cache_manager.allocate(request, i)
|
||||
if self.ec_connector is not None:
|
||||
self.ec_connector.update_state_after_alloc(request, i)
|
||||
if encoder_inputs_to_schedule or external_load_encoder_input:
|
||||
self._allocate_encoder_inputs(
|
||||
request,
|
||||
(encoder_inputs_to_schedule or []) + external_load_encoder_input,
|
||||
duplicate_encoder_inputs,
|
||||
)
|
||||
|
||||
# Record the LoRAs in scheduled_running_reqs
|
||||
scheduled_loras: set[int] = set()
|
||||
@@ -879,7 +886,7 @@ class Scheduler(SchedulerInterface):
|
||||
assert len(scheduled_loras) <= self.lora_config.max_loras
|
||||
|
||||
# Next, schedule the WAITING requests.
|
||||
if not preempted_reqs and self._pause_state == PauseState.UNPAUSED:
|
||||
if not preempted_reqs and self._pause_state != PauseState.PAUSED_ALL:
|
||||
step_skipped_waiting: deque[Request] = deque()
|
||||
step_skipped_kv_holding: deque[Request] = deque()
|
||||
|
||||
@@ -892,8 +899,11 @@ class Scheduler(SchedulerInterface):
|
||||
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
|
||||
# Requests holding KV blocks are always drained first, and are
|
||||
# the only ones admitted under PAUSED_NEW (e.g. async KV loads).
|
||||
request_queue = self.kv_holding_waiting
|
||||
if not request_queue and self._pause_state == PauseState.UNPAUSED:
|
||||
request_queue = self.waiting
|
||||
if not request_queue or input_budget <= draft_slots:
|
||||
break
|
||||
# Paused streaming sessions (WAITING_FOR_STREAMING_REQ) are not
|
||||
@@ -969,14 +979,17 @@ class Scheduler(SchedulerInterface):
|
||||
skip_request(request_queue)
|
||||
continue
|
||||
|
||||
if self.prefix_replay_tokens:
|
||||
# SWA bounded replay recomputes the hit's last
|
||||
if self.prefix_replay_tokens and not (
|
||||
ext_tokens and self._load_restores_replay_window(request)
|
||||
):
|
||||
# DSV41 SWA bounded replay recomputes the hit's last
|
||||
# window, from the block holding its first
|
||||
# token; the sliding-window groups retire
|
||||
# whole blocks below the window of the hit's
|
||||
# next token. Hits end on a block boundary, or
|
||||
# a hit ending one token short of one would
|
||||
# retire the block the replay starts in.
|
||||
# retire the block the replay starts in. A load
|
||||
# that carries the window replays nothing.
|
||||
ext_tokens -= ext_tokens % self.block_size
|
||||
load_kv_async = load_kv_async and ext_tokens > 0
|
||||
|
||||
@@ -1022,9 +1035,17 @@ class Scheduler(SchedulerInterface):
|
||||
num_new_local_computed_tokens + num_external_computed_tokens
|
||||
)
|
||||
assert num_computed_tokens <= request.num_tokens
|
||||
if 0 < num_computed_tokens <= self.prefix_replay_tokens:
|
||||
# SWA bounded replay: a hit no longer than the replayed
|
||||
# window would be recomputed in full and save nothing.
|
||||
# DSV41 SWA bounded replay: a KV load that carries the
|
||||
# window is taken as is; any other hit no longer than the
|
||||
# replayed window would be recomputed in full and save
|
||||
# nothing.
|
||||
window_loaded = bool(
|
||||
num_external_computed_tokens
|
||||
) and self._load_restores_replay_window(request)
|
||||
if (
|
||||
not window_loaded
|
||||
and 0 < num_computed_tokens <= self.prefix_replay_tokens
|
||||
):
|
||||
new_computed_blocks = (
|
||||
self.kv_cache_manager.empty_kv_cache_blocks
|
||||
)
|
||||
@@ -1065,6 +1086,7 @@ class Scheduler(SchedulerInterface):
|
||||
|
||||
encoder_inputs_to_schedule = None
|
||||
external_load_encoder_input = []
|
||||
duplicate_encoder_inputs = []
|
||||
new_encoder_compute_budget = encoder_compute_budget
|
||||
pad_spec_decode = False
|
||||
|
||||
@@ -1086,7 +1108,7 @@ class Scheduler(SchedulerInterface):
|
||||
if did_prefix_cache_lookup:
|
||||
# Fresh admission: local and/or sync external hit.
|
||||
num_replay_tokens = self._mark_prefix_replay(
|
||||
request, num_computed_tokens
|
||||
request, num_computed_tokens, window_loaded
|
||||
)
|
||||
num_computed_tokens -= num_replay_tokens
|
||||
# Number of tokens to be scheduled.
|
||||
@@ -1166,6 +1188,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_new_tokens,
|
||||
new_encoder_compute_budget,
|
||||
external_load_encoder_input,
|
||||
duplicate_encoder_inputs,
|
||||
) = self._try_schedule_encoder_inputs(
|
||||
request,
|
||||
num_computed_tokens,
|
||||
@@ -1261,10 +1284,20 @@ class Scheduler(SchedulerInterface):
|
||||
self.connector_prefix_cache_stats is not None
|
||||
and connector_prefix_cache_queries != 0
|
||||
):
|
||||
preempted = request.num_preemptions > 0
|
||||
self.connector_prefix_cache_stats.record(
|
||||
num_tokens=connector_prefix_cache_queries,
|
||||
num_hits=connector_prefix_cache_hits,
|
||||
preempted=request.num_preemptions > 0,
|
||||
preempted=preempted,
|
||||
# The connector knows the tier only after the load
|
||||
# plan above exists.
|
||||
hits_by_source=(
|
||||
self.connector.get_external_cache_hit_sources(
|
||||
request, connector_prefix_cache_hits
|
||||
)
|
||||
if connector_prefix_cache_hits and not preempted
|
||||
else None
|
||||
),
|
||||
)
|
||||
|
||||
# Record at admission so unscheduled lookups are not counted.
|
||||
@@ -1335,18 +1368,14 @@ class Scheduler(SchedulerInterface):
|
||||
# Encoder-related.
|
||||
if encoder_inputs_to_schedule:
|
||||
scheduled_encoder_inputs[request_id] = encoder_inputs_to_schedule
|
||||
# Allocate the encoder cache.
|
||||
for i in encoder_inputs_to_schedule:
|
||||
self.encoder_cache_manager.allocate(request, i)
|
||||
if self.ec_connector is not None:
|
||||
self.ec_connector.update_state_after_alloc(request, i)
|
||||
encoder_compute_budget = new_encoder_compute_budget
|
||||
# Allocate for external load encoder cache
|
||||
if external_load_encoder_input:
|
||||
for i in external_load_encoder_input:
|
||||
self.encoder_cache_manager.allocate(request, i)
|
||||
if self.ec_connector is not None:
|
||||
self.ec_connector.update_state_after_alloc(request, i)
|
||||
if encoder_inputs_to_schedule or external_load_encoder_input:
|
||||
self._allocate_encoder_inputs(
|
||||
request,
|
||||
(encoder_inputs_to_schedule or [])
|
||||
+ external_load_encoder_input,
|
||||
duplicate_encoder_inputs,
|
||||
)
|
||||
|
||||
# re-queue requests skipped in this pass ahead of older skipped items.
|
||||
if step_skipped_kv_holding:
|
||||
@@ -1632,6 +1661,7 @@ class Scheduler(SchedulerInterface):
|
||||
session.num_prompt_tokens : num_computed_tokens
|
||||
]
|
||||
del session._all_token_ids[num_computed_tokens:]
|
||||
del session.block_hashes[num_computed_tokens // self.hash_block_size :]
|
||||
session._output_token_ids.clear()
|
||||
assert session.prompt_token_ids is not None
|
||||
# Extend prompt with kept output tokens.
|
||||
@@ -1742,6 +1772,20 @@ class Scheduler(SchedulerInterface):
|
||||
self.encoder_cache_mismatch_reqs.add(request.request_id)
|
||||
return True
|
||||
|
||||
def _allocate_encoder_inputs(
|
||||
self,
|
||||
request: Request,
|
||||
input_ids: list[int],
|
||||
duplicate_input_ids: list[int],
|
||||
) -> None:
|
||||
for input_id in input_ids:
|
||||
self.encoder_cache_manager.allocate(request, input_id)
|
||||
if self.ec_connector is not None:
|
||||
self.ec_connector.update_state_after_alloc(request, input_id)
|
||||
|
||||
for input_id in duplicate_input_ids:
|
||||
self.encoder_cache_manager.check_and_update_cache(request, input_id)
|
||||
|
||||
def _try_schedule_encoder_inputs(
|
||||
self,
|
||||
request: Request,
|
||||
@@ -1749,7 +1793,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_new_tokens: int,
|
||||
encoder_compute_budget: int,
|
||||
shift_computed_tokens: int = 0,
|
||||
) -> tuple[list[int], int, int, list[int]]:
|
||||
) -> tuple[list[int], int, int, list[int], list[int]]:
|
||||
"""Determine which encoder inputs need to be scheduled in the current step,
|
||||
and update `num_new_tokens` and encoder token budget accordingly.
|
||||
|
||||
@@ -1770,12 +1814,13 @@ class Scheduler(SchedulerInterface):
|
||||
blocks and externally cached blocks (via KVConnector).
|
||||
"""
|
||||
if num_new_tokens == 0 or not request.has_encoder_inputs:
|
||||
return [], num_new_tokens, encoder_compute_budget, []
|
||||
return [], num_new_tokens, encoder_compute_budget, [], []
|
||||
encoder_inputs_to_schedule: list[int] = []
|
||||
mm_features = request.mm_features
|
||||
assert mm_features is not None
|
||||
assert len(mm_features) > 0
|
||||
external_load_encoder_input = []
|
||||
duplicate_encoder_inputs = []
|
||||
|
||||
# NOTE: since scheduler operates on the request level (possibly with
|
||||
# multiple encoder inputs per request), we need to create temporary
|
||||
@@ -1832,9 +1877,10 @@ class Scheduler(SchedulerInterface):
|
||||
scheduled_num_encoder_embeds,
|
||||
num_encoder_embeds,
|
||||
):
|
||||
return [], 0, encoder_compute_budget, []
|
||||
return [], 0, encoder_compute_budget, [], []
|
||||
# The same encoder input has already been scheduled in the
|
||||
# current step.
|
||||
duplicate_encoder_inputs.append(i)
|
||||
continue
|
||||
|
||||
cached_num_encoder_embeds = (
|
||||
@@ -1849,7 +1895,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_encoder_embeds,
|
||||
)
|
||||
):
|
||||
return [], 0, encoder_compute_budget, []
|
||||
return [], 0, encoder_compute_budget, [], []
|
||||
|
||||
if self.encoder_cache_manager.check_and_update_cache(request, i):
|
||||
# The encoder input is already computed and cached from a
|
||||
@@ -1925,6 +1971,7 @@ class Scheduler(SchedulerInterface):
|
||||
num_new_tokens,
|
||||
encoder_compute_budget,
|
||||
external_load_encoder_input,
|
||||
duplicate_encoder_inputs,
|
||||
)
|
||||
|
||||
def _make_scheduled_encoder_input_stats(
|
||||
@@ -2757,7 +2804,8 @@ class Scheduler(SchedulerInterface):
|
||||
return 0
|
||||
num_running, num_waiting = self.get_request_counts()
|
||||
if self._pause_state == PauseState.PAUSED_NEW:
|
||||
return num_running
|
||||
# Requests holding KV blocks still drain; queued ones stay queued.
|
||||
num_waiting = len(self.kv_holding_waiting)
|
||||
num_waiting -= self.num_waiting_for_streaming_input
|
||||
return num_waiting + num_running
|
||||
|
||||
@@ -3053,16 +3101,31 @@ class Scheduler(SchedulerInterface):
|
||||
self._request_remaining_blocks(req) for req in self._inflight_prefills
|
||||
)
|
||||
|
||||
def _mark_prefix_replay(self, request: Request, num_hit_tokens: int) -> int:
|
||||
def _load_restores_replay_window(self, request: Request) -> bool:
|
||||
"""Whether the KV connector's load for ``request`` restores every DSV41
|
||||
SWA bounded-replay group, as a P/D transfer of the request's own blocks
|
||||
does; a prefix-cache store holds no window."""
|
||||
assert self.connector is not None
|
||||
return bool(self.prefix_replay_group_ids) and set(
|
||||
self.prefix_replay_group_ids
|
||||
).issubset(self.connector.get_loaded_kv_cache_group_ids(request))
|
||||
|
||||
def _mark_prefix_replay(
|
||||
self, request: Request, num_hit_tokens: int, window_loaded: bool
|
||||
) -> int:
|
||||
"""Record where a prefix hit's replay starts and return the number of
|
||||
hit tokens to recompute; the caller rewinds the computed count by it.
|
||||
|
||||
The replayed tokens are the hit's last window (see
|
||||
``Request.replay_start``): the worker rebuilds their sliding-window KV
|
||||
and leaves their cached KV alone.
|
||||
and leaves their cached KV alone. A hit whose KV load carries the
|
||||
window replays nothing.
|
||||
"""
|
||||
if not self.prefix_replay_tokens:
|
||||
return 0
|
||||
if window_loaded:
|
||||
request.replay_start = 0
|
||||
return 0
|
||||
num_replay_tokens = min(self.prefix_replay_tokens, num_hit_tokens)
|
||||
request.replay_start = num_hit_tokens - num_replay_tokens
|
||||
return num_replay_tokens
|
||||
@@ -3076,7 +3139,8 @@ class Scheduler(SchedulerInterface):
|
||||
"""
|
||||
assert self.connector is not None
|
||||
|
||||
if request.request_id in self.failed_recving_kv_req_ids:
|
||||
load_failed = request.request_id in self.failed_recving_kv_req_ids
|
||||
if load_failed:
|
||||
# Request had KV load failures; num_computed_tokens was already
|
||||
# updated in _update_requests_with_invalid_blocks
|
||||
if request.num_computed_tokens:
|
||||
@@ -3102,11 +3166,15 @@ class Scheduler(SchedulerInterface):
|
||||
# This will cache the blocks iff caching is enabled.
|
||||
self.kv_cache_manager.cache_blocks(request, request.num_computed_tokens)
|
||||
|
||||
# SWA bounded replay recomputes the tail of the hit, which covers the
|
||||
# last token; otherwise a full prompt hit re-computes that token so the
|
||||
# next one can be sampled.
|
||||
# DSV41 SWA bounded replay recomputes the tail of a hit loaded without
|
||||
# its window, or of a failed load, which may have lost it; the replay
|
||||
# covers the last token. Otherwise a full prompt hit re-computes that
|
||||
# token so the next one can be sampled.
|
||||
num_replay_tokens = self._mark_prefix_replay(
|
||||
request, request.num_computed_tokens
|
||||
request,
|
||||
request.num_computed_tokens,
|
||||
window_loaded=not load_failed
|
||||
and self._load_restores_replay_window(request),
|
||||
)
|
||||
if num_replay_tokens > 0:
|
||||
request.num_computed_tokens -= num_replay_tokens
|
||||
|
||||
@@ -876,7 +876,14 @@ class FullAttentionManager(SingleTypeKVCacheManager):
|
||||
block are intentionally skipped.
|
||||
"""
|
||||
hash_block_size = self.block_pool.hash_block_size
|
||||
boundary_tokens = request.num_prompt_tokens // hash_block_size * hash_block_size
|
||||
# A resend matches at most `prompt_len - 1` tokens, but EAGLE lookups
|
||||
# read the whole prompt before dropping a hash unit.
|
||||
token_limit = (
|
||||
request.num_prompt_tokens
|
||||
if self.use_eagle
|
||||
else request.num_prompt_tokens - 1
|
||||
)
|
||||
boundary_tokens = token_limit // hash_block_size * hash_block_size
|
||||
if boundary_tokens == 0 or boundary_tokens > num_tokens:
|
||||
return
|
||||
if boundary_tokens % self.block_size == 0:
|
||||
@@ -1797,7 +1804,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
# is kept, so `prefill_end` skips reserving blocks for the others.
|
||||
checkpoint_position = get_mamba_prefill_checkpoint_position(
|
||||
num_tokens,
|
||||
self.block_pool.hash_block_size,
|
||||
self.cache_hit_alignment_tokens,
|
||||
self.drop_eagle_checkpoint_block,
|
||||
)
|
||||
if not self._needs_internal_checkpoint(
|
||||
@@ -1821,7 +1828,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
if num_new_blocks > 0:
|
||||
blocks_allocated = request_id in self._allocated_block_reqs
|
||||
physical_block_cap = 1 + int(has_partial_hit) + checkpoint_block
|
||||
if not blocks_allocated or checkpoint_block:
|
||||
if not blocks_allocated:
|
||||
physical_block_cap += self.num_speculative_blocks
|
||||
num_new_blocks = min(num_new_blocks, physical_block_cap)
|
||||
|
||||
@@ -1894,12 +1901,14 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
[self._null_block for _ in range(prev_block_len, null_end)]
|
||||
)
|
||||
|
||||
if blocks_allocated and not checkpoint_block:
|
||||
# Relocate exclusively owned speculative scratch blocks.
|
||||
if blocks_allocated:
|
||||
# Relocate exclusively owned scratch blocks this step leaves
|
||||
# behind. In a checkpoint step, one at the checkpoint index
|
||||
# stays: the worker exports the checkpoint into that column.
|
||||
for block_idx in range(
|
||||
prev_block_len - self.num_speculative_blocks, prev_block_len
|
||||
):
|
||||
if block_idx < num_skipped_blocks:
|
||||
if block_idx < num_skipped_blocks - checkpoint_block:
|
||||
self._relocate_speculative_block(req_blocks, block_idx)
|
||||
else:
|
||||
break
|
||||
@@ -1907,7 +1916,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
if has_partial_hit:
|
||||
num_new_blocks = max(num_new_blocks, 0) + 1
|
||||
max_new_blocks = 1 + int(has_partial_hit) + checkpoint_block
|
||||
if not blocks_allocated or checkpoint_block:
|
||||
if not blocks_allocated:
|
||||
max_new_blocks += self.num_speculative_blocks
|
||||
assert num_new_blocks <= max_new_blocks
|
||||
new_blocks = self.block_pool.get_new_blocks(num_new_blocks)
|
||||
@@ -2080,20 +2089,29 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
checkpoint_position
|
||||
== get_mamba_prefill_checkpoint_position(
|
||||
request.num_prompt_tokens,
|
||||
hash_block_size,
|
||||
self.cache_hit_alignment_tokens,
|
||||
self.drop_eagle_checkpoint_block,
|
||||
)
|
||||
)
|
||||
is_retained_checkpoint = False
|
||||
if checkpoint_position % self.block_size == 0:
|
||||
block_idx = checkpoint_position // self.block_size - 1
|
||||
retained = self.reachable_block_mask(
|
||||
block_idx,
|
||||
block_idx + 1,
|
||||
self.cache_hit_alignment_tokens,
|
||||
self.kv_cache_spec,
|
||||
self.drop_eagle_checkpoint_block,
|
||||
retention_interval=retention_interval,
|
||||
)
|
||||
is_retained_checkpoint = retained is None or retained[0]
|
||||
if (
|
||||
retention_interval == 0
|
||||
and num_tokens < request.num_prompt_tokens
|
||||
and not is_prompt_checkpoint
|
||||
not is_prompt_checkpoint
|
||||
and not is_retained_checkpoint
|
||||
and checkpoint_position != request.shared_prefix_boundary
|
||||
):
|
||||
# retention_interval == 0 keeps this transient checkpoint
|
||||
# request-local. The slot may carry a hash from this step's
|
||||
# full-block pass; that must go too, since the checkpoint
|
||||
# state is about to overwrite the block.
|
||||
# The transient state overwrites this slot, so neither it nor
|
||||
# the full-block hash registered earlier this step is reusable.
|
||||
self.block_pool._maybe_evict_cached_block(checkpoint_block)
|
||||
return None
|
||||
if checkpoint_block.block_hash_num_tokens == checkpoint_position:
|
||||
@@ -2106,21 +2124,13 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
block_size=self.block_size,
|
||||
replace_existing_hashes=True,
|
||||
)
|
||||
if self.block_size == hash_block_size:
|
||||
if num_tokens <= 0 or num_tokens % hash_block_size != 0:
|
||||
return None
|
||||
if num_tokens % self.block_size == 0:
|
||||
return None
|
||||
if num_tokens % hash_block_size != 0:
|
||||
return None
|
||||
latest_prompt_hash_boundary = (
|
||||
request.num_prompt_tokens // hash_block_size
|
||||
) * hash_block_size
|
||||
if self.drop_eagle_checkpoint_block:
|
||||
# Eagle groups match one hash unit past the candidate and drop it,
|
||||
# so register the tail one unit lower.
|
||||
latest_prompt_hash_boundary = max(
|
||||
latest_prompt_hash_boundary - hash_block_size, 0
|
||||
)
|
||||
latest_prompt_hash_boundary = get_mamba_prefill_checkpoint_position(
|
||||
request.num_prompt_tokens,
|
||||
hash_block_size,
|
||||
self.drop_eagle_checkpoint_block,
|
||||
)
|
||||
# The junction is the other position a sibling resumes at: where one was
|
||||
# observed to stop, and where the scheduler already ends a chunk. Bounded
|
||||
# to the prompt chunk being computed -- during decode the target is the
|
||||
@@ -2133,7 +2143,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
):
|
||||
return None
|
||||
|
||||
block_idx = num_tokens // self.block_size
|
||||
block_idx = cdiv(num_tokens, self.block_size) - 1
|
||||
blocks = self.req_to_blocks[request.request_id]
|
||||
if block_idx >= len(blocks):
|
||||
return None
|
||||
@@ -2148,7 +2158,7 @@ class MambaManager(SingleTypeKVCacheManager):
|
||||
kv_cache_group_id=self.kv_cache_group_id,
|
||||
block_size=self.block_size,
|
||||
)
|
||||
if partial_hash is not None:
|
||||
if partial_hash is not None and num_tokens % self.block_size:
|
||||
self._partial_hit_reqs[request.request_id] = (block_idx, source_block)
|
||||
self.num_cached_block[request.request_id] = block_idx
|
||||
# Producer of this partial tail: the boundary state currently lives
|
||||
|
||||
+73
-26
@@ -13,6 +13,10 @@ import vllm.envs as envs
|
||||
from vllm import TokensPrompt
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.kv_events import KVEventsConfig
|
||||
from vllm.config.profiler import (
|
||||
validate_profile_iteration_bounds,
|
||||
validate_profile_prefix,
|
||||
)
|
||||
from vllm.distributed.weight_transfer.base import (
|
||||
WeightTransferInitRequest,
|
||||
WeightTransferUpdateRequest,
|
||||
@@ -23,6 +27,7 @@ from vllm.entrypoints.serve.elastic_ep.middleware import set_scaling_elastic_ep
|
||||
from vllm.exceptions import (
|
||||
GracefulHTTPError,
|
||||
MaxQueuedTokensError,
|
||||
ProfilerAlreadyActiveError,
|
||||
QueueOverflowError,
|
||||
VLLMClientError,
|
||||
VLLMValidationError,
|
||||
@@ -33,7 +38,7 @@ from vllm.lora.request import LoRARequest
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
|
||||
from vllm.outputs import STREAM_FINISHED, PoolingRequestOutput, RequestOutput
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.profiler.wrapper import TorchProfilerWrapper
|
||||
from vllm.profiler.wrapper import TorchProfilerWrapper, create_frontend_profiler
|
||||
from vllm.renderers import renderer_from_config
|
||||
from vllm.renderers.inputs.preprocess import extract_prompt_components
|
||||
from vllm.sampling_params import RequestOutputKind, SamplingParams
|
||||
@@ -211,24 +216,27 @@ class AsyncLLM(EngineClient):
|
||||
pass
|
||||
|
||||
self.profiler = profiler
|
||||
configured_activities = vllm_config.profiler_config.torch_profiler_activities
|
||||
self._frontend_profiler_injected = profiler is not None
|
||||
self._profile_lock = asyncio.Lock()
|
||||
self._profile_session_guard_enabled = client_count == 1
|
||||
self._profile_session_active = False
|
||||
if (
|
||||
vllm_config.profiler_config.profiler == "torch"
|
||||
and not vllm_config.profiler_config.ignore_frontend
|
||||
and (configured_activities is None or "CPU" in configured_activities)
|
||||
not self._frontend_profiler_injected
|
||||
and vllm_config.profiler_config.should_profile_frontend
|
||||
):
|
||||
profiler_dir = vllm_config.profiler_config.torch_profiler_dir
|
||||
logger.info(
|
||||
"Torch profiler enabled. AsyncLLM CPU traces will be collected under %s", # noqa: E501
|
||||
profiler_dir,
|
||||
)
|
||||
worker_name = f"{socket.gethostname()}_{os.getpid()}.async_llm"
|
||||
self.profiler = TorchProfilerWrapper(
|
||||
vllm_config.profiler_config,
|
||||
worker_name=worker_name,
|
||||
local_rank=0,
|
||||
activities=["CPU"],
|
||||
)
|
||||
if self._profile_session_guard_enabled:
|
||||
self._frontend_profiler_worker_name = (
|
||||
f"{socket.gethostname()}_{os.getpid()}.async_llm"
|
||||
)
|
||||
self.profiler = create_frontend_profiler(
|
||||
vllm_config.profiler_config,
|
||||
worker_name=self._frontend_profiler_worker_name,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"Frontend CPU profiling is disabled when multiple API server "
|
||||
"processes share an engine."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_vllm_config(
|
||||
@@ -443,6 +451,13 @@ class AsyncLLM(EngineClient):
|
||||
"does not match the EngineCoreRequest.request_id attribute. The "
|
||||
"latter will be used, and the former will be ignored."
|
||||
)
|
||||
request_params = request.params
|
||||
if isinstance(request_params, SamplingParams):
|
||||
# This request object is owned by the engine from here on.
|
||||
self.input_processor.apply_watermarking(
|
||||
request_params,
|
||||
self.input_processor.resolve_watermarking(request_params),
|
||||
)
|
||||
else:
|
||||
if isinstance(prompt, dict) and "type" in prompt:
|
||||
# Rendered EngineInput; no blocking preprocessing needed.
|
||||
@@ -910,6 +925,7 @@ class AsyncLLM(EngineClient):
|
||||
sampling_params=SamplingParams(
|
||||
max_tokens=1,
|
||||
extra_args={"kv_transfer_params": dict(kv_transfer_params)},
|
||||
watermarking=False,
|
||||
),
|
||||
pooling_params=None,
|
||||
arrival_time=time.time(),
|
||||
@@ -1073,17 +1089,48 @@ class AsyncLLM(EngineClient):
|
||||
if self.errored:
|
||||
raise self.dead_error
|
||||
|
||||
async def start_profile(self, profile_prefix: str | None = None) -> None:
|
||||
coros = [self.engine_core.profile_async(True, profile_prefix)]
|
||||
if self.profiler is not None:
|
||||
coros.append(asyncio.to_thread(self.profiler.start))
|
||||
await asyncio.gather(*coros)
|
||||
async def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
async with self._profile_lock:
|
||||
if self._profile_session_guard_enabled and self._profile_session_active:
|
||||
raise ProfilerAlreadyActiveError()
|
||||
validate_profile_prefix(profile_prefix)
|
||||
validate_profile_iteration_bounds(delay_iterations, max_iterations)
|
||||
|
||||
if self._profile_session_guard_enabled:
|
||||
self._profile_session_active = True
|
||||
# A cancelled start may still take effect, so only a reported
|
||||
# engine failure clears the session; otherwise /stop_profile is needed.
|
||||
try:
|
||||
await self.engine_core.profile_async(
|
||||
True,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
except Exception:
|
||||
self._profile_session_active = False
|
||||
raise
|
||||
if self.profiler is not None:
|
||||
if not self._frontend_profiler_injected:
|
||||
worker_name = self._frontend_profiler_worker_name
|
||||
if profile_prefix is not None:
|
||||
worker_name = f"{profile_prefix}_{worker_name}"
|
||||
self.profiler.set_output_name(worker_name)
|
||||
await asyncio.to_thread(self.profiler.start)
|
||||
|
||||
async def stop_profile(self) -> None:
|
||||
coros = [self.engine_core.profile_async(False)]
|
||||
if self.profiler is not None:
|
||||
coros.append(asyncio.to_thread(self.profiler.stop))
|
||||
await asyncio.gather(*coros)
|
||||
async with self._profile_lock:
|
||||
coros = [self.engine_core.profile_async(False)]
|
||||
if self.profiler is not None:
|
||||
coros.append(asyncio.to_thread(self.profiler.stop))
|
||||
await asyncio.gather(*coros)
|
||||
self._profile_session_active = False
|
||||
|
||||
async def reset_mm_cache(self) -> None:
|
||||
# Join the background MM warmup first: the mm_processor_cache is not
|
||||
|
||||
+78
-19
@@ -53,6 +53,7 @@ from vllm.v1.core.kv_cache_utils import (
|
||||
get_kv_cache_configs,
|
||||
get_request_block_hasher,
|
||||
init_none_hash,
|
||||
resolve_cache_hit_alignment_tokens,
|
||||
resolve_kv_cache_block_sizes,
|
||||
update_kv_cache_capacity,
|
||||
)
|
||||
@@ -352,6 +353,19 @@ class EngineCore:
|
||||
|
||||
vllm_config.validate_block_size()
|
||||
|
||||
scheduler_block_size, hash_block_size = resolve_kv_cache_block_sizes(
|
||||
scheduler_kv_cache_config, vllm_config
|
||||
)
|
||||
cache_hit_alignment_tokens = resolve_cache_hit_alignment_tokens(
|
||||
scheduler_kv_cache_config,
|
||||
vllm_config,
|
||||
scheduler_block_size,
|
||||
hash_block_size,
|
||||
)
|
||||
for kv_cache_config in kv_cache_configs:
|
||||
kv_cache_config.hash_block_size = hash_block_size
|
||||
kv_cache_config.cache_hit_alignment_tokens = cache_hit_alignment_tokens
|
||||
|
||||
self.model_executor.initialize_from_config(kv_cache_configs)
|
||||
if not envs.VLLM_ELASTIC_EP_SCALE_UP_LAUNCH:
|
||||
self.model_executor.compile_or_warm_up_model()
|
||||
@@ -810,8 +824,19 @@ class EngineCore:
|
||||
cleanup_dist_env_and_memory()
|
||||
logger.debug_once("[shutdown] EngineCore: local resource teardown complete")
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
|
||||
self.model_executor.profile(is_start, profile_prefix)
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
self.model_executor.profile(
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
|
||||
def reset_mm_cache(self):
|
||||
# NOTE: Since this is mainly for debugging, we don't attempt to
|
||||
@@ -1385,6 +1410,50 @@ class EngineCoreProc(EngineCore):
|
||||
vllm_config.kv_transfer_config.engine_id,
|
||||
)
|
||||
|
||||
# declare engine core as None and register signal handler before
|
||||
# engine_core initialization in case engine core process is terminated
|
||||
# in the middle of initialization. For example, frontend process exits
|
||||
# unexpectedly, if signal handler is not registered, engine core process
|
||||
# will use default signal handler which will terminate the process
|
||||
# silently. If engine core model executor has been initialized, it will
|
||||
# not be terminated asap. Register signal handler early and only log a
|
||||
# message will make engine core process alive. engine core process and
|
||||
# its subprocesses(model executor processes) will be force killed in
|
||||
# CoreEngineProcManager.shutdown.
|
||||
engine_core = None
|
||||
# A termination signal can arrive while engine_core is still being
|
||||
# constructed. At that point the request cannot be recorded on
|
||||
# engine_core, so keep it in its own flag and apply it later.
|
||||
shutdown_requested = False
|
||||
|
||||
def wakeup_engine():
|
||||
# Wakes up idle engine via input_queue when shutdown is requested
|
||||
# Not safe in a signal handler - we may interrupt the main thread
|
||||
# while it is holding the non-reentrant input_queue.mutex
|
||||
assert engine_core is not None
|
||||
engine_core.input_queue.put_nowait((EngineCoreRequestType.WAKEUP, None))
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
nonlocal shutdown_requested
|
||||
signal_name = signal.Signals(signum).name
|
||||
logger.info(
|
||||
"[shutdown] EngineCore: trigger received signal=%s",
|
||||
signal_name,
|
||||
)
|
||||
# Record the request first so it survives the construction window.
|
||||
shutdown_requested = True
|
||||
if engine_core is not None:
|
||||
engine_core.shutdown_state = EngineShutdownState.REQUESTED
|
||||
# signal_callback is armed only after engine_core exists. Don't
|
||||
# trigger it earlier: it is one-shot, and a wakeup cannot be
|
||||
# delivered while there is no input_queue to wake.
|
||||
# For more info: https://github.com/vllm-project/vllm/pull/52299#pullrequestreview-5370255271
|
||||
if signal_callback is not None:
|
||||
signal_callback.trigger()
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
|
||||
parallel_config.data_parallel_index = dp_rank
|
||||
if data_parallel and vllm_config.model_config.is_moe:
|
||||
# Set data parallel rank for this engine process.
|
||||
@@ -1399,25 +1468,15 @@ class EngineCoreProc(EngineCore):
|
||||
|
||||
assert engine_core is not None
|
||||
|
||||
def wakeup_engine():
|
||||
# Wakes up idle engine via input_queue when shutdown is requested
|
||||
# Not safe in a signal handler - we may interrupt the main thread
|
||||
# while it is holding the non-reentrant input_queue.mutex
|
||||
engine_core.input_queue.put_nowait((EngineCoreRequestType.WAKEUP, None))
|
||||
|
||||
signal_callback = SignalCallback(wakeup_engine)
|
||||
|
||||
def signal_handler(signum, frame):
|
||||
signal_name = signal.Signals(signum).name
|
||||
logger.info(
|
||||
"[shutdown] EngineCore: trigger received signal=%s",
|
||||
signal_name,
|
||||
)
|
||||
# Apply a signal received during construction before entering the
|
||||
# loop. run_busy_loop calls _handle_shutdown first, so the loop exits
|
||||
# right away instead of blocking on an idle input_queue.
|
||||
if shutdown_requested:
|
||||
engine_core.shutdown_state = EngineShutdownState.REQUESTED
|
||||
signal_callback.trigger()
|
||||
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
# Arm the wakeup callback only now that input_queue exists, so a
|
||||
# later signal can still wake an idle busy loop.
|
||||
signal_callback = SignalCallback(wakeup_engine)
|
||||
|
||||
engine_core.run_busy_loop()
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from collections import Counter, defaultdict
|
||||
from collections.abc import Awaitable, Callable, Sequence
|
||||
from concurrent.futures import Future
|
||||
from dataclasses import dataclass
|
||||
from multiprocessing.connection import Connection
|
||||
from multiprocessing.queues import Queue
|
||||
from threading import Thread
|
||||
from typing import Any, TypeAlias, TypeVar
|
||||
@@ -56,7 +55,8 @@ from vllm.v1.engine.tensor_ipc import TensorIpcSender
|
||||
from vllm.v1.engine.utils import (
|
||||
CoreEngineActorManager,
|
||||
CoreEngineProcManager,
|
||||
get_engine_zmq_addresses,
|
||||
EngineZmqAddresses,
|
||||
get_engine_zmq_bind_addresses,
|
||||
launch_core_engines,
|
||||
)
|
||||
from vllm.v1.executor import Executor
|
||||
@@ -181,7 +181,13 @@ class EngineCoreClient(ABC):
|
||||
def add_request(self, request: EngineCoreRequest) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def reset_mm_cache(self) -> None:
|
||||
@@ -275,7 +281,11 @@ class EngineCoreClient(ABC):
|
||||
raise NotImplementedError
|
||||
|
||||
async def profile_async(
|
||||
self, is_start: bool = True, profile_prefix: str | None = None
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
@@ -392,8 +402,19 @@ class InprocClient(EngineCoreClient):
|
||||
if self._finalizer.detach() is not None:
|
||||
self.engine_core.shutdown()
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
self.engine_core.profile(is_start, profile_prefix)
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
self.engine_core.profile(
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations=delay_iterations,
|
||||
max_iterations=max_iterations,
|
||||
)
|
||||
|
||||
def reset_mm_cache(self) -> None:
|
||||
self.engine_core.reset_mm_cache()
|
||||
@@ -517,10 +538,10 @@ class BackgroundResources:
|
||||
with contextlib.suppress(Exception):
|
||||
task.cancel()
|
||||
|
||||
if loop is not None:
|
||||
if loop is not None and not loop.is_closed():
|
||||
if in_loop(loop):
|
||||
close_sockets_and_tasks()
|
||||
elif not loop.is_closed():
|
||||
else:
|
||||
loop.call_soon_threadsafe(close_sockets_and_tasks)
|
||||
else:
|
||||
# Loop has been closed, try to clean up directly.
|
||||
@@ -613,63 +634,50 @@ class MPClient(EngineCoreClient):
|
||||
self.stats_update_address = client_addresses.get("stats_update_address")
|
||||
# Tensor queues passed via client_addresses for multi-API-server case
|
||||
tensor_queue = client_addresses.get("tensor_queue")
|
||||
input_listener = client_addresses.get("input_listener")
|
||||
output_listener = client_addresses.get("output_listener")
|
||||
self.input_socket = self.resources.input_socket = make_zmq_socket(
|
||||
self.ctx,
|
||||
input_address,
|
||||
zmq.ROUTER,
|
||||
bind=True,
|
||||
router_handover=enable_input_socket_handover,
|
||||
listener=input_listener,
|
||||
)
|
||||
self.resources.output_socket = make_zmq_socket(
|
||||
self.ctx, output_address, zmq.PULL
|
||||
self.ctx,
|
||||
output_address,
|
||||
zmq.PULL,
|
||||
listener=output_listener,
|
||||
)
|
||||
|
||||
# Report bound endpoints back so the parent can forward
|
||||
# them to engines (mirrors the DPCoordinator pattern).
|
||||
actual_address_pipe: Connection | None = client_addresses.get(
|
||||
"actual_address_pipe"
|
||||
)
|
||||
if actual_address_pipe is not None:
|
||||
try:
|
||||
actual_input = self.input_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
actual_output = self.resources.output_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
actual_address_pipe.send(
|
||||
{
|
||||
"input_address": actual_input,
|
||||
"output_address": actual_output,
|
||||
}
|
||||
)
|
||||
finally:
|
||||
actual_address_pipe.close()
|
||||
# Engines are managed externally: this process does not fork
|
||||
# them, so there is no fork race; start the MM warmup now.
|
||||
self._start_mm_warmup()
|
||||
else:
|
||||
# Engines are managed by this client.
|
||||
addresses = get_engine_zmq_addresses(vllm_config)
|
||||
bind_addresses = get_engine_zmq_bind_addresses(vllm_config)
|
||||
self.input_socket = self.resources.input_socket = make_zmq_socket(
|
||||
self.ctx,
|
||||
addresses.inputs[0],
|
||||
bind_addresses.inputs[0],
|
||||
zmq.ROUTER,
|
||||
bind=True,
|
||||
router_handover=enable_input_socket_handover,
|
||||
)
|
||||
self.resources.output_socket = make_zmq_socket(
|
||||
self.ctx, addresses.outputs[0], zmq.PULL
|
||||
self.ctx, bind_addresses.outputs[0], zmq.PULL
|
||||
)
|
||||
|
||||
# Resolve ``tcp://host:0`` placeholders to bound endpoints
|
||||
# before engines DEALER-connect. No-op for IPC.
|
||||
addresses.inputs[0] = self.input_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
addresses.outputs[0] = self.resources.output_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
# EngineZmqAddresses contains only endpoints resolved by the
|
||||
# sockets that own the bind operation.
|
||||
addresses = EngineZmqAddresses(
|
||||
inputs=[self.input_socket.getsockopt(zmq.LAST_ENDPOINT).decode()],
|
||||
outputs=[
|
||||
self.resources.output_socket.getsockopt(
|
||||
zmq.LAST_ENDPOINT
|
||||
).decode()
|
||||
],
|
||||
)
|
||||
|
||||
with launch_core_engines(
|
||||
vllm_config, executor_class, log_stats, addresses
|
||||
@@ -1019,8 +1027,20 @@ class SyncMPClient(MPClient):
|
||||
if request_ids and not self.resources.engine_dead:
|
||||
self._send_input(EngineCoreRequestType.ABORT, request_ids)
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
self.call_utility("profile", is_start, profile_prefix)
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
self.call_utility(
|
||||
"profile",
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
|
||||
def reset_mm_cache(self) -> None:
|
||||
self.call_utility("reset_mm_cache")
|
||||
@@ -1294,9 +1314,19 @@ class AsyncMPClient(MPClient):
|
||||
return await self.call_utility_consensus_async("is_scheduler_paused")
|
||||
|
||||
async def profile_async(
|
||||
self, is_start: bool = True, profile_prefix: str | None = None
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
) -> None:
|
||||
await self.call_utility_async("profile", is_start, profile_prefix)
|
||||
await self.call_utility_async(
|
||||
"profile",
|
||||
is_start,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
|
||||
async def reset_mm_cache_async(self) -> None:
|
||||
await self.call_utility_async("reset_mm_cache")
|
||||
|
||||
@@ -25,7 +25,7 @@ from vllm.platforms import current_platform
|
||||
from vllm.pooling_params import PoolingParams
|
||||
from vllm.renderers import BaseRenderer, renderer_from_config
|
||||
from vllm.renderers.inputs.preprocess import parse_model_prompt
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.sampling_params import BeamSearchParams, SamplingParams
|
||||
from vllm.tasks import GENERATION_TASKS, POOLING_TASKS, SupportedTask
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.utils import length_from_prompt_token_ids_or_embeds, random_uuid
|
||||
@@ -112,12 +112,41 @@ class InputProcessor:
|
||||
|
||||
return partial(validate_logits_processors_parameters, custom_logitsprocs)
|
||||
|
||||
def resolve_watermarking(self, params: SamplingParams | BeamSearchParams) -> bool:
|
||||
"""Return whether watermarking will be applied to this request.
|
||||
|
||||
``None`` and ``True`` request watermarking, while ``False`` opts out.
|
||||
If watermarking is unavailable or incompatible with the request, emit
|
||||
a warning and return ``False``.
|
||||
"""
|
||||
return self.vllm_config._check_supports_watermarking(params)
|
||||
|
||||
def apply_watermarking(self, params: SamplingParams, watermarking: bool) -> None:
|
||||
"""Store the resolved `watermarking` on request-local params.
|
||||
|
||||
Also records whether watermarking was requested on a watermarking
|
||||
engine but could not be applied, as opposed to an explicit opt-out.
|
||||
"""
|
||||
# Sticky, so resolving an already resolved request keeps the flag.
|
||||
params._watermarking_skipped = params._watermarking_skipped or (
|
||||
self.vllm_config.watermark_config is not None
|
||||
and params.watermarking is not False
|
||||
and not watermarking
|
||||
)
|
||||
params.watermarking = watermarking
|
||||
|
||||
def _validate_params(
|
||||
self,
|
||||
params: SamplingParams | PoolingParams,
|
||||
supported_tasks: tuple[SupportedTask, ...],
|
||||
) -> None:
|
||||
"""Raise `ValueError` if SamplingParams or PoolingParams is not valid."""
|
||||
) -> bool | None:
|
||||
"""Raise `ValueError` if SamplingParams or PoolingParams is not valid.
|
||||
|
||||
Returns the resolved `watermarking` value for `SamplingParams` (`None`
|
||||
for `PoolingParams`). The caller applies it to its private copy of the
|
||||
params so that a caller-owned params object is never mutated.
|
||||
"""
|
||||
watermarking: bool | None = None
|
||||
if isinstance(params, SamplingParams):
|
||||
supported_generation_tasks = [
|
||||
task for task in supported_tasks if task in GENERATION_TASKS
|
||||
@@ -189,6 +218,9 @@ class InputProcessor:
|
||||
"enabled. Start the engine with --enable-trace-replay "
|
||||
"to use it."
|
||||
)
|
||||
# Resolved last so that feature gates above report the missing
|
||||
# feature rather than its incompatibility with watermarking.
|
||||
watermarking = self.resolve_watermarking(params)
|
||||
elif isinstance(params, PoolingParams):
|
||||
supported_pooling_tasks = [
|
||||
task for task in supported_tasks if task in POOLING_TASKS
|
||||
@@ -217,6 +249,8 @@ class InputProcessor:
|
||||
f"but got {type(params).__name__}"
|
||||
)
|
||||
|
||||
return watermarking
|
||||
|
||||
def _normalize_trace_replay_params(
|
||||
self, sampling_params: SamplingParams, prompt_len: int
|
||||
) -> None:
|
||||
@@ -352,7 +386,7 @@ class InputProcessor:
|
||||
session_id: str | None = None,
|
||||
kv_hints: KvHintsEnvelope | None = None,
|
||||
) -> EngineCoreRequest:
|
||||
self._validate_params(params, supported_tasks)
|
||||
watermarking = self._validate_params(params, supported_tasks)
|
||||
self._validate_lora(lora_request)
|
||||
|
||||
parallel_config = self.vllm_config.parallel_config
|
||||
@@ -413,6 +447,10 @@ class InputProcessor:
|
||||
if isinstance(params, SamplingParams):
|
||||
# TODO: can we avoid cloning here in multiproc case?
|
||||
sampling_params = params.clone()
|
||||
# Resolve on the request-local copy: `params` may be shared across
|
||||
# prompts, requests and even engines by the caller.
|
||||
assert watermarking is not None
|
||||
self.apply_watermarking(sampling_params, watermarking)
|
||||
prompt_len = length_from_prompt_token_ids_or_embeds(
|
||||
prompt_token_ids, prompt_embeds
|
||||
)
|
||||
|
||||
@@ -12,9 +12,14 @@ from typing_extensions import TypeVar
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import ParallelConfig, VllmConfig
|
||||
from vllm.config.profiler import (
|
||||
validate_profile_iteration_bounds,
|
||||
validate_profile_prefix,
|
||||
)
|
||||
from vllm.distributed import stateless_destroy_torch_distributed_process_group
|
||||
from vllm.distributed.parallel_state import get_dp_group
|
||||
from vllm.engine.arg_utils import EngineArgs
|
||||
from vllm.exceptions import ProfilerAlreadyActiveError
|
||||
from vllm.inputs import EngineInput, PromptType
|
||||
from vllm.logger import configure_logging_if_needed, init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
@@ -116,6 +121,7 @@ class LLMEngine:
|
||||
log_stats=self.log_stats,
|
||||
renderer=renderer,
|
||||
)
|
||||
self._profile_session_active = False
|
||||
|
||||
self.logger_manager: StatLoggerManager | None = None
|
||||
if self.log_stats:
|
||||
@@ -254,6 +260,13 @@ class LLMEngine:
|
||||
"does not match the EngineCoreRequest.request_id attribute. The "
|
||||
"latter will be used, and the former will be ignored."
|
||||
)
|
||||
request_params = request.params
|
||||
if isinstance(request_params, SamplingParams):
|
||||
# This request object is owned by the engine from here on.
|
||||
self.input_processor.apply_watermarking(
|
||||
request_params,
|
||||
self.input_processor.resolve_watermarking(request_params),
|
||||
)
|
||||
else:
|
||||
request = self.input_processor.process_inputs(
|
||||
request_id,
|
||||
@@ -351,11 +364,33 @@ class LLMEngine:
|
||||
|
||||
return processed_outputs.request_outputs
|
||||
|
||||
def start_profile(self, profile_prefix: str | None = None):
|
||||
self.engine_core.profile(True, profile_prefix)
|
||||
def start_profile(
|
||||
self,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
if self._profile_session_active:
|
||||
raise ProfilerAlreadyActiveError()
|
||||
validate_profile_prefix(profile_prefix)
|
||||
validate_profile_iteration_bounds(delay_iterations, max_iterations)
|
||||
|
||||
self._profile_session_active = True
|
||||
try:
|
||||
self.engine_core.profile(
|
||||
True,
|
||||
profile_prefix,
|
||||
delay_iterations,
|
||||
max_iterations,
|
||||
)
|
||||
except BaseException:
|
||||
self._profile_session_active = False
|
||||
raise
|
||||
|
||||
def stop_profile(self):
|
||||
self.engine_core.profile(False)
|
||||
self._profile_session_active = False
|
||||
|
||||
def reset_mm_cache(self):
|
||||
# Join the background MM warmup first: the mm_processor_cache is not
|
||||
|
||||
+85
-16
@@ -23,9 +23,10 @@ from vllm.platforms import current_platform
|
||||
from vllm.ray.ray_env import get_env_vars_to_copy
|
||||
from vllm.utils import numa_utils
|
||||
from vllm.utils.network_utils import (
|
||||
get_open_port,
|
||||
ZmqListener,
|
||||
get_open_zmq_ipc_path,
|
||||
get_tcp_uri,
|
||||
make_zmq_listener,
|
||||
zmq_socket_ctx,
|
||||
)
|
||||
from vllm.utils.system_utils import get_mp_context, set_env_var
|
||||
@@ -82,8 +83,18 @@ class CoreEngine:
|
||||
self.state = CoreEngineState.NEW
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineZmqBindAddresses:
|
||||
"""Frontend endpoints before their owning sockets bind."""
|
||||
|
||||
inputs: list[str]
|
||||
outputs: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineZmqAddresses:
|
||||
"""Resolved frontend endpoints advertised to engine processes."""
|
||||
|
||||
# ZMQ input socket addresses for each front-end client (requests)
|
||||
inputs: list[str]
|
||||
# ZMQ output socket addresses for each front-end client (responses)
|
||||
@@ -98,6 +109,27 @@ class EngineZmqAddresses:
|
||||
frontend_stats_publish_address: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineZmqListeners:
|
||||
inputs: list[ZmqListener]
|
||||
outputs: list[ZmqListener]
|
||||
|
||||
@property
|
||||
def addresses(self) -> EngineZmqAddresses:
|
||||
return EngineZmqAddresses(
|
||||
inputs=[listener.address for listener in self.inputs],
|
||||
outputs=[listener.address for listener in self.outputs],
|
||||
)
|
||||
|
||||
def cleanup(self) -> None:
|
||||
for listener in (*self.inputs, *self.outputs):
|
||||
listener.cleanup()
|
||||
|
||||
def __del__(self) -> None:
|
||||
with contextlib.suppress(Exception):
|
||||
self.cleanup()
|
||||
|
||||
|
||||
@dataclass
|
||||
class EngineHandshakeMetadata:
|
||||
"""Metadata sent to each engine process during startup handshake,
|
||||
@@ -1079,22 +1111,16 @@ class CoreEngineActorManager:
|
||||
ray.util.remove_placement_group(pg)
|
||||
|
||||
|
||||
def get_engine_zmq_addresses(
|
||||
def get_engine_zmq_bind_addresses(
|
||||
vllm_config: VllmConfig,
|
||||
num_api_servers: int = 1,
|
||||
*,
|
||||
defer_api_server_ports: bool = True,
|
||||
) -> EngineZmqAddresses:
|
||||
"""Allocate ZMQ addresses for engine-client communication.
|
||||
) -> EngineZmqBindAddresses:
|
||||
"""Create ZMQ endpoint templates for engine-client communication.
|
||||
|
||||
By default each TCP address is a ``tcp://host:0`` placeholder; the
|
||||
consumer (API-server child or single-process ``MPClient``) binds, then
|
||||
recovers the kernel-assigned port via ``getsockopt(zmq.LAST_ENDPOINT)``
|
||||
and writes it back into ``addresses`` before the engine handshake.
|
||||
|
||||
Set ``defer_api_server_ports=False`` only when the consumer cannot
|
||||
report a bound port back (e.g. the Rust front-end). IPC paths are
|
||||
unaffected."""
|
||||
Each TCP address is a ``tcp://host:0`` placeholder. A single-process
|
||||
``MPClient`` binds its own ZMQ sockets. Cross-process frontends use
|
||||
``bind_engine_zmq_listeners`` so the supervisor binds raw listeners before
|
||||
launching engines and transfers listener ownership to each frontend."""
|
||||
parallel_config = vllm_config.parallel_config
|
||||
local_engine_count = parallel_config.data_parallel_size_local
|
||||
local_start_index = parallel_config.data_parallel_rank_local
|
||||
@@ -1119,14 +1145,39 @@ def get_engine_zmq_addresses(
|
||||
def _addr() -> str:
|
||||
if client_local_only:
|
||||
return get_open_zmq_ipc_path()
|
||||
return get_tcp_uri(host, 0 if defer_api_server_ports else get_open_port())
|
||||
return get_tcp_uri(host, 0)
|
||||
|
||||
return EngineZmqAddresses(
|
||||
return EngineZmqBindAddresses(
|
||||
inputs=[_addr() for _ in range(num_api_servers)],
|
||||
outputs=[_addr() for _ in range(num_api_servers)],
|
||||
)
|
||||
|
||||
|
||||
def bind_engine_zmq_listeners(
|
||||
vllm_config: VllmConfig,
|
||||
num_api_servers: int = 1,
|
||||
) -> EngineZmqListeners:
|
||||
"""Bind frontend transport listeners before launching engines."""
|
||||
bind_addresses = get_engine_zmq_bind_addresses(
|
||||
vllm_config,
|
||||
num_api_servers,
|
||||
)
|
||||
inputs: list[ZmqListener] = []
|
||||
outputs: list[ZmqListener] = []
|
||||
try:
|
||||
inputs.extend(
|
||||
make_zmq_listener(address, zmq.ROUTER) for address in bind_addresses.inputs
|
||||
)
|
||||
outputs.extend(
|
||||
make_zmq_listener(address, zmq.PULL) for address in bind_addresses.outputs
|
||||
)
|
||||
return EngineZmqListeners(inputs=inputs, outputs=outputs)
|
||||
except BaseException:
|
||||
for listener in (*inputs, *outputs):
|
||||
listener.cleanup()
|
||||
raise
|
||||
|
||||
|
||||
FrontendProcess = BaseProcess | _SubprocessWrapper
|
||||
|
||||
|
||||
@@ -1195,6 +1246,23 @@ def launch_core_engines(
|
||||
else:
|
||||
coordinator = None
|
||||
|
||||
# Hold a coordination TCPStore (alive for this frame) so engines pick DP
|
||||
# master ports at bind time; pre-allocated ports can be taken before use.
|
||||
coord_store = None
|
||||
if (
|
||||
dp_size > 1
|
||||
and not offline_mode
|
||||
and dp_rank == 0
|
||||
and local_engine_count > 0
|
||||
and not parallel_config.enable_elastic_ep
|
||||
):
|
||||
from vllm.distributed.utils import create_tcp_store
|
||||
|
||||
coord_store = create_tcp_store(
|
||||
host, 0, is_master=True, world_size=-1, wait_for_workers=False
|
||||
)
|
||||
parallel_config._coord_store_port = coord_store.port
|
||||
|
||||
if parallel_config.data_parallel_backend == "ray":
|
||||
logger.info("Starting ray-based data parallel backend")
|
||||
|
||||
@@ -1415,6 +1483,7 @@ def wait_for_engine_startup(
|
||||
"data_parallel_master_ip",
|
||||
"data_parallel_master_port",
|
||||
"_data_parallel_master_port_list",
|
||||
"_coord_store_port",
|
||||
"data_parallel_size",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import inspect
|
||||
import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Callable
|
||||
@@ -38,6 +39,18 @@ SLEEP_TAGS = frozenset(("weights", "kv_cache"))
|
||||
FailureCallback = Callable[[], None]
|
||||
|
||||
|
||||
def _check_worker_profile_kwargs(worker_cls: str, kwargs: dict[str, int]) -> None:
|
||||
"""Raise if the worker's ``profile`` cannot accept the given overrides."""
|
||||
params = inspect.signature(resolve_obj_by_qualname(worker_cls).profile).parameters
|
||||
if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()):
|
||||
return
|
||||
if unsupported := [name for name in kwargs if name not in params]:
|
||||
raise ValueError(
|
||||
f"Worker class {worker_cls} does not support per-session profiling "
|
||||
f"overrides: {', '.join(unsupported)}"
|
||||
)
|
||||
|
||||
|
||||
class Executor(ABC):
|
||||
"""Abstract base class for vLLM executors.
|
||||
|
||||
@@ -269,8 +282,30 @@ class Executor(ABC):
|
||||
output: list[DraftTokenIds] = self.collective_rpc("take_draft_token_ids")
|
||||
return output[0]
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None):
|
||||
self.collective_rpc("profile", args=(is_start, profile_prefix))
|
||||
def profile(
|
||||
self,
|
||||
is_start: bool = True,
|
||||
profile_prefix: str | None = None,
|
||||
*,
|
||||
delay_iterations: int | None = None,
|
||||
max_iterations: int | None = None,
|
||||
):
|
||||
kwargs: dict[str, int] = {}
|
||||
if delay_iterations is not None:
|
||||
kwargs["delay_iterations"] = delay_iterations
|
||||
if max_iterations is not None:
|
||||
kwargs["max_iterations"] = max_iterations
|
||||
if kwargs:
|
||||
# Reject before dispatch: a failing collective_rpc may leave
|
||||
# unread worker replies queued.
|
||||
_check_worker_profile_kwargs(
|
||||
self.vllm_config.parallel_config.worker_cls, kwargs
|
||||
)
|
||||
self.collective_rpc(
|
||||
"profile",
|
||||
args=(is_start, profile_prefix),
|
||||
kwargs=kwargs or None,
|
||||
)
|
||||
|
||||
def save_sharded_state(
|
||||
self,
|
||||
|
||||
@@ -364,7 +364,11 @@ class MultiprocExecutor(Executor):
|
||||
)
|
||||
|
||||
def execute_dummy_batch(self) -> None:
|
||||
self.collective_rpc("execute_dummy_batch", unique_reply_rank=self.output_rank)
|
||||
self.collective_rpc(
|
||||
"execute_dummy_batch",
|
||||
unique_reply_rank=self.output_rank,
|
||||
timeout=envs.VLLM_EXECUTE_MODEL_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
def take_draft_token_ids(self) -> DraftTokenIds | None:
|
||||
# OPTIMIZATION: Get output only from a single worker (output_rank)
|
||||
|
||||
@@ -147,7 +147,6 @@ def init_hisparse_kv_cache(
|
||||
initialize_hisparse_runtime_buffers(
|
||||
cache_handles,
|
||||
max_num_reqs=vllm_config.scheduler_config.max_num_seqs,
|
||||
max_num_batched_tokens=vllm_config.scheduler_config.max_num_batched_tokens,
|
||||
)
|
||||
return kv_caches
|
||||
except Exception:
|
||||
@@ -197,9 +196,6 @@ def release_hisparse_profiling_cache(forward_context: dict[str, Any]) -> None:
|
||||
)
|
||||
)
|
||||
release_pinned_state(list(runtimes.values()), registered_pools, shared_region)
|
||||
for cache in cache_handles:
|
||||
cache.mirror_staging_cache = None
|
||||
cache.mirror_staging_slots = None
|
||||
|
||||
|
||||
def bind_hisparse_kv_caches(
|
||||
|
||||
@@ -19,6 +19,7 @@ from vllm.v1.core.single_type_kv_cache_manager import (
|
||||
SingleTypeKVCacheManager,
|
||||
)
|
||||
from vllm.v1.hisparse.types import (
|
||||
ACTIVE_TAIL_PAGES,
|
||||
SparseKVOffloadCommand,
|
||||
SparseKVPageTransfer,
|
||||
SparseKVRowMirror,
|
||||
@@ -32,10 +33,6 @@ from vllm.v1.request import Request
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.core.kv_cache_manager import KVCacheManager
|
||||
|
||||
# Sealed pages this many positions behind the block-table tail stay pinned so
|
||||
# a page written by an in-flight step is never handed out under it.
|
||||
_ACTIVE_TAIL_PAGES = 2
|
||||
|
||||
|
||||
@dataclass
|
||||
class _PendingPublication:
|
||||
@@ -171,6 +168,10 @@ class HiSparseCoordinator:
|
||||
# request -> prefix length an external load is still filling in.
|
||||
self._pending_imports: dict[str, int] = {}
|
||||
self.block_table_updates: set[str] = set()
|
||||
# Requests whose resident pages were all non-null when last scanned.
|
||||
# Pages only become null at admission or import (before the first
|
||||
# scan) and when the pool reuses an unpinned page (_lose_page).
|
||||
self._resident_requests: set[str] = set()
|
||||
self.spills_to_send: list[SparseKVPageTransfer] = []
|
||||
self.pending_spills: dict[int, _PendingSpill] = {}
|
||||
self.request_states: dict[str, _HiSparseRequestState] = {}
|
||||
@@ -191,6 +192,7 @@ class HiSparseCoordinator:
|
||||
|
||||
def commit_computed_blocks(self, request_id: str, num_host_pages: int) -> None:
|
||||
"""Account for a prefix hit on host pages the request now references."""
|
||||
self._resident_requests.discard(request_id)
|
||||
if not self.resident_managers or self.host_manager is None:
|
||||
return
|
||||
host_blocks = self.host_manager.req_to_blocks.get(request_id, ())
|
||||
@@ -343,7 +345,7 @@ class HiSparseCoordinator:
|
||||
req_blocks = manager.req_to_blocks.get(request_id)
|
||||
if (
|
||||
req_blocks is None
|
||||
or page_idx >= len(req_blocks) - _ACTIVE_TAIL_PAGES
|
||||
or page_idx >= len(req_blocks) - ACTIVE_TAIL_PAGES
|
||||
or req_blocks[page_idx].is_null
|
||||
):
|
||||
return None
|
||||
@@ -385,6 +387,7 @@ class HiSparseCoordinator:
|
||||
self._lose_page(request_id, page_idx)
|
||||
|
||||
def _lose_page(self, request_id: str, page_idx: int) -> None:
|
||||
self._resident_requests.discard(request_id)
|
||||
state = self.request_states.get(request_id)
|
||||
if state is None:
|
||||
return
|
||||
@@ -533,6 +536,7 @@ class HiSparseCoordinator:
|
||||
|
||||
def record_pending_host_import(self, request_id: str, num_tokens: int) -> None:
|
||||
"""Note a prefix an external load is populating in host pages."""
|
||||
self._resident_requests.discard(request_id)
|
||||
self._pending_imports[request_id] = num_tokens
|
||||
|
||||
def finish_host_import(self, request_id: str, *, failed: bool) -> None:
|
||||
@@ -677,15 +681,22 @@ class HiSparseCoordinator:
|
||||
"""Return whether every scheduled request can read only resident KV."""
|
||||
if not self.resident_managers:
|
||||
return False
|
||||
block_size = self.resident_managers[0].block_size
|
||||
first = self.resident_managers[0]
|
||||
for request_id, num_computed_tokens, num_scheduled_tokens in requests:
|
||||
num_pages = cdiv(num_computed_tokens + num_scheduled_tokens, block_size)
|
||||
for page_idx in range(num_pages):
|
||||
if any(
|
||||
manager.get_resident_page(request_id, page_idx) is None
|
||||
for manager in self.resident_managers
|
||||
):
|
||||
return False
|
||||
num_pages = cdiv(
|
||||
num_computed_tokens + num_scheduled_tokens, first.block_size
|
||||
)
|
||||
if len(first.req_to_blocks.get(request_id, ())) < num_pages:
|
||||
return False
|
||||
if request_id in self._resident_requests:
|
||||
continue
|
||||
if any(
|
||||
block.is_null
|
||||
for manager in self.resident_managers
|
||||
for block in manager.req_to_blocks.get(request_id, ())
|
||||
):
|
||||
return False
|
||||
self._resident_requests.add(request_id)
|
||||
return True
|
||||
|
||||
def take_block_table_updates(self) -> dict[str, tuple[list[int], ...]]:
|
||||
@@ -809,6 +820,7 @@ class HiSparseCoordinator:
|
||||
|
||||
def free(self, request_id: str) -> None:
|
||||
"""Detach the request; its clean pages stay readable copies in the pool."""
|
||||
self._resident_requests.discard(request_id)
|
||||
self._pending_imports.pop(request_id, None)
|
||||
state = self.request_states.pop(request_id, None)
|
||||
if state is None:
|
||||
|
||||
@@ -14,6 +14,7 @@ from vllm.v1.hisparse.runtime import (
|
||||
get_hisparse_host_block_stride,
|
||||
use_shared_hisparse_host_pool,
|
||||
)
|
||||
from vllm.v1.hisparse.types import ACTIVE_TAIL_PAGES
|
||||
from vllm.v1.kv_cache_interface import (
|
||||
HiSparseHotSpec,
|
||||
HiSparseResidentSpec,
|
||||
@@ -373,3 +374,34 @@ def get_hisparse_kv_cache_config(
|
||||
vllm_config.cache_config.prefix_cache_retention_interval
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def get_hisparse_steady_state_concurrency(
|
||||
vllm_config: VllmConfig, kv_cache_config: KVCacheConfig
|
||||
) -> float:
|
||||
"""Max concurrency at max_model_len once running requests read from host.
|
||||
|
||||
A request reading from host pins only its active tail of each resident
|
||||
group, but admitting one still takes its full in-flight window, so the
|
||||
bound is all-but-one requests at steady state plus one being admitted.
|
||||
"""
|
||||
admission_blocks = 0
|
||||
steady_blocks = 0
|
||||
host_blocks = 0
|
||||
for group in kv_cache_config.kv_cache_groups:
|
||||
spec = group.kv_cache_spec
|
||||
required = cdiv(spec.max_memory_usage_bytes(vllm_config), spec.page_size_bytes)
|
||||
if group.host_resident:
|
||||
host_blocks += required
|
||||
continue
|
||||
admission_blocks += required
|
||||
if isinstance(spec, HiSparseResidentSpec):
|
||||
required = min(required, ACTIVE_TAIL_PAGES)
|
||||
steady_blocks += required
|
||||
assert kv_cache_config.hisparse_host_num_blocks is not None
|
||||
num_blocks = kv_cache_config.num_blocks
|
||||
if num_blocks < admission_blocks:
|
||||
gpu_concurrency = num_blocks / admission_blocks
|
||||
else:
|
||||
gpu_concurrency = 1 + (num_blocks - admission_blocks) / steady_blocks
|
||||
return min(gpu_concurrency, kv_cache_config.hisparse_host_num_blocks / host_blocks)
|
||||
|
||||
@@ -894,14 +894,17 @@ class HiSparseRuntime:
|
||||
def begin_forward(self) -> None:
|
||||
self._swap_step = 0
|
||||
|
||||
@property
|
||||
def max_swap_rows(self) -> int:
|
||||
return self.index_group.shared_topk.physical_topk_indices.shape[0]
|
||||
|
||||
def _step_rows(self, num_tokens: int) -> slice:
|
||||
start = self._swap_step * num_tokens
|
||||
stop = start + num_tokens
|
||||
if stop > self.index_group.shared_topk.physical_topk_indices.shape[0]:
|
||||
if stop > self.max_swap_rows:
|
||||
raise ValueError(
|
||||
"HiSparse swap rows exceed the configured speculative decode "
|
||||
f"capacity: stop={stop}, capacity="
|
||||
f"{self.index_group.shared_topk.physical_topk_indices.shape[0]}."
|
||||
f"capacity: stop={stop}, capacity={self.max_swap_rows}."
|
||||
)
|
||||
self._swap_step += 1
|
||||
return slice(start, stop)
|
||||
@@ -1120,10 +1123,7 @@ class HiSparseCacheHandle:
|
||||
self.num_decode_tokens = 0
|
||||
self.req_id_per_token: torch.Tensor | None = None
|
||||
self.host_mirror_required = False
|
||||
self.mirror_from_resident = False
|
||||
self.mirror_slot_mapping: torch.Tensor | None = None
|
||||
self.mirror_staging_cache: torch.Tensor | None = None
|
||||
self.mirror_staging_slots: torch.Tensor | None = None
|
||||
self.submit_layer_mirror: Callable[[], None] | None = None
|
||||
# Speculator layers write their rows after the target forward.
|
||||
self.draft_layer = False
|
||||
@@ -1160,26 +1160,6 @@ class HiSparseCacheHandle:
|
||||
num_rows = min(num_rows, self.runtime.max_num_reqs)
|
||||
return self.view.cache, self.slot_mapping[:num_rows], num_rows
|
||||
|
||||
def mirror_write_target(
|
||||
self, num_rows: int
|
||||
) -> tuple[torch.Tensor, torch.Tensor] | None:
|
||||
if (
|
||||
not self.host_mirror_required
|
||||
or self.decode_batch
|
||||
or self.mirror_from_resident
|
||||
):
|
||||
return None
|
||||
cache = self.mirror_staging_cache
|
||||
slots = self.mirror_staging_slots
|
||||
if cache is None or slots is None:
|
||||
raise RuntimeError("HiSparse prefill mirror staging is not bound.")
|
||||
if num_rows > slots.numel():
|
||||
raise RuntimeError(
|
||||
"HiSparse prefill mirror exceeds staging capacity: "
|
||||
f"{num_rows} > {slots.numel()}."
|
||||
)
|
||||
return cache, slots[:num_rows]
|
||||
|
||||
def finish_kv_update(self) -> None:
|
||||
if self.dummy_batch:
|
||||
return
|
||||
@@ -1242,9 +1222,8 @@ def initialize_hisparse_runtime_buffers(
|
||||
cache_handles: list[HiSparseCacheHandle],
|
||||
*,
|
||||
max_num_reqs: int,
|
||||
max_num_batched_tokens: int,
|
||||
) -> None:
|
||||
"""Allocate shared request state and per-layer prefill staging buffers."""
|
||||
"""Allocate the request state shared by every HiSparse runtime."""
|
||||
assert cache_handles
|
||||
resident = cache_handles[0].view
|
||||
assert resident is not None
|
||||
@@ -1252,26 +1231,8 @@ def initialize_hisparse_runtime_buffers(
|
||||
request_state_indices = torch.full(
|
||||
(max_num_reqs,), -1, dtype=torch.int32, device=device
|
||||
)
|
||||
staging_blocks = (
|
||||
max_num_batched_tokens + resident.block_size - 1
|
||||
) // resident.block_size
|
||||
mirror_staging_caches = torch.empty(
|
||||
(
|
||||
len(cache_handles),
|
||||
staging_blocks,
|
||||
resident.block_size,
|
||||
resident.cache.shape[-1],
|
||||
),
|
||||
dtype=resident.cache.dtype,
|
||||
device=device,
|
||||
)
|
||||
mirror_staging_slots = torch.arange(
|
||||
max_num_batched_tokens, dtype=torch.int64, device=device
|
||||
)
|
||||
for layer_index, cache_handle in enumerate(cache_handles):
|
||||
for cache_handle in cache_handles:
|
||||
cache_handle.runtime.request_state_indices = request_state_indices
|
||||
cache_handle.mirror_staging_cache = mirror_staging_caches[layer_index]
|
||||
cache_handle.mirror_staging_slots = mirror_staging_slots
|
||||
|
||||
|
||||
def create_hisparse_cache_handle(
|
||||
@@ -1325,11 +1286,4 @@ def create_hisparse_cache_handle(
|
||||
config.device_buffer_size,
|
||||
max_num_reqs,
|
||||
)
|
||||
handle = HiSparseCacheHandle(runtime)
|
||||
speculative_config = vllm_config.speculative_config
|
||||
handle.mirror_from_resident = bool(
|
||||
vllm_config.scheduler_config.async_scheduling
|
||||
and speculative_config is not None
|
||||
and speculative_config.uses_draft_kv_cache()
|
||||
)
|
||||
return handle
|
||||
return HiSparseCacheHandle(runtime)
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
# Sealed pages this many positions behind the block-table tail stay pinned so
|
||||
# a page written by an in-flight step is never handed out under it.
|
||||
ACTIVE_TAIL_PAGES = 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SparseKVPageTransfer:
|
||||
|
||||
@@ -11,10 +11,9 @@ from enum import Enum, IntEnum
|
||||
from fractions import Fraction
|
||||
from functools import cached_property
|
||||
from math import prod
|
||||
from typing import TYPE_CHECKING, TypeVar
|
||||
from typing import TYPE_CHECKING, Self, TypeVar
|
||||
|
||||
import torch
|
||||
from typing_extensions import Self
|
||||
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.math_utils import cdiv, round_up
|
||||
@@ -55,6 +54,7 @@ class KVQuantMode(IntEnum):
|
||||
TURBOQUANT_K3V4_NC = 8
|
||||
TURBOQUANT_3BIT_NC = 9
|
||||
NVFP4_DS_MLA = 10 # opaque-bytes NVFP4 DS-MLA layouts (FlashMLA sparse)
|
||||
ULTRAQUANT_4BIT = 11 # packed FP4 values + UE8M0 group scales
|
||||
|
||||
@property
|
||||
def is_per_token_head(self) -> bool:
|
||||
@@ -80,6 +80,11 @@ class KVQuantMode(IntEnum):
|
||||
KVQuantMode.TURBOQUANT_3BIT_NC,
|
||||
)
|
||||
|
||||
@property
|
||||
def is_ultraquant(self) -> bool:
|
||||
"""True for the UltraQuant 4-bit KV-cache format."""
|
||||
return self == KVQuantMode.ULTRAQUANT_4BIT
|
||||
|
||||
|
||||
def get_kv_quant_mode(kv_cache_dtype: str) -> KVQuantMode:
|
||||
"""Map a ``kv_cache_dtype`` string to a :class:`KVQuantMode`."""
|
||||
@@ -98,6 +103,8 @@ def get_kv_quant_mode(kv_cache_dtype: str) -> KVQuantMode:
|
||||
return KVQuantMode.NVFP4
|
||||
if isinstance(kv_cache_dtype, str) and kv_cache_dtype.startswith("turboquant_"):
|
||||
return KVQuantMode[kv_cache_dtype.upper()]
|
||||
if kv_cache_dtype == "ultraquant_4bit":
|
||||
return KVQuantMode.ULTRAQUANT_4BIT
|
||||
if isinstance(kv_cache_dtype, str) and kv_cache_dtype.startswith("fp8"):
|
||||
return KVQuantMode.FP8_PER_TENSOR
|
||||
return KVQuantMode.NONE
|
||||
@@ -1120,7 +1127,10 @@ def get_mamba_prefill_checkpoint_position(
|
||||
drop_eagle_block: bool,
|
||||
) -> int:
|
||||
"""Return the reusable Mamba checkpoint boundary for a prefill."""
|
||||
checkpoint_position = (num_tokens - 1) // hash_block_size * hash_block_size
|
||||
# Without EAGLE, leave one token to recompute on resend.
|
||||
# EAGLE's block drop already leaves tokens to recompute.
|
||||
proof_limit = num_tokens if drop_eagle_block else num_tokens - 1
|
||||
checkpoint_position = proof_limit // hash_block_size * hash_block_size
|
||||
if drop_eagle_block:
|
||||
checkpoint_position -= hash_block_size
|
||||
return max(checkpoint_position, 0)
|
||||
@@ -1480,6 +1490,10 @@ class KVCacheConfig:
|
||||
"""Resolved retention policy for local prefix-cache checkpoints."""
|
||||
kv_cache_layout: str | None = None
|
||||
"""The KV cache layout resolved by the engine core, adopted by all workers."""
|
||||
hash_block_size: int | None = None
|
||||
"""Tokens per prefix-cache block hash, resolved by the engine core."""
|
||||
cache_hit_alignment_tokens: int | None = None
|
||||
"""Token granularity of prefix-cache hits, resolved by the engine core."""
|
||||
hisparse_host_num_blocks: int | None = None
|
||||
"""Capacity of the dedicated HiSparse host-block manager, when enabled."""
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ if TYPE_CHECKING:
|
||||
|
||||
from vllm.v1.kv_hints import KvHintsEnvelope
|
||||
from vllm.v1.kv_offload.config import OffloadingConfig
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
# `OffloadKey` identifies an offloaded block. It combines a block hash with
|
||||
# its KV cache group index, encoded as raw bytes to avoid tuple GC overhead.
|
||||
@@ -248,6 +249,18 @@ class OffloadingManager(ABC):
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_load_source(
|
||||
self, key: OffloadKey, req_context: ReqContext
|
||||
) -> CacheHitSource:
|
||||
"""Return the cache tier that supplied a successful lookup.
|
||||
|
||||
This is queried only after ``lookup`` resolves to ``HIT``. Composing
|
||||
managers can override it to retain the origin across asynchronous
|
||||
promotion into a primary tier. The default keeps out-of-tree managers
|
||||
compatible while making unknown provenance explicit.
|
||||
"""
|
||||
return CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
|
||||
@abstractmethod
|
||||
def prepare_load(
|
||||
self,
|
||||
|
||||
@@ -11,7 +11,6 @@ import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.distributed.device_communicators.cuda_wrapper import CudaRTLibrary
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.triton_utils import HAS_TRITON, triton
|
||||
@@ -27,6 +26,7 @@ from vllm.v1.kv_offload.base import (
|
||||
OffloadingWorker,
|
||||
TransferResult,
|
||||
)
|
||||
from vllm.v1.kv_offload.cpu.host_register import host_register, host_unregister
|
||||
from vllm.v1.kv_offload.cpu.shared_offload_region import SharedOffloadRegion
|
||||
from vllm.v1.kv_offload.cpu.swap_blocks_triton import (
|
||||
THRESHOLD_BYTES,
|
||||
@@ -200,26 +200,7 @@ MAX_HOST_REGISTER_CHUNK_BYTES = 64 * 1024**3
|
||||
|
||||
def pin_mmap_region(region: SharedOffloadRegion) -> None:
|
||||
"""Register row-aligned chunks, rolling back on failure."""
|
||||
if not current_platform.is_cuda_alike():
|
||||
logger.info(
|
||||
"Skipping mmap host registration on %s; cudaHostRegister is only "
|
||||
"available on CUDA/ROCm.",
|
||||
current_platform.device_name,
|
||||
)
|
||||
return
|
||||
|
||||
rank = region.rank
|
||||
try:
|
||||
cudart = CudaRTLibrary()
|
||||
except (AssertionError, AttributeError, OSError):
|
||||
logger.warning(
|
||||
"Could not load the CUDA runtime for host registration on rank=%d; "
|
||||
"the offload region stays pageable",
|
||||
rank,
|
||||
exc_info=True,
|
||||
)
|
||||
return
|
||||
|
||||
base_ptr = region._base.data_ptr()
|
||||
total_size = region.total_size_bytes
|
||||
# Chunks end on block-row boundaries, which are page aligned, so neither the
|
||||
@@ -228,42 +209,30 @@ def pin_mmap_region(region: SharedOffloadRegion) -> None:
|
||||
rows_per_chunk = max(MAX_HOST_REGISTER_CHUNK_BYTES // region._row_stride, 1)
|
||||
chunk_size = rows_per_chunk * region._row_stride
|
||||
|
||||
# Register, drain and roll back through the same runtime handle, so a
|
||||
# failed chunk leaves neither a pending error nor a partly pinned region.
|
||||
# Register, drain and roll back through the same helper, so a failed
|
||||
# chunk leaves neither a pending error nor a partly pinned region.
|
||||
addresses: list[int] = []
|
||||
for offset in range(0, total_size, chunk_size):
|
||||
address = base_ptr + offset
|
||||
size = min(chunk_size, total_size - offset)
|
||||
result = cudart.cudaHostRegister(address, size)
|
||||
if result == 0:
|
||||
if host_register(address, size):
|
||||
addresses.append(address)
|
||||
continue
|
||||
cudart.cudaGetLastError()
|
||||
logger.warning(
|
||||
"cudaHostRegister failed for rank=%d at %.2f of %.2f GB (code=%d); "
|
||||
"host_register failed for rank=%d at %.2f of %.2f GB; "
|
||||
"the offload region stays pageable",
|
||||
rank,
|
||||
offset / 1e9,
|
||||
total_size / 1e9,
|
||||
result,
|
||||
)
|
||||
for registered in reversed(addresses):
|
||||
unregister_result = cudart.cudaHostUnregister(registered)
|
||||
if unregister_result != 0:
|
||||
cudart.cudaGetLastError()
|
||||
logger.warning(
|
||||
"cudaHostUnregister failed for rank=%d at %#x (code=%d); "
|
||||
"that chunk stays registered until the process exits",
|
||||
rank,
|
||||
registered,
|
||||
unregister_result,
|
||||
)
|
||||
host_unregister(registered)
|
||||
return
|
||||
|
||||
region.pinned_addresses.extend(addresses)
|
||||
region.is_pinned = True
|
||||
logger.debug(
|
||||
"cudaHostRegister rank=%d %.2f GB in %d chunk(s)",
|
||||
"Host-registered mmap region rank=%d %.2f GB in %d chunk(s)",
|
||||
rank,
|
||||
total_size / 1e9,
|
||||
len(addresses),
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Registration of existing host memory for pinned DMA transfers.
|
||||
|
||||
Host allocations that the offloading workers share across processes (the
|
||||
`SharedOffloadRegion` mmap) cannot be allocated through the accelerator's
|
||||
pinned allocator, so they must be registered after the fact. Pinning is a
|
||||
pure bandwidth optimization: when registration is unavailable the transfers
|
||||
still run correctly, just as pageable (slower) copies.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.distributed.device_communicators.cuda_wrapper import CudaRTLibrary
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def _load_cudart() -> CudaRTLibrary | None:
|
||||
try:
|
||||
return CudaRTLibrary()
|
||||
except (AssertionError, AttributeError, OSError):
|
||||
logger.warning(
|
||||
"Could not load the CUDA runtime for host registration; "
|
||||
"the offload region stays pageable",
|
||||
exc_info=True,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def host_register(ptr: int, num_bytes: int) -> bool:
|
||||
"""Register a host range as device-accessible pinned memory.
|
||||
|
||||
Args:
|
||||
ptr: Base address of the host range.
|
||||
num_bytes: Size of the host range in bytes.
|
||||
|
||||
Returns:
|
||||
True if the range was registered and later needs `host_unregister`.
|
||||
|
||||
"""
|
||||
if not ptr or num_bytes <= 0:
|
||||
return False
|
||||
|
||||
if current_platform.is_cuda_alike():
|
||||
cudart = _load_cudart()
|
||||
if cudart is None:
|
||||
return False
|
||||
result = cudart.cudaHostRegister(ptr, num_bytes)
|
||||
if result != 0:
|
||||
cudart.cudaGetLastError()
|
||||
logger.warning(
|
||||
"cudaHostRegister failed (code=%d) — transfers will still work "
|
||||
"but may be slower (unpinned DMA)",
|
||||
result,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
if current_platform.is_xpu():
|
||||
if not torch.ops._C.xpu_host_register(ptr, num_bytes):
|
||||
logger.warning(
|
||||
"xpu_host_register failed — transfers will still work "
|
||||
"but may be slower (unpinned DMA)"
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
logger.info_once(
|
||||
"Host registration is not implemented on %s; KV offload transfers will "
|
||||
"use unpinned host memory.",
|
||||
current_platform.device_name,
|
||||
)
|
||||
return False
|
||||
|
||||
|
||||
def host_unregister(ptr: int) -> None:
|
||||
"""Release a host range previously registered by `host_register`."""
|
||||
if not ptr:
|
||||
return
|
||||
|
||||
if current_platform.is_cuda_alike():
|
||||
cudart = _load_cudart()
|
||||
if cudart is None:
|
||||
return
|
||||
result = cudart.cudaHostUnregister(ptr)
|
||||
if result != 0:
|
||||
cudart.cudaGetLastError()
|
||||
logger.warning("cudaHostUnregister failed (code=%d)", result)
|
||||
return
|
||||
|
||||
if current_platform.is_xpu():
|
||||
if not torch.ops._C.xpu_host_unregister(ptr):
|
||||
logger.warning("xpu_host_unregister failed")
|
||||
return
|
||||
@@ -27,6 +27,7 @@ from vllm.v1.kv_offload.cpu.common import (
|
||||
)
|
||||
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
|
||||
from vllm.v1.kv_offload.cpu.policies.factory import CachePolicyFactory
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
@@ -193,6 +194,12 @@ class CPUOffloadingManager(OffloadingManager):
|
||||
return LookupResult.HIT_PENDING
|
||||
return LookupResult.HIT
|
||||
|
||||
@override
|
||||
def get_load_source(
|
||||
self, key: OffloadKey, req_context: ReqContext
|
||||
) -> CacheHitSource:
|
||||
return CacheHitSource.HOST
|
||||
|
||||
@override
|
||||
def prepare_load(
|
||||
self,
|
||||
|
||||
@@ -14,7 +14,7 @@ from vllm.distributed.device_communicators.shm_broadcast import (
|
||||
check_shm_free_space,
|
||||
)
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.v1.kv_offload.cpu.host_register import host_unregister
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -343,20 +343,11 @@ class SharedOffloadRegion:
|
||||
|
||||
def cleanup(self) -> None:
|
||||
if self.is_pinned and self._base is not None:
|
||||
if current_platform.is_cuda_alike():
|
||||
base_ptr = self._base.data_ptr()
|
||||
addresses = self.pinned_addresses or [base_ptr]
|
||||
for address in reversed(addresses):
|
||||
result = torch.cuda.cudart().cudaHostUnregister(address)
|
||||
if result.value != 0:
|
||||
logger.warning(
|
||||
"cudaHostUnregister failed for rank=%d, "
|
||||
"address=%#x (code=%d)",
|
||||
self.rank,
|
||||
address,
|
||||
result.value,
|
||||
)
|
||||
self.pinned_addresses.clear()
|
||||
base_ptr = self._base.data_ptr()
|
||||
addresses = self.pinned_addresses or [base_ptr]
|
||||
for address in reversed(addresses):
|
||||
host_unregister(address)
|
||||
self.pinned_addresses.clear()
|
||||
self.is_pinned = False
|
||||
# Release views before _base: each view holds a _base reference and a
|
||||
# direct StorageImpl reference. Freeing views first lets both refcounts
|
||||
|
||||
@@ -162,7 +162,9 @@ class CPUOffloadingSpec(OffloadingSpec):
|
||||
def _uses_shared_region(self) -> bool:
|
||||
"""Whether the worker CPU buffer is the shared mmap region (vs a private
|
||||
per-rank tensor); replicated-layout dedup is gated on this being True."""
|
||||
return current_platform.is_cuda_alike() and not current_platform.is_rocm()
|
||||
return (
|
||||
current_platform.is_cuda_alike() and not current_platform.is_rocm()
|
||||
) or current_platform.is_xpu()
|
||||
|
||||
def create_worker(self, kv_caches: CanonicalKVCaches) -> CPUOffloadingWorker:
|
||||
mmap_region: SharedOffloadRegion | None = None
|
||||
|
||||
@@ -24,6 +24,7 @@ from vllm.v1.kv_offload.base import (
|
||||
from vllm.v1.kv_offload.tiering.backpressure import (
|
||||
BackpressureDetector,
|
||||
)
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.offloading.metrics import (
|
||||
@@ -141,6 +142,17 @@ class SecondaryTierManager(ABC):
|
||||
"""
|
||||
|
||||
medium: ClassVar[Medium | None] = None
|
||||
# Cache tier reported for hits served from this tier. Derived from
|
||||
# ``medium`` unless a subclass sets it; ``None`` medium means unknown.
|
||||
cache_hit_source: ClassVar[CacheHitSource] = CacheHitSource.EXTERNAL_UNSPECIFIED
|
||||
|
||||
def __init_subclass__(cls, **kwargs: Any) -> None:
|
||||
super().__init_subclass__(**kwargs)
|
||||
if "cache_hit_source" not in cls.__dict__ and cls.medium is not None:
|
||||
cls.cache_hit_source = {
|
||||
Medium.CPU: CacheHitSource.HOST,
|
||||
Medium.STORAGE: CacheHitSource.DISK,
|
||||
}[cls.medium]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
||||
@@ -22,7 +22,6 @@ from kvcr import (
|
||||
KVCRBindings,
|
||||
)
|
||||
from kvcr.config import (
|
||||
FrameworkDramInput,
|
||||
G3Options,
|
||||
KeyAdapter,
|
||||
KVCRBackendConfigs,
|
||||
@@ -43,11 +42,12 @@ from kvcr.types import (
|
||||
BlockKey,
|
||||
CacheTier,
|
||||
InventoryEvent,
|
||||
MemDescriptor,
|
||||
MemoryRef,
|
||||
OpHandle,
|
||||
PinRequestId,
|
||||
PinResult,
|
||||
QueryStatus,
|
||||
RegionDescriptor,
|
||||
)
|
||||
from typing_extensions import override
|
||||
|
||||
@@ -82,6 +82,7 @@ from vllm.v1.kv_offload.tiering.base import (
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.kv_offload.base import OffloadingSpec
|
||||
from vllm.v1.kv_offload.tiering.backpressure import BackpressureDetector
|
||||
|
||||
|
||||
_REQUIRED_ROUTER_CAPABILITIES = ROUTER_HINT_CAPABILITIES
|
||||
@@ -177,7 +178,7 @@ class _FrameworkPinAdapter:
|
||||
|
||||
def _resolve_pin(
|
||||
self, parent: ParentManager, keys: Collection[BlockKey]
|
||||
) -> tuple[str, dict[BlockKey, list[MemDescriptor] | None]] | None:
|
||||
) -> tuple[str, dict[BlockKey, list[MemoryRef] | None]] | None:
|
||||
offload_keys = tuple(OffloadKey(bytes(key)) for key in keys)
|
||||
request_id = f"kvcr-source:{self._next_request_id}"
|
||||
self._next_request_id += 1
|
||||
@@ -202,7 +203,7 @@ class _FrameworkPinAdapter:
|
||||
if len(job_keys) != len(chunk_ids) or set(job_keys) != set(hit_keys):
|
||||
return None
|
||||
|
||||
descriptors: dict[BlockKey, list[MemDescriptor] | None] = {
|
||||
descriptors: dict[BlockKey, list[MemoryRef] | None] = {
|
||||
BlockKey(bytes(key)): None for key in offload_keys
|
||||
}
|
||||
descriptors.update(
|
||||
@@ -295,8 +296,11 @@ class KVCRSecondaryTierManager(SecondaryTierManager):
|
||||
g3: dict[str, Any] | None = None,
|
||||
local_dram_backend: str = "UCX",
|
||||
remote_fw_dram_backend: str = "UCX",
|
||||
backpressure_detector: "BackpressureDetector | None" = None,
|
||||
) -> None:
|
||||
super().__init__(offloading_spec, primary_kv_view, tier_type)
|
||||
super().__init__(
|
||||
offloading_spec, primary_kv_view, tier_type, backpressure_detector
|
||||
)
|
||||
selected_policy = _resolve_policy(policy)
|
||||
if (kvcr_service_socket_path is None) != (compatibility_digest is None):
|
||||
raise ValueError(
|
||||
@@ -350,12 +354,6 @@ class KVCRSecondaryTierManager(SecondaryTierManager):
|
||||
with socket.socket() as _s:
|
||||
_s.bind(("", 0))
|
||||
_nixl_listen_port = _s.getsockname()[1]
|
||||
self._primary_base_addr = ctypes.addressof(
|
||||
ctypes.c_char.from_buffer(primary_kv_view)
|
||||
)
|
||||
if primary_kv_view.strides is None:
|
||||
raise ValueError("primary KV memoryview must expose strides")
|
||||
self._primary_row_stride = int(primary_kv_view.strides[0])
|
||||
if secondary_g2_slots < 0:
|
||||
raise ValueError("secondary_g2_slots must be non-negative")
|
||||
if (
|
||||
@@ -375,7 +373,7 @@ class KVCRSecondaryTierManager(SecondaryTierManager):
|
||||
)
|
||||
else:
|
||||
local_mapping = mmap.mmap(
|
||||
-1, secondary_g2_slots * self._primary_row_stride
|
||||
-1, secondary_g2_slots * self.block_size_bytes
|
||||
)
|
||||
local_dram = LocalDramOptions(
|
||||
pools=[
|
||||
@@ -408,7 +406,7 @@ class KVCRSecondaryTierManager(SecondaryTierManager):
|
||||
try:
|
||||
self._kvcr = KVCR(
|
||||
KVCRConfig(
|
||||
pool_layouts=[("", self._primary_row_stride)],
|
||||
pool_layouts=[("", self.block_size_bytes)],
|
||||
enable_telemetry=enable_telemetry,
|
||||
operation_timeout_ms=operation_timeout_ms,
|
||||
abandon_timeout_ms=abandon_timeout_ms,
|
||||
@@ -429,9 +427,15 @@ class KVCRSecondaryTierManager(SecondaryTierManager):
|
||||
policy=selected_policy,
|
||||
),
|
||||
KVCRBackendConfigs(
|
||||
framework_dram=FrameworkDramInput(
|
||||
self._primary_base_addr, primary_kv_view.nbytes
|
||||
),
|
||||
framework_regions=[
|
||||
RegionDescriptor(
|
||||
addr=ctypes.addressof(
|
||||
ctypes.c_char.from_buffer(primary_kv_view)
|
||||
),
|
||||
size=self.block_size_bytes,
|
||||
count=len(primary_kv_view),
|
||||
)
|
||||
],
|
||||
local_dram=local_dram,
|
||||
g3=g3_config,
|
||||
remote_fw_dram=RemoteFWDramOptions(
|
||||
@@ -621,12 +625,8 @@ class KVCRSecondaryTierManager(SecondaryTierManager):
|
||||
)
|
||||
)
|
||||
|
||||
def _make_descriptor(self, chunk_id: int) -> MemDescriptor:
|
||||
return MemDescriptor(
|
||||
def _make_descriptor(self, chunk_id: int) -> MemoryRef:
|
||||
return MemoryRef(
|
||||
end_point_name=self._kvcr.config.nixl_agent_name,
|
||||
mem_type="DRAM",
|
||||
addr=self._primary_base_addr + chunk_id * self._primary_row_stride,
|
||||
size=self._primary_row_stride,
|
||||
device_Id=0,
|
||||
info="",
|
||||
element_index=chunk_id,
|
||||
)
|
||||
|
||||
@@ -54,6 +54,7 @@ from vllm.v1.kv_offload.tiering.base import (
|
||||
TransferJob,
|
||||
)
|
||||
from vllm.v1.kv_offload.tiering.metrics import TieringMetricsTracker
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -232,6 +233,11 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
# complete_store(), since complete_store() can still submit cascades.
|
||||
self._req_state: dict[str, RequestState] = {}
|
||||
|
||||
# Preserve the original tier for this request's cache-hit metrics,
|
||||
# even after its KV blocks are promoted into host memory
|
||||
# (otherwise a disk or P2P hit would be mislabeled as a host hit).
|
||||
self._request_load_sources: dict[str, dict[OffloadKey, CacheHitSource]] = {}
|
||||
|
||||
# Cached ParentManager wrappers for each secondary tier.
|
||||
self._tier_parents: dict[SecondaryTierManager, _SecondaryTierFacingParent] = {
|
||||
tier: _SecondaryTierFacingParent(self, tier_idx)
|
||||
@@ -293,6 +299,13 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
successful_keys = ()
|
||||
failed_keys = transfer_job.keys
|
||||
|
||||
load_sources = self._request_load_sources.get(transfer_job.req_context.req_id)
|
||||
if load_sources is not None:
|
||||
source = self.secondary_tiers[job_metadata.tier_idx].cache_hit_source
|
||||
for key in failed_keys:
|
||||
if load_sources.get(key) == source:
|
||||
del load_sources[key]
|
||||
|
||||
if successful_keys:
|
||||
self.primary_tier.complete_write(
|
||||
successful_keys,
|
||||
@@ -464,6 +477,15 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
return LookupResult.RETRY
|
||||
return LookupResult.MISS
|
||||
|
||||
@override
|
||||
def get_load_source(
|
||||
self, key: OffloadKey, req_context: ReqContext
|
||||
) -> CacheHitSource:
|
||||
load_sources = self._request_load_sources.get(req_context.req_id)
|
||||
if load_sources is not None and key in load_sources:
|
||||
return load_sources[key]
|
||||
return self.primary_tier.get_load_source(key, req_context)
|
||||
|
||||
def _initiate_promotion(
|
||||
self,
|
||||
tier_idx: int,
|
||||
@@ -501,6 +523,10 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
|
||||
store_spec = primary_write_result.store_spec
|
||||
assert isinstance(store_spec, CPULoadStoreSpec)
|
||||
load_sources = self._request_load_sources.setdefault(req_context.req_id, {})
|
||||
source = self.secondary_tiers[tier_idx].cache_hit_source
|
||||
for promoted_key in primary_write_result.keys_to_store:
|
||||
load_sources[promoted_key] = source
|
||||
# Defer submit_load to on_schedule_end(). Group by (tier, request) so
|
||||
# each request's chunks are submitted as one batched job per tier.
|
||||
tier_pending = self._pending_load_submissions.setdefault(tier_idx, {})
|
||||
@@ -848,6 +874,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
continue
|
||||
tier.on_request_finished(state.req_context)
|
||||
self._metrics.on_request_finished(state.req_context)
|
||||
self._request_load_sources.pop(req_id, None)
|
||||
del self._req_state[req_id]
|
||||
|
||||
@override
|
||||
@@ -930,6 +957,7 @@ class TieringOffloadingManager(OffloadingManager):
|
||||
# reset below invalidates; their submit_load() has not yet been
|
||||
# called so no tier I/O is touching that memory.
|
||||
self._pending_load_submissions.clear()
|
||||
self._request_load_sources.clear()
|
||||
self._metrics.assert_idle()
|
||||
|
||||
finished_req_ids = []
|
||||
|
||||
@@ -11,7 +11,7 @@ import time
|
||||
import uuid
|
||||
from collections.abc import Iterable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Any
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from typing_extensions import override
|
||||
|
||||
@@ -35,6 +35,7 @@ from vllm.v1.kv_offload.tiering.base import (
|
||||
from vllm.v1.kv_offload.tiering.p2p.control import ControlTransport, ZmqTransport
|
||||
from vllm.v1.kv_offload.tiering.p2p.data import DataTransport, NixlTransport
|
||||
from vllm.v1.kv_offload.tiering.p2p.session import P2PSession
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.kv_offload.base import OffloadingSpec
|
||||
@@ -206,6 +207,8 @@ class P2PSecondaryTierManager(SecondaryTierManager):
|
||||
and existing sessions are polled even when no requests are scheduled.
|
||||
"""
|
||||
|
||||
cache_hit_source: ClassVar[CacheHitSource] = CacheHitSource.P2P
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
offloading_spec: OffloadingSpec,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class CacheHitSource(str, Enum):
|
||||
"""Where cached prompt tokens' KV came from.
|
||||
|
||||
Members are listed in the order blocks are offloaded: accelerator, then
|
||||
host memory, then secondary tiers. Per-source token counts are plain
|
||||
``dict[CacheHitSource, int]`` mappings holding only non-zero entries.
|
||||
"""
|
||||
|
||||
DEVICE = "device"
|
||||
HOST = "host"
|
||||
P2P = "p2p"
|
||||
DISK = "disk"
|
||||
# Fallback: uninstrumented connector or remote store. Last, so mixing
|
||||
# with a known tier never reports the known one.
|
||||
EXTERNAL_UNSPECIFIED = "external_unspecified"
|
||||
|
||||
@classmethod
|
||||
def outermost(cls, sources: Iterable[CacheHitSource]) -> CacheHitSource:
|
||||
"""The tier in ``sources`` farthest from the accelerator."""
|
||||
return max(sources, key=_SOURCE_ORDER.__getitem__)
|
||||
|
||||
|
||||
_SOURCE_ORDER = {source: rank for rank, source in enumerate(CacheHitSource)}
|
||||
@@ -23,6 +23,7 @@ from vllm.logger import init_logger
|
||||
from vllm.plugins import STAT_LOGGER_PLUGINS_GROUP, load_plugins_by_group
|
||||
from vllm.v1.engine import FinishReason
|
||||
from vllm.v1.metrics.buckets import histogram_buckets
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.metrics.perf import PerfMetricsLogging, PerfMetricsProm
|
||||
from vllm.v1.metrics.prometheus import unregister_vllm_metrics
|
||||
from vllm.v1.metrics.stats import (
|
||||
@@ -752,6 +753,23 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
|
||||
counter_prompt_tokens_cached, per_engine_labelvalues
|
||||
)
|
||||
|
||||
self.counter_prompt_tokens_cached_by_source = self._counter_cls(
|
||||
name="vllm:prompt_tokens_cached_by_source",
|
||||
documentation=(
|
||||
"Prefix-cache hit tokens by the cache tier that supplied them: "
|
||||
"device (local HBM), host (offloaded to DRAM), disk, p2p "
|
||||
"(transferred from another vLLM instance) or "
|
||||
"external_unspecified. Counted at admission; sums to "
|
||||
"vllm:prefix_cache_hits + vllm:external_prefix_cache_hits."
|
||||
),
|
||||
labelnames=labelnames + ["source"],
|
||||
)
|
||||
for source in CacheHitSource:
|
||||
for labelvalues in per_engine_labelvalues.values():
|
||||
self.counter_prompt_tokens_cached_by_source.labels(
|
||||
*labelvalues, source.value
|
||||
)
|
||||
|
||||
counter_generation_tokens = self._counter_cls(
|
||||
name="vllm:generation_tokens",
|
||||
documentation="Number of generation tokens processed.",
|
||||
@@ -1111,13 +1129,23 @@ class PrometheusStatLogger(AggregateStatLoggerBase):
|
||||
scheduler_stats.prefix_cache_stats.hits
|
||||
)
|
||||
|
||||
if scheduler_stats.connector_prefix_cache_stats is not None:
|
||||
labelvalues = self.per_engine_labelvalues[engine_idx]
|
||||
self.counter_prompt_tokens_cached_by_source.labels(
|
||||
*labelvalues, CacheHitSource.DEVICE.value
|
||||
).inc(scheduler_stats.prefix_cache_stats.hits)
|
||||
|
||||
connector_stats = scheduler_stats.connector_prefix_cache_stats
|
||||
if connector_stats is not None:
|
||||
self.counter_connector_prefix_cache_queries[engine_idx].inc(
|
||||
scheduler_stats.connector_prefix_cache_stats.queries
|
||||
connector_stats.queries
|
||||
)
|
||||
self.counter_connector_prefix_cache_hits[engine_idx].inc(
|
||||
scheduler_stats.connector_prefix_cache_stats.hits
|
||||
connector_stats.hits
|
||||
)
|
||||
for tier, num_tokens in connector_stats.hits_by_source.items():
|
||||
self.counter_prompt_tokens_cached_by_source.labels(
|
||||
*labelvalues, tier.value
|
||||
).inc(num_tokens)
|
||||
|
||||
if scheduler_stats.spec_decoding_stats is not None:
|
||||
self.spec_decoding_prom.observe(
|
||||
|
||||
@@ -10,12 +10,11 @@ import time
|
||||
from abc import ABC, abstractmethod
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from typing import Any, Protocol
|
||||
from typing import Any, Protocol, Self
|
||||
|
||||
import prometheus_client
|
||||
import torch
|
||||
from pydantic import BaseModel, Field, ValidationError, model_validator
|
||||
from typing_extensions import Self
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
@@ -8,9 +8,13 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.metrics.cache_hit_source import CacheHitSource
|
||||
from vllm.v1.metrics.perf import PerfStats
|
||||
from vllm.v1.spec_decode.metrics import SpecDecodingStats
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.engine import EngineCoreEvent, EngineCoreOutput, FinishReason
|
||||
|
||||
@@ -128,19 +132,42 @@ class PrefixCacheStats(BaseCacheStats):
|
||||
|
||||
preempted_hits: int = 0
|
||||
"""The `hits` number for preempted requests."""
|
||||
hits_by_source: dict[CacheHitSource, int] = field(default_factory=dict)
|
||||
"""`hits` split by the cache tier that supplied them (connector stats only)."""
|
||||
|
||||
def record(self, num_tokens: int, num_hits: int, preempted: bool) -> None:
|
||||
def record(
|
||||
self,
|
||||
num_tokens: int,
|
||||
num_hits: int,
|
||||
preempted: bool,
|
||||
hits_by_source: dict[CacheHitSource, int] | None = None,
|
||||
) -> None:
|
||||
"""Aggregate request information into the stats."""
|
||||
if preempted:
|
||||
# Previously preempted request
|
||||
self.preempted_requests += 1
|
||||
self.preempted_queries += num_tokens
|
||||
self.preempted_hits += num_hits
|
||||
else:
|
||||
# New request
|
||||
self.requests += 1
|
||||
self.queries += num_tokens
|
||||
self.hits += num_hits
|
||||
return
|
||||
# New request
|
||||
self.requests += 1
|
||||
self.queries += num_tokens
|
||||
self.hits += num_hits
|
||||
if hits_by_source is None:
|
||||
return
|
||||
if sum(hits_by_source.values()) != num_hits:
|
||||
logger.warning_once(
|
||||
"Connector attributed %s for %d cached tokens; reporting them as %s.",
|
||||
str(hits_by_source),
|
||||
num_hits,
|
||||
CacheHitSource.EXTERNAL_UNSPECIFIED.value,
|
||||
)
|
||||
hits_by_source = {CacheHitSource.EXTERNAL_UNSPECIFIED: num_hits}
|
||||
for source, num_source_hits in hits_by_source.items():
|
||||
if num_source_hits:
|
||||
self.hits_by_source[source] = (
|
||||
self.hits_by_source.get(source, 0) + num_source_hits
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
@@ -319,11 +319,11 @@ class TopKTopPSampler(nn.Module):
|
||||
k: torch.Tensor | None,
|
||||
p: torch.Tensor | None,
|
||||
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
||||
"""Fused Gumbel-max sampling for CPU.
|
||||
"""CPU Gumbel-max sampling with per-token SplitMix64 noise.
|
||||
|
||||
Uses a precomputed Gumbel table + single-pass argmax over logits,
|
||||
skipping softmax and intermediate allocations entirely.
|
||||
Falls back to the native path when fp64 Gumbel noise is requested.
|
||||
Independent (seed, token) streams avoid the wrapping-window bias
|
||||
(#59786). Falls back to native sampling when fp64 Gumbel noise
|
||||
is requested.
|
||||
"""
|
||||
logits = apply_top_k_top_p(logits, k, p)
|
||||
logits_to_return = None
|
||||
|
||||
@@ -216,6 +216,7 @@ class SimpleCPUOffloadScheduler:
|
||||
scheduler_block_size=self.block_size,
|
||||
hash_block_size=self.hash_block_size,
|
||||
allow_partial_hash_hits=not lazy_offload,
|
||||
num_prefill_lookahead=vllm_config.num_prefill_lookahead_tokens,
|
||||
)
|
||||
self.group_block_sizes = self.cpu_coordinator.group_block_sizes
|
||||
# FA group's own resolved block_size; divides scheduler_block_size (the
|
||||
@@ -837,19 +838,6 @@ class SimpleCPUOffloadScheduler:
|
||||
)
|
||||
request = state.request
|
||||
confirmed_tokens = request.num_computed_tokens - request.num_output_placeholders
|
||||
# Truncate to the granularity a lookup can actually land on. With
|
||||
# fine-grained hits that is hash_block_size; otherwise hits only land on
|
||||
# the scheduler block (the group LCM). Using the LCM unconditionally
|
||||
# would drop whole blocks that sit between the last LCM boundary and a
|
||||
# reachable fine-grained boundary, so the other groups would hold that
|
||||
# boundary and this one would not, and the joint hybrid lookup would
|
||||
# reconcile to zero.
|
||||
store_alignment = (
|
||||
self.hash_block_size
|
||||
if self.cpu_coordinator.enable_partial_hash_hits
|
||||
else self.block_size
|
||||
)
|
||||
aligned_tokens = confirmed_tokens // store_alignment * store_alignment
|
||||
num_free = self.cpu_block_pool.get_num_free_blocks()
|
||||
|
||||
for g, group_gpu_ids in enumerate(block_ids_by_group):
|
||||
@@ -864,7 +852,11 @@ class SimpleCPUOffloadScheduler:
|
||||
# num_stored_blocks can be stale and omit evicted blocks in
|
||||
# the middle of the request.
|
||||
group_size = self.group_block_sizes[g]
|
||||
ready = min(len(group_gpu_ids), aligned_tokens // group_size)
|
||||
# Mimic the GPU KV cache manager's cacheable prefix.
|
||||
cacheable_tokens = self.cpu_coordinator.get_num_cacheable_tokens(
|
||||
confirmed_tokens, g
|
||||
)
|
||||
ready = min(len(group_gpu_ids), cacheable_tokens // group_size)
|
||||
resolved_hashes = resolve_block_hashes(
|
||||
request.block_hashes, self.hash_block_size, group_size
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import multiprocessing
|
||||
from collections.abc import Iterable, Sequence
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import TYPE_CHECKING, NamedTuple
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.logger import init_logger
|
||||
@@ -33,6 +33,17 @@ else:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class ConstraintBounds(NamedTuple):
|
||||
"""Where tokens start being fed to the grammar and being masked."""
|
||||
|
||||
grammar_start: int
|
||||
constraint_start: int
|
||||
|
||||
|
||||
_CONSTRAINED_FROM_START = ConstraintBounds(0, 0)
|
||||
_NO_SPEC_TOKENS = ConstraintBounds(1, 1)
|
||||
|
||||
|
||||
class StructuredOutputManager:
|
||||
"""Engine-level manager for structured output requests."""
|
||||
|
||||
@@ -217,32 +228,34 @@ class StructuredOutputManager:
|
||||
) -> Future:
|
||||
return self.executor_for_fillmask.submit(self._fill_bitmasks, batch)
|
||||
|
||||
def _get_constraint_start(
|
||||
def _get_constraint_bounds(
|
||||
self,
|
||||
request: "Request",
|
||||
spec_tokens: Sequence[int],
|
||||
spec_tokens_committed: bool = False,
|
||||
) -> int:
|
||||
) -> ConstraintBounds:
|
||||
"""Return the index into `spec_tokens` where tokens should start being
|
||||
constrained by the grammar.
|
||||
Assumes `spec_tokens` are stripped of -1 padding tokens.
|
||||
Returns `len(spec_tokens) + 1` if no token should be constrained after
|
||||
accepting all `spec_tokens`.
|
||||
This is `constraint_start`; `grammar_start` is one less if reasoning ends
|
||||
implicitly on a content token (e.g. a tool-call start).
|
||||
|
||||
`spec_tokens_committed` is True if spec_tokens is already in
|
||||
`request.all_token_ids`.
|
||||
"""
|
||||
if self.enable_in_reasoning:
|
||||
return 0
|
||||
return _CONSTRAINED_FROM_START
|
||||
|
||||
structured_req = request.structured_output_request
|
||||
assert structured_req is not None
|
||||
if structured_req.reasoning_ended:
|
||||
return 0
|
||||
return _CONSTRAINED_FROM_START
|
||||
|
||||
reasoner = self._get_reasoner(request)
|
||||
if reasoner is None:
|
||||
return 0
|
||||
return _CONSTRAINED_FROM_START
|
||||
|
||||
if structured_req.reasoning_ended is None:
|
||||
# This should be removed here, but since `openai_gptoss`
|
||||
@@ -250,30 +263,33 @@ class StructuredOutputManager:
|
||||
# After unifying the `openai_gptoss` and non-`openai_gptoss` styles,
|
||||
# it can be removed.
|
||||
if reasoner.is_reasoning_end(request.prompt_token_ids or []):
|
||||
return 0
|
||||
return _CONSTRAINED_FROM_START
|
||||
structured_req.reasoning_ended = False
|
||||
|
||||
num_spec_tokens = len(spec_tokens)
|
||||
if num_spec_tokens <= 0:
|
||||
return num_spec_tokens + 1
|
||||
return _NO_SPEC_TOKENS
|
||||
|
||||
# Use `find_reasoning_end_offset` to find constraint start if supported
|
||||
# Engine-based parsers also report whether the end token is content.
|
||||
if (
|
||||
isinstance(reasoner, ParserEngineReasoningAdapter)
|
||||
and reasoner.reasoning_end_token_ids
|
||||
):
|
||||
offset = reasoner.find_reasoning_end_offset(spec_tokens)
|
||||
if offset is not None:
|
||||
return offset + 1
|
||||
end = reasoner.find_reasoning_end(spec_tokens)
|
||||
if end is not None:
|
||||
constraint_start = end.offset + 1
|
||||
if end.implicit:
|
||||
return ConstraintBounds(end.offset, constraint_start)
|
||||
return ConstraintBounds(constraint_start, constraint_start)
|
||||
|
||||
# Fallback to `find_reasoning_end_offset`
|
||||
# Fallback: the grammar starts after the end token.
|
||||
# TODO: Build a read-only Sequence view over all_token_ids
|
||||
# instead of copying the entire all_token_ids into input_ids.
|
||||
if spec_tokens_committed:
|
||||
if not spec_tokens or not reasoner.is_reasoning_end_streaming(
|
||||
request.all_token_ids, spec_tokens
|
||||
):
|
||||
return num_spec_tokens + 1
|
||||
return ConstraintBounds(num_spec_tokens + 1, num_spec_tokens + 1)
|
||||
|
||||
input_ids = request.all_token_ids.copy()
|
||||
delta_ids = list(spec_tokens)
|
||||
@@ -281,15 +297,15 @@ class StructuredOutputManager:
|
||||
input_ids = request.all_token_ids.copy()
|
||||
input_ids.extend(spec_tokens)
|
||||
if not reasoner.is_reasoning_end_streaming(input_ids, spec_tokens):
|
||||
return num_spec_tokens + 1
|
||||
return ConstraintBounds(num_spec_tokens + 1, num_spec_tokens + 1)
|
||||
delta_ids = list(spec_tokens)
|
||||
|
||||
for i in range(num_spec_tokens - 1, 0, -1):
|
||||
input_ids.pop()
|
||||
delta_ids.pop()
|
||||
if not reasoner.is_reasoning_end_streaming(input_ids, delta_ids):
|
||||
return i + 1
|
||||
return 1
|
||||
return ConstraintBounds(i + 1, i + 1)
|
||||
return ConstraintBounds(1, 1)
|
||||
|
||||
def validate_tokens(self, request: "Request", spec_tokens: list[int]) -> list[int]:
|
||||
"""Return the longest unconstrained or grammar-valid prefix of `spec_tokens`."""
|
||||
@@ -297,8 +313,8 @@ class StructuredOutputManager:
|
||||
return spec_tokens
|
||||
|
||||
spec_tokens = strip_speculative_padding(spec_tokens)
|
||||
constraint_start = self._get_constraint_start(request, spec_tokens)
|
||||
if constraint_start >= len(spec_tokens):
|
||||
grammar_start, _ = self._get_constraint_bounds(request, spec_tokens)
|
||||
if grammar_start >= len(spec_tokens):
|
||||
return spec_tokens
|
||||
|
||||
structured_req = request.structured_output_request
|
||||
@@ -307,8 +323,8 @@ class StructuredOutputManager:
|
||||
grammar = structured_req.grammar
|
||||
if TYPE_CHECKING:
|
||||
assert isinstance(grammar, StructuredOutputGrammar)
|
||||
prefix = spec_tokens[:constraint_start]
|
||||
validated = grammar.validate_tokens(spec_tokens[constraint_start:])
|
||||
prefix = spec_tokens[:grammar_start]
|
||||
validated = grammar.validate_tokens(spec_tokens[grammar_start:])
|
||||
return prefix + validated
|
||||
|
||||
def grammar_bitmask(
|
||||
@@ -358,7 +374,9 @@ class StructuredOutputManager:
|
||||
if TYPE_CHECKING:
|
||||
assert isinstance(grammar, StructuredOutputGrammar)
|
||||
|
||||
apply_bitmask = self._get_constraint_start(request, ()) == 0
|
||||
apply_bitmask = (
|
||||
self._get_constraint_bounds(request, ()).constraint_start == 0
|
||||
)
|
||||
batch.append((grammar, cumulative_index, apply_bitmask))
|
||||
if len(batch) == self.fill_bitmask_parallel_batch_size:
|
||||
promises.append(self._async_submit_fill_bitmask(batch))
|
||||
@@ -384,7 +402,7 @@ class StructuredOutputManager:
|
||||
assert isinstance(grammar, StructuredOutputGrammar)
|
||||
|
||||
req_tokens = scheduled_spec_decode_tokens.get(req_id, list())
|
||||
constraint_start = self._get_constraint_start(
|
||||
grammar_start, constraint_start = self._get_constraint_bounds(
|
||||
request, strip_speculative_padding(req_tokens)
|
||||
)
|
||||
state_advancements = 0
|
||||
@@ -402,7 +420,7 @@ class StructuredOutputManager:
|
||||
self._fill_bitmasks(((grammar, cumulative_index, apply_bitmask),))
|
||||
if token == -1:
|
||||
seen_padding = True
|
||||
elif apply_bitmask:
|
||||
elif not seen_padding and i >= grammar_start:
|
||||
if not grammar.is_terminated() and grammar.accept_tokens(
|
||||
req_id, [token]
|
||||
):
|
||||
@@ -453,17 +471,15 @@ class StructuredOutputManager:
|
||||
if TYPE_CHECKING:
|
||||
assert isinstance(grammar, StructuredOutputGrammar)
|
||||
|
||||
constraint_start = self._get_constraint_start(
|
||||
grammar_start, _ = self._get_constraint_bounds(
|
||||
request, new_token_ids, spec_tokens_committed=True
|
||||
)
|
||||
# Early return only when the constraint hasn't started.
|
||||
# Early return only when no reasoning-end token is present.
|
||||
# Otherwise, latch structured_req.reasoning_ended.
|
||||
if constraint_start > len(new_token_ids):
|
||||
if grammar_start > len(new_token_ids):
|
||||
return True
|
||||
structured_req.reasoning_ended = True
|
||||
return grammar.accept_tokens(
|
||||
request.request_id, new_token_ids[constraint_start:]
|
||||
)
|
||||
return grammar.accept_tokens(request.request_id, new_token_ids[grammar_start:])
|
||||
|
||||
def clear_backend(self) -> None:
|
||||
if self.backend is not None:
|
||||
|
||||
@@ -34,17 +34,58 @@ else:
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
_SCHEMA_MAP_KEYWORDS = (
|
||||
"properties",
|
||||
"patternProperties",
|
||||
"$defs",
|
||||
"definitions",
|
||||
"dependentSchemas",
|
||||
"dependencies",
|
||||
)
|
||||
|
||||
_SUBSCHEMA_KEYWORDS = (
|
||||
"additionalProperties",
|
||||
"unevaluatedProperties",
|
||||
"propertyNames",
|
||||
"contains",
|
||||
"additionalItems",
|
||||
"unevaluatedItems",
|
||||
"not",
|
||||
"if",
|
||||
"then",
|
||||
"else",
|
||||
"contentSchema",
|
||||
"items",
|
||||
"prefixItems",
|
||||
"allOf",
|
||||
"anyOf",
|
||||
"oneOf",
|
||||
)
|
||||
|
||||
|
||||
def _walk_json_for_additional_properties(data: object):
|
||||
if isinstance(data, dict):
|
||||
for value in data.values():
|
||||
_walk_json_for_additional_properties(value)
|
||||
for key in _SCHEMA_MAP_KEYWORDS:
|
||||
value = data.get(key)
|
||||
if isinstance(value, dict):
|
||||
for subschema in value.values():
|
||||
if isinstance(subschema, dict):
|
||||
_walk_json_for_additional_properties(subschema)
|
||||
|
||||
for key in _SUBSCHEMA_KEYWORDS:
|
||||
value = data.get(key)
|
||||
if isinstance(value, (dict, list)):
|
||||
_walk_json_for_additional_properties(value)
|
||||
|
||||
if "additionalProperties" not in data and (
|
||||
"properties" in data or "patternProperties" in data
|
||||
isinstance(data.get("properties"), dict)
|
||||
or isinstance(data.get("patternProperties"), dict)
|
||||
):
|
||||
data["additionalProperties"] = False
|
||||
elif isinstance(data, list):
|
||||
for item in data:
|
||||
_walk_json_for_additional_properties(item)
|
||||
if isinstance(item, dict):
|
||||
_walk_json_for_additional_properties(item)
|
||||
|
||||
|
||||
def has_guidance_unsupported_json_features(schema: dict[str, Any]) -> bool:
|
||||
|
||||
@@ -4,10 +4,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import importlib
|
||||
import json
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from re import _constants, _parser # type: ignore[attr-defined]
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
@@ -36,19 +35,6 @@ else:
|
||||
oc = LazyLoader("oc", globals(), "outlines_core")
|
||||
json_schema = LazyLoader("json_schema", globals(), "outlines_core.json_schema")
|
||||
|
||||
# Python 3.11+ sre_parse and sre_constants
|
||||
# are deprecated, so we must import them from re
|
||||
if sys.version_info >= (3, 11):
|
||||
# Hack to get around pre-commit regex module rule
|
||||
# because going through re is the only way to get sre_parse
|
||||
# and sre_constants in Python 3.11+
|
||||
_re = importlib.import_module("re")
|
||||
sre_parse = _re._parser
|
||||
sre_constants = _re._constants
|
||||
else:
|
||||
import sre_constants
|
||||
import sre_parse
|
||||
|
||||
|
||||
@dataclass
|
||||
class OutlinesBackend(StructuredOutputBackend):
|
||||
@@ -261,20 +247,20 @@ def _prefix_needs_context(parsed) -> bool:
|
||||
tokens = parsed.data if hasattr(parsed, "data") else parsed
|
||||
for ttype, tval in tokens:
|
||||
# literal, character class, or dot always consumes
|
||||
if ttype in (sre_parse.LITERAL, sre_parse.IN, sre_parse.ANY):
|
||||
if ttype in (_parser.LITERAL, _parser.IN, _parser.ANY):
|
||||
return True
|
||||
# quantified subpattern: check inner pattern
|
||||
elif ttype == sre_parse.MAX_REPEAT:
|
||||
elif ttype == _parser.MAX_REPEAT:
|
||||
_, mx, sub = tval
|
||||
if mx != 0 and subpattern_consumes(sub):
|
||||
return True
|
||||
# alternation: if any branch consumes, the whole does
|
||||
elif ttype == sre_parse.BRANCH:
|
||||
elif ttype == _parser.BRANCH:
|
||||
_, branches = tval
|
||||
if any(subpattern_consumes(br) for br in branches):
|
||||
return True
|
||||
# grouped subpattern: recurse into its contents
|
||||
elif ttype == sre_parse.SUBPATTERN and subpattern_consumes(tval[3]):
|
||||
elif ttype == _parser.SUBPATTERN and subpattern_consumes(tval[3]):
|
||||
return True
|
||||
# No consumers, return False
|
||||
return False
|
||||
@@ -282,14 +268,11 @@ def _prefix_needs_context(parsed) -> bool:
|
||||
tokens = parsed.data if hasattr(parsed, "data") else parsed
|
||||
for ttype, tval in tokens:
|
||||
# Direct anchors or look-around
|
||||
if ttype == sre_parse.AT or ttype in (
|
||||
sre_constants.ASSERT,
|
||||
sre_constants.ASSERT_NOT,
|
||||
):
|
||||
if ttype == _parser.AT or ttype in (_constants.ASSERT, _constants.ASSERT_NOT):
|
||||
return True
|
||||
|
||||
# Nested subpattern: check
|
||||
if ttype == sre_parse.SUBPATTERN:
|
||||
if ttype == _parser.SUBPATTERN:
|
||||
# tval: (group, add_flags, del_flags, subpattern)
|
||||
if _prefix_needs_context(tval[3]):
|
||||
return True
|
||||
@@ -298,7 +281,7 @@ def _prefix_needs_context(parsed) -> bool:
|
||||
|
||||
# if any branch has a prefix anchor => True,
|
||||
# else if at least one branch consumes => prefix ends => False
|
||||
elif ttype == sre_parse.BRANCH:
|
||||
elif ttype == _parser.BRANCH:
|
||||
saw_consumer = False
|
||||
for br in tval[1]:
|
||||
if _prefix_needs_context(br):
|
||||
@@ -309,11 +292,11 @@ def _prefix_needs_context(parsed) -> bool:
|
||||
return False
|
||||
|
||||
# Immediate consumer tokens
|
||||
elif ttype in (sre_parse.LITERAL, sre_parse.IN, sre_parse.ANY):
|
||||
elif ttype in (_parser.LITERAL, _parser.IN, _parser.ANY):
|
||||
return False
|
||||
|
||||
# if subpattern has anchor => True, if it can consume => stop
|
||||
elif ttype == sre_parse.MAX_REPEAT:
|
||||
elif ttype == _parser.MAX_REPEAT:
|
||||
if _prefix_needs_context(tval[2]):
|
||||
return True
|
||||
if subpattern_consumes(tval[2]):
|
||||
@@ -327,26 +310,28 @@ def _check_unsupported(parsed) -> None:
|
||||
tokens = parsed.data if hasattr(parsed, "data") else parsed
|
||||
for ttype, tval in tokens:
|
||||
# backreference
|
||||
if ttype in (sre_parse.GROUPREF, sre_parse.GROUPREF_EXISTS):
|
||||
if ttype in (_parser.GROUPREF, _parser.GROUPREF_EXISTS):
|
||||
raise ValueError("Backreferences are unsupported.")
|
||||
|
||||
# look-around assertion
|
||||
elif ttype in (sre_constants.ASSERT, sre_constants.ASSERT_NOT):
|
||||
elif ttype in (_constants.ASSERT, _constants.ASSERT_NOT):
|
||||
raise ValueError("Look-Around assertion are unsupported.")
|
||||
|
||||
# unicode word boundaries
|
||||
elif ttype == sre_parse.AT:
|
||||
if tval in (sre_constants.AT_BOUNDARY, sre_constants.AT_NON_BOUNDARY):
|
||||
elif ttype == _parser.AT:
|
||||
if tval in (_constants.AT_BOUNDARY, _constants.AT_NON_BOUNDARY):
|
||||
raise ValueError("Unicode word boundaries are unsupported.")
|
||||
|
||||
elif ttype == sre_parse.BRANCH:
|
||||
elif ttype == _parser.BRANCH:
|
||||
# tval is (None, branches)
|
||||
for branch in tval[1]:
|
||||
_check_unsupported(branch)
|
||||
|
||||
# tval is (min, max, subpattern)
|
||||
elif ttype == sre_parse.MAX_REPEAT:
|
||||
_check_unsupported(tval[2])
|
||||
else:
|
||||
nested = tval if isinstance(tval, tuple) else (tval,)
|
||||
for sub in nested:
|
||||
if isinstance(sub, _parser.SubPattern):
|
||||
_check_unsupported(sub)
|
||||
|
||||
|
||||
def validate_regex_is_buildable(pattern: str) -> None:
|
||||
@@ -357,9 +342,9 @@ def validate_regex_is_buildable(pattern: str) -> None:
|
||||
https://docs.rs/regex-automata/latest/regex_automata/dfa/trait.Automaton.html#method.universal_start_state
|
||||
"""
|
||||
try:
|
||||
parsed = sre_parse.parse(pattern)
|
||||
parsed = _parser.parse(pattern)
|
||||
|
||||
except sre_constants.error as e:
|
||||
except _constants.error as e:
|
||||
raise VLLMValidationError(f"Error parsing regex: {e}") from e
|
||||
|
||||
try:
|
||||
|
||||
@@ -10,7 +10,7 @@ import torch
|
||||
import vllm.envs
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.sampling_params import SamplingParams, check_json_nesting
|
||||
from vllm.utils.import_utils import LazyLoader
|
||||
from vllm.utils.mistral import is_mistral_tokenizer
|
||||
from vllm.v1.structured_output.backend_types import (
|
||||
@@ -89,13 +89,36 @@ class XgrammarBackend(StructuredOutputBackend):
|
||||
grammar_spec: str,
|
||||
stop_token_ids: set[int] | None = None,
|
||||
) -> StructuredOutputGrammar:
|
||||
# Note(arpera):
|
||||
# Our flag disable_any_whitespace does NOT map directly to
|
||||
# xgrammar's flag any_whitespace
|
||||
# To achieve desired behavior of disable_any_whitespace
|
||||
# we have to set not only any_whitespace
|
||||
# but also specify a list of separators after which
|
||||
# xgrammar must not insert spaces.
|
||||
# This is a requirement of xgrammar's API, so we must comply with it.
|
||||
#
|
||||
# FIXME(arpera):
|
||||
# Currently xgrammar v0.2.8 DOES emit spaces after comma
|
||||
# even if we specify it in separators list.
|
||||
# The bug has been reported to xgrammar team:
|
||||
# https://github.com/mlc-ai/xgrammar/issues/945
|
||||
# Please, track that issue, and once it is resolved remove this comment.
|
||||
# Upd. this bug was fixed in xgrammar main branch on Oct 8, 2026
|
||||
# and will be available in next release.
|
||||
# So, remove this comment once xgrammar updates to v0.2.9
|
||||
separators = (",", ":") if self.disable_any_whitespace else None
|
||||
if request_type == StructuredOutputOptions.JSON:
|
||||
ctx = self.compiler.compile_json_schema(
|
||||
grammar_spec, any_whitespace=not self.disable_any_whitespace
|
||||
grammar_spec,
|
||||
any_whitespace=not self.disable_any_whitespace,
|
||||
separators=separators,
|
||||
)
|
||||
elif request_type == StructuredOutputOptions.JSON_OBJECT:
|
||||
ctx = self.compiler.compile_json_schema(
|
||||
'{"type": "object"}', any_whitespace=not self.disable_any_whitespace
|
||||
'{"type": "object"}',
|
||||
any_whitespace=not self.disable_any_whitespace,
|
||||
separators=separators,
|
||||
)
|
||||
elif request_type == StructuredOutputOptions.GRAMMAR:
|
||||
if grammar_is_likely_lark(grammar_spec):
|
||||
@@ -273,18 +296,29 @@ def has_xgrammar_unsupported_json_features(schema: dict[str, Any]) -> bool:
|
||||
|
||||
schema_types = _schema_types(obj)
|
||||
|
||||
# Check for numeric ranges
|
||||
# integer/number + multipleOf is unsupported by xgrammar
|
||||
# This is known behavior and xgrammar emits warning in logs:
|
||||
# [21:18:08] /project/cpp/json_schema_converter.cc:1053:
|
||||
# Warning: multipleOf is not supported for type:number; ignoring multipleOf
|
||||
# This warning was added in PR
|
||||
# https://github.com/mlc-ai/xgrammar/pull/670
|
||||
# So, no need to track progress on this
|
||||
if (schema_types & {"integer", "number"}) and ("multipleOf" in obj):
|
||||
return True
|
||||
|
||||
# Check for array unsupported keywords
|
||||
# array + some constraints is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/968
|
||||
if "array" in schema_types and any(
|
||||
key in obj
|
||||
for key in ("uniqueItems", "contains", "minContains", "maxContains")
|
||||
):
|
||||
return True
|
||||
|
||||
# Unsupported keywords for strings
|
||||
# string + format with unsupported keywords
|
||||
# is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/967
|
||||
# See tests on this in test_backend_xgrammar.py
|
||||
# unsupported_string_schemas
|
||||
if (
|
||||
"string" in schema_types
|
||||
and "format" in obj
|
||||
@@ -292,47 +326,67 @@ def has_xgrammar_unsupported_json_features(schema: dict[str, Any]) -> bool:
|
||||
):
|
||||
return True
|
||||
|
||||
# A string mixing a generative constraint (pattern or format) with
|
||||
# explicit length bounds. xgrammar compiles the pattern/format side
|
||||
# and silently drops minLength/maxLength from the grammar, so output
|
||||
# can violate the bound without any error surfacing. Verified against
|
||||
# the compiled EBNF: pattern/format grammars come out byte-identical
|
||||
# with and without the length keywords, while maxLength alone lowers
|
||||
# to {0, N} correctly.
|
||||
# string + format/pattern + length constraint is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/966
|
||||
# See tests on this in test_backend_xgrammar.py
|
||||
# unsupported_string_schemas
|
||||
if "string" in schema_types and _has_pattern_and_length_bounds(obj):
|
||||
return True
|
||||
|
||||
# propertyNames validates names, so it is a string schema even when it
|
||||
# omits "type", which is the form that escapes the check above.
|
||||
if (
|
||||
"object" in schema_types
|
||||
and isinstance(obj.get("propertyNames"), dict)
|
||||
and _has_pattern_and_length_bounds(obj["propertyNames"])
|
||||
):
|
||||
return True
|
||||
# propertyNames is not supported in pair with some constraints
|
||||
# in xgrammar
|
||||
# See tests on this in test_backend_xgrammar.py
|
||||
# unsupported_propertyNames_combinations
|
||||
if "object" in schema_types and "propertyNames" in obj:
|
||||
# propertyNames + maxLength is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/960
|
||||
property_names = obj.get("propertyNames")
|
||||
if isinstance(property_names, dict) and _has_pattern_and_length_bounds(
|
||||
property_names
|
||||
):
|
||||
return True
|
||||
# propertyNames + patternProperties is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/959
|
||||
if "patternProperties" in obj:
|
||||
return True
|
||||
# propertyNames + properties is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/958
|
||||
if "properties" in obj:
|
||||
return True
|
||||
# propertyNames + unevaluatedProperties is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/961
|
||||
if obj.get("unevaluatedProperties", True) is not True:
|
||||
return True
|
||||
|
||||
# FIXME: propertyNames conflicts with properties/patternProperties/
|
||||
# additionalProperties/unevaluatedProperties under xgrammar.
|
||||
# https://github.com/mlc-ai/xgrammar/issues/826
|
||||
if (
|
||||
"object" in schema_types
|
||||
and "propertyNames" in obj
|
||||
and (
|
||||
"properties" in obj
|
||||
or "patternProperties" in obj
|
||||
or isinstance(obj.get("additionalProperties"), dict)
|
||||
or obj.get("unevaluatedProperties", True) is not True
|
||||
)
|
||||
):
|
||||
return True
|
||||
# patternProperties is not supported in pair with some constraints
|
||||
# in xgrammar
|
||||
# See tests on this in test_backend_xgrammar.py
|
||||
# unsupported_patternProperties_combinations
|
||||
if "object" in schema_types and isinstance(obj.get("patternProperties"), dict):
|
||||
# patternProperties + properties is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/964
|
||||
if "properties" in obj:
|
||||
return True
|
||||
# patternProperties + patternProperties is unsupported by xgrammar
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/965
|
||||
if len(obj["patternProperties"]) > 1:
|
||||
return True
|
||||
|
||||
# FIXME: multiple patternProperties, or patternProperties alongside
|
||||
# properties, conflict under xgrammar.
|
||||
if (
|
||||
"object" in schema_types
|
||||
and isinstance(obj.get("patternProperties"), dict)
|
||||
and ("properties" in obj or len(obj["patternProperties"]) > 1)
|
||||
):
|
||||
# Note(arpera):
|
||||
# Xgrammar lacks support of multi-branch allOf
|
||||
# For instance, this schema:
|
||||
# {
|
||||
# "allOf": [
|
||||
# { "type": "string" },
|
||||
# { "enum": ["yes", "no"] }
|
||||
# ]
|
||||
# }
|
||||
# would accept any kind of json, such as
|
||||
# "maybe", "", 42, {}, [], {"a": 1}, etc.
|
||||
# which is NOT what is expected.
|
||||
# Tracking issue: https://github.com/mlc-ai/xgrammar/issues/937
|
||||
allof = obj.get("allOf")
|
||||
if isinstance(allof, list) and len(allof) >= 2:
|
||||
return True
|
||||
|
||||
# Recursively check all nested objects and arrays
|
||||
@@ -392,6 +446,7 @@ def validate_xgrammar_grammar(sampling_params: SamplingParams) -> None:
|
||||
return
|
||||
|
||||
if so_params.json:
|
||||
check_json_nesting(so_params.json)
|
||||
if isinstance(so_params.json, str):
|
||||
try:
|
||||
schema = json.loads(so_params.json)
|
||||
@@ -400,13 +455,15 @@ def validate_xgrammar_grammar(sampling_params: SamplingParams) -> None:
|
||||
else:
|
||||
schema = so_params.json
|
||||
|
||||
if has_xgrammar_unsupported_json_features(schema):
|
||||
raise VLLMValidationError(
|
||||
"The provided JSON schema contains features not supported by xgrammar."
|
||||
)
|
||||
|
||||
try:
|
||||
if has_xgrammar_unsupported_json_features(schema):
|
||||
raise VLLMValidationError(
|
||||
"The provided JSON schema contains features not supported "
|
||||
"by xgrammar."
|
||||
)
|
||||
xgr.Grammar.from_json_schema(schema)
|
||||
except VLLMValidationError:
|
||||
raise
|
||||
except Exception as err:
|
||||
raise VLLMValidationError(
|
||||
f"Failed to transform json schema into a grammar: {err}"
|
||||
@@ -426,6 +483,7 @@ def validate_xgrammar_grammar(sampling_params: SamplingParams) -> None:
|
||||
return
|
||||
|
||||
if so_params.structural_tag:
|
||||
check_json_nesting(so_params.structural_tag, structural_tag=True)
|
||||
try:
|
||||
s_tag = json.loads(so_params.structural_tag)
|
||||
|
||||
|
||||
+113
-128
@@ -29,7 +29,7 @@ from torch.autograd.profiler import record_function
|
||||
import vllm.envs as envs
|
||||
from vllm.logger import init_logger
|
||||
from vllm.usage.usage_lib import UsageContext, is_usage_stats_enabled, usage_message
|
||||
from vllm.utils.network_utils import get_open_zmq_ipc_path, get_tcp_uri
|
||||
from vllm.utils.network_utils import ZmqListener, get_open_zmq_ipc_path, get_tcp_uri
|
||||
from vllm.utils.system_utils import decorate_logs, kill_process_tree, set_process_title
|
||||
from vllm.utils.torch_utils import PIN_MEMORY
|
||||
from vllm.v1.core.sched.output import SchedulerOutput
|
||||
@@ -177,28 +177,22 @@ class APIServerProcessManager:
|
||||
sock: Any,
|
||||
args: argparse.Namespace,
|
||||
num_servers: int,
|
||||
input_addresses: list[str],
|
||||
output_addresses: list[str],
|
||||
input_listeners: list[ZmqListener],
|
||||
output_listeners: list[ZmqListener],
|
||||
target_server_fn: Callable | None = None,
|
||||
stats_update_address: str | None = None,
|
||||
tensor_queue: Queue | None = None,
|
||||
):
|
||||
"""Initialize and start API server worker processes.
|
||||
|
||||
``input_addresses``/``output_addresses`` may contain
|
||||
``tcp://host:0`` placeholders; each child must report the actual
|
||||
bound endpoint over its ``actual_address_pipe`` in ``client_config``
|
||||
and the parent collects them via
|
||||
:py:meth:`gather_actual_addresses`.
|
||||
|
||||
Args:
|
||||
target_server_fn: Override function to call for each API server process
|
||||
listen_address: Address to listen for client connections
|
||||
sock: Socket for client connections
|
||||
args: Command line arguments
|
||||
num_servers: Number of API server processes to start
|
||||
input_addresses: Input addresses for each API server
|
||||
output_addresses: Output addresses for each API server
|
||||
input_listeners: Input listeners for each API server
|
||||
output_listeners: Output listeners for each API server
|
||||
stats_update_address: Optional stats update address
|
||||
tensor_queue: Optional tensor IPC queue for sharing MM tensors
|
||||
|
||||
@@ -209,7 +203,6 @@ class APIServerProcessManager:
|
||||
|
||||
spawn_context = multiprocessing.get_context("spawn")
|
||||
self.processes: list[BaseProcess] = []
|
||||
self._address_pipes: list[connection.Connection] = []
|
||||
|
||||
admission_counters = None
|
||||
if num_servers > 1 and getattr(args, "max_num_queued_reqs", None) is not None:
|
||||
@@ -220,126 +213,75 @@ class APIServerProcessManager:
|
||||
SharedAdmissionStats.num_counters(num_servers),
|
||||
)
|
||||
|
||||
for i, in_addr, out_addr in zip(
|
||||
range(num_servers), input_addresses, output_addresses
|
||||
):
|
||||
client_config: dict[str, Any] = {
|
||||
"input_address": in_addr,
|
||||
"output_address": out_addr,
|
||||
"client_count": num_servers,
|
||||
"client_index": i,
|
||||
}
|
||||
if admission_counters is not None:
|
||||
client_config["mp_admission_counters"] = admission_counters
|
||||
if stats_update_address is not None:
|
||||
client_config["stats_update_address"] = stats_update_address
|
||||
if tensor_queue is not None:
|
||||
client_config["tensor_queue"] = tensor_queue
|
||||
# Open connections per API server, to accept on the least loaded one;
|
||||
# a server that has not started yet is never the least loaded.
|
||||
api_server_loads = (
|
||||
spawn_context.RawArray("i", [2**31 - 1] * num_servers)
|
||||
if num_servers > 1
|
||||
else None
|
||||
)
|
||||
|
||||
parent_recv, child_send = spawn_context.Pipe(duplex=False)
|
||||
self._address_pipes.append(parent_recv)
|
||||
client_config["actual_address_pipe"] = child_send
|
||||
|
||||
proc = spawn_context.Process(
|
||||
target=target_server_fn or run_api_server_worker_proc,
|
||||
name=f"ApiServer_{i}",
|
||||
args=(listen_address, sock, args, client_config),
|
||||
listeners = [*input_listeners, *output_listeners]
|
||||
self._listeners = listeners
|
||||
try:
|
||||
listener_pairs = zip(
|
||||
range(num_servers), input_listeners, output_listeners, strict=True
|
||||
)
|
||||
self.processes.append(proc)
|
||||
proc.start()
|
||||
for i, input_listener, output_listener in listener_pairs:
|
||||
client_config: dict[str, Any] = {
|
||||
"input_address": input_listener.address,
|
||||
"output_address": output_listener.address,
|
||||
"input_listener": input_listener.socket,
|
||||
"output_listener": output_listener.socket,
|
||||
"client_count": num_servers,
|
||||
"client_index": i,
|
||||
}
|
||||
if api_server_loads is not None:
|
||||
client_config["api_server_loads"] = api_server_loads
|
||||
if admission_counters is not None:
|
||||
client_config["mp_admission_counters"] = admission_counters
|
||||
if stats_update_address is not None:
|
||||
client_config["stats_update_address"] = stats_update_address
|
||||
if tensor_queue is not None:
|
||||
client_config["tensor_queue"] = tensor_queue
|
||||
|
||||
# Drop parent's write end so reader sees EOF on child death.
|
||||
child_send.close()
|
||||
proc = spawn_context.Process(
|
||||
target=target_server_fn or run_api_server_worker_proc,
|
||||
name=f"ApiServer_{i}",
|
||||
args=(listen_address, sock, args, client_config),
|
||||
)
|
||||
self.processes.append(proc)
|
||||
proc.start()
|
||||
input_listener.close()
|
||||
output_listener.close()
|
||||
except BaseException:
|
||||
_shutdown_processes_and_cleanup_listeners(self.processes, listeners)
|
||||
raise
|
||||
|
||||
logger.info("Started %d API server processes", len(self.processes))
|
||||
|
||||
# Shutdown only the API server processes on garbage collection
|
||||
# The extra processes are managed by their owners
|
||||
self._finalizer = weakref.finalize(self, shutdown, self.processes)
|
||||
|
||||
def gather_actual_addresses(
|
||||
self,
|
||||
timeout: float = envs.VLLM_ENGINE_READY_TIMEOUT_S,
|
||||
) -> tuple[list[str], list[str]]:
|
||||
"""Return (inputs, outputs) reported by each child, indexed by
|
||||
``client_index``. Raises ``RuntimeError`` on timeout or premature
|
||||
child exit."""
|
||||
n = len(self._address_pipes)
|
||||
inputs: list[str | None] = [None] * n
|
||||
outputs: list[str | None] = [None] * n
|
||||
pending: dict[connection.Connection, int] = {
|
||||
pipe: i for i, pipe in enumerate(self._address_pipes)
|
||||
}
|
||||
sentinel_to_idx: dict[Any, int] = {
|
||||
proc.sentinel: i for i, proc in enumerate(self.processes)
|
||||
}
|
||||
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
while pending:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
missing = [self.processes[i].name for i in pending.values()]
|
||||
raise RuntimeError(
|
||||
f"Timed out after {timeout:.1f}s waiting for "
|
||||
f"API server(s) to report bound ZMQ addresses: "
|
||||
f"{missing}"
|
||||
)
|
||||
waitables: list[Any] = list(pending.keys()) + list(
|
||||
sentinel_to_idx.keys()
|
||||
)
|
||||
ready = connection.wait(waitables, timeout=remaining)
|
||||
# Drain pipes before checking sentinels: a child that sent
|
||||
# its message and then exited can surface both events in
|
||||
# the same poll, and we must record the success first.
|
||||
for item in ready:
|
||||
if isinstance(item, connection.Connection) and item in pending:
|
||||
idx = pending.pop(item)
|
||||
try:
|
||||
msg: dict[str, str] = item.recv()
|
||||
except EOFError as e:
|
||||
raise RuntimeError(
|
||||
f"API server {self.processes[idx].name} "
|
||||
f"closed its address pipe without "
|
||||
f"reporting its bound ZMQ addresses"
|
||||
) from e
|
||||
inputs[idx] = msg["input_address"]
|
||||
outputs[idx] = msg["output_address"]
|
||||
item.close()
|
||||
for item in ready:
|
||||
if item in sentinel_to_idx:
|
||||
idx = sentinel_to_idx.pop(item)
|
||||
pipe = self._address_pipes[idx]
|
||||
if pipe in pending:
|
||||
proc = self.processes[idx]
|
||||
raise RuntimeError(
|
||||
f"API server process {proc.name} exited "
|
||||
f"(code={proc.exitcode}) before reporting "
|
||||
f"its bound ZMQ addresses"
|
||||
)
|
||||
finally:
|
||||
for pipe in pending:
|
||||
with contextlib.suppress(Exception):
|
||||
pipe.close()
|
||||
|
||||
return inputs, outputs # type: ignore[return-value]
|
||||
self._finalizer = weakref.finalize(
|
||||
self,
|
||||
_shutdown_processes_and_cleanup_listeners,
|
||||
self.processes,
|
||||
listeners,
|
||||
)
|
||||
|
||||
def shutdown(self, timeout: float | None = None) -> None:
|
||||
"""Shutdown API server processes with configurable timeout"""
|
||||
for pipe in self._address_pipes:
|
||||
with contextlib.suppress(Exception):
|
||||
pipe.close()
|
||||
self._address_pipes = []
|
||||
|
||||
if self._finalizer.detach() is not None:
|
||||
shutdown(self.processes, timeout=timeout)
|
||||
_shutdown_processes_and_cleanup_listeners(
|
||||
self.processes, self._listeners, timeout=timeout
|
||||
)
|
||||
|
||||
|
||||
class RustFrontendProcessManager:
|
||||
"""Manages a single Rust frontend subprocess.
|
||||
|
||||
Launches the Rust vllm-rs binary in 'frontend' mode, passing the
|
||||
listening socket fd and ZMQ transport addresses. Provides the same
|
||||
HTTP and ZMQ listener file descriptors. Provides the same
|
||||
interface as APIServerProcessManager for process monitoring.
|
||||
"""
|
||||
|
||||
@@ -348,8 +290,8 @@ class RustFrontendProcessManager:
|
||||
binary_path: str,
|
||||
sock: Any,
|
||||
args: argparse.Namespace,
|
||||
input_address: str,
|
||||
output_address: str,
|
||||
input_listener: ZmqListener,
|
||||
output_listener: ZmqListener,
|
||||
engine_start_index: int,
|
||||
engine_count: int,
|
||||
data_parallel_size: int,
|
||||
@@ -359,18 +301,22 @@ class RustFrontendProcessManager:
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
fd = sock.fileno()
|
||||
os.set_inheritable(fd, True)
|
||||
listen_fd = sock.fileno()
|
||||
input_fd = input_listener.socket.fileno()
|
||||
output_fd = output_listener.socket.fileno()
|
||||
inherited_fds = [listen_fd, input_fd, output_fd]
|
||||
for fd in inherited_fds:
|
||||
os.set_inheritable(fd, True)
|
||||
|
||||
cmd = [
|
||||
binary_path,
|
||||
"frontend",
|
||||
"--listen-fd",
|
||||
str(fd),
|
||||
"--input-address",
|
||||
input_address,
|
||||
"--output-address",
|
||||
output_address,
|
||||
str(listen_fd),
|
||||
"--input-listener-fd",
|
||||
str(input_fd),
|
||||
"--output-listener-fd",
|
||||
str(output_fd),
|
||||
"--engine-start-index",
|
||||
str(engine_start_index),
|
||||
"--engine-count",
|
||||
@@ -378,12 +324,11 @@ class RustFrontendProcessManager:
|
||||
"--data-parallel-size",
|
||||
str(data_parallel_size),
|
||||
]
|
||||
pass_fds = [fd]
|
||||
if grpc_sock is not None:
|
||||
grpc_fd = grpc_sock.fileno()
|
||||
os.set_inheritable(grpc_fd, True)
|
||||
cmd.extend(["--grpc-listen-fd", str(grpc_fd)])
|
||||
pass_fds.append(grpc_fd)
|
||||
inherited_fds.append(grpc_fd)
|
||||
if stats_update_address is not None:
|
||||
cmd.extend(["--coordinator-address", stats_update_address])
|
||||
from vllm.entrypoints.serve.utils.api_utils import jsonify_non_default_args
|
||||
@@ -425,18 +370,34 @@ class RustFrontendProcessManager:
|
||||
|
||||
redacted_json = json.dumps(redact_sensitive_args(args_dict), sort_keys=True)
|
||||
logger.info("Launching Rust frontend: %s", " ".join(cmd[:-1] + [redacted_json]))
|
||||
self._proc = subprocess.Popen(cmd, pass_fds=pass_fds)
|
||||
self._listeners = [input_listener, output_listener]
|
||||
try:
|
||||
self._proc = subprocess.Popen(cmd, pass_fds=inherited_fds)
|
||||
except BaseException:
|
||||
for listener in self._listeners:
|
||||
listener.cleanup()
|
||||
raise
|
||||
else:
|
||||
input_listener.close()
|
||||
output_listener.close()
|
||||
|
||||
# Create a process wrapper with a sentinel fd for monitoring
|
||||
self.processes: list[_SubprocessWrapper] = [
|
||||
_SubprocessWrapper(self._proc, "RustFrontend")
|
||||
]
|
||||
|
||||
self._finalizer = weakref.finalize(self, _shutdown_subprocesses, self.processes)
|
||||
self._finalizer = weakref.finalize(
|
||||
self,
|
||||
_shutdown_subprocesses_and_cleanup_listeners,
|
||||
self.processes,
|
||||
self._listeners,
|
||||
)
|
||||
|
||||
def shutdown(self, timeout: float | None = None) -> None:
|
||||
if self._finalizer.detach() is not None:
|
||||
_shutdown_subprocesses(self.processes, timeout=timeout)
|
||||
_shutdown_subprocesses_and_cleanup_listeners(
|
||||
self.processes, self._listeners, timeout=timeout
|
||||
)
|
||||
|
||||
|
||||
class _SubprocessWrapper:
|
||||
@@ -533,6 +494,18 @@ def _shutdown_subprocesses(
|
||||
logger.debug_once("[shutdown] Subprocess manager: complete")
|
||||
|
||||
|
||||
def _shutdown_subprocesses_and_cleanup_listeners(
|
||||
procs: list[_SubprocessWrapper],
|
||||
listeners: list[ZmqListener],
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
_shutdown_subprocesses(procs, timeout=timeout)
|
||||
finally:
|
||||
for listener in listeners:
|
||||
listener.cleanup()
|
||||
|
||||
|
||||
def run_api_server_worker_proc(
|
||||
listen_address, sock, args, client_config=None, **uvicorn_kwargs
|
||||
) -> None:
|
||||
@@ -687,6 +660,18 @@ def shutdown(procs: list[BaseProcess], timeout: float | None = None) -> None:
|
||||
logger.debug_once("[shutdown] Process manager: complete")
|
||||
|
||||
|
||||
def _shutdown_processes_and_cleanup_listeners(
|
||||
procs: list[BaseProcess],
|
||||
listeners: list[ZmqListener],
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
shutdown(procs, timeout=timeout)
|
||||
finally:
|
||||
for listener in listeners:
|
||||
listener.cleanup()
|
||||
|
||||
|
||||
def copy_slice(
|
||||
from_tensor: torch.Tensor, to_tensor: torch.Tensor, length: int
|
||||
) -> torch.Tensor:
|
||||
|
||||
@@ -221,7 +221,7 @@ class DualKeyGumbelWatermarkDetector(GumbelWatermarkDetector):
|
||||
p_value_threshold: float = 0.01,
|
||||
prf: WatermarkPRFName = "philox",
|
||||
deduplicate_contexts: bool = True,
|
||||
alpha: float = 0.2,
|
||||
alpha: float = 0.1,
|
||||
) -> None:
|
||||
if not 0 <= alpha <= 1:
|
||||
raise ValueError("alpha must be between 0 and 1")
|
||||
|
||||
@@ -268,7 +268,9 @@ class CPUWorker(Worker):
|
||||
self.model_runner.warming_up_model()
|
||||
# Reset the seed to ensure that the random state is not affected by
|
||||
# the model initialization and profiling.
|
||||
set_random_seed(self.model_config.seed)
|
||||
set_random_seed(
|
||||
self.model_config.seed, self.parallel_config.data_parallel_index
|
||||
)
|
||||
return CompilationTimes(
|
||||
language_model=self.compilation_config.compilation_time,
|
||||
encoder=self.compilation_config.encoder_compilation_time,
|
||||
|
||||
@@ -23,6 +23,7 @@ from vllm.model_executor.models.interfaces import (
|
||||
from vllm.model_executor.models.utils import scatter_output_slices
|
||||
from vllm.model_executor.models.vision import get_load_balance_assignment
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
from vllm.utils.math_utils import round_up_to
|
||||
from vllm.utils.torch_utils import current_stream
|
||||
from vllm.v1.worker.encoder_cudagraph_defs import (
|
||||
ENCODER_CUDAGRAPH_AXIS_KEYS_KWARG,
|
||||
@@ -347,17 +348,17 @@ class EncoderCudaGraphManager:
|
||||
def _find_smallest_fitting_budget_given_tokens(
|
||||
self, total_tokens: int, budgets: list[int] | None = None
|
||||
) -> int | None:
|
||||
"""Find smallest budget >= total_tokens.
|
||||
|
||||
Returns:
|
||||
Token budget if found, None if no fitting budget.
|
||||
|
||||
"""
|
||||
"""Find smallest budget >= total_tokens, or None if none fits."""
|
||||
budgets = budgets if budgets is not None else self.token_budgets
|
||||
for budget in budgets:
|
||||
if budget >= total_tokens:
|
||||
return budget
|
||||
return None
|
||||
return round_up_to(budgets, total_tokens)
|
||||
|
||||
def _path_fitting_budget(self, path: str, tokens: int) -> int | None:
|
||||
"""Smallest captured budget on a path; 0 when idle, None if oversized."""
|
||||
if tokens == 0:
|
||||
return 0
|
||||
return self._find_smallest_fitting_budget_given_tokens(
|
||||
tokens, self.path_token_budgets[path]
|
||||
)
|
||||
|
||||
def _get_item_specs(self, mm_kwargs: dict[str, Any]) -> list[EncoderItemSpec]:
|
||||
"""Get item specs from the model."""
|
||||
@@ -479,24 +480,38 @@ class EncoderCudaGraphManager:
|
||||
if not current_batch:
|
||||
return
|
||||
path_budgets = {
|
||||
path: (
|
||||
0
|
||||
if current_tokens[path] == 0
|
||||
else self._find_smallest_fitting_budget_given_tokens(
|
||||
current_tokens[path], self.path_token_budgets[path]
|
||||
)
|
||||
)
|
||||
path: self._path_fitting_budget(path, current_tokens[path])
|
||||
for path in paths
|
||||
}
|
||||
batches.append((list(current_batch), path_budgets))
|
||||
|
||||
def should_defer_item(item_tokens: dict[str, int]) -> bool:
|
||||
"""Whether closing the batch strictly reduces summed budgets."""
|
||||
for path in paths:
|
||||
item = item_tokens[path]
|
||||
if item == 0:
|
||||
continue
|
||||
cur = current_tokens[path]
|
||||
b_cur = self._path_fitting_budget(path, cur)
|
||||
b_alone = self._path_fitting_budget(path, item)
|
||||
b_merged = self._path_fitting_budget(path, cur + item)
|
||||
# Only called when the item fits; lookups land on a budget.
|
||||
assert (
|
||||
b_cur is not None and b_alone is not None and b_merged is not None
|
||||
)
|
||||
# Only defer items that alone outweigh the whole current
|
||||
# batch; splitting smaller ones fragments flood packing.
|
||||
if b_cur + b_alone < b_merged and b_alone >= b_cur:
|
||||
return True
|
||||
return False
|
||||
|
||||
for orig_idx in sorted_indices:
|
||||
item_tokens = {path: per_item_path_tokens[path][orig_idx] for path in paths}
|
||||
fits = len(current_batch) < self.max_batch_size and all(
|
||||
current_tokens[path] + item_tokens[path] <= max_path_budgets[path]
|
||||
for path in paths
|
||||
)
|
||||
if current_batch and not fits:
|
||||
if current_batch and (not fits or should_defer_item(item_tokens)):
|
||||
append_current_batch()
|
||||
current_batch = []
|
||||
current_tokens = dict.fromkeys(paths, 0)
|
||||
|
||||
@@ -262,7 +262,7 @@ class AsyncPoolingOutput(AsyncModelRunnerOutput):
|
||||
|
||||
|
||||
def async_copy_to_np(x: torch.Tensor) -> np.ndarray:
|
||||
return x.to("cpu", non_blocking=True).numpy()
|
||||
return x.to("cpu", non_blocking=True, copy=True).numpy()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
|
||||
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import (
|
||||
VllmConfig,
|
||||
get_layers_from_vllm_config,
|
||||
@@ -224,6 +225,14 @@ def init_attn_backend(
|
||||
|
||||
for layer_name in layer_names:
|
||||
attn_backend = attn_layers[layer_name].get_attn_backend()
|
||||
if (
|
||||
envs.VLLM_BATCH_INVARIANT
|
||||
and not attn_backend.supports_batch_invariance()
|
||||
):
|
||||
raise RuntimeError(
|
||||
"VLLM batch_invariant mode is not supported for "
|
||||
f"{attn_backend.get_name()}."
|
||||
)
|
||||
if layer_name in fast_prefill_eligible_layers:
|
||||
attn_backend = create_fast_prefill_custom_backend(
|
||||
"FastPrefill", attn_backend
|
||||
|
||||
@@ -54,8 +54,8 @@ class NonUvaBuffer:
|
||||
|
||||
def uva(self, n: int | None = None) -> torch.Tensor:
|
||||
if n is None:
|
||||
return self._uva.copy_(self.cpu)
|
||||
return self._uva[:n].copy_(self.cpu[:n])
|
||||
return self._uva.copy_(self.cpu, non_blocking=True)
|
||||
return self._uva[:n].copy_(self.cpu[:n], non_blocking=True)
|
||||
|
||||
|
||||
class UvaBufferPool:
|
||||
|
||||
@@ -272,6 +272,7 @@ class CudaGraphManager:
|
||||
if (
|
||||
speculative_config
|
||||
and speculative_config.uses_dynamic_speculative_decoding()
|
||||
and self.decode_query_len > self.vllm_config.num_speculative_tokens
|
||||
):
|
||||
# decode_query_len = num_speculative_steps + num_new_sampled_tokens
|
||||
# _per_step. Recover num_new_sampled_tokens_per_step
|
||||
|
||||
@@ -150,9 +150,12 @@ class EncoderRunner:
|
||||
def execute_mm_encoder(
|
||||
self, mm_kwargs: list[tuple[str, MultiModalKwargsItem]]
|
||||
) -> list[torch.Tensor]:
|
||||
# Stable-sort items by modality so each modality is encoded in as few
|
||||
# batches as possible. The returned outputs are restored to input order.
|
||||
order = sorted(range(len(mm_kwargs)), key=lambda i: mm_kwargs[i][0])
|
||||
encoder_outputs: list[torch.Tensor] = []
|
||||
for modality, num_items, mm_kwargs_batch in group_and_batch_mm_kwargs(
|
||||
mm_kwargs, device=self.device, pin_memory=PIN_MEMORY
|
||||
[mm_kwargs[i] for i in order], device=self.device, pin_memory=PIN_MEMORY
|
||||
):
|
||||
cg_manager = self.cudagraph_manager
|
||||
cudagraph_output = (
|
||||
@@ -169,7 +172,7 @@ class EncoderRunner:
|
||||
)
|
||||
sanity_check_mm_encoder_outputs(batch_outputs, expected_num_items=num_items)
|
||||
encoder_outputs.extend(batch_outputs)
|
||||
return encoder_outputs
|
||||
return [encoder_outputs[i] for i in np.argsort(order)]
|
||||
|
||||
@contextmanager
|
||||
def timed_encoder_operation(self, request_ids: Collection[str]):
|
||||
|
||||
@@ -6,6 +6,7 @@ import numpy as np
|
||||
|
||||
from vllm.lora.layers import LoRAMapping, LoRAMappingType
|
||||
from vllm.lora.worker_manager import WorkerLoRAManager
|
||||
from vllm.multimodal.inputs import MultiModalFeatureSpec
|
||||
from vllm.v1.worker.gpu.lora_utils import LoraState
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
|
||||
@@ -31,7 +32,7 @@ def set_active_mm_loras(
|
||||
encoder_token_counts: list[int] = []
|
||||
connector_token_counts: list[int] = []
|
||||
|
||||
# iterate through images
|
||||
mm_items: list[tuple[int, MultiModalFeatureSpec]] = []
|
||||
for req_id, encoder_input_ids in scheduled_encoder_inputs.items():
|
||||
req_idx = req_id_to_index.get(req_id)
|
||||
if req_idx is None:
|
||||
@@ -39,27 +40,29 @@ def set_active_mm_loras(
|
||||
|
||||
lora_id = int(lora_state.lora_ids[req_idx])
|
||||
mm_features = encoder_cache.mm_features[req_id]
|
||||
|
||||
# iterate through visual tokens
|
||||
for mm_input_id in encoder_input_ids:
|
||||
pos_info = mm_features[mm_input_id].mm_position
|
||||
|
||||
tower_tokens, connector_tokens = model.get_mm_lora_token_counts(
|
||||
modality=mm_features[mm_input_id].modality,
|
||||
mm_kwargs=mm_features[mm_input_id].data,
|
||||
num_mm_embeds=pos_info.get_num_embeds(),
|
||||
)
|
||||
|
||||
prompt_lora_mapping.append(lora_id)
|
||||
token_lora_mapping.extend([lora_id] * tower_tokens)
|
||||
encoder_token_counts.append(tower_tokens)
|
||||
connector_token_counts.append(connector_tokens)
|
||||
mm_items.extend((lora_id, mm_features[i]) for i in encoder_input_ids)
|
||||
|
||||
if lora_id > 0:
|
||||
lora_request = lora_state.lora_requests.get(req_id)
|
||||
if lora_request is not None:
|
||||
lora_requests.add(lora_request)
|
||||
|
||||
# Runs items sorted by modality.
|
||||
mm_items.sort(key=lambda x: x[1].modality)
|
||||
for lora_id, mm_feature in mm_items:
|
||||
pos_info = mm_feature.mm_position
|
||||
|
||||
tower_tokens, connector_tokens = model.get_mm_lora_token_counts(
|
||||
modality=mm_feature.modality,
|
||||
mm_kwargs=mm_feature.data,
|
||||
num_mm_embeds=pos_info.get_num_embeds(),
|
||||
)
|
||||
|
||||
prompt_lora_mapping.append(lora_id)
|
||||
token_lora_mapping.extend([lora_id] * tower_tokens)
|
||||
encoder_token_counts.append(tower_tokens)
|
||||
connector_token_counts.append(connector_tokens)
|
||||
|
||||
if not prompt_lora_mapping:
|
||||
return
|
||||
|
||||
|
||||
@@ -265,13 +265,32 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.encoder_cache = EncoderCache()
|
||||
self.ec_connector = get_ec_connector(vllm_config, self.encoder_cache)
|
||||
|
||||
self.num_speculative_steps = vllm_config.num_speculative_tokens
|
||||
num_prefill_lookahead = max(1, vllm_config.num_prefill_lookahead_tokens)
|
||||
use_dense_all_token_ids = (
|
||||
self.speculative_config is not None and self.speculative_config.use_ngram()
|
||||
)
|
||||
|
||||
# General request states.
|
||||
self.req_states = RequestState(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
max_model_len=self.max_model_len,
|
||||
max_num_batched_tokens=self.max_num_tokens,
|
||||
num_speculative_steps=self.num_speculative_steps,
|
||||
vocab_size=self.vocab_size,
|
||||
device=self.device,
|
||||
num_prefill_lookahead=num_prefill_lookahead,
|
||||
use_dense_all_token_ids=use_dense_all_token_ids,
|
||||
)
|
||||
|
||||
# Speculative decoding.
|
||||
self.speculator = None
|
||||
self.use_aux_hidden_state_outputs = False
|
||||
self.num_speculative_steps = vllm_config.num_speculative_tokens
|
||||
if self.speculative_config is not None:
|
||||
if self.is_last_pp_rank:
|
||||
self.speculator = init_speculator(self.vllm_config, self.device)
|
||||
self.speculator = init_speculator(
|
||||
self.vllm_config, self.device, self.req_states
|
||||
)
|
||||
|
||||
if self.speculative_config.method in (
|
||||
"eagle3",
|
||||
@@ -291,20 +310,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.is_pooling_model = self.model_config.runner_type == "pooling"
|
||||
self.pooling_runner: PoolingRunner | None = None
|
||||
|
||||
num_prefill_lookahead = max(1, vllm_config.num_prefill_lookahead_tokens)
|
||||
|
||||
self.step_timing = StepTimingCollector()
|
||||
|
||||
# General request states.
|
||||
self.req_states = RequestState(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
max_model_len=self.max_model_len,
|
||||
max_num_batched_tokens=self.max_num_tokens,
|
||||
num_speculative_steps=self.num_speculative_steps,
|
||||
vocab_size=self.vocab_size,
|
||||
device=self.device,
|
||||
num_prefill_lookahead=num_prefill_lookahead,
|
||||
)
|
||||
self.adaptive_verification: AdaptiveVerificationManager | None = None
|
||||
self.input_buffers = InputBuffers(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
@@ -482,7 +488,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
custom = self.model_state.custom_sampler(self.sampler)
|
||||
|
||||
if custom:
|
||||
self.vllm_config._check_watermarking_unsupported(custom_sampler=True)
|
||||
self.vllm_config._check_supports_watermarking(custom_sampler=True)
|
||||
self.sampler, self.rejection_sampler = custom
|
||||
elif self.speculative_config is not None:
|
||||
self.rejection_sampler = RejectionSampler(
|
||||
@@ -724,7 +730,6 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
attn_cg_support.min_cg_attn_backend,
|
||||
self.decode_query_len,
|
||||
use_v2_model_runner=True,
|
||||
tensor_parallel_size=self.parallel_config.tensor_parallel_size,
|
||||
kv_cache_config=self.kv_cache_config,
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
is_profiling=is_profiling,
|
||||
@@ -772,6 +777,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.kv_caches = [
|
||||
cache for cache in kv_caches_dict.values() if cache.device == self.device
|
||||
]
|
||||
self.model_state.initialize_kv_cache(self.kv_cache_config, self.block_tables)
|
||||
if is_profiling:
|
||||
self.kv_connector = NO_OP_KV_CONNECTOR
|
||||
else:
|
||||
@@ -813,7 +819,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
"skip_attn must only be True for initial memory profiling."
|
||||
)
|
||||
|
||||
# Create a dummy scheduler output. Plain draft-model speculation adds
|
||||
# Create a dummy scheduler output. Standalone AR 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
|
||||
@@ -909,14 +915,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
)
|
||||
mm_inputs = [], all_false
|
||||
|
||||
# Let the target override the hidden state fed to the drafter
|
||||
# (e.g. DeepSeek V4 MTP needs the pre-hc_head residual). The
|
||||
# target returns a persistent buffer sized at max_num_batched_tokens;
|
||||
# slice to the active token count that propose() expects.
|
||||
spec_hidden_states = hidden_states
|
||||
if hasattr(self.model, "get_mtp_target_hidden_states"):
|
||||
pre_hc_hidden_states = self.model.get_mtp_target_hidden_states()
|
||||
spec_hidden_states = pre_hc_hidden_states[: hidden_states.shape[0]] # type: ignore[union-attr]
|
||||
spec_hidden_states = self._get_drafter_hidden_states(hidden_states)
|
||||
if isinstance(self.sampler, GPUWatermarkSampler):
|
||||
self.speculator.prepare_watermarking(
|
||||
self.sampler, input_batch.idx_mapping
|
||||
@@ -1077,6 +1076,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.lora_config, self
|
||||
),
|
||||
)
|
||||
self.model_state.capture_inner_cudagraphs(
|
||||
input_buffers,
|
||||
self.block_tables,
|
||||
self.attn_groups,
|
||||
self.kv_cache_config,
|
||||
)
|
||||
if self.speculator is not None:
|
||||
with use_workspace_lane(self._draft_workspace_lane):
|
||||
self.speculator.capture()
|
||||
@@ -2057,6 +2062,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
finished_req_ids=finished_req_ids,
|
||||
ec_connector_output=ec_connector_output,
|
||||
cudagraph_stats=cudagraph_stats,
|
||||
num_spec_tokens_to_schedule=scheduler_output.num_spec_tokens_to_schedule,
|
||||
)
|
||||
|
||||
if not self.is_last_pp_rank:
|
||||
@@ -2068,6 +2074,24 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
)
|
||||
return None
|
||||
|
||||
def _get_drafter_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
||||
"""Hidden states fed to the drafter.
|
||||
|
||||
Targets such as DeepSeek V4 expose the pre-hc_head residual through
|
||||
get_mtp_target_hidden_states(). The buffer is sized at
|
||||
max_num_batched_tokens and only allocated for drafters that consume
|
||||
target hidden states, so None means "use the regular hidden states".
|
||||
"""
|
||||
get_target_hidden_states = getattr(
|
||||
self.model, "get_mtp_target_hidden_states", None
|
||||
)
|
||||
if get_target_hidden_states is None:
|
||||
return hidden_states
|
||||
target_hidden_states = get_target_hidden_states()
|
||||
if target_hidden_states is None:
|
||||
return hidden_states
|
||||
return target_hidden_states[: hidden_states.shape[0]]
|
||||
|
||||
@torch.inference_mode()
|
||||
@step_eplb_after()
|
||||
def sample_tokens(
|
||||
@@ -2086,6 +2110,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
finished_req_ids = self.execute_model_state.finished_req_ids
|
||||
ec_connector_output = self.execute_model_state.ec_connector_output
|
||||
cudagraph_stats = self.execute_model_state.cudagraph_stats
|
||||
num_spec_tokens = self.execute_model_state.num_spec_tokens_to_schedule
|
||||
self.execute_model_state = None
|
||||
|
||||
if not self.is_last_pp_rank:
|
||||
@@ -2212,14 +2237,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.speculator.observe_verification(
|
||||
input_batch.idx_mapping, num_sampled, num_rejected
|
||||
)
|
||||
# Let the target override the hidden state fed to the drafter
|
||||
# (e.g. DeepSeek V4 MTP needs the pre-hc_head residual). The
|
||||
# target returns a persistent buffer sized at max_num_batched_tokens;
|
||||
# slice to the active token count that propose() expects.
|
||||
spec_hidden_states = draft_hidden_states
|
||||
if hasattr(self.model, "get_mtp_target_hidden_states"):
|
||||
pre_hc_hidden_states = self.model.get_mtp_target_hidden_states()
|
||||
spec_hidden_states = pre_hc_hidden_states[: draft_hidden_states.size(0)]
|
||||
spec_hidden_states = self._get_drafter_hidden_states(draft_hidden_states)
|
||||
if isinstance(self.sampler, GPUWatermarkSampler):
|
||||
self.speculator.prepare_watermarking(
|
||||
self.sampler, input_batch.idx_mapping
|
||||
@@ -2237,9 +2255,12 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
self.req_states.next_prefill_tokens,
|
||||
self.sampler.sampling_states.temperature.gpu,
|
||||
self.sampler.sampling_states.seeds.gpu,
|
||||
num_speculative_tokens=num_spec_tokens,
|
||||
dp_sync=dp_sync,
|
||||
mm_inputs=mm_inputs,
|
||||
)
|
||||
if num_spec_tokens < self.num_speculative_steps:
|
||||
draft_tokens[:, num_spec_tokens:] = -1
|
||||
self.req_states.draft_tokens[input_batch.idx_mapping] = draft_tokens
|
||||
if self.adaptive_verification is not None:
|
||||
self.adaptive_verification.record_confidences(
|
||||
@@ -2251,7 +2272,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
|
||||
# not have a speculator (i.e. self.speculator is None)
|
||||
self.draft_tokens_handler.set_draft_tokens(
|
||||
input_batch,
|
||||
self.req_states.draft_tokens[input_batch.idx_mapping],
|
||||
self.req_states.draft_tokens[input_batch.idx_mapping, :num_spec_tokens],
|
||||
)
|
||||
if self.pp_handler is not None:
|
||||
self.pp_handler.broadcast_drafts(
|
||||
@@ -2396,6 +2417,7 @@ class ExecuteModelState(NamedTuple):
|
||||
finished_req_ids: set[str]
|
||||
ec_connector_output: ECConnectorOutput | None
|
||||
cudagraph_stats: CUDAGraphStat | None
|
||||
num_spec_tokens_to_schedule: int
|
||||
|
||||
|
||||
class BatchReqState(NamedTuple):
|
||||
|
||||
@@ -17,7 +17,8 @@ from vllm.v1.attention.backend import AttentionCGSupport
|
||||
from vllm.v1.core.sched.output import NewRequestData
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.worker.encoder_cudagraph import EncoderCudaGraphManager
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch, InputBuffers
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.mm.encoder_runner import EncoderRunner
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
@@ -126,6 +127,22 @@ class ModelState(ABC):
|
||||
def apply_staged_writes(self) -> None:
|
||||
return None
|
||||
|
||||
def initialize_kv_cache(
|
||||
self, kv_cache_config: KVCacheConfig, block_tables: BlockTables
|
||||
) -> None:
|
||||
"""Hook run after the KV cache tensors are allocated and bound."""
|
||||
return None
|
||||
|
||||
def capture_inner_cudagraphs(
|
||||
self,
|
||||
input_buffers: InputBuffers,
|
||||
block_tables: BlockTables,
|
||||
attn_groups: list[list[AttentionGroup]],
|
||||
kv_cache_config: KVCacheConfig,
|
||||
) -> None:
|
||||
"""Capture the CUDA graphs this state runs inside the model's forward."""
|
||||
return None
|
||||
|
||||
def get_additional_cg_support(self) -> tuple[AttentionCGSupport, str | None]:
|
||||
"""Cudagraph support of attention groups this ModelState builds outside
|
||||
``init_attn_backend`` (e.g. encoder-only layers).
|
||||
|
||||
@@ -21,6 +21,7 @@ from vllm.v1.core.sched.output import NewRequestData
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig, MambaSpec
|
||||
from vllm.v1.utils import CpuGpuBuffer
|
||||
from vllm.v1.worker.gpu.attn_utils import build_attn_metadata
|
||||
from vllm.v1.worker.gpu.block_table import BlockTables
|
||||
from vllm.v1.worker.gpu.input_batch import InputBatch
|
||||
from vllm.v1.worker.gpu.mm.encoder_cache import EncoderCache
|
||||
from vllm.v1.worker.gpu.model_states.default import DefaultModelState
|
||||
@@ -114,8 +115,13 @@ class MambaHybridModelState(DefaultModelState):
|
||||
self.num_accepted_tokens_gpu[req_index].fill_(1)
|
||||
if self._align_mode:
|
||||
# Seed the running state block from the resumed/prefilled position.
|
||||
# The column is in mamba blocks. cache_config.block_size is the
|
||||
# min over prefix-cacheable groups, so a drafter group with its own
|
||||
# smaller block (e.g. DFlash) pulls it below mamba_block_size.
|
||||
mamba_block_size = self.cache_config.mamba_block_size
|
||||
assert mamba_block_size is not None
|
||||
self._mamba_state_idx_gpu[req_index].fill_(
|
||||
(new_req_data.num_computed_tokens - 1) // self.cache_config.block_size
|
||||
(new_req_data.num_computed_tokens - 1) // mamba_block_size
|
||||
)
|
||||
|
||||
def _get_mamba_group_info(
|
||||
@@ -134,47 +140,42 @@ class MambaHybridModelState(DefaultModelState):
|
||||
self._mamba_spec = mamba_spec
|
||||
return self._mamba_group_ids, self._mamba_spec
|
||||
|
||||
def _ensure_align_ctx(
|
||||
self,
|
||||
kv_cache_config: KVCacheConfig,
|
||||
mamba_group_ids: list[int],
|
||||
block_tables: tuple[torch.Tensor, ...],
|
||||
) -> MambaSpecDecodeGPUContext:
|
||||
def initialize_kv_cache(
|
||||
self, kv_cache_config: KVCacheConfig, block_tables: BlockTables
|
||||
) -> None:
|
||||
if not self._align_mode:
|
||||
return
|
||||
mamba_group_ids, _ = self._get_mamba_group_info(kv_cache_config)
|
||||
if self._mamba_state_copy_funcs is None:
|
||||
mamba_groups = get_mamba_groups(kv_cache_config)
|
||||
mamba_types = {spec.mamba_type for spec in mamba_groups}
|
||||
copy_funcs = self.model.get_mamba_state_copy_funcs(mamba_types)
|
||||
validate_mamba_state_copy_funcs(mamba_groups, copy_funcs)
|
||||
self._mamba_state_copy_funcs = copy_funcs
|
||||
copy_funcs = self._mamba_state_copy_funcs
|
||||
if self._mamba_ctx is None:
|
||||
# Both SD and DS conv layouts support a >0 spec-decode shift: the
|
||||
# fused pre-copy kernel (``_copy_mamba_state_block``) applies the
|
||||
# ``token_bias = num_accepted - 1`` window shift per conv layout
|
||||
# (SD: contiguous slice; DS: per-dim-row strided slice), matching
|
||||
# the V1 ``get_conv_copy_spec`` semantics.
|
||||
self._mamba_ctx = MambaSpecDecodeGPUContext.create(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
kv_cache_config=kv_cache_config,
|
||||
copy_funcs=copy_funcs,
|
||||
device=self.device,
|
||||
make_buffer=lambda n, dtype: CpuGpuBuffer(
|
||||
n, dtype=dtype, device=self.device
|
||||
),
|
||||
)
|
||||
ctx = self._mamba_ctx
|
||||
if not ctx.is_initialized:
|
||||
forward_context = self.vllm_config.compilation_config.static_forward_context
|
||||
# block_tables are batch-order slices of the persistent
|
||||
# input_block_tables (stable data_ptr), so the metadata is captured
|
||||
# once here and reused across steps.
|
||||
ctx.initialize_from_forward_context(
|
||||
kv_cache_config,
|
||||
forward_context,
|
||||
copy_funcs,
|
||||
[block_tables[gid] for gid in mamba_group_ids],
|
||||
)
|
||||
return ctx
|
||||
# Both SD and DS conv layouts support a >0 spec-decode shift: the
|
||||
# fused pre-copy kernel (``_copy_mamba_state_block``) applies the
|
||||
# ``token_bias = num_accepted - 1`` window shift per conv layout
|
||||
# (SD: contiguous slice; DS: per-dim-row strided slice), matching
|
||||
# the V1 ``get_conv_copy_spec`` semantics.
|
||||
self._mamba_ctx = MambaSpecDecodeGPUContext.create(
|
||||
max_num_reqs=self.max_num_reqs,
|
||||
kv_cache_config=kv_cache_config,
|
||||
copy_funcs=self._mamba_state_copy_funcs,
|
||||
device=self.device,
|
||||
make_buffer=lambda n, dtype: CpuGpuBuffer(
|
||||
n, dtype=dtype, device=self.device
|
||||
),
|
||||
)
|
||||
# Under PP a step's postprocess runs after later steps re-gathered the
|
||||
# batch-ordered input tables, so state copies read the per-request-slot
|
||||
# tables. Aligned state indices are for the current batch only.
|
||||
self._mamba_ctx.initialize_from_forward_context(
|
||||
kv_cache_config,
|
||||
self.vllm_config.compilation_config.static_forward_context,
|
||||
self._mamba_state_copy_funcs,
|
||||
[block_tables.block_tables[gid].gpu for gid in mamba_group_ids],
|
||||
[block_tables.input_block_tables[gid] for gid in mamba_group_ids],
|
||||
)
|
||||
|
||||
def preprocess_state(
|
||||
self,
|
||||
@@ -194,8 +195,9 @@ class MambaHybridModelState(DefaultModelState):
|
||||
num_reqs = input_batch.num_reqs
|
||||
if num_reqs == 0:
|
||||
return
|
||||
mamba_group_ids, mamba_spec = self._get_mamba_group_info(kv_cache_config)
|
||||
ctx = self._ensure_align_ctx(kv_cache_config, mamba_group_ids, block_tables)
|
||||
_, mamba_spec = self._get_mamba_group_info(kv_cache_config)
|
||||
ctx = self._mamba_ctx
|
||||
assert ctx is not None
|
||||
|
||||
# The state-advance + pre-copy kernels run every step; they fast-exit per
|
||||
# request when src_col < 0 or src_col == dst_col, so no copy happens on
|
||||
@@ -277,18 +279,19 @@ class MambaHybridModelState(DefaultModelState):
|
||||
]
|
||||
|
||||
# GDN uses >= 0 to select spec-decode rows, so non-decode rows
|
||||
# need the -1 sentinel rather than a raw zero draft count.
|
||||
# need the -1 sentinel. Decode rows without drafts stay spec rows:
|
||||
# only that path applies the previous step's accepted offset.
|
||||
num_decode_draft_tokens_np = np.full(num_reqs, -1, dtype=np.int32)
|
||||
num_draft_tokens_per_req = input_batch.num_draft_tokens_per_req
|
||||
if num_draft_tokens_per_req is not None:
|
||||
# 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.
|
||||
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
|
||||
)
|
||||
if num_draft_tokens_per_req is None:
|
||||
num_draft_tokens_per_req = np.zeros(input_batch.num_reqs, np.int32)
|
||||
# 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.
|
||||
is_decode = ~is_prefilling_np & (input_batch.num_scheduled_tokens > 0)
|
||||
num_decode_draft_tokens_np[: input_batch.num_reqs] = np.where(
|
||||
is_decode, num_draft_tokens_per_req, -1
|
||||
)
|
||||
num_decode_draft_tokens_cpu = torch.from_numpy(num_decode_draft_tokens_np)
|
||||
|
||||
if self._align_mode:
|
||||
@@ -300,10 +303,8 @@ class MambaHybridModelState(DefaultModelState):
|
||||
if hasattr(builder, "mamba_aligned_state_indices"):
|
||||
aligned_index_builders.append((group_idx, builder))
|
||||
if aligned_index_builders:
|
||||
ctx = self._ensure_align_ctx(
|
||||
kv_cache_config, mamba_group_ids, block_tables
|
||||
)
|
||||
all_group_indices = ctx.compute_aligned_state_indices(
|
||||
assert self._mamba_ctx is not None
|
||||
all_group_indices = self._mamba_ctx.compute_aligned_state_indices(
|
||||
input_batch.seq_lens, num_reqs
|
||||
)
|
||||
for group_idx, builder in aligned_index_builders:
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
def init_speculator(vllm_config: VllmConfig, device: torch.device):
|
||||
|
||||
def init_speculator(
|
||||
vllm_config: VllmConfig,
|
||||
device: torch.device,
|
||||
req_states: "RequestState",
|
||||
):
|
||||
"""Build the speculator for this config."""
|
||||
speculative_config = vllm_config.speculative_config
|
||||
assert speculative_config is not None
|
||||
if speculative_config.method == "extract_hidden_states":
|
||||
@@ -61,10 +71,16 @@ 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,
|
||||
from vllm.v1.worker.gpu.spec_decode.standalone_ar.speculator import (
|
||||
StandaloneARSpeculator,
|
||||
)
|
||||
|
||||
return PlainDraftModelSpeculator(vllm_config, device)
|
||||
return StandaloneARSpeculator(vllm_config, device)
|
||||
elif speculative_config.use_ngram():
|
||||
from vllm.v1.worker.gpu.spec_decode.ngram.speculator import (
|
||||
NgramGPUSpeculator,
|
||||
)
|
||||
|
||||
return NgramGPUSpeculator(vllm_config, device, req_states)
|
||||
else:
|
||||
raise NotImplementedError(f"{speculative_config.method} is not supported yet.")
|
||||
|
||||
@@ -360,6 +360,7 @@ class DFlashSpeculator(DraftModelSpeculator):
|
||||
skip_attn_for_dummy_run: bool = False,
|
||||
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
|
||||
is_profile: bool = False,
|
||||
num_speculative_tokens: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
num_reqs = input_batch.num_reqs
|
||||
num_target_tokens = input_batch.num_tokens
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
|
||||
AutoRegressiveSpeculator,
|
||||
)
|
||||
from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model
|
||||
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
|
||||
TargetDependentARSpeculator,
|
||||
)
|
||||
|
||||
|
||||
class EagleSpeculator(AutoRegressiveSpeculator):
|
||||
class EagleSpeculator(TargetDependentARSpeculator):
|
||||
def load_draft_model(
|
||||
self,
|
||||
target_model: nn.Module,
|
||||
|
||||
@@ -103,6 +103,7 @@ class ExtractHiddenStatesSpeculator(DraftModelSpeculator):
|
||||
skip_attn_for_dummy_run: bool = False,
|
||||
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
|
||||
is_profile: bool = False,
|
||||
num_speculative_tokens: int | None = None,
|
||||
) -> torch.Tensor:
|
||||
del (
|
||||
last_hidden_states,
|
||||
|
||||
@@ -17,8 +17,8 @@ from vllm.distributed.parallel_state import get_pp_group
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.model_loader import get_model
|
||||
from vllm.model_executor.model_loader.utils import get_draft_load_config
|
||||
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
|
||||
AutoRegressiveSpeculator,
|
||||
from vllm.v1.worker.gpu.spec_decode.target_dependent_ar.speculator import (
|
||||
TargetDependentARSpeculator,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -45,7 +45,7 @@ def _copy_target_kv_scales(attn: nn.Module, target_attn: nn.Module) -> None:
|
||||
getattr(attn, scale_name).copy_(getattr(target_attn, scale_name))
|
||||
|
||||
|
||||
class Gemma4Speculator(AutoRegressiveSpeculator):
|
||||
class Gemma4Speculator(TargetDependentARSpeculator):
|
||||
@property
|
||||
def advance_draft_positions(self) -> bool:
|
||||
# Gemma4 MTP is Q-only and reads K/V from the target's existing cache.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user