Merge remote-tracking branch 'origin/main' into sync/lesj/qwen4exp-bugfixes

Signed-off-by: lesj0610 <lesj0610@users.noreply.github.com>
This commit is contained in:
lesj0610
2026-09-16 20:33:18 +09:00
117 changed files with 6209 additions and 995 deletions
+8 -2
View File
@@ -1482,8 +1482,14 @@ def cutlass_w4a8_moe_mm(
Cumulative token offsets
problem_sizes:
Per-expert (M, N, K) GEMM sizes used by the grouped GEMM launcher.
a/b/c/group_scale_strides:
Strides describing the memory layout of the input tensors.
a_strides:
Strides describing the memory layout of a_tensors.
b_strides:
Strides describing the memory layout of b_tensors.
c_strides:
Strides describing the memory layout of out_tensors.
group_scale_strides:
Strides describing the memory layout of b_group_scales.
maybe_schedule:
Optional override to choose a specific kernel or epilogue schedule.
+3
View File
@@ -211,6 +211,8 @@ class CacheConfig:
"""The number of blocks to allocate for CPU memory."""
# Set after KV cache initialization.
effective_attention_block_size: int | None = field(default=None, init=False)
"""Full-attention block size in tokens, including DCP, or None if unavailable."""
kv_cache_size_tokens: int | None = field(default=None, init=False)
"""Per-DP-engine KV cache capacity in tokens (group-aware). Uses
group-aware capacity since num_gpu_blocks * block_size can be wrong
@@ -277,6 +279,7 @@ class CacheConfig:
# Post-init/derived counters
"num_gpu_blocks",
"num_cpu_blocks",
"effective_attention_block_size",
"kv_cache_size_tokens",
"kv_cache_max_concurrency",
# WIP feature toggle not impacting compiled graph shape
@@ -34,6 +34,7 @@ import vllm.envs as envs
from vllm.distributed.utils import StatelessProcessGroup, sched_yield
from vllm.logger import init_logger
from vllm.platforms import current_platform
from vllm.utils.cpu_resource_utils import check_cgroup_memory_available
from vllm.utils.network_utils import (
get_ip,
get_open_zmq_inproc_path,
@@ -224,26 +225,37 @@ class SpinCondition:
SHM_PATH = "/dev/shm"
def check_shm_free_space(required_bytes: int, shm_path: str = SHM_PATH) -> None:
"""Raise if ``shm_path`` cannot fit a ``required_bytes`` shared segment.
def check_shm_free_space(
required_bytes: int,
shm_path: str = SHM_PATH,
*,
allocation_name: str = "shared-memory allocation",
) -> None:
"""Raise if SHM cannot fit a shared segment and log cgroup headroom.
Args:
required_bytes: Size of the shared-memory segment to be created.
shm_path: Mount point backing POSIX shared memory; skipped if absent.
shm_path: Mount point backing POSIX shared memory; its filesystem
check is skipped if absent.
allocation_name: Human-readable name used in errors and logs.
Raises:
RuntimeError: If ``required_bytes`` exceeds the free space.
RuntimeError: If the SHM filesystem has insufficient space.
"""
if not os.path.isdir(shm_path):
return
free_bytes = shutil.disk_usage(shm_path).free
if required_bytes <= free_bytes:
return
mib = 1 << 20
raise RuntimeError(
f"Insufficient space in {shm_path}: {required_bytes / mib:.0f} MiB "
f"required, {free_bytes / mib:.0f} MiB free. Increase {shm_path} "
"(e.g. --shm-size or --ipc=host)."
if os.path.isdir(shm_path):
free_bytes = shutil.disk_usage(shm_path).free
if required_bytes > free_bytes:
mib = 1 << 20
raise RuntimeError(
f"Insufficient space in {shm_path} for {allocation_name}: "
f"{required_bytes / mib:.0f} MiB required, "
f"{free_bytes / mib:.0f} MiB free. Increase {shm_path} "
"(e.g. --shm-size or --ipc=host)."
)
check_cgroup_memory_available(
required_bytes,
allocation_name,
)
@@ -2,7 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import time
from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from dataclasses import dataclass, field, replace
from itertools import chain, islice
from typing import Any, NamedTuple
@@ -114,7 +114,10 @@ class GroupOffloadConfig(NamedTuple):
window = max(
window,
cdiv(
self.kv_cache_spec.sliding_window - 1 + right_padding,
self.kv_cache_spec.sliding_window
- 1
+ self.kv_cache_spec.extra_retained_tokens
+ right_padding,
self.tokens_per_chunk,
),
)
@@ -126,7 +129,13 @@ def get_sliding_window_size_in_chunks(
) -> int | None:
if isinstance(kv_cache_spec, SlidingWindowSpec):
assert kv_cache_spec.sliding_window > 0
return cdiv(kv_cache_spec.sliding_window, tokens_per_chunk)
return max(
cdiv(kv_cache_spec.sliding_window, tokens_per_chunk),
cdiv(
kv_cache_spec.sliding_window - 1 + kv_cache_spec.extra_retained_tokens,
tokens_per_chunk,
),
)
if isinstance(kv_cache_spec, ChunkedLocalAttentionSpec):
# Attention never reaches back past one chunk
@@ -418,8 +427,11 @@ class RequestOffloadState:
None,
group_config.hashes_per_chunk,
):
group_state.offload_keys.append(
make_offload_key(req_block_hash, group_config.group_idx)
key = make_offload_key(req_block_hash, group_config.group_idx)
group_state.offload_keys.append(key)
self.req_context.set_offload_key_position(
key,
len(group_state.offload_keys) * group_config.tokens_per_chunk,
)
def update_block_id_groups(
@@ -733,37 +745,6 @@ class OffloadingConnectorScheduler:
)
return None if defer_lookup or pending_in_window else consecutive_hits
def _touch(self, req_status: RequestOffloadState):
for group_config, group_state in zip(
self.config.kv_group_configs, req_status.group_states
):
if group_config.sliding_window_size_in_chunks is None:
self.manager.touch(group_state.offload_keys, req_status.req_context)
else:
# Keep only chunks needed to hit the original request, plus
# decoded chunks.
chunks_to_skip = max(
0,
group_state.num_hit_chunks
- group_config.sliding_window_size_in_chunks,
)
self.manager.touch(
group_state.offload_keys[chunks_to_skip:],
req_status.req_context,
)
if req_status.partial_tail_boundary is not None:
self.manager.touch(
tuple(
self._make_boundary_key(
req_status.req,
group.group_idx,
req_status.partial_tail_boundary,
)
for group in self.config.kv_group_configs
),
req_status.req_context,
)
def _lookup_complete_chunks(
self,
req_status: RequestOffloadState,
@@ -968,10 +949,16 @@ class OffloadingConnectorScheduler:
return num_hit_tokens
def _make_boundary_key(
self, request: Request, group_idx: int, boundary_tokens: int
self,
request: Request,
group_idx: int,
boundary_tokens: int,
req_context: ReqContext,
) -> OffloadKey:
hash_idx = boundary_tokens // self.config.tokens_per_hash - 1
return make_offload_key(request.block_hashes[hash_idx], group_idx)
key = make_offload_key(request.block_hashes[hash_idx], group_idx)
req_context.set_offload_key_position(key, boundary_tokens)
return key
def _lookup(
self,
@@ -1006,7 +993,10 @@ class OffloadingConnectorScheduler:
boundary_keys = []
for group_config in self.config.kv_group_configs:
key = self._make_boundary_key(
req_status.req, group_config.group_idx, boundary
req_status.req,
group_config.group_idx,
boundary,
req_status.req_context,
)
boundary_keys.append(key)
result = self.manager.lookup(key, req_status.req_context)
@@ -1099,8 +1089,6 @@ class OffloadingConnectorScheduler:
self._maybe_observe_lookup_async_delay(req_status)
req_status.update_num_hit_chunks(num_computed_tokens + (num_hit_tokens or 0))
self._touch(req_status)
return num_hit_tokens, bool(num_hit_tokens)
def update_state_after_alloc(
@@ -1174,7 +1162,10 @@ class OffloadingConnectorScheduler:
if partial_tail_boundary is not None:
keys_to_load.append(
self._make_boundary_key(
request, group_config.group_idx, partial_tail_boundary
request,
group_config.group_idx,
partial_tail_boundary,
req_status.req_context,
)
)
@@ -1298,7 +1289,9 @@ class OffloadingConnectorScheduler:
):
continue
key = self._make_boundary_key(req, group_idx, boundary)
key = self._make_boundary_key(
req, group_idx, boundary, req_status.req_context
)
store_output = self.manager.prepare_store([key], req_status.req_context)
if store_output is None:
self._connector_stats.increase_counter(
@@ -1393,7 +1386,9 @@ class OffloadingConnectorScheduler:
):
continue
keys = [
self._make_boundary_key(req, group.group_idx, boundary)
self._make_boundary_key(
req, group.group_idx, boundary, req_status.req_context
)
for group in self.config.kv_group_configs
]
block_ids = [
@@ -1461,11 +1456,24 @@ class OffloadingConnectorScheduler:
) -> list[bool] | None:
"""Build the block mask for a range of candidate offload chunks."""
blocks_per_chunk = self.config.blocks_per_chunk
kv_cache_spec = group_config.kv_cache_spec
if isinstance(kv_cache_spec, SlidingWindowSpec) and (
kv_cache_spec.extra_retained_tokens
):
# Offload restores all allocated history, including MTP re-prefill
# tokens. Widen only the store mask, not the model's attention window.
kv_cache_spec = replace(
kv_cache_spec,
sliding_window=(
kv_cache_spec.sliding_window + kv_cache_spec.extra_retained_tokens
),
extra_retained_tokens=0,
)
return group_config.manager_cls.reachable_block_mask(
start_block=start_chunk_idx * blocks_per_chunk,
end_block=end_chunk_idx * blocks_per_chunk,
alignment_tokens=self.config.alignment_tokens,
kv_cache_spec=group_config.kv_cache_spec,
kv_cache_spec=kv_cache_spec,
use_eagle=group_config.is_eagle_group,
retention_interval=self.config.retention_interval,
reachable_boundaries=reachable_boundaries,
@@ -1667,8 +1675,6 @@ class OffloadingConnectorScheduler:
req_status.advance_stored_idx(num_offloadable_tokens)
continue
self._touch(req_status)
keys_to_store = set(store_output.keys_to_store)
group_sizes: list[int] = []
+1 -1
View File
@@ -2051,7 +2051,7 @@ class EngineArgs:
device_config = DeviceConfig(device=cast(Device, current_platform.device_type))
envs.validate_environ(self.fail_on_environ_validation)
current_platform.validate_environ(self.fail_on_environ_validation)
# Check if the model is a speculator and override model/tokenizer/config
# BEFORE creating ModelConfig, so the config is created with the target model
+19 -5
View File
@@ -46,21 +46,35 @@ def _interactive_cli(args: argparse.Namespace) -> tuple[str, OpenAI]:
def _print_chat_stream(stream, stats: bool = False) -> str:
output = ""
start = time.perf_counter()
output: str = ""
in_reasoning: bool = False
start: float = time.perf_counter()
ttft: float | None = None
completion_tokens = 0
completion_tokens: int = 0
for chunk in stream:
if chunk.usage is not None:
completion_tokens = chunk.usage.completion_tokens
if not chunk.choices:
continue
delta = chunk.choices[0].delta
reasoning = getattr(delta, "reasoning", None) or getattr(
delta, "reasoning_content", None
)
if ttft is None and (reasoning or delta.content):
ttft = time.perf_counter() - start
if reasoning:
if not in_reasoning:
print("<think>", flush=True)
in_reasoning = True
print(reasoning, end="", flush=True)
if delta.content:
if ttft is None:
ttft = time.perf_counter() - start
if in_reasoning:
print("\n</think>", flush=True)
in_reasoning = False
output += delta.content
print(delta.content, end="", flush=True)
if in_reasoning:
print("\n</think>", end="", flush=True)
print()
if stats:
_print_metrics(start, ttft, completion_tokens)
+7 -1
View File
@@ -565,6 +565,7 @@ class ParsableContext(ConversationContext):
mcp_tools: dict[str, Mcp],
):
if tool_server:
initialized_session = False
for tool_name in self.available_tools:
if tool_name in self._tool_sessions:
continue
@@ -577,6 +578,8 @@ class ParsableContext(ConversationContext):
tool_server.new_session(tool_name, request_id, headers)
)
self._tool_sessions[tool_name] = tool_session
initialized_session = True
if initialized_session:
exit_stack.push_async_exit(self.cleanup_session)
async def cleanup_session(self, *args, **kwargs) -> None:
@@ -863,6 +866,7 @@ class HarmonyContext(ConversationContext):
mcp_tools: dict[str, Mcp],
):
if tool_server:
initialized_session = False
for tool_name in self.available_tools:
if tool_name not in self._tool_sessions:
tool_type = _map_tool_name_to_tool_type(tool_name)
@@ -873,7 +877,9 @@ class HarmonyContext(ConversationContext):
tool_server.new_session(tool_name, request_id, headers)
)
self._tool_sessions[tool_name] = tool_session
exit_stack.push_async_exit(self.cleanup_session)
initialized_session = True
if initialized_session:
exit_stack.push_async_exit(self.cleanup_session)
async def call_container_tool(
self, tool_session: Union["ClientSession", Tool], last_msg: Message
+28 -2
View File
@@ -1,8 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import logging
import model_hosting_container_standards.sagemaker as sagemaker_standards
from fastapi import APIRouter, Depends, FastAPI, Request
from fastapi.responses import JSONResponse, Response
@@ -22,6 +21,12 @@ router = APIRouter()
def attach_router(app: FastAPI):
"""Attach the LoRA adapter load/unload endpoints to the API server.
Does nothing when dynamic LoRA updating is disabled. Handler levels are
snapshotted and restored because importing
model_hosting_container_standards may reconfigure root logging.
"""
if not envs.VLLM_ALLOW_RUNTIME_LORA_UPDATING:
"""If LoRA dynamic loading & unloading is not enabled, do nothing."""
return
@@ -30,6 +35,23 @@ def attach_router(app: FastAPI):
"This should ONLY be used for local development!"
)
snapshot = [
(h, h.level)
for lg in (logging.getLogger(), logging.getLogger("vllm"))
for h in lg.handlers
]
try:
_attach_router(app)
finally:
for handler, level in snapshot:
handler.setLevel(level)
def _attach_router(app: FastAPI):
"""Register the LoRA adapter load/unload routes on the app."""
import model_hosting_container_standards.sagemaker as sagemaker_standards
@sagemaker_standards.register_load_adapter_handler(
request_shape={
"lora_name": "body.name",
@@ -40,6 +62,8 @@ def attach_router(app: FastAPI):
)
@router.post("/v1/load_lora_adapter", dependencies=[Depends(validate_json_request)])
async def load_lora_adapter(request: LoadLoRAAdapterRequest, raw_request: Request):
"""Handle POST /v1/load_lora_adapter: load a LoRA adapter into the
serving engine."""
handler: OpenAIServingModels = models(raw_request)
response = await handler.load_lora_adapter(request)
if isinstance(response, ErrorResponse):
@@ -60,6 +84,8 @@ def attach_router(app: FastAPI):
async def unload_lora_adapter(
request: UnloadLoRAAdapterRequest, raw_request: Request
):
"""Handle POST /v1/unload_lora_adapter: unload a LoRA adapter from
the serving engine."""
handler: OpenAIServingModels = models(raw_request)
response = await handler.unload_lora_adapter(request)
if isinstance(response, ErrorResponse):
+59 -2
View File
@@ -1,11 +1,11 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import logging
from collections.abc import Awaitable, Callable
from http import HTTPStatus
from typing import Any
import model_hosting_container_standards.sagemaker as sagemaker_standards
import pydantic
from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, Response
@@ -27,11 +27,55 @@ GetHandlerFn = Callable[[Request], BaseServing | None]
EndpointFn = Callable[[RequestType, Request], Awaitable[Any]]
def _snapshot_handler_levels() -> list[tuple[logging.Handler, int]]:
"""Snapshot handler levels for loggers that may be affected by third-party
logging configuration side effects (e.g. model_hosting_container_standards
calling configure_root_logger() at import time)."""
loggers = [logging.getLogger(), logging.getLogger("vllm")]
seen: set[int] = set()
snapshot: list[tuple[logging.Handler, int]] = []
for logger in loggers:
for handler in logger.handlers:
if id(handler) not in seen:
seen.add(id(handler))
snapshot.append((handler, handler.level))
return snapshot
def _restore_handler_levels(
snapshot: list[tuple[logging.Handler, int]],
) -> None:
"""Restore handler levels from a snapshot."""
for handler, level in snapshot:
handler.setLevel(level)
def attach_router(
app: FastAPI,
supported_tasks: tuple["SupportedTask", ...],
model_config: ModelConfig | None = None,
):
"""Attach the SageMaker hosting endpoints to the API server.
Handler levels are snapshotted and restored because importing
model_hosting_container_standards may reconfigure root logging.
"""
snapshot = _snapshot_handler_levels()
try:
_attach_router(app, supported_tasks, model_config)
finally:
_restore_handler_levels(snapshot)
def _attach_router(
app: FastAPI,
supported_tasks: tuple["SupportedTask", ...],
model_config: ModelConfig | None = None,
):
"""Register the SageMaker hosting routes (/ping, /invocations) on the
app."""
import model_hosting_container_standards.sagemaker as sagemaker_standards
router = APIRouter()
# NOTE: Construct the TypeAdapters only once
@@ -99,4 +143,17 @@ def attach_router(
def sagemaker_standards_bootstrap(app: FastAPI) -> FastAPI:
return sagemaker_standards.bootstrap(app)
"""Bootstrap the app with the SageMaker hosting standards.
Handler levels are restored right after the import because importing
model_hosting_container_standards may reconfigure root logging, and
bootstrap must run with the original levels.
"""
snapshot = _snapshot_handler_levels()
try:
import model_hosting_container_standards.sagemaker as sagemaker_standards
app = sagemaker_standards.bootstrap(app)
finally:
_restore_handler_levels(snapshot)
return app
-9
View File
@@ -2249,15 +2249,6 @@ def is_set(name: str):
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def validate_environ(hard_fail: bool) -> None:
for env in os.environ:
if env.startswith("VLLM_") and env not in environment_variables:
if hard_fail:
raise ValueError(f"Unknown vLLM environment variable detected: {env}")
else:
logger.warning("Unknown vLLM environment variable detected: %s", env)
def compile_factors() -> dict[str, object]:
"""Return env vars used for torch.compile cache keys.
+30 -2
View File
@@ -34,13 +34,38 @@ direct_register_aiter_op = functools.partial(
AITER_SUPPORTED = is_aiter_found()
"""Most kernels in this file are supported if AITER is installed."""
def flatten_to_2d_is_free(x: Tensor) -> bool:
"""Whether ``x.reshape(-1, x.shape[-1])`` is a view with unit-stride rows.
The AITER norm kernels only take dense 2D inputs, so the wrappers below
flatten the leading dims with ``Tensor.reshape``, which silently falls back
to ``contiguous()`` when the flattened shape is not expressible with the
existing strides, adding a whole-tensor device copy that costs more than
the kernel saves. A strided last dim flattens without a copy but not into a
dense buffer, so it is rejected too.
"""
if x.dim() <= 2:
return True
if x.stride(-1) != 1:
return False
expected_stride = x.size(-1)
for i in range(x.dim() - 2, -1, -1):
if x.size(i) != 1 and x.stride(i) != expected_stride:
return False
expected_stride *= x.size(i)
return True
rms_no_var_16bit_only = (
lambda x, weight, epsilon, variance_size=None: variance_size is None
and x.dtype in (torch.float16, torch.bfloat16)
and (weight is None or weight.dtype == x.dtype)
and flatten_to_2d_is_free(x)
)
"""AITER rms_norm only supports float16 and bfloat16 acts, no var_size override,
and requires weight dtype to match x dtype."""
requires weight dtype to match x dtype, and requires flattening the activation
to 2D to be free."""
@ir.ops.rms_norm.register_impl(
@@ -79,10 +104,13 @@ rms_add_no_var_16bit_only = (
lambda x, x_residual, weight, epsilon, variance_size=None: variance_size is None
and x.dtype in (torch.float16, torch.bfloat16)
and (weight is None or weight.dtype == x.dtype)
and flatten_to_2d_is_free(x)
and flatten_to_2d_is_free(x_residual)
)
"""
AITER fused_add_rms_norm only supports 16-bit activations and no var_size override.
Requires weight dtype to match x dtype.
Requires weight dtype to match x dtype, and flattening both the activation and the
residual to 2D to be free.
"""
@@ -190,9 +190,11 @@ def candidate_blocks_to_sparse_indices(
candidate_blocks: [rows, K] int32 request-local candidate block ids
(-1 padded), in units of ``candidate_block_size`` positions. K
must be a power of two (the in-kernel sort); rows may be strided.
row_ks/row_ke: [rows] int32 per-row K range; bounds are in the same
row_ks: [rows] int32 per-row K range start; bounds are in the same
(packed-workspace) coordinates the sparse kernel iterates over.
Pass zeros for the paged path, whose blocks are context-relative.
row_ke: [rows] int32 per-row K range end, in the same coordinates as
``row_ks``.
candidate_block_size: Positions per candidate block.
sparse_block_kv: Positions per sparse block (8 or 16).
out: Optional ``(sparse_indices, end)`` buffers to write into,
@@ -322,12 +324,16 @@ def sparse_mqa_logits_prefill_chunk(
k_scale: [total_kv] int32 packed UE8M0 K scales.
weights: [rows, H] bf16 per-head weights; the sparse kernels take
bf16 and do not fold the Q scale in.
cu_seqlen_ks/cu_seqlen_ke: [rows] int32 per-token K bounds in the
packed workspace.
cu_seqlen_ks: [rows] int32 per-token K start bounds in the packed
workspace.
cu_seqlen_ke: [rows] int32 per-token K end bounds in the packed
workspace.
candidate_blocks: [rows, K] int32 request-local candidate block ids.
topk_indices: [rows, topk_tokens] output buffer.
sparse_indices/end/col_indices: Caller-owned scratch, see
`candidate_blocks_to_sparse_indices` and `sparse_topk_remap`.
sparse_indices: Caller-owned scratch, see
`candidate_blocks_to_sparse_indices`.
end: Caller-owned scratch, see `candidate_blocks_to_sparse_indices`.
col_indices: Caller-owned scratch, see `sparse_topk_remap`.
kernel_metadata: DeepGEMM schedule from a previous call with the same
candidates and bounds (i.e. another indexer layer in the same
step). When given, the candidate expansion is skipped and
@@ -413,7 +419,9 @@ def sparse_mqa_logits_paged_decode(
candidate_blocks: [rows, K] int32 candidate block ids.
topk_indices: [rows, topk_tokens] output buffer.
row_ks: [rows] int32 zeros (paged blocks are context-relative).
sparse_indices/end/col_indices: Caller-owned scratch.
sparse_indices: Caller-owned scratch.
end: Caller-owned scratch.
col_indices: Caller-owned scratch.
kernel_metadata: See `sparse_mqa_logits_prefill_chunk`.
Returns:
@@ -187,6 +187,7 @@ from vllm.model_executor.kernels.linear.scaled_mm.b12x import (
)
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8BlockScaledMMKernel,
CPUFp8PerTensorScaledMMLinearKernel,
CPUInt8ScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.cutlass import (
@@ -438,6 +439,7 @@ _POSSIBLE_FP8_KERNELS: dict[PlatformEnum, list[type[FP8ScaledMMLinearKernel]]] =
ChannelWiseTorchFP8ScaledMMLinearKernel,
],
PlatformEnum.CPU: [
CPUFp8PerTensorScaledMMLinearKernel,
PerTensorTorchFP8ScaledMMLinearKernel,
ChannelWiseTorchFP8ScaledMMLinearKernel,
],
@@ -9,6 +9,7 @@ from vllm.model_executor.kernels.linear.scaled_mm.BlockScaledMMLinearKernel impo
)
from vllm.model_executor.kernels.linear.scaled_mm.cpu import (
CPUFp8BlockScaledMMKernel,
CPUFp8PerTensorScaledMMLinearKernel,
CPUInt8ScaledMMLinearKernel,
)
from vllm.model_executor.kernels.linear.scaled_mm.cutlass import (
@@ -67,5 +68,6 @@ __all__ = [
"ZentorchInt8ScaledMMLinearKernel",
"Fp8BlockScaledMMLinearKernel",
"CPUFp8BlockScaledMMKernel",
"CPUFp8PerTensorScaledMMLinearKernel",
"XPUFp8BlockScaledMMKernel",
]
@@ -21,10 +21,14 @@ from .BlockScaledMMLinearKernel import (
FP8ScaledMMLinearLayerConfig,
)
from .ScaledMMLinearKernel import (
FP8ScaledMMLinearKernel,
Int8ScaledMMLinearKernel,
Int8ScaledMMLinearLayerConfig,
)
# BLOCK_K in csrc/cpu/sgl-kernels/gemm.h — the AMX kernel's fixed K-block size.
_BLOCK_SIZE_K = 128
class CPUInt8ScaledMMLinearKernel(Int8ScaledMMLinearKernel):
@classmethod
@@ -330,3 +334,99 @@ class CPUFp8BlockScaledMMKernel(Fp8BlockScaledMMLinearKernel):
raise NotImplementedError(
"CPUFp8BlockScaledMMKernel overrides apply_weights directly."
)
class CPUFp8PerTensorScaledMMLinearKernel(FP8ScaledMMLinearKernel):
"""FP8 W8A16 per-tensor-scaled GEMM via AMX BRGEMM on CPU.
Reuses the block-scaled AMX kernel (fp8_scaled_mm_cpu) with a single
synthetic block spanning the whole weight, so activations stay BF16/FP32
— no FP8 activation quantization, unlike PerTensorTorchFP8ScaledMMLinearKernel.
"""
@classmethod
def is_supported(
cls, compute_capability: int | None = None
) -> tuple[bool, str | None]:
if not current_platform.is_cpu():
return False, "requires CPU platform."
if not torch.cpu._is_amx_tile_supported():
return False, "requires AMX tile support (Sapphire Rapids or newer)."
if not ops._supports_cpu_fp8_w8a16:
return False, "fp8_scaled_mm_cpu op not available."
return True, None
@classmethod
def can_implement(cls, c: FP8ScaledMMLinearLayerConfig) -> tuple[bool, str | None]:
if not c.weight_quant_key.scale.group_shape.is_per_tensor():
return False, "requires a per-tensor weight scale."
if not c.activation_quant_key.scale.group_shape.is_per_tensor():
return False, "requires a per-tensor activation scale."
if c.out_dtype not in (torch.bfloat16, torch.float32):
return False, "Only bfloat16/float32 output dtype supported."
n = c.weight_shape[0]
if n % 32 != 0:
# The AMX tinygemm kernel tiles N in chunks of 32 and cannot
# handle a remainder tile smaller than that.
return False, f"requires weight output dim (N={n}) to be a multiple of 32."
return True, None
def process_weights_after_loading(self, layer: torch.nn.Module) -> None:
w_name, w_s_name, _, _ = self.layer_param_names
# Fp8LinearMethod transposes weight to (K, N) for torch._scaled_mm-style
# kernels; convert_weight_packed/fp8_scaled_mm_cpu expect (N, K), as
# produced by CUDA nn.Linear-style checkpoints.
weight = getattr(layer, w_name).t().contiguous()
n, k = weight.shape
packed_weight = torch.ops._C.convert_weight_packed(weight)
replace_parameter(
layer, w_name, torch.nn.Parameter(packed_weight, requires_grad=False)
)
# Synthesize a single-block "block scale" tensor from the scalar
# per-tensor weight scale so fp8_scaled_mm_cpu can be reused as-is.
weight_scale = getattr(layer, w_s_name)
self._block_size_n = -(-n // 32) * 32 # round up to a multiple of 32
num_k_blocks = -(-k // _BLOCK_SIZE_K)
block_scale = weight_scale.reshape(()).expand(1, num_k_blocks).contiguous()
replace_parameter(
layer, w_s_name, torch.nn.Parameter(block_scale, requires_grad=False)
)
def apply_weights(
self,
layer: torch.nn.Module,
x: torch.Tensor,
bias: torch.Tensor | None = None,
) -> torch.Tensor:
w_name, w_s_name, _, _ = self.layer_param_names
weight = getattr(layer, w_name)
weight_scale = getattr(layer, w_s_name)
x_2d = x.reshape(-1, x.shape[-1]) if x.dim() > 2 else x
out = torch.ops._C.fp8_scaled_mm_cpu(
x_2d,
weight,
weight_scale,
[self._block_size_n, _BLOCK_SIZE_K],
bias,
x.dtype,
True, # is_vnni (weight already prepacked)
)
return out.reshape(x.shape[:-1] + (out.size(-1),)) if x.dim() > 2 else out
def apply_scaled_mm(
self,
*,
A: torch.Tensor,
B: torch.Tensor,
out_dtype: torch.dtype,
As: torch.Tensor,
Bs: torch.Tensor,
bias: torch.Tensor | None,
output_shape: list,
) -> torch.Tensor:
raise NotImplementedError(
"CPUFp8PerTensorScaledMMLinearKernel overrides apply_weights directly."
)
@@ -615,14 +615,15 @@ class RoutedExperts(PluggableLayer):
# compressed-tensors checkpoints with packed weights are stored flipped
# TODO (mgoin): check self.quant_method.quant_config.quant_format
# against known CompressionFormat enum values that have this quality
if quant_method_name in (
"CompressedTensorsWNA16MoEMethod",
"CompressedTensorsW4A16FlydslMoEMethod",
if (
quant_method_name
in (
"CompressedTensorsWNA16MoEMethod",
"CompressedTensorsW4A16FlydslMoEMethod",
)
and is_transposed
):
if is_transposed:
loaded_weight = loaded_weight.t().contiguous()
else:
loaded_weight = loaded_weight
loaded_weight = loaded_weight.t().contiguous()
if shard_id not in ("w1", "w2", "w3"):
raise ValueError(f"shard_id must be ['w1','w2','w3'] but got {shard_id}.")
@@ -727,11 +727,15 @@ def _get_available_ram_bytes() -> int:
host_available = psutil.virtual_memory().available
from vllm.utils.cpu_resource_utils import get_cgroup_memory_limit
from vllm.utils.cpu_resource_utils import (
get_cgroup_memory_limit,
get_cgroup_memory_usage,
)
cgroup_limit, cgroup_usage = get_cgroup_memory_limit()
cgroup_limit = get_cgroup_memory_limit()
if cgroup_limit is None:
return host_available
cgroup_usage = get_cgroup_memory_usage()
cgroup_available = (
cgroup_limit if cgroup_usage is None else max(0, cgroup_limit - cgroup_usage)
)
+1 -3
View File
@@ -780,9 +780,7 @@ class DeepCLIPVisionEmbeddings(CLIPVisionEmbeddings):
self, pixel_values: torch.Tensor, patch_embeds: torch.Tensor | None = None
) -> torch.Tensor:
batch_size = pixel_values.shape[0]
if patch_embeds is not None:
patch_embeds = patch_embeds
else:
if patch_embeds is None:
patch_embeds = self.patch_embedding(pixel_values)
patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
@@ -964,7 +964,6 @@ class MiMoV2OmniMultiModalProcessor(BaseMultiModalProcessor[MiMoV2OmniProcessing
assert isinstance(va_item, (list, tuple)) and len(va_item) == 2
vid, audio_src = va_item
va_item = VideoAudioInput(video=vid, audio=audio_src)
vid = vid
# Convert video frames to (TCHW, timestamps) if needed
if (
isinstance(vid, tuple)
@@ -253,6 +253,7 @@ class Qwen2AudioMultiModalProcessor(BaseMultiModalProcessor[Qwen2AudioProcessing
hf_processor_mm_kwargs = dict(
**hf_processor_mm_kwargs,
sampling_rate=feature_extractor.sampling_rate,
truncation=True,
)
return mm_data, hf_processor_mm_kwargs
-1
View File
@@ -173,7 +173,6 @@ class Step3p5Attention(nn.Module):
rope_scaling = None
if sliding_window is not None and enable_sliding_window:
sliding_window = sliding_window
if swa_num_attention_heads is not None:
num_heads = swa_num_attention_heads
self.total_num_heads = swa_num_attention_heads
+48 -5
View File
@@ -204,6 +204,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
self.top_k = top_k
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.unpadded_intermediate_size = intermediate_size
self.num_shared_experts = num_shared_experts
self.max_num_tokens = vllm_config.scheduler_config.max_num_batched_tokens
@@ -386,6 +387,17 @@ class DeepseekV4MegaMoEExperts(nn.Module):
# the generic linear post-load hook replaces the raw checkpoint scales
# with its 128x128 DeepGEMM layout.
checkpoint_scale_dtypes = (torch.float8_e8m0fnu, torch.uint8)
unpadded_size = self.unpadded_intermediate_size * self.num_shared_experts
padding = self.intermediate_size * self.num_shared_experts - unpadded_size
pad_weights = (
padding > 0
and gate_up_weight.dtype == torch.float8_e4m3fn
and down_weight.dtype == torch.float8_e4m3fn
and gate_up_weight.shape == (2 * unpadded_size, self.hidden_size)
and down_weight.shape == (self.hidden_size, unpadded_size)
and gate_up_scale.dtype in checkpoint_scale_dtypes
and down_scale.dtype in checkpoint_scale_dtypes
)
if (
gate_up_scale.dtype in checkpoint_scale_dtypes
and down_scale.dtype in checkpoint_scale_dtypes
@@ -396,6 +408,7 @@ class DeepseekV4MegaMoEExperts(nn.Module):
gate_up_scale,
gate_up_weight.shape[0],
gate_up_weight.shape[1],
padding=(padding, 0) if pad_weights else (0, 0),
)
down_scale = self._prepare_shared_expert_scale(
deep_gemm,
@@ -403,12 +416,27 @@ class DeepseekV4MegaMoEExperts(nn.Module):
down_scale,
down_weight.shape[0],
down_weight.shape[1],
padding=(0, padding) if pad_weights else (0, 0),
)
if gate_up_scale is None or down_scale is None:
self.num_shared_experts = 0
return
if pad_weights:
# Pad gate/up separately so the SwiGLU split stays at the midpoint.
gate_up_weight = (
torch.nn.functional.pad(
gate_up_weight.view(torch.uint8).unflatten(0, (2, unpadded_size)),
(0, 0, 0, padding),
)
.flatten(0, 1)
.view(gate_up_weight.dtype)
)
down_weight = torch.nn.functional.pad(
down_weight.view(torch.uint8), (0, padding)
).view(down_weight.dtype)
shared_intermediate_size = self.intermediate_size * self.num_shared_experts
expected_gate_up_shape = (
2 * shared_intermediate_size,
@@ -449,11 +477,11 @@ class DeepseekV4MegaMoEExperts(nn.Module):
# released instead of adding roughly 0.7 GiB per rank on DSV4-Flash.
# The generic linear post-load hook may still repack the serial scales,
# but this shared MLP is never called after native fusion is enabled.
gate_up.weight.data = transformed_l1[0]
self._transformed_shared_l1_weights = (
gate_up.weight.data,
transformed_l1[1],
)
# Padded weights need separate storage: the generic linear post-load
# hooks still expect the original checkpoint weight/scale shapes.
if not pad_weights:
gate_up.weight.data = transformed_l1[0]
self._transformed_shared_l1_weights = transformed_l1
self._transformed_shared_l2_weights = transformed_l2
def _prepare_shared_expert_scale(
@@ -463,6 +491,8 @@ class DeepseekV4MegaMoEExperts(nn.Module):
scale: torch.Tensor,
mn: int,
k: int,
*,
padding: tuple[int, int] = (0, 0),
) -> torch.Tensor | None:
block_size = getattr(linear, "weight_block_size", None)
if block_size is None or len(block_size) != 2:
@@ -497,6 +527,19 @@ class DeepseekV4MegaMoEExperts(nn.Module):
.repeat_interleave(block_k // 32, dim=1)[:mn, : k // 32]
.contiguous()
)
pad_m, pad_k = padding
if pad_m:
scale_1x32 = torch.nn.functional.pad(
scale_1x32.unflatten(0, (2, mn // 2)),
(0, 0, 0, pad_m),
value=1.0,
).flatten(0, 1)
mn += 2 * pad_m
if pad_k:
scale_1x32 = torch.nn.functional.pad(
scale_1x32, (0, pad_k // 32), value=1.0
)
k += pad_k
# The grouped API is used with a singleton dimension to request the
# MN-major, TMA-aligned packed-UE8M0 strides, then squeezed back to the
# 2D layout required for a shared expert.
+2 -1
View File
@@ -636,7 +636,8 @@ class DeepseekV41ROCMAiterMLAAttention(DeepseekV4Attention):
transpose_scale=False,
)
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
# ROCm BF16 reference wo_a path (inverse RoPE + einsum) + wo_b.
z = rocm_inv_rope_einsum(
self.rotary_emb,
+150 -54
View File
@@ -44,6 +44,7 @@ from vllm.config import (
VllmConfig,
get_current_vllm_config,
)
from vllm.config.cache import CacheDType
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
@@ -127,34 +128,40 @@ def _use_v41_mxfp8_kv_record() -> bool:
def _resolve_dsv4_kv_cache_dtype(
use_fp8_ds_mla_layout: bool,
kv_cache_dtype: str,
kv_cache_dtype: CacheDType,
cache_config: CacheConfig | None,
) -> tuple[str, torch.dtype]:
packed_kv_cache_dtype: CacheDType = "fp8_ds_mla",
) -> tuple[CacheDType, torch.dtype]:
"""Map ``(layout, --kv-cache-dtype)`` to ``(cache_dtype_str, torch_dtype)``.
Both layouts are paged; they differ in the per-token block format. The
``fp8_ds_mla`` format is UE8M0 block-scaled fp8 packed as ``uint8`` (the
canonical ``fp8_ds_mla`` string is written back onto ``cache_config`` so the
page-size specs pick the 576B per-token slot). Plain-row backends store each
token's KV row in its element dtype: bf16 or per-tensor FP8 E4M3.
packed formats are ``uint8``-backed: ``fp8_ds_mla`` is UE8M0 block-scaled
fp8 throughout, ``nvfp4_ds_mla`` keeps that sliding-window record and
stores the compressed cache as NVFP4. An unspecific ``--kv-cache-dtype``
(``auto`` / ``fp8``) resolves to ``packed_kv_cache_dtype``, the record this
layer's kernel prefers, and the canonical string is written back onto
``cache_config`` so the page-size specs pick the right per-token slot.
Plain-row backends store each token's KV row in its element dtype: bf16 or
per-tensor FP8 E4M3.
"""
if use_fp8_ds_mla_layout:
# fp8_ds_mla block format: UE8M0 block-scaled fp8 packed as uint8.
if kv_cache_dtype == "auto":
kv_cache_dtype = "fp8"
if not kv_cache_dtype.startswith("fp8"):
if kv_cache_dtype in ("auto", "fp8"):
kv_cache_dtype = packed_kv_cache_dtype
elif not kv_cache_dtype.endswith("_ds_mla"):
raise ValueError(
"DeepseekV4 fp8_ds_mla layout only supports fp8 "
f"kv-cache, got {kv_cache_dtype}. Please set "
"`--kv-cache-dtype fp8` or select a backend that supports "
"bfloat16 KV cache."
"DeepseekV4 packed KV layouts only support fp8 kv-cache, got "
f"{kv_cache_dtype}. Please set `--kv-cache-dtype fp8` or "
"select a backend that supports bfloat16 KV cache."
)
if kv_cache_dtype != "fp8_ds_mla":
if cache_config is not None:
cache_config.cache_dtype = "fp8_ds_mla"
kv_cache_dtype = "fp8_ds_mla"
logger.info_once("Using DeepSeek's fp8_ds_mla KV cache format.")
if cache_config is not None and cache_config.cache_dtype != kv_cache_dtype:
cache_config.cache_dtype = kv_cache_dtype
logger.info_once("Using DeepSeek's %s KV cache format.", kv_cache_dtype)
return kv_cache_dtype, torch.uint8
if kv_cache_dtype.endswith("_ds_mla"):
raise ValueError(
f"{kv_cache_dtype} is a packed FlashMLA DeepSeek V4.1 KV cache "
"format; the selected backend stores plain KV rows."
)
# Plain bf16 / per-tensor fp8 KV row (FlashInfer).
if kv_cache_dtype.startswith("fp8"):
@@ -189,6 +196,28 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# path to pre-reserve that workspace.
PREFILL_CHUNK_SIZE: ClassVar[int] = 4
# ---- attention-interface contract, declared by the platform subclass ----
@property
def accepts_unnormed_unroped_query(self) -> bool:
"""Whether ``forward_mqa``'s ``q`` is the raw ``wq_b`` output.
True when the attention kernel applies the Q norm and RoPE itself, and
reads Q in its own chunk-interleaved layout, so the layer only
zero-pads Q to ``padded_heads`` and inserts KV before calling it.
"""
return False
@property
def packed_kv_cache_dtype(self) -> CacheDType:
"""The packed KV record this layer's kernel prefers.
What an unspecific ``--kv-cache-dtype`` (``auto`` / ``fp8``) resolves
to. Mega attention overrides it: its kernel is the one that can read
an NVFP4 compressed cache.
"""
return "fp8_ds_mla"
@classmethod
@abstractmethod
def get_padded_num_q_heads(cls, num_heads: int) -> int:
@@ -213,8 +242,19 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
raise NotImplementedError
@abstractmethod
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
"""Inverse-RoPE + wo_a + wo_b output projection (platform-specific)."""
def _o_proj(
self,
attn_out: "torch.Tensor | QuantizedActivation",
positions: torch.Tensor,
) -> torch.Tensor:
"""Project whatever ``_alloc_attn_out`` produced through wo_a and wo_b.
Takes the buffer whole, so each layer owns the shape it allocated: the
bf16 layers slice off their padding heads and apply the inverse RoPE,
while a layer whose attention kernel already did the inverse RoPE and
the FP8 cast gets a QuantizedActivation and has only wo_a and wo_b
left.
"""
raise NotImplementedError
def _uses_fp8_ds_mla_layout(self) -> bool:
@@ -459,11 +499,27 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# Resolve the kv-cache dtype from this backend's block format. The same
# resolution drives the SWA cache tensor dtype below.
self.kv_cache_dtype, self.kv_cache_torch_dtype = _resolve_dsv4_kv_cache_dtype(
self._uses_fp8_ds_mla_layout(), cache_config.cache_dtype, cache_config
self._uses_fp8_ds_mla_layout(),
cache_config.cache_dtype,
cache_config,
self.packed_kv_cache_dtype,
)
self.kv_mxfp8 = _use_v41_mxfp8_kv_record()
self.kv_bytes_per_token = 528 if self.kv_mxfp8 else 584
self.swa_bytes_per_token = 528 if self.kv_mxfp8 else 584
# nvfp4_ds_mla keeps the MXFP8 sliding-window record and stores the
# compressed cache as NVFP4 (256 B of e2m1 pairs + 32 e4m3 scales).
self.compressed_bytes_per_token = (
288 if self.kv_cache_dtype == "nvfp4_ds_mla" else self.swa_bytes_per_token
)
# One alignment for every page in the block: the block stride is their
# sum, and 512 satisfies both TMA strides in play (512 for the V4.1
# fp8 record, 256 for NVFP4).
self.kv_page_alignment = 512 if self.kv_mxfp8 else 576
if self.kv_cache_dtype == "nvfp4_ds_mla" and not self.kv_mxfp8:
raise ValueError(
"nvfp4_ds_mla needs the V4.1 KV records, which FlashMLA "
"decodes only on SM100."
)
self.swa_cache_layer = DeepseekV4SWACache(
head_dim=self.head_dim,
@@ -473,7 +529,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
cache_config=cache_config,
backend_cls=self.swa_backend_cls,
block_size=32,
packed_bytes_per_token=self.kv_bytes_per_token,
packed_bytes_per_token=self.swa_bytes_per_token,
packed_page_alignment=self.kv_page_alignment,
)
@@ -553,8 +609,12 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
block_size=self.swa_cache_layer.block_size,
)
# Every backend that gathers a chunk's KV through
# combine_topk_swa_indices needs its Triton kernel warmed, mega
# attention included -- it calls it from _forward_prefill_mega.
if self.backend_cls.get_name() in (
"FLASHMLA_SPARSE_DSV41",
"FLASHMLA_MEGA_ATTN_DSV41",
"ROCM_FLASHMLA_SPARSE_DSV4",
):
from vllm.models.deepseek_v41.common.ops.cache_utils import (
@@ -569,14 +629,10 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
hidden_states: torch.Tensor,
llama_4_scaling: torch.Tensor | None = None,
) -> torch.Tensor:
# Pre-allocate attention output with FlashMLA-padded head count.
# The op writes into `o_padded`; we slice to n_local_heads after.
num_tokens = hidden_states.shape[0]
o_padded = torch.empty(
(num_tokens, self.padded_heads, self.head_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
)
# The eager attention region writes into a caller-owned buffer
# (breakable_cudagraph needs in-place outputs); its shape and how it is
# projected afterwards follow the interface contract above.
attn_out = self._alloc_attn_out(hidden_states.shape[0], hidden_states)
# Keep the attention input preparation in the captured graph. Only the
# sparse indexer and MLA attention run in the eager break below.
@@ -593,12 +649,19 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
kv_score,
indexer_weights,
positions,
o_padded,
attn_out,
)
o = o_padded[:, : self.n_local_heads, :]
return self._o_proj(attn_out, positions)
# Inverse-RoPE + wo_a + wo_b output projection (platform-specific).
return self._o_proj(o, positions)
def _alloc_attn_out(
self, num_tokens: int, hidden_states: torch.Tensor
) -> "torch.Tensor | QuantizedActivation":
"""The buffer ``forward_mqa`` fills, per the interface contract."""
return torch.empty(
(num_tokens, self.padded_heads, self.head_dim),
dtype=hidden_states.dtype,
device=hidden_states.device,
)
@cached_property
def _can_fuse_query_quant(self) -> bool:
@@ -652,7 +715,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
kv_score: torch.Tensor,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
o_padded: torch.Tensor,
attn_out: "torch.Tensor | QuantizedActivation",
) -> None:
"""Wide eager region: the whole of ``_prepare_and_attn`` runs eagerly.
@@ -667,7 +730,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
kv_score,
indexer_weights,
positions,
o_padded,
attn_out,
)
def _prepare_and_attn(
@@ -679,7 +742,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
kv_score: torch.Tensor,
indexer_weights: torch.Tensor,
positions: torch.Tensor,
o_padded: torch.Tensor,
attn_out: "torch.Tensor | QuantizedActivation",
) -> None:
"""Attention input preparation followed by the sparse indexer and MLA.
@@ -751,7 +814,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
q,
kv,
positions,
o_padded,
attn_out,
)
def _fused_wqa_wkv_gemm(self, hidden_states: torch.Tensor) -> torch.Tensor:
@@ -858,16 +921,28 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
dict[str, AttentionMetadata] | list[dict[str, AttentionMetadata]] | None
),
) -> torch.Tensor:
"""Ready ``q`` for the attention kernel and publish this step's KV.
One launch does both. With ``accepts_unnormed_unroped_query`` the
attention kernel norms and rotates Q itself and reads it in its own
chunk-interleaved layout, so the Q half of the launch is a zero-pad to
``padded_heads`` -- and nothing at all once the shard is that wide.
"""
if not isinstance(attn_metadata, dict):
# Profile run: kernel doesn't fire; produce a padded tensor so
# downstream FlashMLA gets the right shape.
if self.n_local_heads < self.padded_heads:
return F.pad(
q,
(0, 0, 0, self.padded_heads - self.n_local_heads),
value=0.0,
)
return q
if self.n_local_heads >= self.padded_heads:
return q
if self.accepts_unnormed_unroped_query:
# Padding heads sit at the tail of every head-dim chunk in
# that layout, so no head-major pad of `q` reproduces it --
# and nothing reads it on a profile run.
return q.new_zeros((q.shape[0], self.padded_heads, q.shape[2]))
return F.pad(
q,
(0, 0, 0, self.padded_heads - self.n_local_heads),
value=0.0,
)
swa_metadata = cast(
"DeepseekSparseSWAMetadata | None",
@@ -886,23 +961,38 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
if cache_dtype == torch.uint8:
# fp8_ds_mla UE8M0 paged path. Horizontally fused:
# Q side: GPT-J RoPE, zero-filling the padding head slots; the
# kernel allocates and returns the padded q tensor.
# kernel allocates and returns the padded q tensor. An
# interleaved Q skips the RoPE its attention kernel owns
# and keeps only the pad, which q_head_padded=0 drops
# too once the shard is already padded_heads wide.
# KV side: GPT-J RoPE + UE8M0 FP8 quant + paged cache insert.
swa_kv_cache_2d = swa_kv_cache.view(swa_kv_cache.shape[0], -1)
return torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
pad_to = (
0
if self.accepts_unnormed_unroped_query
and self.n_local_heads == self.padded_heads
else self.padded_heads
)
q_padded = torch.ops._C.fused_deepseek_v4_qnorm_rope_kv_rope_quant_insert(
q,
kv,
swa_kv_cache_2d,
swa_metadata.slot_mapping,
positions,
cos_sin_cache,
self.padded_heads,
pad_to,
self.eps,
swa_metadata.block_size,
False,
False, # apply_q_norm: qr is normed before wq_b
self.kv_mxfp8,
not self.accepts_unnormed_unroped_query, # apply_q_rope
self.accepts_unnormed_unroped_query, # is_q_interleaved
)
return q if pad_to == 0 else q_padded
assert not self.accepts_unnormed_unroped_query, (
"the chunk-interleaved Q layout only pairs with a packed KV record"
)
# Plain-row path: the [num_blocks, block_size, 512] cache stores the KV
# row in its element dtype (no Q padding). bf16 rewrites q in place;
# per-tensor fp8 writes a separately-allocated fp8 q and quantizes the
@@ -959,7 +1049,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
# fp8_ds_mla is a UE8M0 block-scaled uint8 layout whose page rounds up
# to the decode kernel's TMA stride; plain bf16 / per-tensor fp8 rows
# use natural element-size pages.
uses_fp8_ds_mla_layout = self.kv_cache_dtype == "fp8_ds_mla"
uses_fp8_ds_mla_layout = self.kv_cache_dtype in ("fp8_ds_mla", "nvfp4_ds_mla")
return MLAAttentionSpec(
block_size=vllm_config.cache_config.block_size,
num_kv_heads=1,
@@ -972,7 +1062,7 @@ class DeepseekV4Attention(nn.Module, AttentionLayerBase, ABC):
kv_quant_mode=get_kv_quant_mode(self.kv_cache_dtype),
# Packed record width; head_size stays semantic (512).
state_content_bytes=(
self.kv_bytes_per_token if uses_fp8_ds_mla_layout else None
self.compressed_bytes_per_token if uses_fp8_ds_mla_layout else None
),
)
@@ -1016,7 +1106,13 @@ class DeepseekV4IndexerCache(torch.nn.Module, AttentionLayerBase):
def get_kv_cache_spec(self, vllm_config: VllmConfig) -> KVCacheSpec:
# head_dim already carries the fp8 scale padding
# tokens_per_state=1 for V3.2, >1 for DeepseekV4; same cache layout.
uses_fp8_ds_mla_layout = vllm_config.cache_config.cache_dtype == "fp8_ds_mla"
# nvfp4_ds_mla is packed too: its compressed record is NVFP4 but the
# sliding-window record stays the V4.1 MXFP8 one, so the indexer page
# takes the same alignment either way.
uses_fp8_ds_mla_layout = vllm_config.cache_config.cache_dtype in (
"fp8_ds_mla",
"nvfp4_ds_mla",
)
page_alignment = (
576 if uses_fp8_ds_mla_layout and not _use_v41_mxfp8_kv_record() else 512
)
@@ -43,10 +43,16 @@ from vllm.utils.math_utils import next_power_of_2
# dims each plus a pad byte.
# V4.1 (528 B): all 512 dims as fp8 e4m3 (RoPE included), then 16 UE8M0
# scales of 32 dims each. FlashMLA's ``ModelType::V41``.
# V4.1 NVFP4 (288 B): 512 e2m1 values packed two per byte (even element in
# the low nibble), then 32 e4m3 scales of 16 dims each.
# FlashMLA's ``ModelType::V41_FP4``, compressed cache only.
V4_BYTES_PER_TOKEN = 584
V41_BYTES_PER_TOKEN = 528
V41_QUANT_BLOCK = 32
V41_NUM_SCALES = 512 // V41_QUANT_BLOCK # 16
V41_NVFP4_BYTES_PER_TOKEN = 288
V41_NVFP4_QUANT_BLOCK = 16
V41_NVFP4_NUM_SCALES = 512 // V41_NVFP4_QUANT_BLOCK # 32
@triton.jit
@@ -496,6 +502,73 @@ def _dequantize_and_gather_k_mxfp8_kernel(
tl.store(output_row_ptr + d, dequant.to(tl.bfloat16))
@triton.jit
def _dequantize_and_gather_k_nvfp4_kernel(
out_ptr,
out_stride0,
out_stride1,
k_cache_ptr,
seq_lens_ptr,
block_table_ptr,
offset,
gather_lens_ptr,
max_blocks_per_seq: tl.constexpr,
head_dim: tl.constexpr, # 512
scale_dim: tl.constexpr, # 32
quant_block: tl.constexpr, # 16
cache_block_size: tl.constexpr,
block_stride: tl.constexpr,
):
"""Gather and dequantize V4.1 NVFP4 rows into a bf16 workspace."""
batch_idx = tl.program_id(0)
worker_id = tl.program_id(1)
num_workers = tl.num_programs(1)
seq_len = tl.load(seq_lens_ptr + batch_idx)
if gather_lens_ptr is not None: # noqa: SIM108
gather_len = tl.load(gather_lens_ptr + batch_idx)
else:
gather_len = seq_len
start_pos = seq_len - gather_len
packed_bytes: tl.constexpr = head_dim // 2
d = tl.arange(0, head_dim)
for i in range(worker_id, gather_len, num_workers):
pos = start_pos + i
block_in_seq = pos // cache_block_size
pos_in_block = pos % cache_block_size
physical_block_idx = tl.load(
block_table_ptr + batch_idx * max_blocks_per_seq + block_in_seq
)
page = k_cache_ptr + physical_block_idx.to(tl.int64) * block_stride
packed = tl.load(
page + pos_in_block * packed_bytes + tl.arange(0, packed_bytes)
)
# Even element in the low nibble, odd in the high nibble.
codes = tl.interleave((packed & 0xF).to(tl.int32), (packed >> 4).to(tl.int32))
# e2m1 magnitudes: 0, 0.5, 1, 1.5, 2, 3, 4, 6.
mag_code = codes & 7
e = (mag_code >> 1).to(tl.float32)
m = (mag_code & 1).to(tl.float32)
mag = tl.where(mag_code < 2, m * 0.5, (1.0 + m * 0.5) * tl.exp2(e - 1.0))
vals = tl.where(codes >= 8, -mag, mag)
sf = tl.load(
page
+ cache_block_size * packed_bytes
+ pos_in_block * scale_dim
+ tl.arange(0, scale_dim)
)
scale = sf.to(tl.float8e4nv, bitcast=True).to(tl.float32)
tiles = tl.reshape(vals, (scale_dim, quant_block))
dequant = tl.reshape(tiles * tl.reshape(scale, (scale_dim, 1)), (head_dim,))
output_row_ptr = out_ptr + batch_idx * out_stride0 + (offset + i) * out_stride1
tl.store(output_row_ptr + d, dequant.to(tl.bfloat16))
def dequantize_and_gather_k_cache_triton(
# [num_reqs, max_num_tokens, head_size]
out: torch.Tensor,
@@ -513,6 +586,25 @@ def dequantize_and_gather_k_cache_triton(
) -> None:
num_reqs = seq_lens.shape[0]
NUM_WORKERS = 128
if k_cache.shape[-1] == V41_NVFP4_BYTES_PER_TOKEN:
_dequantize_and_gather_k_nvfp4_kernel[(num_reqs, NUM_WORKERS)](
out,
out.stride(0),
out.stride(1),
k_cache,
seq_lens,
block_table,
offset,
gather_lens,
max_blocks_per_seq=block_table.shape[-1],
head_dim=512,
scale_dim=V41_NVFP4_NUM_SCALES,
quant_block=V41_NVFP4_QUANT_BLOCK,
cache_block_size=block_size,
block_stride=k_cache.stride(0),
)
return
if k_cache.shape[-1] == V41_BYTES_PER_TOKEN:
_dequantize_and_gather_k_mxfp8_kernel[(num_reqs, NUM_WORKERS)](
out,
@@ -581,14 +673,16 @@ def dequantize_and_gather_k_cache(
) -> None:
"""Dequantize and gather a paged DSv4 K cache.
The record is read off ``k_cache.shape[-1]``; see the module header.
The record is read off ``k_cache.shape[-1]``; see the module header. Only
the fp8 records have a CuteDSL gather, so NVFP4 always takes the Triton
path.
``use_fnuz`` MUST match the encoder of the specific cache being read:
``False`` for ``compressed_k_cache`` (Triton encoder is OCP everywhere),
``current_platform.is_fp8_fnuz()`` for ``swa_k_cache`` (C++ encoder
writes FNUZ on gfx942 and OCP on gfx950).
"""
if has_cutedsl():
if has_cutedsl() and k_cache.shape[-1] != V41_NVFP4_BYTES_PER_TOKEN:
# lazily import, otherwise some tests fail due to CUDA driver init failure.
from vllm.models.deepseek_v4.nvidia.ops.dequant_gather_k_cutedsl import (
_DEQUANT_GATHER_K_CACHE_CUTEDSL_KERNEL,
@@ -4,6 +4,7 @@
import torch
from vllm.models.deepseek_v4.common.ops.fused_indexer_q import _fp32x2_to_fp4x2
from vllm.platforms import current_platform
from vllm.triton_utils import tl, triton
@@ -232,13 +233,14 @@ def rope_quant_insert(
The BF16 latent supplies both NoPE quantization and RoPE input. It is read
only for valid slots at group boundaries. The cache dtype selects the
layout: ``uint8`` is the fp8_ds_mla paged layout, whose record the
per-token byte width names -- 584 B for V4 (576 value bytes and eight
segregated UE8M0 scale bytes, including one zero padding scale) or 528 B
for V4.1 (512 MXFP8 value bytes covering the RoPE dims too, then 16 UE8M0
scales of 32 dims each). ``bfloat16`` and ``float8_e4m3fn`` are the plain
[448 NoPE | 64 RoPE] rows read by FlashInfer, the latter scaled by the
per-tensor ``fp8_scale``.
layout: ``uint8`` is a paged FlashMLA layout, whose record the per-token
byte width names -- 584 B for V4 (576 value bytes and eight segregated
UE8M0 scale bytes, including one zero padding scale), 528 B for V4.1
(512 MXFP8 value bytes covering the RoPE dims too, then 16 UE8M0 scales of
32 dims each), or 288 B for V4.1 NVFP4 (256 bytes of e2m1 pairs then 32
e4m3 scales of 16 dims each), which only the compressed cache uses.
``bfloat16`` and ``float8_e4m3fn`` are the plain [448 NoPE | 64 RoPE] rows
read by FlashInfer, the latter scaled by the per-tensor ``fp8_scale``.
"""
assert compress_ratio in (1, 2)
assert latent.shape[1] == 512 and latent.dtype == torch.bfloat16
@@ -249,14 +251,14 @@ def rope_quant_insert(
return
launch_kwargs = {"launch_pdl": False} if current_platform.is_cuda() else {}
if kv_cache.dtype == torch.uint8:
assert kv_cache.shape[-1] in (584, 528), (
kernel = {
584: _rope_quant_insert_kernel,
528: _rope_quant_insert_mxfp8_kernel,
288: _rope_quant_insert_nvfp4_kernel,
}.get(kv_cache.shape[-1])
assert kernel is not None, (
f"unsupported paged KV record width {kv_cache.shape[-1]}"
)
kernel = (
_rope_quant_insert_mxfp8_kernel
if kv_cache.shape[-1] == 528
else _rope_quant_insert_kernel
)
kernel[(num_tokens,)](
latent,
positions,
@@ -402,6 +404,62 @@ def _rope_quant_insert_mxfp8_kernel(
tl.store(scales + tl.arange(0, 16), encoded.to(tl.uint8))
@triton.jit
def _rope_quant_insert_nvfp4_kernel(
latent,
positions,
cos_sin,
cache,
cache_slots,
COS_STRIDE: tl.constexpr,
CACHE_STRIDE: tl.constexpr,
CACHE_BLOCK: tl.constexpr,
COMPRESS_RATIO: tl.constexpr,
SANITIZE_CACHE_NANS: tl.constexpr,
):
"""V4.1 NVFP4 record: RoPE, then e2m1 with one e4m3 scale per 16 dims.
The scale is ``amax / 6`` (6 is e2m1's largest magnitude) clamped to the
e4m3 range, with no per-tensor scale on top.
"""
t = tl.program_id(0)
slot = tl.load(cache_slots + t)
if slot < 0:
return
position = tl.load(positions + t)
if (position + 1) % COMPRESS_RATIO != 0:
return
d = tl.arange(0, 512)
normed = tl.load(latent + t.to(tl.int64) * 512 + d).to(tl.float32)
# NoPE pairs load (cos, sin) = (1, 0), so the rotation is the identity there.
even, odd = tl.split(tl.reshape(normed, (256, 2)))
pair = tl.arange(0, 256) - 224
cs = cos_sin + (position // COMPRESS_RATIO * COMPRESS_RATIO) * COS_STRIDE
c = tl.load(cs + tl.maximum(pair, 0), pair >= 0, other=1.0).to(tl.float32)
s = tl.load(cs + 32 + tl.maximum(pair, 0), pair >= 0, other=0.0).to(tl.float32)
rotated = tl.interleave(even * c - odd * s, odd * c + even * s)
if SANITIZE_CACHE_NANS:
rotated = tl.where(rotated == rotated, rotated, 0.0)
tiles = tl.reshape(rotated, (32, 16))
amax = tl.max(tl.abs(tiles), 1)
# 2**-9 is the smallest normal e4m3 magnitude; 448 the largest.
scale = tl.clamp(amax * (1.0 / 6.0), 0.001953125, 448.0).to(tl.float8e4nv)
# Round-to-nearest division: Triton's default div.full misplaces values
# that land exactly on an e2m1 tie.
scaled = tl.math.div_rn(tiles, tl.reshape(scale.to(tl.float32), (32, 1)))
lo, hi = tl.split(tl.reshape(tl.reshape(scaled, (512,)), (256, 2)))
page = cache + (slot // CACHE_BLOCK).to(tl.int64) * CACHE_STRIDE
tl.store(
page + (slot % CACHE_BLOCK) * 256 + tl.arange(0, 256),
_fp32x2_to_fp4x2(lo, hi),
)
scales = page + CACHE_BLOCK * 256 + (slot % CACHE_BLOCK) * 32
tl.store(scales + tl.arange(0, 32), scale.to(tl.uint8, bitcast=True))
@triton.jit
def _rope_plain_insert_kernel(
latent,
@@ -0,0 +1,86 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Weight permutations for FlashMLA's mega-attention kernel.
The kernel reads Q with 16-element head-dim chunks interleaved across heads and
writes O with 32-element chunks interleaved across the 8 heads of a ``wo_a``
group. Every permutation here satisfies ``fused = standard[perm]``, and is
applied once to ``wq_b`` rows and ``wo_a`` columns at load time so the
surrounding GEMMs produce and consume the kernel's layouts directly -- no
per-step shuffle.
"""
import torch
HEAD_DIM = 512
Q_CHUNK = 16
O_CHUNK = 32
WV_GROUP_SIZE = 8
def q_fused_permutation(num_heads: int, head_dim: int = HEAD_DIM) -> torch.Tensor:
"""``fused[(d // 16) * (H * 16) + h * 16 + d % 16] = standard[h * D + d]``."""
h = torch.arange(num_heads).view(num_heads, 1)
d = torch.arange(head_dim).view(1, head_dim)
fused_index = (d // Q_CHUNK) * (num_heads * Q_CHUNK) + h * Q_CHUNK + d % Q_CHUNK
perm = torch.empty(num_heads * head_dim, dtype=torch.long)
perm[fused_index.reshape(-1)] = torch.arange(num_heads * head_dim)
return perm
def o_fused_permutation(
heads_per_group: int = WV_GROUP_SIZE, head_dim: int = HEAD_DIM
) -> torch.Tensor:
"""``fused[(c * G + h) * 32 + j] = standard[h * D + c * 32 + j]`` per group."""
h = torch.arange(heads_per_group).view(-1, 1, 1)
c = torch.arange(head_dim // O_CHUNK).view(1, -1, 1)
j = torch.arange(O_CHUNK).view(1, 1, -1)
fused_index = (c * heads_per_group + h) * O_CHUNK + j
perm = torch.empty(heads_per_group * head_dim, dtype=torch.long)
perm[fused_index.reshape(-1)] = torch.arange(heads_per_group * head_dim)
return perm
def o_fused_chunk_permutation(
heads_per_group: int = WV_GROUP_SIZE, head_dim: int = HEAD_DIM
) -> torch.Tensor:
"""Per-32-element-chunk form of :func:`o_fused_permutation`, for scales."""
return o_fused_permutation(heads_per_group, head_dim)[::O_CHUNK] // O_CHUNK
def permute_q_to_fused(q: torch.Tensor) -> torch.Tensor:
"""``[N, H, D]`` standard layout -> the same shape in the fused layout."""
n, h, d = q.shape
perm = q_fused_permutation(h, d).to(q.device)
return q.reshape(n, h * d)[:, perm].view(n, h, d)
def _bytes_view(t: torch.Tensor) -> torch.Tensor:
"""Byte view of a 1-byte-element tensor, so fp8/ue8m0 can be gathered."""
return t.view(torch.uint8) if t.element_size() == 1 else t
def permute_wq_b_(
weight: torch.Tensor, weight_scale: torch.Tensor, num_local_heads: int
) -> None:
"""Permute an MXFP8 ``wq_b`` shard's rows and per-row scales, in place."""
head_dim = weight.shape[0] // num_local_heads
perm = q_fused_permutation(num_local_heads, head_dim).to(weight.device)
for t in (weight, weight_scale):
b = _bytes_view(t)
b.copy_(b[perm])
def permute_wo_a_(
weight: torch.Tensor,
weight_scale: torch.Tensor,
heads_per_group: int = WV_GROUP_SIZE,
) -> None:
"""Permute an MXFP8 ``wo_a`` shard's input columns and scales, in place."""
head_dim = weight.shape[1] // heads_per_group
perm = o_fused_permutation(heads_per_group, head_dim).to(weight.device)
w = _bytes_view(weight)
w.copy_(w[:, perm])
chunk_perm = o_fused_chunk_permutation(heads_per_group, head_dim)
s = _bytes_view(weight_scale)
s.copy_(s[:, chunk_perm.to(weight.device)])
+14
View File
@@ -477,8 +477,22 @@ class DSparkDeepseekV4ForCausalLM(nn.Module):
for layer in self.model.layers:
layer.ffn.finalize_mega_moe_weights()
def _finalize_attn(self) -> None:
"""Run the attention backend's post-load weight step on the draft layers.
They are ordinary DeepseekV4DecoderLayers, so they take the engine-wide
attention backend and owe it whatever the target model owes it -- mega
attention permutes wq_b / wo_a here and refuses to run without it.
Idempotent, like the target's.
"""
for layer in self.model.layers:
finalize = getattr(layer.attn, "finalize_loaded_weights", None)
if finalize is not None:
finalize()
def process_weights_after_loading(self) -> None:
self._finalize_moe()
self._finalize_attn()
def _remap_dspark_name(self, name: str) -> str | None:
"""Map a checkpoint ``mtp.{i}.*`` name to this model's parameter path.
@@ -0,0 +1,497 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""DeepSeek V4.1 attention on FlashMLA's mega-attention kernel (SM100).
One kernel does Q RoPE, sparse attention, the inverse RoPE of the output and
its FP8 cast, and writes straight into the buffer ``wo_a`` consumes. So the
layer declares ``accepts_unnormed_unroped_query`` -- the kernel RoPEs Q itself,
leaving the fused KV insert only the zero-pad to the kernel's head count -- and
its ``_alloc_attn_out`` / ``_o_proj`` pair speaks QuantizedActivation instead
of bf16, since the output needs no rotation or quantization here.
``wq_b`` rows and ``wo_a`` columns are permuted once at load so the surrounding
GEMMs speak the kernel's chunk-interleaved layouts directly. A step's prefill
and decode segments write disjoint token ranges of one output buffer pair, so
a single ``wo_a`` einsum covers the whole step.
"""
from dataclasses import replace
from typing import TYPE_CHECKING, cast
import torch
from vllm.config import VllmConfig
from vllm.config.cache import CacheDType
from vllm.forward_context import get_forward_context
from vllm.model_executor.layers.fusion.quant_activation import QuantizedActivation
from vllm.model_executor.layers.quantization.utils.quant_utils import kMxfp8Dynamic
from vllm.models.deepseek_v41.common.ops import (
combine_topk_swa_indices,
compute_global_topk_indices_and_lens,
dequantize_and_gather_k_cache,
)
from vllm.models.deepseek_v41.common.ops.fused_layout import (
WV_GROUP_SIZE,
permute_wo_a_,
permute_wq_b_,
)
from vllm.models.deepseek_v41.nvidia.flashmla import DeepseekV4FlashMLAAttention
from vllm.models.deepseek_v41.sparse_mla import (
DeepseekV4FlashMLAMetadata,
FlashMLAMegaAttnBackend,
)
from vllm.platforms import current_platform
from vllm.utils.deep_gemm import fp8_einsum, get_tma_aligned_size
from vllm.utils.math_utils import round_up
from vllm.v1.attention.ops.flashmla import is_flashmla_sparse_supported
from vllm.v1.worker.workspace import current_workspace_manager
if TYPE_CHECKING:
from vllm.v1.attention.backends.mla.sparse_swa import DeepseekSparseSWAMetadata
_HEAD_DIM_V = 512
_ROPE_DIM = 64
# The kernel always emits per-32 scales, whatever num_per_channels says.
_QUANT_GROUP = 32
# Fixed kernel conventions: GPT-J (non-neox) RoPE, TMA-aligned col-major
# scales, round-to-nearest, packed ue8m0 -- i.e. what DeepGEMM's fp8_einsum
# consumes. Q norm is off: the V4.1 layer norms qr before wq_b.
_ROPE_ARGS = (False, _ROPE_DIM)
_SF_ARGS = (_QUANT_GROUP, True, True, True)
# Decode always goes through the mega kernel: there is no batch size at which
# falling back to the split-KV decode pays, so there is no minimum-token
# threshold and no fallback path to maintain. What decides whether this layer
# is worth selecting at all is TP, not the batch size.
#
# Measured on one GB300 with benchmarks/kernels/benchmark_dsv41_mega_attn.py,
# CUDA graphs on, counting every per-step op each path runs (64-head model,
# topk_swa=128, topk_extra=512, NVFP4 compressed cache), as mega / split-KV
# microseconds:
#
# s_q 1 32 128 256 512
# TP1 (64 live heads) 29/29 31/31 31/40 53/72 96/140
# TP2 (32 live) 29/29 31/30 35/35 61/63 110/119
# TP4 (16 live) 29/29 31/29 34/34 59/58 109/109
# TP8 (8 live) 29/29 31/29 33/33 59/57 107/104
#
# The kernel absorbs the inverse RoPE and the FP8 cast, whose cost scales with
# *live* heads, while its own cost scales with *padded* heads -- always 64,
# since FlashMLA's FP8 decode takes only h_q in {64, 128}. So it wins at TP1
# (up to 1.45x, and TP1 is also where the fused insert skips the Q pad
# entirely) and from TP2 down the two cancel to within a few percent, with a
# fixed ~2 us penalty at small s_q where the padded-head cost dominates.
# Measure before assuming a win at high TP -- and measure under CUDA graphs:
# in eager mode launch overhead swamps both paths and overstates the fused one
# several-fold.
def is_flashmla_mega_attn_supported() -> tuple[bool, str | None]:
"""Whether FlashMLA's fused mega-attention kernels are usable here."""
is_available, maybe_reason = is_flashmla_sparse_supported()
if not is_available:
return False, maybe_reason
if not current_platform.is_device_capability_family(100):
return False, "FlashMLA mega attention requires sm_10x GPUs."
if not hasattr(torch.ops._flashmla_C, "fused_norm_rope_attn_rope_cast_decode"):
return False, "vllm._flashmla_C was built without the mega attention ops."
if not hasattr(torch.ops._flashmla_C, "permute_q_b_proj"):
return False, "vllm._flashmla_C predates the mega attention weight permutes."
return True, None
def alloc_mega_attn_output(
num_tokens: int,
n_wv_group: int,
device: torch.device,
) -> QuantizedActivation:
"""Allocate the output buffer pair the mega-attention kernels write into.
One pair per forward step: the prefill and decode segments fill disjoint
token ranges, so a single ``fp8_einsum`` over all ``num_tokens`` can
consume the result instead of one call per segment.
The scale buffer is MN-major -- stride 1 along tokens, head-dim stride
``ceil4(num_tokens)`` -- which is both what the kernel requires of a
caller-provided buffer and what DeepGEMM expects for this N.
"""
d = WV_GROUP_SIZE * _HEAD_DIM_V
data = torch.empty(
(num_tokens, n_wv_group, d), dtype=torch.float8_e4m3fn, device=device
)
aligned = get_tma_aligned_size(num_tokens, torch.int32.itemsize)
scale = torch.empty(
(n_wv_group, d // (_QUANT_GROUP * 4), aligned),
dtype=torch.int32,
device=device,
).permute(2, 0, 1)[:num_tokens]
return QuantizedActivation(
data=data,
scale=scale,
orig_dtype=torch.bfloat16,
orig_shape=data.shape,
quant_key=kMxfp8Dynamic,
)
def _token_slice(out: QuantizedActivation, start: int, end: int) -> QuantizedActivation:
"""The ``[start, end)`` token slice of a mega-attention output buffer."""
data = out.data[start:end]
return replace(out, data=data, scale=out.scale[start:end], orig_shape=data.shape)
class DeepseekV4MegaAttnAttention(DeepseekV4FlashMLAAttention):
"""FlashMLA mega-attention layer for DeepSeek V4.1 (SM100)."""
backend_cls = FlashMLAMegaAttnBackend
@classmethod
def is_available_for(cls, vllm_config: VllmConfig) -> bool:
"""Whether this layer can serve the configured model on this device.
The kernel is SM100-only and wants ``WV_GROUP_SIZE`` heads per ``wo_a``
group, which stops holding once TP divides the head count far enough
(TP16 on a 64-head model leaves 4). ``__init__`` raises on both, so the
default-backend selector asks here first rather than turning an
unsupported topology into a startup crash.
"""
if not is_flashmla_mega_attn_supported()[0]:
return False
config = vllm_config.model_config.hf_config
config = getattr(config, "text_config", config)
n_heads = getattr(config, "num_attention_heads", 0) or 0
n_groups = getattr(config, "o_groups", 0) or 0
tp_size = vllm_config.parallel_config.tensor_parallel_size
if n_heads % tp_size or n_groups % tp_size:
return False
n_local_heads, n_local_groups = n_heads // tp_size, n_groups // tp_size
if not n_local_groups or n_local_heads % WV_GROUP_SIZE:
return False
return n_local_heads // n_local_groups == WV_GROUP_SIZE
def __init__(self, vllm_config: VllmConfig, *args, **kwargs) -> None:
super().__init__(vllm_config, *args, **kwargs)
if self.n_local_heads % WV_GROUP_SIZE:
raise ValueError(
f"{self.prefix}: mega attention needs the local head count "
f"({self.n_local_heads}) to be a multiple of {WV_GROUP_SIZE}."
)
if self.n_local_heads // self.n_local_groups != WV_GROUP_SIZE:
raise ValueError(
f"{self.prefix}: mega attention needs {WV_GROUP_SIZE} heads per "
"wo_a group."
)
self.n_wv_group = self.padded_heads // WV_GROUP_SIZE
self._fused_layouts_ready = False
# ---- interface contract ------------------------------------------------
@property
def accepts_unnormed_unroped_query(self) -> bool:
return True
@property
def packed_kv_cache_dtype(self) -> CacheDType:
# This kernel is the only one that reads an NVFP4 compressed cache, so
# it is what an unspecific --kv-cache-dtype resolves to here.
return "nvfp4_ds_mla"
def _alloc_attn_out(
self, num_tokens: int, hidden_states: torch.Tensor
) -> QuantizedActivation:
return alloc_mega_attn_output(num_tokens, self.n_wv_group, hidden_states.device)
def _o_proj(
self, attn_out: QuantizedActivation, positions: torch.Tensor
) -> torch.Tensor:
"""Grouped ``wo_a`` then ``wo_b`` over the kernel's quantized output.
The inverse RoPE and the FP8 cast happened inside the attention
kernel, and ``wo_a`` is permuted for its output layout, so there is
nothing to rotate or quantize here and ``positions`` is unused. The
scale already is DeepGEMM's packed-ue8m0 MN-major layout, so the
einsum consumes the kernel's output with no repacking.
"""
groups = self.n_local_groups
z = torch.empty(
(attn_out.data.shape[0], groups, self.o_lora_rank),
dtype=torch.bfloat16,
device=attn_out.data.device,
)
fp8_einsum(
"bhr,hdr->bhd",
(attn_out.data[:, :groups], attn_out.scale[:, :groups]),
(self.wo_a.weight, self.wo_a.weight_scale),
z,
recipe=self._einsum_recipe,
)
return self.wo_b(z.flatten(1))
# ---- weights -----------------------------------------------------------
def finalize_loaded_weights(self) -> None:
"""Permute wq_b rows / wo_a columns into the kernel's layouts.
Idempotent: a second post-load pass must not permute twice.
"""
if self._fused_layouts_ready:
return
permute_wq_b_(
self.wq_b.weight.data, self.wq_b.weight_scale.data, self.n_local_heads
)
permute_wo_a_(
self.wo_a.weight.data,
self.wo_a.weight_scale.data,
self.n_local_heads // self.n_local_groups,
)
self._fused_layouts_ready = True
# ---- forward -----------------------------------------------------------
def forward_mqa(
self,
q: torch.Tensor,
kv: torch.Tensor,
positions: torch.Tensor,
output: QuantizedActivation,
) -> None:
if not self._fused_layouts_ready:
raise RuntimeError(
f"{self.prefix}: wq_b / wo_a were never permuted for the mega "
"attention kernel; refusing to run with mismatched layouts."
)
attn_metadata = get_forward_context().attn_metadata
if attn_metadata is None:
# Warmup dummy run: reserve the prefill workspace, produce zeros.
self._reserve_prefill_workspace(q)
output.data.zero_()
output.scale.zero_()
return
assert isinstance(attn_metadata, dict)
# q was zero-padded to the kernel's head count by the fused KV insert.
assert q.shape[1] == self.padded_heads
flashmla_metadata = cast(
DeepseekV4FlashMLAMetadata | None,
attn_metadata.get(self.compressed_cache_prefix)
if self.compressed_cache_prefix is not None
else None,
)
swa_metadata = cast(
"DeepseekSparseSWAMetadata", attn_metadata[self.swa_cache_layer.prefix]
)
# The kernel takes int32 RoPE positions.
positions_int32 = positions.to(torch.int32)
num_decode_tokens = swa_metadata.num_decode_tokens
if swa_metadata.num_prefills > 0:
self._forward_prefill_mega(
q[num_decode_tokens:],
positions_int32[num_decode_tokens:],
flashmla_metadata,
swa_metadata,
output,
num_decode_tokens,
)
if swa_metadata.num_decodes > 0:
self._forward_decode_mega(
q[:num_decode_tokens],
positions_int32[:num_decode_tokens],
flashmla_metadata,
swa_metadata,
_token_slice(output, 0, num_decode_tokens),
)
def _reserve_prefill_workspace(self, q: torch.Tensor) -> None:
swa_only = self.compress_ratio == 0
n = 0 if swa_only else -(-self.max_model_len // self.compress_ratio)
m = n + self.window_size + self.max_num_batched_tokens
if swa_only:
top_k = 0
else:
assert self.topk_indices_buffer is not None
top_k = self.topk_indices_buffer.shape[-1]
combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128)
current_workspace_manager().get_simultaneous(
((self.PREFILL_CHUNK_SIZE, m, q.shape[-1]), torch.bfloat16),
((self.max_num_batched_tokens, combined_topk), torch.int32),
((self.max_num_batched_tokens,), torch.int32),
)
def _decode_compressed_kv_and_topk(
self,
flashmla_metadata: DeepseekV4FlashMLAMetadata | None,
swa_metadata: "DeepseekSparseSWAMetadata",
) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]:
"""The compressed cache and its ``[n, topk]`` slot indices / lengths."""
if self.compress_ratio == 0:
return None, None, None
assert flashmla_metadata is not None
assert swa_metadata.is_valid_token is not None
assert self.topk_indices_buffer is not None
num_decode_tokens = swa_metadata.num_decode_tokens
indices, lens = compute_global_topk_indices_and_lens(
self.topk_indices_buffer[:num_decode_tokens],
swa_metadata.token_to_req_indices,
flashmla_metadata.block_table[: swa_metadata.num_decodes],
flashmla_metadata.block_size // self.compress_ratio,
swa_metadata.is_valid_token[:num_decode_tokens],
)
return self._compressed_kv_cache().unsqueeze(-2), indices, lens
def _forward_decode_mega(
self,
q: torch.Tensor,
positions_int32: torch.Tensor,
flashmla_metadata: DeepseekV4FlashMLAMetadata | None,
swa_metadata: "DeepseekSparseSWAMetadata",
out: QuantizedActivation,
) -> None:
"""Mega attention over the paged quantized caches, in place into ``out``.
The caches are ``[num_blocks, page, 1, bytes]``, the record taken from
``bytes`` (528 V4.1 fp8, 288 V4.1 NVFP4; NVFP4 only as the compressed
cache beside an fp8 SWA one), and the indices ``[s_q, topk]`` int32
slot ids (``block * page + offset``, ``-1`` invalid).
"""
extra_cache, extra_idx, extra_len = self._decode_compressed_kv_and_topk(
flashmla_metadata, swa_metadata
)
assert swa_metadata.decode_swa_indices is not None
torch.ops._flashmla_C.fused_norm_rope_attn_rope_cast_decode(
q,
self.swa_cache_layer.kv_cache.unsqueeze(-2),
swa_metadata.decode_swa_indices.view(q.shape[0], -1),
self.scale,
_HEAD_DIM_V,
self.attn_sink,
swa_metadata.decode_swa_lens,
extra_cache,
extra_idx,
extra_len,
False, # enable_q_norm
0.0, # rms_norm_eps
positions_int32,
*_ROPE_ARGS,
self.rotary_emb.cos_sin_cache,
self.n_wv_group,
*_SF_ARGS,
out.data,
out.scale,
)
def _forward_prefill_mega(
self,
q: torch.Tensor,
positions_int32: torch.Tensor,
flashmla_metadata: DeepseekV4FlashMLAMetadata | None,
swa_metadata: "DeepseekSparseSWAMetadata",
out: QuantizedActivation,
token_base: int,
) -> None:
swa_only = self.compress_ratio == 0
num_decodes = swa_metadata.num_decodes
num_decode_tokens = swa_metadata.num_decode_tokens
seq_lens = swa_metadata.prefill_seq_lens
gather_lens = swa_metadata.prefill_gather_lens
query_start_loc_cpu = swa_metadata.query_start_loc_cpu
query_start_loc = swa_metadata.query_start_loc
assert seq_lens is not None and gather_lens is not None
assert query_start_loc_cpu is not None and query_start_loc is not None
prefill_token_base = query_start_loc_cpu[num_decodes]
assert self.topk_indices_buffer is not None
topk_indices = self.topk_indices_buffer[num_decode_tokens:][
: swa_metadata.num_prefill_tokens
]
top_k = 0 if swa_only else topk_indices.shape[-1]
chunk_plan = swa_metadata.get_prefill_chunk_plan(
compress_ratio=self.compress_ratio,
prefill_chunk_size=self.PREFILL_CHUNK_SIZE,
has_compressed=not swa_only,
)
assert chunk_plan, "prefill chunk plan must be non-empty when num_prefills > 0"
workspace_manager = current_workspace_manager()
combined_topk = round_up(top_k + self.window_size + self.max_image_tokens, 128)
for chunk_start, chunk_end, chunk_n, chunk_m in chunk_plan:
chunk_size = chunk_end - chunk_start
kv_ws, idx_ws, lens_ws = workspace_manager.get_simultaneous(
((chunk_size, chunk_m, q.shape[-1]), torch.bfloat16),
((self.max_num_batched_tokens, combined_topk), torch.int32),
((self.max_num_batched_tokens,), torch.int32),
)
if not swa_only:
assert flashmla_metadata is not None
dequantize_and_gather_k_cache(
kv_ws[:chunk_size],
self._compressed_kv_cache(),
seq_lens=seq_lens[chunk_start:chunk_end] // self.compress_ratio,
gather_lens=None,
block_table=flashmla_metadata.block_table[num_decodes:][
chunk_start:chunk_end
],
block_size=flashmla_metadata.block_size // self.compress_ratio,
offset=0,
)
dequantize_and_gather_k_cache(
kv_ws[:chunk_size],
self.swa_cache_layer.kv_cache,
seq_lens=seq_lens[chunk_start:chunk_end],
gather_lens=gather_lens[chunk_start:chunk_end],
block_table=swa_metadata.block_table[num_decodes:][
chunk_start:chunk_end
],
block_size=swa_metadata.block_size,
offset=chunk_n,
)
first, last = num_decodes + chunk_start, num_decodes + chunk_end
qs = int(query_start_loc_cpu[first] - prefill_token_base)
qe = int(query_start_loc_cpu[last] - prefill_token_base)
combined_indices, combined_lens = combine_topk_swa_indices(
topk_indices[qs:qe],
query_start_loc[first : last + 1],
seq_lens[chunk_start:chunk_end],
gather_lens[chunk_start:chunk_end],
self.window_size,
self.compress_ratio,
top_k,
chunk_m,
chunk_n,
out=(idx_ws[: qe - qs], lens_ws[: qe - qs]),
left_visible=(
swa_metadata.prefill_left_visible[
num_decode_tokens + qs : num_decode_tokens + qe
]
if swa_metadata.prefill_left_visible is not None
else None
),
right_visible=(
swa_metadata.prefill_right_visible[
num_decode_tokens + qs : num_decode_tokens + qe
]
if swa_metadata.prefill_right_visible is not None
else None
),
max_image_tokens=self.max_image_tokens,
)
chunk_out = _token_slice(out, token_base + qs, token_base + qe)
# Mega attention over the gathered non-paged bf16 KV (RoPE already
# applied), in place into this chunk's token range. `indices`
# entries outside [0, s_kv) skip.
torch.ops._flashmla_C.fused_norm_rope_attn_rope_cast_fwd(
q[qs:qe],
kv_ws.view(-1, 1, q.shape[-1]),
combined_indices.unsqueeze(1),
self.scale,
_HEAD_DIM_V,
self.attn_sink,
combined_lens,
False, # enable_q_norm
0.0, # rms_norm_eps
positions_int32[qs:qe],
*_ROPE_ARGS,
self.rotary_emb.cos_sin_cache,
self.n_wv_group,
*_SF_ARGS,
chunk_out.data,
chunk_out.scale,
)
@@ -201,7 +201,8 @@ class DeepseekV4FlashInferMLAAttention(DeepseekV4Attention):
def get_padded_num_q_heads(cls, num_heads: int) -> int:
return _pad_to_supported_q_heads(num_heads)
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
return deep_gemm_fp8_o_proj(
o,
positions,
@@ -562,7 +563,8 @@ class DeepseekV4FlashInferSM120Attention(DeepseekV4Attention):
def get_padded_num_q_heads(cls, num_heads: int) -> int:
return _pad_to_supported_q_heads(num_heads)
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
return deep_gemm_fp8_o_proj(
o,
positions,
+2 -1
View File
@@ -58,7 +58,8 @@ class DeepseekV4FlashMLAAttention(DeepseekV4Attention):
self._o_proj_block_size
)
def _o_proj(self, o: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
def _o_proj(self, attn_out: torch.Tensor, positions: torch.Tensor) -> torch.Tensor:
o = attn_out[:, : self.n_local_heads, :]
return deep_gemm_fp8_o_proj(
o,
positions,
+28 -2
View File
@@ -64,6 +64,9 @@ from vllm.models.deepseek_v4.nvidia.model import (
make_deepseek_v4_expert_params_mapping,
)
from vllm.models.deepseek_v41.attention import DeepseekV4Attention
from vllm.models.deepseek_v41.nvidia.flash_mla_mega_attn import (
DeepseekV4MegaAttnAttention,
)
from vllm.models.deepseek_v41.nvidia.flashinfer_sparse import (
DeepseekV4FlashInferMLAAttention,
DeepseekV4FlashInferSM120Attention,
@@ -119,8 +122,9 @@ def _select_dsv4_attn_cls(vllm_config: VllmConfig) -> type[DeepseekV4Attention]:
The generic CUDA backend selector does not instantiate DSv4 layers directly,
so map generic sparse-MLA choices to the DSv4-specialized attention class.
Without an explicit backend, SM12 defaults to FlashInfer while the other
CUDA arches keep the FlashMLA path.
Without an explicit backend: SM12 takes FlashInfer, SM100 takes mega
attention where the topology allows it, and everything else keeps the
FlashMLA path.
"""
backend = vllm_config.attention_config.backend
device_capability = current_platform.get_device_capability()
@@ -140,6 +144,8 @@ def _select_dsv4_attn_cls(vllm_config: VllmConfig) -> type[DeepseekV4Attention]:
if device_capability is not None and device_capability.major == 12:
return DeepseekV4FlashInferSM120Attention
return DeepseekV4FlashInferMLAAttention
if backend is AttentionBackendEnum.FLASHMLA_MEGA_ATTN_DSV41:
return DeepseekV4MegaAttnAttention
if backend in (
AttentionBackendEnum.FLASHMLA_SPARSE,
AttentionBackendEnum.FLASHMLA_SPARSE_DSV4,
@@ -149,6 +155,14 @@ def _select_dsv4_attn_cls(vllm_config: VllmConfig) -> type[DeepseekV4Attention]:
if device_capability is not None and device_capability.major == 12:
return DeepseekV4FlashInferSM120Attention
# Mega attention is the SM100 default: it fuses Q RoPE, sparse attention,
# the output's inverse RoPE and its FP8 cast into one launch, and brings
# the 288 B NVFP4 compressed record -- the format the reference
# implementation itself stores. It declines topologies it cannot serve
# (non-SM100, TP that leaves fewer than WV_GROUP_SIZE heads per wo_a
# group, a build without the kernel), which then fall through to FlashMLA.
if DeepseekV4MegaAttnAttention.is_available_for(vllm_config):
return DeepseekV4MegaAttnAttention
return DeepseekV4FlashMLAAttention
@@ -936,6 +950,17 @@ class DeepseekV4Model(nn.Module, EagleModelMixin):
for layer in islice(self.layers, self.start_layer, self.end_layer):
layer.ffn.finalize_mega_moe_weights()
def finalize_mega_attn_weights(self) -> None:
"""Permute wq_b / wo_a into FlashMLA's mega-attention layouts.
A no-op for every other attention layer, and idempotent, so a second
post-load pass cannot permute twice.
"""
for layer in islice(self.layers, self.start_layer, self.end_layer):
finalize = getattr(layer.attn, "finalize_loaded_weights", None)
if finalize is not None:
finalize()
def finalize_mhc_broadcast_weights(self) -> None:
if not get_pp_group().is_first_rank or self.start_layer >= self.end_layer:
return
@@ -1190,6 +1215,7 @@ class DeepseekV41LLMForCausalLM(
def process_weights_after_loading(self) -> None:
self.model.finalize_mega_moe_weights()
self.model.finalize_mhc_broadcast_weights()
self.model.finalize_mega_attn_weights()
def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
return self.model.get_expert_mapping()
+51
View File
@@ -229,3 +229,54 @@ class DeepseekV4FlashMLABackend(DeepseekV4SparseMLABackend):
@staticmethod
def get_builder_cls() -> type[DeepseekV4FlashMLAMetadataBuilder]:
return DeepseekV4FlashMLAMetadataBuilder
class FlashMLAMegaAttnBackend(DeepseekV4FlashMLABackend):
"""FlashMLA's mega-attention kernel: Q RoPE + sparse attention + inverse
RoPE + FP8 cast of the output, in one launch.
Same metadata and KV-cache geometry as ``FLASHMLA_SPARSE_DSV41`` -- what
differs is the attention layer's interface contract (it takes an unnormed,
unroped Q and returns an already-inverse-RoPE'd, quantized output) and the
extra ``nvfp4_ds_mla`` compressed-cache record only this kernel can read.
SM100 only; the kernel has no SM90 instantiation.
"""
supported_kv_cache_dtypes: ClassVar[list[CacheDType]] = [
"auto",
"fp8_ds_mla",
"fp8", # alias for fp8_ds_mla
"nvfp4_ds_mla", # V4.1 fp8 SWA cache + NVFP4 compressed cache
]
@staticmethod
def get_name() -> str:
return "FLASHMLA_MEGA_ATTN_DSV41"
@staticmethod
def get_supported_kernel_block_sizes() -> list[int | MultipleOf]:
return [128]
@classmethod
def supports_compute_capability(cls, capability: DeviceCapability) -> bool:
return capability.major == 10
@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:
# Imported here: the layer module imports this backend class.
from vllm.models.deepseek_v41.nvidia.flash_mla_mega_attn import (
is_flashmla_mega_attn_supported,
)
return is_flashmla_mega_attn_supported()[1]
+729
View File
@@ -0,0 +1,729 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Custom Sparse Attention Indexer layers."""
import torch
import vllm.envs as envs
from vllm import _custom_ops # noqa: F401 # registers the torch.ops._C kernels
from vllm._aiter_ops import rocm_aiter_ops
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import get_current_vllm_config_or_none
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.custom_op import CustomOp
from vllm.models.glm5next.amd.ops import kpool_compress as kpool_ops
from vllm.models.glm5next.common.sparse_indexer import (
RADIX_TOPK_WORKSPACE_SIZE,
_build_decode_scatter_indices,
_decode_topk_seq_lens,
_fill_causal_indices,
_fill_short_decode_causal_indices,
_gather_workspace_shapes,
_scatter_decode_tokens_by_request,
kv_cache_as_quant_view,
)
from vllm.platforms import current_platform
from vllm.utils.torch_utils import (
LayerNameType,
_encode_layer_name,
_resolve_layer_name,
)
from vllm.v1.attention.backends.mla.indexer import (
DeepseekV32IndexerMetadata,
)
from vllm.v1.attention.ops.common import pack_seq_triton, unpack_seq_triton
from vllm.v1.worker.workspace import current_workspace_manager
logger = init_logger(__name__)
# kpool write helper: form pools from the current token batch and compress them
# into the index K cache via the fused Triton kernel.
def _kpool_compress_insert(
k: torch.Tensor,
gate_score: torch.Tensor,
ape: torch.Tensor,
kv_cache: torch.Tensor,
slot_mapping: torch.Tensor,
kpool: int,
head_dim: int,
round_scale: bool,
) -> None:
"""Pool ``kpool`` consecutive tokens into one fp8 K and write at pool slots.
``slot_mapping`` is pool-granular (compress_ratio == kpool on the spec):
only the *last* token of each complete pool carries a valid (>=0) slot;
intra-pool tokens are -1. Every position is treated as a pool-completion
candidate and non-completions are masked off inside the kernel. Compacting
the valid rows first costs two device syncs on the eager prefill path and
buys nothing numerically. Assumes pool-aligned chunk starts.
"""
n = slot_mapping.shape[0]
# No pool can complete in a batch smaller than one pool; also keeps the
# clamped gather indices below in bounds.
if n < kpool:
return
pos = torch.arange(n, device=k.device)
valid = slot_mapping >= 0
# Drop pools whose start falls before the batch (leading padding); their
# gate/k data is undefined anyway.
write_mask = valid & (pos >= kpool - 1)
offs = torch.arange(kpool, device=k.device)
idx = (pos - (kpool - 1)).clamp_min(0)[:, None] + offs[None, :]
kpool_ops.kpool_compress_and_write_cache(
kv_cache,
k[idx], # [n, kpool, head_dim]
gate_score[idx],
ape,
slot_mapping.to(torch.int64),
pool_size=kpool,
head_dim=head_dim,
write_mask=write_mask,
round_scale=round_scale,
write_cache=True,
return_compressed=False,
)
@eager_break_during_capture
def sparse_attn_indexer_kpool(
hidden_states: torch.Tensor,
k_cache_prefix: LayerNameType,
kv_cache: torch.Tensor,
q_quant: torch.Tensor,
q_scale: torch.Tensor | None,
k: torch.Tensor,
weights: torch.Tensor,
quant_block_size: int,
scale_fmt: str | None,
topk_tokens: int,
head_dim: int,
max_model_len: int,
total_seq_lens: int,
topk_indices_buffer: torch.Tensor,
skip_k_cache_insert: bool,
use_fp4_cache: bool = False,
# kpool params (Plan-A: gate is consumed at write time and read back at
# topk time to softmax-weight the pool).
gate_score: torch.Tensor | None = None,
compress_ape: torch.Tensor | None = None,
index_kpool: int = 1,
positions: torch.Tensor | None = None,
# Paged tail cache (in-progress pool's raw K + gate score), replacing the
# transient _DECODE_TAIL ring. tail_prefix resolves attn_metadata[tail_prefix]
# for the tail group's token-granular slot_mapping. None on the dummy/profiling
# path and when the tail cache is disabled.
tail_kv_cache: torch.Tensor | None = None,
tail_prefix: str | None = None,
) -> torch.Tensor:
# careful! this will be None in dummy run
attn_metadata = get_forward_context().attn_metadata
fp8_dtype = current_platform.fp8_dtype()
k_cache_prefix = _resolve_layer_name(k_cache_prefix)
# assert isinstance(attn_metadata, dict)
if not isinstance(attn_metadata, dict):
# Reserve workspace for indexer during profiling run
values_spec, scales_spec = _gather_workspace_shapes(
total_seq_lens, head_dim, fp8_dtype, use_fp4_cache
)
current_workspace_manager().get_simultaneous(
values_spec,
scales_spec,
((RADIX_TOPK_WORKSPACE_SIZE,), torch.uint8),
)
# Reserve profiler-visible memory for the worst-case decode logits,
# whose shape is [B * next_n, max_model_len]. This profiling branch
# returns before invoking the logits kernel itself.
cfg = get_current_vllm_config_or_none()
worst_decode_tokens = 0
if cfg is not None:
sched = cfg.scheduler_config
num_spec = (
cfg.speculative_config.num_speculative_tokens
if cfg.speculative_config is not None
else 0
)
worst_decode_tokens = min(
sched.max_num_seqs * (num_spec + 1),
sched.max_num_batched_tokens,
)
# float32 logits -> 4 bytes/element; uint8 sentinel so elems == bytes.
decode_logits_elems = worst_decode_tokens * max_model_len * 4
prefill_cap_elems = envs.VLLM_SPARSE_INDEXER_MAX_LOGITS_MB * 1024 * 1024
max_logits_elems = max(decode_logits_elems, prefill_cap_elems)
_ = torch.empty(
max_logits_elems, dtype=torch.uint8, device=hidden_states.device
)
return topk_indices_buffer
attn_metadata_narrowed = attn_metadata[k_cache_prefix]
assert isinstance(attn_metadata_narrowed, DeepseekV32IndexerMetadata)
slot_mapping = attn_metadata_narrowed.slot_mapping
has_decode = attn_metadata_narrowed.num_decodes > 0
has_prefill = attn_metadata_narrowed.num_prefills > 0
num_decode_tokens = attn_metadata_narrowed.num_decode_tokens
# q_scale is required iff the FP4 cache path is enabled; the FP8 path
# folds the Q scale into `weights` inside fused_indexer_q_rope_quant.
if use_fp4_cache:
assert q_scale is not None, "use_fp4_cache=True requires q_scale"
else:
assert q_scale is None, "q_scale must be None when use_fp4_cache=False"
# During speculative decoding, k may be padded to the CUDA graph batch
# size while slot_mapping only covers actual tokens. Truncate k to avoid
# out-of-bounds reads in the kernel.
num_tokens = slot_mapping.shape[0]
if k is not None:
k = k[:num_tokens]
if not skip_k_cache_insert:
assert not use_fp4_cache, "Unfused FP4 Insert is not supported yet"
if index_kpool > 1 and gate_score is not None and compress_ape is not None:
# kpool prefill write: pool kpool consecutive prefill tokens via
# softmax(gate+ape)-weighted sum -> Hadamard -> fp8 -> pool slots.
# Decode tokens (the first num_decode_tokens in the batch) cannot be
# pooled here — their pool's earlier tokens are not in this batch —
# so they are deferred to the tail-buffer kernel in has_decode.
# compress_ratio == index_kpool makes slot_mapping pool-granular.
n_prefill = num_tokens - num_decode_tokens
if n_prefill > 0:
# decode tokens are batched first; prefill tokens follow.
prefill_slice = slice(num_decode_tokens, num_tokens)
_kpool_compress_insert(
k[prefill_slice],
gate_score[prefill_slice],
compress_ape,
kv_cache,
slot_mapping[prefill_slice],
index_kpool,
head_dim,
round_scale=(scale_fmt is not None),
)
# Persist each request's incomplete prefill pool so decode can
# finish it, including after PD transfer. Tail slots use
# ``pos % kpool`` within the request's tail block. Processing
# only the batch's trailing tokens would miss all but the last
# request in a multi-request prefill.
if tail_kv_cache is not None and tail_prefix is not None:
tail_meta = attn_metadata.get(_resolve_layer_name(tail_prefix))
if tail_meta is not None:
assert isinstance(tail_meta, DeepseekV32IndexerMetadata)
kpool_ops.kpool_seed_tail_cache(
tail_kv_cache,
k[prefill_slice],
gate_score[prefill_slice],
tail_meta.slot_mapping[prefill_slice],
index_kpool,
head_dim,
)
else:
# standard: per-token fp8 quant + scatter (all tokens).
assert scale_fmt is not None
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
indexer_k_quant_and_cache_triton,
)
indexer_k_quant_and_cache_triton(
k,
kv_cache,
slot_mapping,
quant_block_size,
scale_fmt,
)
topk_indices_buffer[: hidden_states.shape[0]] = -1
if has_prefill:
prefill_metadata = attn_metadata_narrowed.prefill
assert prefill_metadata is not None
# Short sequences select every pool, so skip sparse scoring and fill
# the top-k buffer with all causal token indices. The index-K cache was
# already written above.
n_prefill_sf = num_tokens - num_decode_tokens
# Host-side short-prefill predicate: max_prefill_seq_len is computed
# in the metadata builder (exact for prefill rows) and equals
# positions[prefill_slice].max() + 1, so this replaces a
# positions.max().item() device sync per layer. -1 (unknown metadata)
# falls back to the device-side check.
if prefill_metadata.max_prefill_seq_len >= 0:
short_prefill = (
n_prefill_sf > 0
and positions is not None
and prefill_metadata.max_prefill_seq_len <= topk_tokens
)
else:
short_prefill = (
n_prefill_sf > 0
and positions is not None
and int(positions[num_decode_tokens:num_tokens].max().item()) + 1
<= topk_tokens
)
if short_prefill:
# short_prefill is only True when positions is not None (above),
# but narrow explicitly for the indexer below.
assert positions is not None
_pos = positions[num_decode_tokens:num_tokens].to(torch.int32)
_buf = topk_indices_buffer[num_decode_tokens:num_tokens]
_fill_causal_indices(_buf, _pos)
# Get the full shared workspace buffers once (will allocate on first use).
# Layout switches between FP8 (head_dim bytes + 4-byte fp32 scale) and
# MXFP4 (head_dim/2 bytes packed + head_dim/MXFP4_BLOCK_SIZE ue8m0
# scales) based on use_fp4_cache.
workspace_manager = current_workspace_manager()
values_spec, scales_spec = _gather_workspace_shapes(
total_seq_lens, head_dim, fp8_dtype, use_fp4_cache
)
k_quant_full, k_scale_full = workspace_manager.get_simultaneous(
values_spec,
scales_spec,
)
for chunk in prefill_metadata.chunks if not short_prefill else ():
k_quant = k_quant_full[: chunk.total_seq_lens]
k_scale = k_scale_full[: chunk.total_seq_lens]
if not chunk.skip_kv_gather:
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
cp_gather_indexer_k_quant_cache_triton,
)
cp_gather_indexer_k_quant_cache_triton(
kv_cache,
k_quant,
k_scale,
chunk.block_table,
chunk.cu_seq_lens,
token_to_seq=chunk.token_to_seq,
)
q_slice = q_quant[chunk.token_start : chunk.token_end]
q_scale_slice = (
q_scale[chunk.token_start : chunk.token_end]
if q_scale is not None
else None
)
# DeepGEMM scalar-type tags (zero-copy): MXFP4 values → int8
# (kPackedFP4), scales → int32 squeezed to 1-D kv_sf / 2-D q_sf.
if use_fp4_cache:
q_slice_cast = q_slice.view(torch.int8)
k_quant_cast = k_quant.view(torch.int8)
k_scale_cast = k_scale.view(torch.int32).squeeze(-1)
else:
q_slice_cast = q_slice
k_quant_cast = k_quant
k_scale_cast = k_scale.view(torch.float32).squeeze(-1)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_fp8_mqa_logits,
)
assert q_scale_slice is None
logits = rocm_fp8_mqa_logits(
q_slice_cast,
(k_quant_cast, k_scale_cast),
weights[chunk.token_start : chunk.token_end],
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
)
num_rows = logits.shape[0]
# kpool: logits are pool-granular (compress_ratio == index_kpool),
# so topk selects pools. We pick topk_tokens // kpool pools then
# expand each pool back to its kpool constituent tokens.
select_k = topk_tokens // index_kpool if index_kpool > 1 else topk_tokens
if index_kpool > 1:
pool_topk = torch.empty(
(num_rows, select_k), dtype=torch.int32, device=logits.device
)
topk_dst = pool_topk
else:
topk_dst = topk_indices_buffer[
chunk.token_start : chunk.token_end, :topk_tokens
]
torch.ops._C.top_k_per_row_prefill(
logits,
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
if index_kpool > 1:
pool_ids = pool_topk.to(torch.int64)
if positions is not None:
# Fused expand-pools + append-tail into one Triton kernel
# (replaces ~25 elementwise ops). seq_len is token-granular
# (pos+1); the kernel derives pool_len internally.
q_seq = (
positions[chunk.token_start : chunk.token_end].to(torch.int32)
+ 1
)
expanded = kpool_ops.expand_pools_and_append_tail(
pool_ids, q_seq, index_kpool
)
else:
valid = pool_ids >= 0
expanded = kpool_ops.expand_pools_to_tokens(
pool_ids, valid, topk_tokens, index_kpool
)
topk_indices_buffer[
chunk.token_start : chunk.token_end, : expanded.shape[-1]
] = expanded
if has_decode:
decode_metadata = attn_metadata_narrowed.decode
assert decode_metadata is not None
kv_cache_raw = kv_cache # raw [num_blocks, block_size, head_dim+4] for writes
kv_cache = kv_cache_as_quant_view(kv_cache, head_dim, use_fp4_cache)
# Update the tail before reading logits; completed pools are compressed
# into the slot supplied by slot_mapping.
# Spec verification groups tokens by request and preserves position
# order so each token is stashed before the next completes its pool.
# Positions must remain token-granular because the kernel derives the
# pool phase and tail index from ``pos % kpool``.
if (
index_kpool > 1
and gate_score is not None
and compress_ape is not None
and positions is not None
and not skip_k_cache_insert
):
num_requests = attn_metadata_narrowed.num_decodes
# Kpool writes must recover the original request grouping after the
# indexer's flattened decode path. Host metadata avoids a CUDA graph
# sync when choosing the uniform or padded layout.
per_req_lens = decode_metadata.per_req_decode_lens
if per_req_lens is not None:
use_uniform = (
decode_metadata.decode_is_uniform
and num_decode_tokens
== num_requests * decode_metadata.write_max_decode_len
)
group_lens = per_req_lens
lmax = decode_metadata.write_max_decode_len
else:
# Legacy metadata without per-request lens: fall back to the
# host-side requires_padding flag. Unreached now (per-request
# lens is always populated for decode), kept defensive.
use_uniform = not decode_metadata.requires_padding
group_lens = decode_metadata.decode_lens
lmax = int(decode_metadata.decode_lens.max().item())
if not use_uniform:
# Non-uniform decode_lens (mixed plain-decode + spec-verify, or
# a variable MTP-verify batch): scatter actual tokens into a
# padded [B, lmax] layout. int32 tensors can't go through
# pack_seq_triton (float/uint8 only). The scatter indices are
# shared by all five scatters below (and the tail slot one).
scatter_idx = _build_decode_scatter_indices(
group_lens, num_requests, num_decode_tokens
)
dec_k = _scatter_decode_tokens_by_request(
k[:num_decode_tokens], 0, num_requests, lmax, scatter_idx
)
dec_gate = _scatter_decode_tokens_by_request(
gate_score[:num_decode_tokens],
0,
num_requests,
lmax,
scatter_idx,
)
dec_slot = _scatter_decode_tokens_by_request(
slot_mapping[:num_decode_tokens],
-1,
num_requests,
lmax,
scatter_idx,
)
dec_pos = _scatter_decode_tokens_by_request(
positions[:num_decode_tokens].to(torch.int32),
-1,
num_requests,
lmax,
scatter_idx,
)
else:
next_n = num_decode_tokens // num_requests
shape2 = (num_requests, next_n)
dec_k = k[:num_decode_tokens].view(*shape2, head_dim)
dec_gate = gate_score[:num_decode_tokens].view(*shape2, head_dim)
dec_slot = slot_mapping[:num_decode_tokens].view(shape2)
dec_pos = positions[:num_decode_tokens].to(torch.int32).view(shape2)
tail_meta = (
attn_metadata.get(_resolve_layer_name(tail_prefix))
if tail_prefix is not None
else None
)
# Paged tail cache replaces the transient _DECODE_TAIL ring. Group
# the tail group's token-granular slot_mapping per-request, mirroring
# dec_slot / dec_pos, so the kernel gets each request's current-token
# tail slot (block * kpool + pos % kpool).
if tail_meta is not None:
assert isinstance(tail_meta, DeepseekV32IndexerMetadata)
if tail_meta is None or tail_kv_cache is None:
dec_tail_slot = None
elif not use_uniform:
dec_tail_slot = _scatter_decode_tokens_by_request(
tail_meta.slot_mapping[:num_decode_tokens],
-1,
num_requests,
lmax,
scatter_idx,
)
else:
dec_tail_slot = tail_meta.slot_mapping[:num_decode_tokens].view(shape2)
# The compress kernel writes the raw fp8 cache (not the quant view);
# pass the underlying kv_cache, not kv_cache_quant_view.
if dec_tail_slot is not None:
# Single batched launch over [num_requests, next_n] replaces the
# per-token sequential loop. The kernel iterates each request's
# tokens in position order internally, preserving the
# pool-completion read-after-stash dependency that the loop
# provided. Inputs are already grouped per request (uniform:
# view; non-uniform: _scatter_decode_tokens_by_request padded to
# [B, lmax]) — no per-token .contiguous() copies needed.
kpool_ops.kpool_decode_update_and_maybe_write_cache_batched(
kv_cache_raw,
tail_kv_cache,
dec_tail_slot,
dec_k,
dec_gate,
compress_ape,
dec_slot,
dec_pos,
index_kpool,
head_dim,
round_scale=(scale_fmt is not None),
)
if current_platform.is_cuda_alike() and _fill_short_decode_causal_indices(
topk_indices_buffer,
positions,
num_decode_tokens,
attn_metadata_narrowed.max_seq_len,
topk_tokens,
):
return topk_indices_buffer
decode_lens = decode_metadata.decode_lens
if decode_metadata.requires_padding:
# Padding also covers short chunked prefills classified as decode.
# MXFP4 uses zero-byte padding so padded slots dequantize to zero.
if q_scale is not None:
padded_q_quant_decode_tokens = pack_seq_triton(
q_quant[:num_decode_tokens], decode_lens, pad_value=0
)
padded_q_scale = pack_seq_triton(
q_scale[:num_decode_tokens], decode_lens, pad_value=0
)
else:
padded_q_quant_decode_tokens = pack_seq_triton(
q_quant[:num_decode_tokens], decode_lens
)
padded_q_scale = None
padded_weights = pack_seq_triton(
weights[:num_decode_tokens], decode_lens, pad_value=0
).reshape(-1, *weights.shape[1:])
else:
padded_q_quant_decode_tokens = q_quant[:num_decode_tokens].reshape(
decode_lens.shape[0], -1, *q_quant.shape[1:]
)
if q_scale is not None:
padded_q_scale = q_scale[:num_decode_tokens].reshape(
decode_lens.shape[0], -1, *q_scale.shape[1:]
)
else:
padded_q_scale = None
padded_weights = weights[:num_decode_tokens]
# TODO: move and optimize below logic with triton kernels
batch_size = padded_q_quant_decode_tokens.shape[0]
next_n = padded_q_quant_decode_tokens.shape[1]
num_padded_tokens = batch_size * next_n
seq_lens = decode_metadata.seq_lens[:batch_size]
# seq_lens is always 2D: (B, next_n) for native spec decode, (B, 1)
# otherwise. deep_gemm fp8_fp4_paged_mqa_logits requires 2D context_lens;
# the downstream topk kernels accept both 1D and 2D.
padded_q_quant_cast = (
padded_q_quant_decode_tokens.view(torch.int8)
if use_fp4_cache
else padded_q_quant_decode_tokens
)
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_fp8_paged_mqa_logits,
)
assert padded_q_scale is None
logits = rocm_fp8_paged_mqa_logits(
padded_q_quant_cast,
kv_cache,
padded_weights[:num_padded_tokens],
seq_lens,
decode_metadata.block_table,
decode_metadata.schedule_metadata,
max_model_len=max_model_len,
)
num_rows = logits.shape[0]
# kpool: logits are pool-granular -> select topk_tokens//kpool pools,
# then expand each pool back to its kpool tokens.
select_k = topk_tokens // index_kpool if index_kpool > 1 else topk_tokens
if index_kpool > 1:
pool_topk = torch.empty(
(num_rows, select_k), dtype=torch.int32, device=logits.device
)
topk_dst = pool_topk
else:
topk_dst = topk_indices_buffer[:num_padded_tokens, :topk_tokens]
torch.ops._C.top_k_per_row_decode(
logits,
next_n,
seq_lens,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
# Resolve to token-level indices in the output buffer.
if index_kpool > 1:
pool_ids = pool_topk.to(torch.int64)
n = pool_topk.shape[0]
# Decode seq_lens are pool-granular; recover token lengths from
# positions using the padded [B, next_n] row layout when needed.
if positions is not None:
dec_seq = _decode_topk_seq_lens(
positions,
decode_lens,
num_decode_tokens,
batch_size,
next_n,
decode_metadata.requires_padding,
)
else:
dec_seq = decode_metadata.seq_lens[:n]
if dec_seq.ndim == 2:
dec_seq = dec_seq[:, -1]
dec_seq = dec_seq.to(torch.int32)
out = kpool_ops.expand_pools_and_append_tail(pool_ids, dec_seq, index_kpool)
else:
out = topk_dst
if decode_metadata.requires_padding:
# Drop padded query rows introduced by the next_n padding above.
out = unpack_seq_triton(
out.reshape(batch_size, -1, out.shape[-1]), decode_lens
)
topk_indices_buffer[: out.shape[0], : out.shape[-1]] = out
return topk_indices_buffer
@CustomOp.register("sparse_attn_indexer_kpool")
class SparseAttnIndexerKpool(CustomOp):
"""Sparse Attention Indexer Custom Op Layer. This layer is extracted as a
separate custom op since it involves heavy custom kernels like `mqa_logits`,
`paged_mqa_logits` and `top_k_per_row`, etc. Those kernels maybe requires
specific memory layout or implementation for different hardware backends to
achieve optimal performance.
For now, the default native path will use CUDA backend path. Other platform
may requires add the corresponding Custom Op name `sparse_attn_indexer` to
`custom_ops` in `CompilationConfig` to enable the platform specific path.
"""
def __init__(
self,
k_cache,
quant_block_size: int,
scale_fmt: str,
topk_tokens: int,
head_dim: int,
max_model_len: int,
max_total_seq_len: int,
topk_indices_buffer: torch.Tensor,
skip_k_cache_insert: bool = False,
use_fp4_cache: bool = False,
tail_cache=None,
):
super().__init__()
self.k_cache = k_cache
self.tail_cache = tail_cache
self.quant_block_size = quant_block_size
self.scale_fmt = scale_fmt
self.topk_tokens = topk_tokens
self.head_dim = head_dim
self.max_model_len = max_model_len
self.max_total_seq_len = max_total_seq_len
self.topk_indices_buffer = topk_indices_buffer
self.skip_k_cache_insert = skip_k_cache_insert
self.use_fp4_cache = use_fp4_cache
def forward_native(
self,
hidden_states: torch.Tensor,
q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
k: torch.Tensor,
weights: torch.Tensor,
*,
gate_score: torch.Tensor | None = None,
compress_ape: torch.Tensor | None = None,
index_kpool: int = 1,
positions: torch.Tensor | None = None,
):
assert not self.use_fp4_cache, "AMD platform doesn't support fp4 cache yet"
assert isinstance(q_quant, torch.Tensor), (
"AMD sparse_attn_indexer expects a single FP8 q_quant tensor"
)
if not rocm_aiter_ops.is_enabled():
raise RuntimeError(
"Sparse attention indexer ROCm path is only supported on AITER. "
"Please enable aiter with VLLM_ROCM_USE_AITER=1"
)
if index_kpool <= 1:
return torch.ops.vllm.rocm_aiter_sparse_attn_indexer(
hidden_states,
_encode_layer_name(self.k_cache.prefix),
self.k_cache.kv_cache,
q_quant,
k,
weights,
self.quant_block_size,
self.scale_fmt,
self.topk_tokens,
self.head_dim,
self.max_model_len,
self.max_total_seq_len,
self.topk_indices_buffer,
skip_k_cache_insert=self.skip_k_cache_insert,
)
return sparse_attn_indexer_kpool(
hidden_states,
self.k_cache.prefix,
self.k_cache.kv_cache,
q_quant,
None,
k,
weights,
self.quant_block_size,
self.scale_fmt,
self.topk_tokens,
self.head_dim,
self.max_model_len,
self.max_total_seq_len,
self.topk_indices_buffer,
self.skip_k_cache_insert,
self.use_fp4_cache,
gate_score,
compress_ape,
index_kpool,
positions,
self.tail_cache.kv_cache if self.tail_cache is not None else None,
self.tail_cache.prefix if self.tail_cache is not None else None,
)
+1 -1
View File
@@ -23,7 +23,6 @@ from vllm.model_executor.layers.linear import (
from vllm.model_executor.layers.mla import MLAModules, MultiHeadLatentAttentionWrapper
from vllm.model_executor.layers.quantization.base_config import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding import RotaryEmbedding, get_rope
from vllm.model_executor.layers.sparse_attn_indexer_kpool import SparseAttnIndexerKpool
from vllm.model_executor.models.deepseek_v2 import (
DeepSeekV2FusedQkvAProjLinear,
DeepseekV32IndexerCache,
@@ -31,6 +30,7 @@ from vllm.model_executor.models.deepseek_v2 import (
)
from vllm.model_executor.utils import maybe_disable_graph_partition
from vllm.models.glm5next.nvidia.ops.kpool_compress import fwht128_quant_fp8
from vllm.models.glm5next.sparse_indexer import SparseAttnIndexerKpool
from vllm.platforms import current_platform
from vllm.transformers_utils.configs.glm5_next import Glm5NextConfig
from vllm.utils.deep_gemm import PAGED_MQA_PAGE_SIZES
@@ -0,0 +1,170 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Shared helpers for the glm5next sparse attention indexer (kpool) layers."""
import torch
RADIX_TOPK_WORKSPACE_SIZE = 1024 * 1024
# MXFP4 layout: 2 values packed per byte, ue8m0 (1-byte) scale per block of 32.
MXFP4_BLOCK_SIZE = 32
def _build_decode_scatter_indices(
decode_lens: torch.Tensor,
num_requests: int,
n: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Per-token (request id, intra-request index) for a non-uniform decode
batch, with ``n == decode_lens.sum()`` as a host int (avoids a
device sync and keeps both repeat_interleaves sync-free).
Shared by every ``_scatter_decode_tokens_by_request`` call in a step:
building it per call would repeat the same repeat_interleave/cumsum chain
up to 5x per layer on the eager decode break.
"""
device = decode_lens.device
dl = decode_lens.to(torch.int64)
req_id = torch.repeat_interleave(
torch.arange(num_requests, device=device, dtype=torch.int64),
dl,
output_size=n,
)
req_starts = torch.cumsum(
torch.cat([torch.zeros(1, device=device, dtype=torch.int64), dl[:-1]]),
dim=0,
)
# Broadcast the per-request start offsets to per-token (length n ==
# dl.sum()) so each token's intra-request index subtracts its own
# request's start.
starts = torch.repeat_interleave(req_starts, dl, output_size=n)
intra = torch.arange(n, device=device, dtype=torch.int64) - starts
return req_id, intra
def _scatter_decode_tokens_by_request(
tokens: torch.Tensor,
pad_value,
num_requests: int,
lmax: int,
scatter_indices: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
"""Group ``[N, ...]`` decode tokens into a padded ``[num_requests, lmax, ...]``
layout: request ``r``'s tokens at row ``r`` in order; short requests padded.
Unlike ``pack_seq_triton`` this is dtype-agnostic (needed for the int32
slot/pos tensors) — it scatters with the shared per-step indices from
``_build_decode_scatter_indices``. Used only for the non-uniform
(``requires_padding``) decode batch; uniform batches use a zero-copy
reshape.
"""
req_id, intra = scatter_indices
out = torch.full(
(num_requests, lmax, *tokens.shape[1:]),
pad_value,
dtype=tokens.dtype,
device=tokens.device,
)
out[req_id, intra] = tokens
return out
def _decode_topk_seq_lens(
positions: torch.Tensor,
decode_lens: torch.Tensor,
num_decode_tokens: int,
batch_size: int,
next_n: int,
requires_padding: bool,
) -> torch.Tensor:
"""Token-granular seq_len (pos + 1) per pool-topk row, layout-aware.
``pool_topk`` (and the logits it comes from) follow the padded
``[batch_size, next_n]`` grid whenever ``requires_padding`` is set, so row
``(b, t)`` corresponds to flat decode token ``offset_b + t`` -- NOT
``b * next_n + t``. Slicing flat ``positions[: batch_size * next_n]``
(the uniform-layout shortcut) misaligns every row after the first
non-uniform request and, past the decode region, reads prefill tokens'
positions; ``expand_pools_and_append_tail`` then anchors the tail at
another request's length, dropping the row's real tail tokens or emitting
indices past its sequence (out-of-bounds block-table reads). Padded rows
get 0 (empty tail); they are dropped by ``unpack_seq_triton`` anyway.
"""
n = batch_size * next_n
if not requires_padding:
return positions[:n].to(torch.int32) + 1
scatter_idx = _build_decode_scatter_indices(
decode_lens, batch_size, num_decode_tokens
)
padded = _scatter_decode_tokens_by_request(
positions[:num_decode_tokens].to(torch.int32),
-1,
batch_size,
next_n,
scatter_idx,
)
return padded.reshape(n) + 1 # pad rows: -1 + 1 = 0 -> empty tail
def _fill_causal_indices(rows: torch.Tensor, positions: torch.Tensor) -> None:
causal_range = torch.arange(rows.shape[1], device=rows.device, dtype=torch.int32)
positions = positions.to(torch.int32)
rows[:] = causal_range[None, :]
rows[causal_range[None, :] > positions[:, None]] = -1
def _fill_short_decode_causal_indices(
topk_indices_buffer: torch.Tensor,
positions: torch.Tensor | None,
num_decode_tokens: int,
max_seq_len: int,
topk_tokens: int,
) -> bool:
"""Fill exact causal rows when sparse decode would select every token."""
if positions is None or positions.numel() == 0 or max_seq_len > topk_tokens:
return False
_fill_causal_indices(
topk_indices_buffer[:num_decode_tokens], positions[:num_decode_tokens]
)
return True
def _gather_workspace_shapes(
total_seq_lens: int,
head_dim: int,
fp8_dtype: torch.dtype,
use_fp4_cache: bool,
) -> tuple[tuple[tuple[int, int], torch.dtype], tuple[tuple[int, int], torch.dtype]]:
"""Return ((values_shape, values_dtype), (scales_shape, scales_dtype)) for
the K-gather workspace. FP8 path: (T, head_dim) fp8 + (T, 4) uint8 fp32
scales. MXFP4 path: (T, head_dim // 2) uint8 packed mxfp4 +
(T, head_dim // MXFP4_BLOCK_SIZE) uint8 ue8m0 scales."""
if use_fp4_cache:
return (
((total_seq_lens, head_dim // 2), torch.uint8),
((total_seq_lens, head_dim // MXFP4_BLOCK_SIZE), torch.uint8),
)
return (
((total_seq_lens, head_dim), fp8_dtype),
((total_seq_lens, 4), torch.uint8),
)
def kv_cache_as_quant_view(
kv_cache: torch.Tensor,
head_dim: int,
use_fp4_cache: bool,
) -> torch.Tensor:
"""4D ``[num_blocks, block_size, 1, head_width]`` view expected by
DeepGEMM, from the 3D indexer kv-cache allocation."""
if use_fp4_cache:
assert kv_cache.ndim == 3 and kv_cache.dtype == torch.uint8
num_blocks, block_size, _ = kv_cache.shape
page_bytes = int(kv_cache.stride(0))
fp4_bytes = head_dim // 2 + head_dim // MXFP4_BLOCK_SIZE
return torch.as_strided(
kv_cache,
size=(num_blocks, block_size, 1, fp4_bytes),
stride=(page_bytes, fp4_bytes, fp4_bytes, 1),
)
return kv_cache.unsqueeze(-2)
@@ -2,30 +2,29 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Custom Sparse Attention Indexer layers."""
from typing import TYPE_CHECKING
import torch
import vllm.envs as envs
from vllm._aiter_ops import rocm_aiter_ops
from vllm.compilation.breakable_cudagraph import eager_break_during_capture
from vllm.config import get_current_vllm_config_or_none
from vllm.forward_context import get_forward_context
from vllm.logger import init_logger
from vllm.model_executor.custom_op import CustomOp
from vllm.models.glm5next.common.sparse_indexer import (
RADIX_TOPK_WORKSPACE_SIZE,
_build_decode_scatter_indices,
_decode_topk_seq_lens,
_fill_causal_indices,
_fill_short_decode_causal_indices,
_gather_workspace_shapes,
_scatter_decode_tokens_by_request,
kv_cache_as_quant_view,
)
from vllm.models.glm5next.nvidia.ops import kpool_compress as kpool_ops
from vllm.platforms import current_platform
if TYPE_CHECKING:
from vllm.models.glm5next.nvidia.ops import kpool_compress as kpool_ops
elif current_platform.is_rocm():
from vllm.models.glm5next.amd.ops import kpool_compress as kpool_ops
else:
from vllm.models.glm5next.nvidia.ops import kpool_compress as kpool_ops
from vllm.utils.deep_gemm import has_deep_gemm
from vllm.utils.torch_utils import (
LayerNameType,
_encode_layer_name,
_resolve_layer_name,
)
from vllm.v1.attention.backends.mla.indexer import (
@@ -36,16 +35,9 @@ from vllm.v1.worker.workspace import current_workspace_manager
if current_platform.is_cuda_alike():
from vllm import _custom_ops as ops
elif current_platform.is_xpu():
from vllm._xpu_ops import xpu_ops
logger = init_logger(__name__)
RADIX_TOPK_WORKSPACE_SIZE = 1024 * 1024
# MXFP4 layout: 2 values packed per byte, ue8m0 (1-byte) scale per block of 32.
MXFP4_BLOCK_SIZE = 32
# kpool write helper: form pools from the current token batch and compress them
# into the index K cache via the fused Triton kernel.
@@ -96,166 +88,6 @@ def _kpool_compress_insert(
)
def _build_decode_scatter_indices(
decode_lens: torch.Tensor,
num_requests: int,
n: int,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Per-token (request id, intra-request index) for a non-uniform decode
batch, with ``n == decode_lens.sum()`` as a host int (avoids a
device sync and keeps both repeat_interleaves sync-free).
Shared by every ``_scatter_decode_tokens_by_request`` call in a step:
building it per call would repeat the same repeat_interleave/cumsum chain
up to 5x per layer on the eager decode break.
"""
device = decode_lens.device
dl = decode_lens.to(torch.int64)
req_id = torch.repeat_interleave(
torch.arange(num_requests, device=device, dtype=torch.int64),
dl,
output_size=n,
)
req_starts = torch.cumsum(
torch.cat([torch.zeros(1, device=device, dtype=torch.int64), dl[:-1]]),
dim=0,
)
# Broadcast the per-request start offsets to per-token (length n ==
# dl.sum()) so each token's intra-request index subtracts its own
# request's start.
starts = torch.repeat_interleave(req_starts, dl, output_size=n)
intra = torch.arange(n, device=device, dtype=torch.int64) - starts
return req_id, intra
def _scatter_decode_tokens_by_request(
tokens: torch.Tensor,
pad_value,
num_requests: int,
lmax: int,
scatter_indices: tuple[torch.Tensor, torch.Tensor],
) -> torch.Tensor:
"""Group ``[N, ...]`` decode tokens into a padded ``[num_requests, lmax, ...]``
layout: request ``r``'s tokens at row ``r`` in order; short requests padded.
Unlike ``pack_seq_triton`` this is dtype-agnostic (needed for the int32
slot/pos tensors) — it scatters with the shared per-step indices from
``_build_decode_scatter_indices``. Used only for the non-uniform
(``requires_padding``) decode batch; uniform batches use a zero-copy
reshape.
"""
req_id, intra = scatter_indices
out = torch.full(
(num_requests, lmax, *tokens.shape[1:]),
pad_value,
dtype=tokens.dtype,
device=tokens.device,
)
out[req_id, intra] = tokens
return out
def _decode_topk_seq_lens(
positions: torch.Tensor,
decode_lens: torch.Tensor,
num_decode_tokens: int,
batch_size: int,
next_n: int,
requires_padding: bool,
) -> torch.Tensor:
"""Token-granular seq_len (pos + 1) per pool-topk row, layout-aware.
``pool_topk`` (and the logits it comes from) follow the padded
``[batch_size, next_n]`` grid whenever ``requires_padding`` is set, so row
``(b, t)`` corresponds to flat decode token ``offset_b + t`` -- NOT
``b * next_n + t``. Slicing flat ``positions[: batch_size * next_n]``
(the uniform-layout shortcut) misaligns every row after the first
non-uniform request and, past the decode region, reads prefill tokens'
positions; ``expand_pools_and_append_tail`` then anchors the tail at
another request's length, dropping the row's real tail tokens or emitting
indices past its sequence (out-of-bounds block-table reads). Padded rows
get 0 (empty tail); they are dropped by ``unpack_seq_triton`` anyway.
"""
n = batch_size * next_n
if not requires_padding:
return positions[:n].to(torch.int32) + 1
scatter_idx = _build_decode_scatter_indices(
decode_lens, batch_size, num_decode_tokens
)
padded = _scatter_decode_tokens_by_request(
positions[:num_decode_tokens].to(torch.int32),
-1,
batch_size,
next_n,
scatter_idx,
)
return padded.reshape(n) + 1 # pad rows: -1 + 1 = 0 -> empty tail
def _fill_causal_indices(rows: torch.Tensor, positions: torch.Tensor) -> None:
causal_range = torch.arange(rows.shape[1], device=rows.device, dtype=torch.int32)
positions = positions.to(torch.int32)
rows[:] = causal_range[None, :]
rows[causal_range[None, :] > positions[:, None]] = -1
def _fill_short_decode_causal_indices(
topk_indices_buffer: torch.Tensor,
positions: torch.Tensor | None,
num_decode_tokens: int,
max_seq_len: int,
topk_tokens: int,
) -> bool:
"""Fill exact causal rows when sparse decode would select every token."""
if positions is None or positions.numel() == 0 or max_seq_len > topk_tokens:
return False
_fill_causal_indices(
topk_indices_buffer[:num_decode_tokens], positions[:num_decode_tokens]
)
return True
def _gather_workspace_shapes(
total_seq_lens: int,
head_dim: int,
fp8_dtype: torch.dtype,
use_fp4_cache: bool,
) -> tuple[tuple[tuple[int, int], torch.dtype], tuple[tuple[int, int], torch.dtype]]:
"""Return ((values_shape, values_dtype), (scales_shape, scales_dtype)) for
the K-gather workspace. FP8 path: (T, head_dim) fp8 + (T, 4) uint8 fp32
scales. MXFP4 path: (T, head_dim // 2) uint8 packed mxfp4 +
(T, head_dim // MXFP4_BLOCK_SIZE) uint8 ue8m0 scales."""
if use_fp4_cache:
return (
((total_seq_lens, head_dim // 2), torch.uint8),
((total_seq_lens, head_dim // MXFP4_BLOCK_SIZE), torch.uint8),
)
return (
((total_seq_lens, head_dim), fp8_dtype),
((total_seq_lens, 4), torch.uint8),
)
def kv_cache_as_quant_view(
kv_cache: torch.Tensor,
head_dim: int,
use_fp4_cache: bool,
) -> torch.Tensor:
"""4D ``[num_blocks, block_size, 1, head_width]`` view expected by
DeepGEMM, from the 3D indexer kv-cache allocation."""
if use_fp4_cache:
assert kv_cache.ndim == 3 and kv_cache.dtype == torch.uint8
num_blocks, block_size, _ = kv_cache.shape
page_bytes = int(kv_cache.stride(0))
fp4_bytes = head_dim // 2 + head_dim // MXFP4_BLOCK_SIZE
return torch.as_strided(
kv_cache,
size=(num_blocks, block_size, 1, fp4_bytes),
stride=(page_bytes, fp4_bytes, fp4_bytes, 1),
)
return kv_cache.unsqueeze(-2)
@eager_break_during_capture
def sparse_attn_indexer_kpool(
hidden_states: torch.Tensor,
@@ -393,26 +225,13 @@ def sparse_attn_indexer_kpool(
else:
# standard: per-token fp8 quant + scatter (all tokens).
assert scale_fmt is not None
if current_platform.is_rocm():
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
indexer_k_quant_and_cache_triton,
)
indexer_k_quant_and_cache_triton(
k,
kv_cache,
slot_mapping,
quant_block_size,
scale_fmt,
)
else:
ops.indexer_k_quant_and_cache(
k,
kv_cache,
slot_mapping,
quant_block_size,
scale_fmt,
)
ops.indexer_k_quant_and_cache(
k,
kv_cache,
slot_mapping,
quant_block_size,
scale_fmt,
)
topk_indices_buffer[: hidden_states.shape[0]] = -1
if has_prefill:
@@ -466,27 +285,13 @@ def sparse_attn_indexer_kpool(
k_scale = k_scale_full[: chunk.total_seq_lens]
if not chunk.skip_kv_gather:
if current_platform.is_rocm():
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
cp_gather_indexer_k_quant_cache_triton,
)
cp_gather_indexer_k_quant_cache_triton(
kv_cache,
k_quant,
k_scale,
chunk.block_table,
chunk.cu_seq_lens,
token_to_seq=chunk.token_to_seq,
)
else:
ops.cp_gather_indexer_k_quant_cache(
kv_cache,
k_quant,
k_scale,
chunk.block_table,
chunk.cu_seq_lens,
)
ops.cp_gather_indexer_k_quant_cache(
kv_cache,
k_quant,
k_scale,
chunk.block_table,
chunk.cu_seq_lens,
)
q_slice = q_quant[chunk.token_start : chunk.token_end]
q_scale_slice = (
@@ -504,30 +309,16 @@ def sparse_attn_indexer_kpool(
q_slice_cast = q_slice
k_quant_cast = k_quant
k_scale_cast = k_scale.view(torch.float32).squeeze(-1)
if current_platform.is_rocm():
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_fp8_mqa_logits,
)
from vllm.utils.deep_gemm import fp8_fp4_mqa_logits
assert q_scale_slice is None
logits = rocm_fp8_mqa_logits(
q_slice_cast,
(k_quant_cast, k_scale_cast),
weights[chunk.token_start : chunk.token_end],
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
)
else:
from vllm.utils.deep_gemm import fp8_fp4_mqa_logits
logits = fp8_fp4_mqa_logits(
(q_slice_cast, q_scale_slice),
(k_quant_cast, k_scale_cast),
weights[chunk.token_start : chunk.token_end],
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
clean_logits=False,
)
logits = fp8_fp4_mqa_logits(
(q_slice_cast, q_scale_slice),
(k_quant_cast, k_scale_cast),
weights[chunk.token_start : chunk.token_end],
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
clean_logits=False,
)
num_rows = logits.shape[0]
# kpool: logits are pool-granular (compress_ratio == index_kpool),
@@ -544,28 +335,16 @@ def sparse_attn_indexer_kpool(
chunk.token_start : chunk.token_end, :topk_tokens
]
if current_platform.is_xpu():
xpu_ops.top_k_per_row_prefill( # type: ignore[attr-defined]
logits,
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
else:
torch.ops._C.top_k_per_row_prefill(
logits,
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
torch.ops._C.top_k_per_row_prefill(
logits,
chunk.cu_seqlen_ks,
chunk.cu_seqlen_ke,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
if index_kpool > 1:
pool_ids = pool_topk.to(torch.int64)
@@ -765,34 +544,18 @@ def sparse_attn_indexer_kpool(
if use_fp4_cache
else padded_q_quant_decode_tokens
)
if current_platform.is_rocm():
from vllm.v1.attention.ops.rocm_aiter_mla_sparse import (
rocm_fp8_paged_mqa_logits,
)
from vllm.utils.deep_gemm import fp8_fp4_paged_mqa_logits
assert padded_q_scale is None
logits = rocm_fp8_paged_mqa_logits(
padded_q_quant_cast,
kv_cache,
padded_weights[:num_padded_tokens],
seq_lens,
decode_metadata.block_table,
decode_metadata.schedule_metadata,
max_model_len=max_model_len,
)
else:
from vllm.utils.deep_gemm import fp8_fp4_paged_mqa_logits
logits = fp8_fp4_paged_mqa_logits(
(padded_q_quant_cast, padded_q_scale),
kv_cache,
padded_weights[:num_padded_tokens],
seq_lens,
decode_metadata.block_table,
decode_metadata.schedule_metadata,
max_model_len=max_model_len,
clean_logits=False,
)
logits = fp8_fp4_paged_mqa_logits(
(padded_q_quant_cast, padded_q_scale),
kv_cache,
padded_weights[:num_padded_tokens],
seq_lens,
decode_metadata.block_table,
decode_metadata.schedule_metadata,
max_model_len=max_model_len,
clean_logits=False,
)
num_rows = logits.shape[0]
# kpool: logits are pool-granular -> select topk_tokens//kpool pools,
# then expand each pool back to its kpool tokens.
@@ -819,28 +582,16 @@ def sparse_attn_indexer_kpool(
attn_metadata_narrowed.max_seq_len,
)
else:
if current_platform.is_xpu():
xpu_ops.top_k_per_row_decode( # type: ignore[attr-defined]
logits,
next_n,
seq_lens,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
else:
torch.ops._C.top_k_per_row_decode(
logits,
next_n,
seq_lens,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
torch.ops._C.top_k_per_row_decode(
logits,
next_n,
seq_lens,
topk_dst,
num_rows,
logits.stride(0),
logits.stride(1),
select_k,
)
# Resolve to token-level indices in the output buffer.
if index_kpool > 1:
@@ -942,33 +693,16 @@ class SparseAttnIndexerKpool(CustomOp):
index_kpool: int = 1,
positions: torch.Tensor | None = None,
):
if current_platform.is_cuda() or current_platform.is_xpu():
return self.forward_cuda(
hidden_states,
q_quant,
k,
weights,
gate_score=gate_score,
compress_ape=compress_ape,
index_kpool=index_kpool,
positions=positions,
)
elif current_platform.is_rocm():
return self.forward_hip(
hidden_states,
q_quant,
k,
weights,
gate_score=gate_score,
compress_ape=compress_ape,
index_kpool=index_kpool,
positions=positions,
)
else:
raise NotImplementedError(
"SparseAttnIndexer native forward is only implemented for "
"CUDA, ROCm and XPU platforms."
)
return self.forward_cuda(
hidden_states,
q_quant,
k,
weights,
gate_score=gate_score,
compress_ape=compress_ape,
index_kpool=index_kpool,
positions=positions,
)
def forward_cuda(
self,
@@ -1012,52 +746,3 @@ class SparseAttnIndexerKpool(CustomOp):
self.tail_cache.kv_cache if self.tail_cache is not None else None,
self.tail_cache.prefix if self.tail_cache is not None else None,
)
def forward_hip(
self,
hidden_states: torch.Tensor,
q_quant: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
k: torch.Tensor,
weights: torch.Tensor,
*,
gate_score: torch.Tensor | None = None,
compress_ape: torch.Tensor | None = None,
index_kpool: int = 1,
positions: torch.Tensor | None = None,
):
assert not self.use_fp4_cache, "AMD platform doesn't support fp4 cache yet"
assert isinstance(q_quant, torch.Tensor), (
"AMD sparse_attn_indexer expects a single FP8 q_quant tensor"
)
if rocm_aiter_ops.is_enabled():
if index_kpool <= 1:
return torch.ops.vllm.rocm_aiter_sparse_attn_indexer(
hidden_states,
_encode_layer_name(self.k_cache.prefix),
self.k_cache.kv_cache,
q_quant,
k,
weights,
self.quant_block_size,
self.scale_fmt,
self.topk_tokens,
self.head_dim,
self.max_model_len,
self.max_total_seq_len,
self.topk_indices_buffer,
skip_k_cache_insert=self.skip_k_cache_insert,
)
return self.forward_cuda(
hidden_states,
q_quant,
k,
weights,
gate_score=gate_score,
compress_ape=compress_ape,
index_kpool=index_kpool,
positions=positions,
)
raise RuntimeError(
"Sparse attention indexer ROCm path is only supported on AITER. "
"Please enable aiter with VLLM_ROCM_USE_AITER=1"
)
+22
View File
@@ -0,0 +1,22 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Sparse attention indexer (kpool) — hardware-isolated entry point.
The implementation lives under ``nvidia/`` and ``amd/`` (with shared helpers
in ``common/``); this module picks the right one for the current platform.
"""
from vllm.platforms import current_platform
if current_platform.is_rocm():
from .amd.sparse_indexer import (
SparseAttnIndexerKpool,
)
else:
from .nvidia.sparse_indexer import (
SparseAttnIndexerKpool,
)
__all__ = [
"SparseAttnIndexerKpool",
]
+19 -10
View File
@@ -48,6 +48,19 @@ def _get_hasher_factory(
raise ValueError(f"Unsupported hash algorithm: {algorithm}")
def _get_image_id_bytes(image: Image.Image) -> bytes | None:
try:
exif = image.getexif()
image_id = exif.get(Image.ExifTags.Base.ImageID)
if isinstance(image_id, uuid.UUID):
return image_id.bytes
except Exception:
# Tolerate malformed EXIF metadata (e.g. invalid TIFF header)
# and fall back to serializing raw image data or bytes.
pass
return None
class MultiModalHasher:
@classmethod
def serialize_item(cls, obj: object) -> Iterable[bytes | memoryview]:
@@ -60,11 +73,9 @@ class MultiModalHasher:
return (np.array(obj).tobytes(),)
if isinstance(obj, Image.Image):
exif = obj.getexif()
if Image.ExifTags.Base.ImageID in exif and isinstance(
exif[Image.ExifTags.Base.ImageID], uuid.UUID
):
return (exif[Image.ExifTags.Base.ImageID].bytes,)
image_id = _get_image_id_bytes(obj)
if image_id is not None:
return (image_id,)
data = {"mode": obj.mode, "data": np.asarray(obj)}
palette = obj.palette
@@ -76,11 +87,9 @@ class MultiModalHasher:
return cls.iter_item_to_bytes("image", data)
if isinstance(obj, MediaWithBytes) and isinstance(obj.media, Image.Image):
exif = obj.media.getexif()
if Image.ExifTags.Base.ImageID in exif and isinstance(
exif[Image.ExifTags.Base.ImageID], uuid.UUID
):
return (exif[Image.ExifTags.Base.ImageID].bytes,)
image_id = _get_image_id_bytes(obj.media)
if image_id is not None:
return (image_id,)
if obj.io_config:
return cls.iter_item_to_bytes(
+41
View File
@@ -0,0 +1,41 @@
# vllm/parser
Model-output parsing for the serving layer. `Parser` (`abstract_parser.py`)
unifies reasoning extraction and tool-call extraction behind one object; the
serving layer calls `parse` / `parse_delta` and `is_reasoning_end` on it.
## Layout
- `abstract_parser.py` — `Parser`, and `DelegatingParser` for wrapping a legacy
`ReasoningParser` + `ToolParser` pair.
- `parser_manager.py` — resolves parser names to classes.
- `engine/` — the declarative parser engine. A `ParserEngineConfig`
(`parser_engine_config.py`) is a set of terminals, transitions and content
events; `parser_engine.py` and `streaming_parser_engine.py` drive it for the
non-streaming and streaming paths; `token_id_scanner.py` pre-lexes
special-token ids and `incremental_lexer.py` lexes text; `adapters.py`
exposes an engine through the legacy reasoning/tool parser interfaces.
- `<model>.py` — one file per model family. Most subclass `ParserEngine`
(`deepseek_v4.py`, `qwen3.py`, ...); a few are `DelegatingParser` wrappers
over legacy parsers (`harmony.py`, `kimi_k3.py`).
## Guidelines
- A new parser either subclasses `ParserEngine` with a declarative config, or
subclasses `Parser` and implements `parse` / `parse_delta` directly. Use the
engine when the format is expressible as terminals and transitions, and
subclass an existing config when it is a variant of one (`seed_oss.py`,
`ling3.py`). `DelegatingParser` exists for backward compatibility with the
separate `ReasoningParser` / `ToolParser` classes; do not use it for new
formats.
- Keep a model-specific fix inside that model's `<model>.py` where possible.
Change `engine/` or `abstract_parser.py` only when the behavior is wrong for
every parser, and say so in the PR.
- Text emitted in a state with no `content_events` entry is discarded. Make
that deliberate when adding a state.
- Special tokens reach the engine as token ids, not text. A text terminal that
spans a special token never matches in streaming; list it in
`token_id_terminals`.
- Comment only where the code alone would leave a reader with a question —
a non-obvious transition, a deliberate swallow, a model quirk being worked
around. Keep it minimal and concise.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+19
View File
@@ -672,11 +672,30 @@ class ParserEngine(Parser):
return not wait_for_reasoning
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
config = self.parser_engine_config
wait_for_reasoning = config.wait_for_reasoning
if wait_for_reasoning is None:
wait_for_reasoning = config.initial_state is ParserState.REASONING
if not wait_for_reasoning:
return input_ids
end_id = self._reasoning_end_token_id
if end_id is not None:
for i in range(len(input_ids) - 1, -1, -1):
if input_ids[i] == end_id:
return input_ids[i + 1 :]
end_ids = self._reasoning_end_token_ids
if end_ids:
turn_start = 0
boundary_ids = self._turn_boundary_token_ids
for i in range(len(input_ids) - 1, -1, -1):
if input_ids[i] in boundary_ids:
turn_start = i + 1
break
for i in range(turn_start, len(input_ids)):
if input_ids[i] in end_ids:
return input_ids[i:]
return input_ids
def get_streaming_fallback_content(
+8 -6
View File
@@ -41,6 +41,13 @@ ARG_KEY_END = "</arg_key>"
ARG_VALUE_START = "<arg_value>"
ARG_VALUE_END = "</arg_value>"
# Special tokens that delimit conversation turns in a rendered GLM prompt.
# Reasoning markers belonging to earlier turns must not be mistaken for the
# state of the turn currently being generated.
GLM_TURN_BOUNDARIES = frozenset(
("<|system|>", "<|user|>", "<|assistant|>", "<|observation|>")
)
_ARG_RE = re.compile(
r"<arg_key>(?P<key>.*?)</arg_key>\s*"
r"<arg_value>(?P<value>.*?)</arg_value>",
@@ -123,7 +130,6 @@ def glm47_moe_config(thinking: bool = True) -> ParserEngineConfig:
return ParserEngineConfig(
name="glm47_moe",
initial_state=ParserState.REASONING if thinking else ParserState.CONTENT,
wait_for_reasoning=thinking,
terminals={
**reasoning_terminals,
"TOOL_START": TOOL_CALL_START,
@@ -166,6 +172,7 @@ def glm47_moe_config(thinking: bool = True) -> ParserEngineConfig:
),
**arg_tag_transitions,
},
turn_boundary_tokens=GLM_TURN_BOUNDARIES,
arg_converter=_glm47_arg_converter,
stream_arg_deltas=True,
tool_args_json=False,
@@ -207,11 +214,6 @@ class Glm47MoeParser(ParserEngine):
self._tool_slots[idx].name = self._tool_slots[idx].name.strip()
super()._handle_tool_end(event, deltas)
def extract_content_ids(self, input_ids: list[int]) -> list[int]:
if not self.thinking_enabled:
return input_ids
return super().extract_content_ids(input_ids)
def extract_reasoning(
self,
model_output: str,
+9
View File
@@ -217,6 +217,15 @@ def cpu_platform_plugin() -> str | None:
"AMD Zen CPU detected but zentorch not installed, "
"falling back to CpuPlatform."
)
except OSError:
# An ABI-mismatched build fails here with an undefined-symbol
# error; other failures are not known to be safe to recover from.
logger.warning(
"AMD Zen CPU detected but zentorch failed to import, falling "
"back to CpuPlatform. This usually means the zentorch build "
"does not match the installed torch version.",
exc_info=True,
)
return "vllm.platforms.cpu.CpuPlatform"
+18
View File
@@ -1334,6 +1334,24 @@ class Platform:
"""
return False
@classmethod
def validate_environ(cls, hard_fail: bool) -> None:
"""
Validate environment variables for the current platform.
"""
from vllm import envs
for env in os.environ:
if env.startswith("VLLM_") and env not in envs.environment_variables:
if hard_fail:
raise ValueError(
f"Unknown vLLM environment variable detected: {env}"
)
else:
logger.warning(
"Unknown vLLM environment variable detected: %s", env
)
class UnspecifiedPlatform(Platform):
_enum = PlatformEnum.UNSPECIFIED
+54
View File
@@ -0,0 +1,54 @@
# vllm/reasoning
Every `--reasoning-parser` name resolves here. The parser has two consumers:
`ParserManager.get_parser` composes it with the tool parser into the unified
`Parser` the serving layer uses, and the structured-output manager
(`vllm/v1/structured_output/__init__.py`) instantiates it directly and calls
`is_reasoning_end` / `is_reasoning_end_streaming` every decode step to decide
when the grammar bitmask starts applying. The `ReasoningParser` interface
itself is legacy: it is kept so existing in-tree parsers and out-of-tree
plugins keep working, not as the base for new ones.
## Layout
- `abs_reasoning_parsers.py` — `ReasoningParser` (`extract_reasoning`,
`extract_reasoning_streaming`, `is_reasoning_end`,
`is_reasoning_end_streaming`, `extract_content_ids`, `adjust_request`) and
`ReasoningParserManager`.
- `__init__.py` — `_REASONING_PARSERS_TO_REGISTER`, the name → (file, class)
table that lazily registers every built-in parser.
- `basic_parsers.py` — `BaseThinkingReasoningParser`, the base for parsers
that only need a start/end token pair.
- `<model>_reasoning_parser.py` — one file per family. Either a subclass of a
`ParserReasoningAdapter` generated from a `vllm/parser/<model>.py` engine
grammar (`mistral_reasoning_parser.py`, `kimi_k2_reasoning_parser.py`; the
`_engine_` suffix is not applied consistently), or a self-contained
`ReasoningParser` subclass.
## Guidelines
- Do not change the `ReasoningParser` interface in `abs_reasoning_parsers.py`.
Out-of-tree plugins loaded through
`ReasoningParserManager.import_reasoning_parser` subclass it. New
capabilities go on `Parser` in `vllm/parser/`; if a legacy parser needs the
same capability, `DelegatingParser` supplies the default.
- For a new model, implement a unified `Parser` in `vllm/parser/` first, then
expose it here as a thin adapter subclass plus an entry in
`_REASONING_PARSERS_TO_REGISTER`.
- The `_REASONING_PARSERS_TO_REGISTER` key is what users pass on the command
line; treat renames as breaking.
- Keep adapters thin: registration, `adjust_request` tweaks, and class
attributes. Parsing logic belongs in `vllm/parser/`.
- Keep a model-specific fix inside that model's `<model>_reasoning_parser.py`,
or its grammar in `vllm/parser/<model>.py`, where possible. Touch
`abs_reasoning_parsers.py` or `basic_parsers.py` only for behavior every
parser needs, and say so in the PR.
- `is_reasoning_end_streaming` runs on the engine core for every decode step
of every structured-output request. Work on `delta_ids`; re-scanning the
full sequence makes the step cost grow with sequence length.
- The structured-output gate and the frontend's extraction must agree on
where reasoning ends, whether the turn continues with content or a tool
call. Test the end-detection methods with the same inputs as extraction.
- Comment only where the code alone would leave a reader with a question —
a request tweak in `adjust_request`, a marker handled unusually, a model
quirk being worked around. Keep it minimal and concise.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+53 -6
View File
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from io import BytesIO
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Final
import pybase64
import torch
@@ -17,6 +17,27 @@ if TYPE_CHECKING:
from vllm.config import ModelConfig
# How much of torch's own reason is repeated back to the caller. The reason is
# built from bytes the caller sent, so it is bounded rather than echoed whole.
_MAX_EMBED_ERROR_REASON_CHARS: Final = 200
def _truncated_reason(exc: Exception) -> str:
"""`exc`'s message, capped, saying how much was left out when it is capped.
Without the count a capped reason reads like the whole one, so a caller
debugging a large payload cannot tell that torch said more than this.
"""
reason: Final = str(exc).strip() or type(exc).__name__
omitted: Final = len(reason) - _MAX_EMBED_ERROR_REASON_CHARS
if omitted <= 0:
return reason
return (
f"{reason[:_MAX_EMBED_ERROR_REASON_CHARS]}"
f"... ({omitted} more characters truncated)"
)
def safe_load_prompt_embeds(
model_config: "ModelConfig",
embed: bytes,
@@ -27,12 +48,38 @@ def safe_load_prompt_embeds(
parameter="prompt_embeds",
)
# Decoded outside the try below so that a body which is not base64 keeps
# raising binascii.Error, which is a ValueError and already answered 400.
payload: Final = pybase64.b64decode(embed, validate=True)
with check_sparse_tensor_invariants_threadsafe():
tensor = torch.load(
BytesIO(pybase64.b64decode(embed, validate=True)),
weights_only=True,
map_location=torch.device("cpu"),
)
try:
tensor = torch.load(
BytesIO(payload),
weights_only=True,
map_location=torch.device("cpu"),
)
except (torch.OutOfMemoryError, MemoryError):
# Running out of memory is the server's condition, not the caller's.
raise
except Exception as exc:
# Everything else here is about the bytes the caller sent, and torch
# has no single error type for "this is not a tensor file": the zip
# reader raises `RuntimeError`, the legacy pickle path raises
# `UnpicklingError`, `KeyError` or `IndexError`, an empty payload
# raises `EOFError`. None of them is a `ValueError`, so the
# entrypoints' fallback mapped them all to 500. Catching by
# behaviour rather than by type also survives torch changing which
# error it raises for a given malformed payload.
#
# torch's reason is worth keeping -- for a malformed sparse tensor
# it names the offending index -- but it is built from the caller's
# own bytes, so it is truncated rather than echoed whole.
raise VLLMValidationError(
"`prompt_embeds` could not be deserialized as a torch tensor: "
f"{_truncated_reason(exc)}",
parameter="prompt_embeds",
) from exc
tensor = safe_to_dense(tensor, parameter="prompt_embeds")
if tensor.dim() > 2:
+45
View File
@@ -0,0 +1,45 @@
# vllm/tool_parsers
Every `--tool-call-parser` name resolves here. `ParserManager.get_parser`
composes the tool parser chosen by name with the reasoning parser into the
unified `Parser` the serving layer uses. The `ToolParser` interface itself is
legacy: it is kept so existing in-tree parsers and out-of-tree plugins keep
working, not as the base for new ones.
## Layout
- `abstract_tool_parser.py` — `ToolParser` (`extract_tool_calls`,
`extract_tool_calls_streaming`, `adjust_request`) and `ToolParserManager`.
- `__init__.py` — `_TOOL_PARSERS_TO_REGISTER`, the name → (file, class) table
that lazily registers every built-in parser.
- `structural_tag_registry.py` — structural-tag builders used to constrain
tool-call output for `tool_choice="required"` / named tools.
- `<model>_tool_parser.py` — one file per family. Either a subclass of a
`ParserToolAdapter` generated from a `vllm/parser/<model>.py` engine grammar
(`mistral_tool_parser.py`, `kimi_k2_tool_parser.py`; the `_engine_` suffix
is not applied consistently), or a self-contained `ToolParser` subclass.
## Guidelines
- Do not change the `ToolParser` interface in `abstract_tool_parser.py`.
Out-of-tree plugins loaded through `ToolParserManager.import_tool_parser`
subclass it. New capabilities go on `Parser` in `vllm/parser/`; if a legacy
parser needs the same capability, `DelegatingParser` supplies the default.
- For a new model, implement a unified `Parser` in `vllm/parser/` first, then
expose it here as a thin adapter subclass plus an entry in
`_TOOL_PARSERS_TO_REGISTER`.
- The `_TOOL_PARSERS_TO_REGISTER` key is what users pass on the command line;
treat renames as breaking.
- Keep adapters thin: registration, `adjust_request` tweaks, and class
attributes. Parsing logic belongs in `vllm/parser/`.
- Keep a model-specific fix inside that model's `<model>_tool_parser.py`, or
its grammar in `vllm/parser/<model>.py`, where possible. Touch
`abstract_tool_parser.py` or `structural_tag_registry.py` only for behavior
every parser needs, and say so in the PR.
- Set `structural_tag_model` only to a key in `SUPPORTED_STRUCTURAL_TAG_MODELS`
(an xgrammar builtin, or one registered with `register_vllm_structural_tag`).
It only takes effect under `VLLM_ENFORCE_STRICT_TOOL_CALLING`, where it also
disables the generic required/named handling for that parser.
- Comment only where the code alone would leave a reader with a question —
a request tweak in `adjust_request`, a marker handled unusually, a model
quirk being worked around. Keep it minimal and concise.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+78 -11
View File
@@ -12,8 +12,12 @@ from functools import cache
import psutil
import regex as re
from vllm.logger import init_logger
DEVICE_CONTROL_ENV_VAR = "CPU_VISIBLE_MEMORY_NODES"
logger = init_logger(__name__)
@dataclass
class LogicalCPUInfo:
@@ -63,21 +67,20 @@ def _read_int_file(path: str) -> int | None:
@cache
def get_cgroup_memory_limit() -> tuple[int | None, int | None]:
"""Return (limit, usage) in bytes from cgroup, or (None, None).
def get_cgroup_memory_limit() -> int | None:
"""Return the cgroup memory limit in bytes, or None.
Supports both cgroup v2 (unified) and v1. Returns (None, None) when
Supports both cgroup v2 (unified) and v1. Returns None when
not running under a constrained cgroup (e.g. bare metal, or limit
reported as `max`/an unrealistically large value).
"""
if sys.platform != "linux":
return None, None
return None
# cgroup v2 unified hierarchy
v2_limit = _read_int_file("/sys/fs/cgroup/memory.max")
if v2_limit is not None:
v2_usage = _read_int_file("/sys/fs/cgroup/memory.current")
return v2_limit, v2_usage
return v2_limit
# cgroup v1
v1_limit = _read_int_file("/sys/fs/cgroup/memory/memory.limit_in_bytes")
@@ -85,11 +88,74 @@ def get_cgroup_memory_limit() -> tuple[int | None, int | None]:
# cgroup v1 reports a huge sentinel (close to PAGE_COUNTER_MAX)
# when unlimited. Treat absurdly large values as "no limit".
if v1_limit >= (1 << 62):
return None, None
v1_usage = _read_int_file("/sys/fs/cgroup/memory/memory.usage_in_bytes")
return v1_limit, v1_usage
return None
return v1_limit
return None, None
return None
def get_cgroup_memory_usage() -> int | None:
"""Return the current cgroup memory usage in bytes, or None.
The usage value is intentionally read on every call because cgroup
memory usage changes while the process is running.
"""
if sys.platform != "linux":
return None
# cgroup v2 unified hierarchy
if _read_int_file("/sys/fs/cgroup/memory.max") is not None:
return _read_int_file("/sys/fs/cgroup/memory.current")
# cgroup v1
v1_limit = _read_int_file("/sys/fs/cgroup/memory/memory.limit_in_bytes")
if v1_limit is not None and v1_limit < (1 << 62):
return _read_int_file("/sys/fs/cgroup/memory/memory.usage_in_bytes")
return None
def check_cgroup_memory_available(
required_bytes: int,
allocation_name: str,
) -> None:
"""Log cgroup memory headroom for an upcoming allocation.
Args:
required_bytes: Bytes required by the allocation.
allocation_name: Human-readable name used in log messages.
Low headroom logs a warning, but does not reject the allocation because
cgroup usage can include reclaimable memory. If the cgroup limit or usage
cannot be read, the check is skipped.
"""
cgroup_limit = get_cgroup_memory_limit()
cgroup_usage = get_cgroup_memory_usage()
if cgroup_limit is None or cgroup_usage is None:
return
cgroup_available = max(0, cgroup_limit - cgroup_usage)
mib = 1 << 20
remaining_bytes = cgroup_available - required_bytes
log_fn = logger.debug if remaining_bytes >= 0 else logger.warning
status = (
"current headroom meets the requested allocation"
if remaining_bytes >= 0
else "current headroom is below the requested allocation; allocation "
"will still be attempted because cgroup usage may be reclaimable"
)
log_fn(
"Cgroup memory preflight for %s: %.0f MiB required, %.0f MiB current "
"usage, %.0f MiB available under %.0f MiB limit, %.0f MiB remaining "
"after allocation based on current usage; %s.",
allocation_name,
required_bytes / mib,
cgroup_usage / mib,
cgroup_available / mib,
cgroup_limit / mib,
remaining_bytes / mib,
status,
)
def get_memory_affinity(pid: int = 0) -> list[int]:
@@ -161,7 +227,8 @@ def get_memory_node_info(node_id: int = 0) -> MemoryNodeInfo:
# would be applied to host RAM instead of the pod's limit. cgroup
# does not expose per-NUMA-node limits, so we just clamp the totals
# against the pod-wide limit here.
cgroup_limit, cgroup_usage = get_cgroup_memory_limit()
cgroup_limit = get_cgroup_memory_limit()
cgroup_usage = get_cgroup_memory_usage()
if cgroup_limit is not None and cgroup_limit < total_memory:
total_memory = cgroup_limit
cgroup_available = cgroup_limit - (cgroup_usage or 0)
+3 -1
View File
@@ -726,8 +726,10 @@ def get_sparse_mqa_logits_metadata(
need a host-side sync to pick one.
Args:
cu_seqlen_ks/cu_seqlen_ke: Per-row K range bounds in the packed KV
cu_seqlen_ks: Per-row K range start bounds in the packed KV
workspace, shape [num_q_tokens], dtype int32.
cu_seqlen_ke: Per-row K range end bounds in the packed KV workspace,
shape [num_q_tokens], dtype int32.
num_kv_tokens: Total KV tokens in the packed workspace.
sparse_kv_block_indices: Per-row candidate block ids, shape
[num_q_tokens, num_max_sparse_blocks], dtype int32. Each row's
+4 -1
View File
@@ -112,7 +112,10 @@ class DeepseekV4SWACache(torch.nn.Module, AttentionLayerBase):
# fp8_ds_mla's UE8M0 paged layout rounds its page up to the decode
# kernel's TMA stride; contiguous bf16/fp8 cache uses the natural
# element-size page.
uses_fp8_ds_mla_layout = self.cache_config.cache_dtype == "fp8_ds_mla"
uses_fp8_ds_mla_layout = self.cache_config.cache_dtype in (
"fp8_ds_mla",
"nvfp4_ds_mla",
)
return SlidingWindowMLASpec(
block_size=self.block_size,
num_kv_heads=1,
+3
View File
@@ -114,6 +114,9 @@ class AttentionBackendEnum(Enum, metaclass=_AttentionBackendEnumMeta):
"vllm.models.deepseek_v41.nvidia.flashinfer_sparse."
"DeepseekV4FlashInferMLASparseBackend"
)
FLASHMLA_MEGA_ATTN_DSV41 = (
"vllm.models.deepseek_v41.sparse_mla.FlashMLAMegaAttnBackend"
)
B12X = "vllm.v1.attention.backends.b12x.B12xPagedAttentionBackend"
FLASH_ATTN_MLA = "vllm.v1.attention.backends.mla.flashattn_mla.FlashAttnMLABackend"
FLASH_ATTN_MLA_SPARSE = (
+4 -4
View File
@@ -1796,10 +1796,10 @@ class MambaManager(SingleTypeKVCacheManager):
self._checkpoints.pop(request_id, None)
if num_new_blocks > 0:
blocks_allocated = request_id in self._allocated_block_reqs
if not (checkpoint_block and blocks_allocated):
num_new_blocks = 1 + int(has_partial_hit) + checkpoint_block
if not blocks_allocated:
num_new_blocks += self.num_speculative_blocks
physical_block_cap = 1 + int(has_partial_hit) + checkpoint_block
if not blocks_allocated or checkpoint_block:
physical_block_cap += self.num_speculative_blocks
num_new_blocks = min(num_new_blocks, physical_block_cap)
num_evictable_computed_blocks = self._get_num_evictable_blocks(
new_computed_blocks
+2
View File
@@ -102,6 +102,8 @@ class EngineCoreReadyResponse:
weight_transfer_backend: str | None = None
enable_sleep_mode: bool = False
supports_draft_weight_updates: bool = False
# Full-attention block size in tokens after initialization, or unavailable.
effective_attention_block_size: int | None = None
class EngineCoreRequest(
+20 -1
View File
@@ -85,7 +85,7 @@ from vllm.v1.fault_tolerance.engine_core_sentinel import (
EngineCoreSentinel,
fault_tolerant_wrapper,
)
from vllm.v1.kv_cache_interface import KVCacheConfig
from vllm.v1.kv_cache_interface import KVCacheConfig, is_full_attention_spec
from vllm.v1.metrics.stats import SchedulerIterationDetails, SchedulerStats
from vllm.v1.outputs import ModelRunnerOutput
from vllm.v1.request import Request, RequestStatus
@@ -168,6 +168,7 @@ class EngineCore:
block_size=scheduler_block_size,
hash_block_size=hash_block_size,
)
self._initialize_effective_attention_block_size()
self.use_spec_decode = vllm_config.speculative_config is not None
self.check_for_draft_tokens = (
self.use_spec_decode or vllm_config.model_config.is_diffusion
@@ -382,6 +383,21 @@ class EngineCore:
)
return scheduler_kv_cache_config
def _initialize_effective_attention_block_size(self) -> None:
cache_config = self.vllm_config.cache_config
cache_config.effective_attention_block_size = None
cache_manager = getattr(self.scheduler, "kv_cache_manager", None)
if cache_manager is None:
return
block_sizes = {
manager.block_size
for manager in cache_manager.coordinator.single_type_managers
if is_full_attention_spec(manager.kv_cache_spec)
}
cache_config.effective_attention_block_size = (
block_sizes.pop() if len(block_sizes) == 1 else None
)
def get_supported_tasks(self) -> tuple[SupportedTask, ...]:
supported_tasks = self.model_executor.supported_tasks
self._log_pooler_config(supported_tasks)
@@ -1649,6 +1665,9 @@ class EngineCoreProc(EngineCore):
num_gpu_blocks=self.vllm_config.cache_config.num_gpu_blocks or 0,
block_size=self.vllm_config.cache_config.block_size,
mamba_block_size=self.vllm_config.cache_config.mamba_block_size,
effective_attention_block_size=(
self.vllm_config.cache_config.effective_attention_block_size
),
dp_stats_address=self.frontend_stats_publish_address,
dtype=str(self.vllm_config.model_config.dtype).removeprefix("torch."),
vllm_version=VLLM_VERSION,
+15 -3
View File
@@ -566,6 +566,7 @@ class MPClient(EngineCoreClient):
):
self.vllm_config = vllm_config
self._renderer: BaseRenderer | None = renderer
self._effective_attention_block_sizes: set[int | None] = set()
# ZMQ setup.
sync_ctx = zmq.Context(io_threads=2)
@@ -803,10 +804,21 @@ class MPClient(EngineCoreClient):
def _apply_ready_response(self, payload: bytes) -> None:
"""Decode an EngineCoreReadyResponse and sync any post-initialization
config changes (e.g. auto-fitted max_model_len) back to the frontend."""
if not payload:
return
vllm_config = self.vllm_config
response = msgspec.msgpack.decode(payload, type=EngineCoreReadyResponse)
response = (
msgspec.msgpack.decode(payload, type=EngineCoreReadyResponse)
if payload
else None
)
self._effective_attention_block_sizes.add(
response.effective_attention_block_size if response is not None else None
)
sizes = self._effective_attention_block_sizes
vllm_config.cache_config.effective_attention_block_size = (
next(iter(sizes)) if len(sizes) == 1 else None
)
if response is None:
return
vllm_config.model_config.max_model_len = min(
vllm_config.model_config.max_model_len, response.max_model_len
)
+12
View File
@@ -96,6 +96,12 @@ class ReqContext:
# kv_transfer_params once (in on_new_request) and read the result back
# on later calls for the same request.
_state: dict[type, Any] = field(default_factory=dict, repr=False, init=False)
# End-token position for each key in this request. The scheduler records
# these positions so managers can recover prefix order even when store
# calls arrive out of order (for example, SWA backfills).
_offload_key_positions: dict[OffloadKey, int] = field(
default_factory=dict, repr=False, init=False
)
def set_state(self, val: Any) -> None:
self._state[type(val)] = val
@@ -103,6 +109,12 @@ class ReqContext:
def get_state(self, cls: type[_T]) -> _T | None:
return self._state.get(cls)
def set_offload_key_position(self, key: OffloadKey, end_token: int) -> None:
self._offload_key_positions[key] = end_token
def get_offload_key_position(self, key: OffloadKey) -> int | None:
return self._offload_key_positions.get(key)
class LookupResult(Enum):
"""Result of OffloadingManager.lookup()."""
+141 -5
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import OrderedDict
from collections.abc import Collection, Iterable
from dataclasses import dataclass, field
from typing_extensions import override
@@ -18,6 +19,7 @@ from vllm.v1.kv_offload.base import (
PrepareStoreOutput,
ReqContext,
RequestOffloadingContext,
get_offload_group_idx,
)
from vllm.v1.kv_offload.cpu.common import (
CPULoadStoreSpec,
@@ -27,6 +29,20 @@ from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
from vllm.v1.kv_offload.cpu.policies.factory import CachePolicyFactory
@dataclass(slots=True)
class _RequestCacheAccess:
"""Cache keys observed by one request, grouped in prefix order."""
owner: object
cache_generation: int
key_groups: dict[int, list[OffloadKey]] = field(default_factory=dict)
seen_keys: set[OffloadKey] = field(default_factory=set)
inserted_keys: set[OffloadKey] = field(default_factory=set)
reused_keys: set[OffloadKey] = field(default_factory=set)
store_miss_keys: set[OffloadKey] = field(default_factory=set)
finished: bool = False
class CPUOffloadingManager(OffloadingManager):
"""
An OffloadingManager with a pluggable CachePolicy, resolved by name via
@@ -66,6 +82,7 @@ class CPUOffloadingManager(OffloadingManager):
self.max_tracker_size: int = max_tracker_size
self.stores_skipped_in_current_batch: int = 0
self.allocation_sizes_in_current_batch: list[int] = []
self._cache_generation = 0
# Number of chunk references. It is ordered so can evict the LRU entry in O(1).
self.counts: OrderedDict[OffloadKey, int] | None = (
@@ -124,10 +141,48 @@ class CPUOffloadingManager(OffloadingManager):
num_unprotected -= 1
self.counts[key] = 1
def _get_request_cache_access(self, req_context: ReqContext) -> _RequestCacheAccess:
state = req_context.get_state(_RequestCacheAccess)
if (
state is None
or state.owner is not self
or state.cache_generation != self._cache_generation
):
state = _RequestCacheAccess(
owner=self, cache_generation=self._cache_generation
)
req_context.set_state(state)
return state
def _record_request_cache_access(
self,
keys: Iterable[OffloadKey],
req_context: ReqContext,
inserted_keys: Iterable[OffloadKey] = (),
reused_keys: Iterable[OffloadKey] = (),
) -> None:
state = self._get_request_cache_access(req_context)
for key in keys:
if key in state.seen_keys:
continue
assert not state.finished, (
"New cache keys observed after request finalization"
)
group_idx = get_offload_group_idx(key)
state.key_groups.setdefault(group_idx, []).append(key)
state.seen_keys.add(key)
state.inserted_keys.update(inserted_keys)
# Re-reading a chunk inserted by this request is an internal transfer
# (for example, a tiering cascade), not a second cache access.
state.reused_keys.update(
key for key in reused_keys if key not in state.inserted_keys
)
# --- OffloadingManager interface ---
@override
def on_new_request(self, req_context: ReqContext) -> RequestOffloadingContext:
self._get_request_cache_access(req_context)
return RequestOffloadingContext()
@override
@@ -144,6 +199,15 @@ class CPUOffloadingManager(OffloadingManager):
self,
keys: Collection[OffloadKey],
req_context: ReqContext,
) -> LoadStoreSpec:
return self._prepare_load(keys, req_context, record_access=True)
def _prepare_load(
self,
keys: Collection[OffloadKey],
req_context: ReqContext,
*,
record_access: bool,
) -> LoadStoreSpec:
chunks = []
for key in keys:
@@ -156,6 +220,8 @@ class CPUOffloadingManager(OffloadingManager):
assert self._num_evictable_cache_chunks >= 0
chunk.ref_cnt += 1
chunks.append(chunk)
if record_access:
self._record_request_cache_access(keys, req_context, reused_keys=keys)
return self._get_load_store_spec(keys, chunks)
@override
@@ -181,13 +247,52 @@ class CPUOffloadingManager(OffloadingManager):
keys: Collection[OffloadKey],
req_context: ReqContext,
) -> PrepareStoreOutput | None:
keys = list(keys)
if self.counts is not None:
num_keys = len(keys)
self._record_accesses(keys)
keys = [k for k in keys if self.counts.get(k, 0) >= self.store_threshold]
self.stores_skipped_in_current_batch += num_keys - len(keys)
# filter out chunks that are already stored
keys_to_store = [k for k in keys if self._policy.get(k) is None]
# Partition the original offer before admission filtering. Ready
# resident chunks are request reuses even if their tracker entry was
# aged out; the threshold applies only to new store candidates.
keys_to_store: list[OffloadKey] = []
ready_existing_keys: list[OffloadKey] = []
for key in keys:
chunk = self._policy.get(key)
if chunk is None:
keys_to_store.append(key)
else:
if chunk.is_ready:
ready_existing_keys.append(key)
if self.counts is not None:
num_store_candidates = len(keys_to_store)
keys_to_store = [
key
for key in keys_to_store
if self.counts.get(key, 0) >= self.store_threshold
]
self.stores_skipped_in_current_batch += num_store_candidates - len(
keys_to_store
)
state = self._get_request_cache_access(req_context)
new_store_misses = [
key for key in keys_to_store if key not in state.store_miss_keys
]
if new_store_misses:
# ARC learns from B1/B2 before insert() removes the ghost entry.
# Deduplication makes this one policy observation per request.
self._policy.on_store_miss(new_store_misses, req_context)
state.store_miss_keys.update(new_store_misses)
recorded_keys = set(keys_to_store)
recorded_keys.update(ready_existing_keys)
# Record once before any allocation-related early return. Store
# candidates are classified as insertions only after allocation succeeds.
self._record_request_cache_access(
(key for key in keys if key in recorded_keys),
req_context,
reused_keys=ready_existing_keys,
)
if not keys_to_store:
return PrepareStoreOutput(
@@ -239,6 +344,7 @@ class CPUOffloadingManager(OffloadingManager):
for key, chunk in zip(keys_to_store, chunks):
self._policy.insert(key, chunk)
self._num_write_pending_chunks += len(keys_to_store)
state.inserted_keys.update(keys_to_store)
# build store specs for allocated chunks
store_spec = self._get_load_store_spec(keys_to_store, chunks)
@@ -284,6 +390,35 @@ class CPUOffloadingManager(OffloadingManager):
)
)
@override
def on_request_finished(self, req_context: ReqContext) -> None:
state = req_context.get_state(_RequestCacheAccess)
if (
state is None
or state.owner is not self
or state.cache_generation != self._cache_generation
or state.finished
):
return
state.finished = True
key_groups = []
for group_idx in sorted(state.key_groups):
keys = state.key_groups[group_idx]
positions = {
key: position
for key in keys
if (position := req_context.get_offload_key_position(key)) is not None
}
if len(positions) == len(keys):
keys = sorted(keys, key=positions.__getitem__)
key_groups.append(tuple(keys))
self._policy.on_request_finished(
tuple(key_groups),
state.inserted_keys - state.reused_keys,
state.reused_keys,
req_context,
)
@override
def reset_cache(self) -> None:
# Clear ALL chunks unconditionally. The scheduler's _stale_job_threshold
@@ -292,6 +427,7 @@ class CPUOffloadingManager(OffloadingManager):
# flushes in-flight load job IDs to the workers before any new stores
# can begin, preventing a cross-direction data race on reused offload chunk IDs.
self._policy.clear()
self._cache_generation += 1
self._num_evictable_cache_chunks = 0
self._num_write_pending_chunks = 0
+58 -21
View File
@@ -1,12 +1,16 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import OrderedDict
from collections.abc import Iterable, Iterator
from collections.abc import Iterable, Iterator, Sequence
from typing_extensions import override
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
from vllm.v1.kv_offload.cpu.policies.base import (
CachePolicy,
ChunkStatus,
order_request_keys,
)
class ARCCachePolicy(CachePolicy):
@@ -24,12 +28,11 @@ class ARCCachePolicy(CachePolicy):
Searches T1 and T2 for chunk hashes and counts consecutive hits
until a miss or non-ready chunk is encountered.
2. Cache touch (touch) - Adaptive Learning:
For each key (in reverse order):
- If in T1: Move to T2 (promotion from recent to frequent).
- If in T2: Move to MRU position (end of queue).
- If in B1 ghost list: Increase target_t1_size.
- If in B2 ghost list: Decrease target_t1_size.
2. Request access - Adaptive Learning:
- Ready chunks reused by a request move from T1 to T2 once, or
move to the MRU end of T2.
- B1/B2 misses adjust target_t1_size once per request before
insertion removes their ghost entries.
3. Chunk eviction (evict) - Adaptive Replacement:
Determines eviction source based on adaptive target:
@@ -39,7 +42,7 @@ class ARCCachePolicy(CachePolicy):
4. Chunk insertion (insert):
New chunks are always inserted into T1 and removed from B1/B2 if
present. Chunks may later be promoted to T2 during touch operations.
present. A later request reuse may promote them to T2.
Adaptive Behavior:
The algorithm self-tunes the recency vs. frequency trade-off:
@@ -71,6 +74,26 @@ class ARCCachePolicy(CachePolicy):
if self.t1.pop(key, None) is None:
self.t2.pop(key, None)
def _adapt_to_ghost_hit(self, key: OffloadKey) -> bool:
if key in self.b1:
delta = max(1, len(self.b2) / len(self.b1))
self.target_t1_size = min(self.target_t1_size + delta, self.cache_capacity)
self.b1.move_to_end(key)
return True
if key in self.b2:
delta = max(1, len(self.b1) / len(self.b2))
self.target_t1_size = max(self.target_t1_size - delta, 0)
self.b2.move_to_end(key)
return True
return False
@override
def on_store_miss(
self, keys: Iterable[OffloadKey], req_context: ReqContext
) -> None:
for key in reversed(list(keys)):
self._adapt_to_ghost_hit(key)
@override
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
for key in reversed(list(keys)):
@@ -86,19 +109,33 @@ class ARCCachePolicy(CachePolicy):
elif key in self.t2:
self.t2.move_to_end(key)
elif key in self.b1:
delta = max(1, len(self.b2) / len(self.b1))
self.target_t1_size = min(
self.target_t1_size + delta, self.cache_capacity
)
# move to MRU position (end) to keep it fresh in the ghost list
self.b1.move_to_end(key)
else:
self._adapt_to_ghost_hit(key)
elif key in self.b2:
delta = max(1, len(self.b1) / len(self.b2))
self.target_t1_size = max(self.target_t1_size - delta, 0)
# move to MRU position (end) to keep it fresh in the ghost list
self.b2.move_to_end(key)
@override
def on_request_finished(
self,
key_groups: Sequence[Sequence[OffloadKey]],
insertion_only_keys: set[OffloadKey],
reused_keys: set[OffloadKey],
req_context: ReqContext,
) -> None:
for key in reversed(order_request_keys(key_groups, req_context)):
if key in insertion_only_keys:
# A store is not a frequency hit. Preserve T1 membership
# while still restoring tail-to-head recency.
if key in self.t1:
self.t1.move_to_end(key)
elif key in self.t2:
self.t2.move_to_end(key)
continue
# Ready chunks reused by this request count as one access.
if key in reused_keys and key in self.t1:
chunk = self.t1.pop(key)
self.t2[key] = chunk
elif key in reused_keys and key in self.t2:
self.t2.move_to_end(key)
@override
def clear(self) -> None:
+51 -1
View File
@@ -2,11 +2,26 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import ctypes
from abc import ABC, abstractmethod
from collections.abc import Iterable
from collections.abc import Iterable, Sequence
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
def order_request_keys(
key_groups: Sequence[Sequence[OffloadKey]], req_context: ReqContext
) -> list[OffloadKey]:
"""Return one head-to-tail order across all KV cache groups."""
keys = [key for group in key_groups for key in group]
positions = {
key: position
for key in keys
if (position := req_context.get_offload_key_position(key)) is not None
}
if len(positions) == len(keys):
keys.sort(key=positions.__getitem__)
return keys
class ChunkStatus(ctypes.Structure):
"""
Offloading status for a single chunk of KV data.
@@ -66,6 +81,41 @@ class CachePolicy(ABC):
req_context: Per-request context for the request touching these chunks.
"""
def on_store_miss(
self, keys: Iterable[OffloadKey], req_context: ReqContext
) -> None:
"""Observe store misses before their cache entries are inserted.
The default delegates to ``touch`` for compatibility with external
policies. Policies may override this hook when a miss has distinct
semantics, such as ARC adapting to a ghost-list hit.
"""
self.touch(keys, req_context)
def on_request_finished(
self,
key_groups: Sequence[Sequence[OffloadKey]],
insertion_only_keys: set[OffloadKey],
reused_keys: set[OffloadKey],
req_context: ReqContext,
) -> None:
"""Apply one request-scoped cache access in prefix order.
``key_groups`` contains keys observed for each KV cache group in
head-to-tail order. ``insertion_only_keys`` and ``reused_keys``
distinguish chunks only created by this request from ready chunks it
actually reused, which matters for policies such as ARC where reuse
changes frequency but insertion and pending observations do not.
The default forwards one touch per group, preserving compatibility
for experimental out-of-tree policies while moving those touches to
request finalization. Policies that distinguish insertion from reuse
can override this hook and inspect the access classifications.
"""
del insertion_only_keys, reused_keys
for keys in key_groups:
self.touch(keys, req_context)
@abstractmethod
def evict(
self, n: int, protected: set[OffloadKey]
+112 -28
View File
@@ -1,28 +1,74 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections import OrderedDict
from collections.abc import Iterable
import heapq
from collections.abc import Iterable, Sequence
from typing_extensions import override
from vllm.v1.kv_offload.base import OffloadKey, ReqContext
from vllm.v1.kv_offload.cpu.policies.base import CachePolicy, ChunkStatus
from vllm.v1.kv_offload.cpu.policies.base import (
CachePolicy,
ChunkStatus,
order_request_keys,
)
class LRUCachePolicy(CachePolicy):
"""
LRU Caching policy that keeps a dedicated evictable list for fast eviction.
LRU caching policy with logical recency independent of transfer pinning.
Evictable chunks live in a lazy-invalidating min-heap. A chunk's recency
can therefore be updated while it is pinned; when it later becomes
evictable, it enters the heap with the order assigned by the request
rather than its transfer-completion time.
A use is indicated by,
- First time the key is added (store).
- Load job completion
- touch
- A request-scoped access.
"""
def __init__(self, cache_capacity: int):
super().__init__(cache_capacity)
# Chunks with ref_cnt 0 (not participating in any loads/stores) ordered in LRU
self.evictable_chunks: OrderedDict[OffloadKey, None] = OrderedDict()
self.chunks: dict[OffloadKey, ChunkStatus] = {}
self._ranks: dict[OffloadKey, int] = {}
self._evictable: set[OffloadKey] = set()
self._heap: list[tuple[int, OffloadKey]] = []
self._next_rank = 0
def _assign_new_rank(self, key: OffloadKey) -> bool:
if key not in self.chunks:
return False
self._next_rank += 1
self._ranks[key] = self._next_rank
return key in self._evictable
def _push_evictable(self, key: OffloadKey) -> None:
heapq.heappush(
self._heap,
(self._ranks[key], key),
)
def _is_current(self, entry: tuple[int, OffloadKey]) -> bool:
rank, key = entry
return key in self._evictable and self._ranks.get(key) == rank
def _maybe_compact_heap(self) -> None:
if len(self._heap) < max(64, 2 * len(self._evictable)):
return
self._heap = [(self._ranks[key], key) for key in self._evictable]
heapq.heapify(self._heap)
def _update_recency(self, keys: Iterable[OffloadKey]) -> None:
updated_evictable = [key for key in keys if self._assign_new_rank(key)]
# Rebuilding is linear and substantially cheaper than k heap pushes
# for a long prefix. Small updates retain the incremental path.
if len(updated_evictable) >= max(64, len(self._evictable) // 4):
self._heap = [(self._ranks[key], key) for key in self._evictable]
heapq.heapify(self._heap)
else:
for key in updated_evictable:
self._push_evictable(key)
self._maybe_compact_heap()
@override
def get(self, key: OffloadKey) -> ChunkStatus | None:
@@ -31,26 +77,40 @@ class LRUCachePolicy(CachePolicy):
@override
def insert(self, key: OffloadKey, chunk: ChunkStatus) -> None:
self.chunks[key] = chunk
self._next_rank += 1
self._ranks[key] = self._next_rank
if chunk.ref_cnt == 0:
self.evictable_chunks[key] = None
self._evictable.add(key)
self._push_evictable(key)
@override
def remove(self, key: OffloadKey) -> None:
del self.chunks[key]
self.evictable_chunks.pop(key, None)
self._ranks.pop(key, None)
self._evictable.discard(key)
@override
def touch(self, keys: Iterable[OffloadKey], req_context: ReqContext) -> None:
for key in reversed(list(keys)):
if key in self.evictable_chunks:
self.evictable_chunks.move_to_end(key)
# active chunks are untouched as they are non-evictable now. They
# will eventually reach the end of evictable_chunks when they finish.
self._update_recency(reversed(list(keys)))
@override
def on_request_finished(
self,
key_groups: Sequence[Sequence[OffloadKey]],
insertion_only_keys: set[OffloadKey],
reused_keys: set[OffloadKey],
req_context: ReqContext,
) -> None:
del insertion_only_keys, reused_keys
self._update_recency(reversed(order_request_keys(key_groups, req_context)))
@override
def clear(self) -> None:
self.evictable_chunks.clear()
self.chunks.clear()
self._ranks.clear()
self._evictable.clear()
self._heap.clear()
self._next_rank = 0
@override
def evict(
@@ -59,22 +119,44 @@ class LRUCachePolicy(CachePolicy):
if n == 0:
return []
candidates: list[tuple[OffloadKey, ChunkStatus]] = []
for key, _ in self.evictable_chunks.items():
selected: list[tuple[tuple[int, OffloadKey], ChunkStatus]] = []
selected_keys: set[OffloadKey] = set()
deferred: list[tuple[int, OffloadKey]] = []
while self._heap and len(selected) < n:
entry = heapq.heappop(self._heap)
if not self._is_current(entry):
continue
key = entry[1]
# Re-pinning without a recency change can leave an equivalent
# lazy entry behind. Select each cache key at most once.
if key in selected_keys:
continue
if key in protected:
deferred.append(entry)
continue
chunk = self.chunks[key]
assert chunk.ref_cnt == 0
candidates.append((key, chunk))
if len(candidates) == n:
break
selected.append((entry, chunk))
selected_keys.add(key)
if len(candidates) < n:
if len(selected) < n:
for entry, _ in selected:
heapq.heappush(self._heap, entry)
for entry in deferred:
heapq.heappush(self._heap, entry)
return None
for key, _ in candidates:
del self.evictable_chunks[key]
for entry in deferred:
heapq.heappush(self._heap, entry)
candidates: list[tuple[OffloadKey, ChunkStatus]] = []
for entry, chunk in selected:
key = entry[1]
self._evictable.remove(key)
del self.chunks[key]
del self._ranks[key]
candidates.append((key, chunk))
self._maybe_compact_heap()
return candidates
@override
@@ -82,9 +164,11 @@ class LRUCachePolicy(CachePolicy):
# chunks can become evictable when,
# store completes - i.e. ref_cnt -1 -> 0 # not in evictable list
# all loads complete - i.e ref_cnt 1 -> 0 # not in evictable list
self.evictable_chunks[key] = None
self._evictable.add(key)
self._push_evictable(key)
self._maybe_compact_heap()
@override
def mark_non_evictable(self, key: OffloadKey) -> None:
# key must have been in the evictable list.
del self.evictable_chunks[key]
# key must have been evictable before it was pinned.
self._evictable.remove(key)
@@ -135,7 +135,10 @@ class SharedOffloadRegion:
self._creator = True
if creator_memory_check is not None:
creator_memory_check(self.total_size_bytes)
check_shm_free_space(self.total_size_bytes)
check_shm_free_space(
self.total_size_bytes,
allocation_name="CPU KV offload shared region in /dev/shm",
)
os.ftruncate(self.fd, self.total_size_bytes)
logger.info(
"Created mmap file %s (%.2f GB)",
+13 -5
View File
@@ -110,13 +110,22 @@ class CPUPrimaryTierOffloadingManager(CPUOffloadingManager):
# read/write is for CPU<->secondary transfers,
# load/store is for CPU<->GPU transfers.
# These aliases avoid calling prepare_load inside a store path.
self.prepare_read = self.prepare_load
self.complete_read = self.complete_load
self.prepare_write = self.prepare_store
self.complete_write = self.complete_store
self._kv_memoryview = mmap_region.create_kv_memoryview()
def prepare_read(
self, keys: Collection[OffloadKey], req_context: ReqContext
) -> LoadStoreSpec:
"""Pin chunks for a CPU-to-secondary transfer.
Cascade reads are implementation details of tiering, not additional
request accesses, so they must not alter request-scoped recency.
"""
return self._prepare_load(keys, req_context, record_access=False)
def get_kv_memoryview(self) -> memoryview:
"""Return the memoryview over the primary tier's KV cache buffer.
@@ -781,11 +790,10 @@ class TieringOffloadingManager(OffloadingManager):
req_id: str,
exclude_tier_idx: int | None = None,
) -> None:
"""Finalize secondary tiers once no more store cascades can be submitted.
"""Finalize secondary tiers once no more cascades can be submitted.
Finalization means forwarding on_request_finished() to secondary tiers.
It is delayed until pending GPU->primary stores finish, since their
complete_store() callbacks may still submit primary->secondary stores.
Their finalization is delayed until pending GPU->primary stores
finish, since those callbacks may still submit secondary stores.
"""
state = self._req_state[req_id]
if not state.is_finished:
+100 -8
View File
@@ -2,10 +2,10 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import torch
from vllm.triton_utils import HAS_TRITON, tl, tldevice, triton
from vllm.triton_utils import HAS_TRITON, tl, triton
# Smallest positive value produced by Triton's fp32 `tl.rand`. Used to clamp
# zero draws before the flipped Gumbel transform below.
# Smallest positive value produced by Triton's fp32 `tl.rand`. Used by the
# retained Philox helper for rejection sampling.
#
# Triton requires globals accessed from `@triton.jit` functions to be wrapped
# in `tl.constexpr(...)`. We can only do that when Triton is actually
@@ -87,6 +87,97 @@ def tl_rand32(seed, offset, includes_zero: tl.constexpr):
return u
@triton.jit
def _murmur3_rotl32(value, shift: tl.constexpr):
return (value << shift) | (value >> (32 - shift))
@triton.jit
def _murmur3_mix(h, key):
key *= 0xCC9E2D51
key = _murmur3_rotl32(key, 15)
key *= 0x1B873593
h ^= key
h = _murmur3_rotl32(h, 13)
return h * 5 + 0xE6546B64
@triton.jit
def _murmur3_fmix32(h):
h ^= h >> 16
h *= 0x85EBCA6B
h ^= h >> 13
h *= 0xC2B2AE35
return h ^ (h >> 16)
@triton.jit
def murmur3_hash32(seed, pos, offset, domain: tl.constexpr = 0):
seed = seed.to(tl.int64)
pos = pos.to(tl.int64)
offset = offset.to(tl.uint32)
# Keep the request-wide prefix scalar until the token offset is mixed in.
h = (seed ^ seed).to(tl.uint32)
h ^= domain
h = _murmur3_mix(h, (seed & 0xFFFFFFFF).to(tl.uint32))
h = _murmur3_mix(h, ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32))
h = _murmur3_mix(h, (pos & 0xFFFFFFFF).to(tl.uint32))
h = _murmur3_mix(h, offset)
return _murmur3_fmix32(h ^ 16)
@triton.jit
def murmur3_uniform32(seed, pos, offset):
random32 = murmur3_hash32(seed, pos, offset)
# Split the uint32 before converting to fp32 so backends without a native
# uint32-to-float conversion can still use all 32 source bits. Both 16-bit
# halves convert exactly; their sum is the correctly rounded fp32 value of
# (random32 + 0.5) * 2**-32. In particular, the u -> 0 winning tail keeps
# the full 32-bit source resolution instead of being truncated to 24 bits.
hi16 = (random32 >> 16).to(tl.int32)
lo16 = (random32 & 0xFFFF).to(tl.int32)
return (
hi16.to(tl.float32) * 1.52587890625e-05
+ (lo16.to(tl.float32) + 0.5) * 2.3283064365386963e-10
)
@triton.jit
def _uniform64_from_random53(random53):
uniform = (random53.to(tl.float64) + 0.5) * 1.1102230246251565e-16
# The largest midpoint rounds to 1.0 in fp64; keep the uniform open without
# relying on a near-one literal that Triton may materialize in fp32.
return tl.where(uniform == 1.0, uniform - 1.1102230246251565e-16, uniform)
@triton.jit
def murmur3_uniform64(seed, pos, offset):
lo = murmur3_hash32(seed, pos, offset).to(tl.uint64)
hi = murmur3_hash32(seed, pos, offset, domain=0x9E3779B9).to(tl.uint64)
random53 = ((hi << 32) | lo) >> 11
return _uniform64_from_random53(random53)
@triton.jit
def _log1p_neg_stable(value):
# Preserve precision for the positive Gumbel tail without relying on a
# backend-specific libdevice log1p. The degree-8 series has absolute error
# below 6e-7 on [0, 0.25]; subtraction is well-conditioned elsewhere for
# the part of the distribution that can win the argmax.
polynomial = 1.0 / 8.0
polynomial = 1.0 / 7.0 + value * polynomial
polynomial = 1.0 / 6.0 + value * polynomial
polynomial = 1.0 / 5.0 + value * polynomial
polynomial = 1.0 / 4.0 + value * polynomial
polynomial = 1.0 / 3.0 + value * polynomial
polynomial = 1.0 / 2.0 + value * polynomial
polynomial = 1.0 + value * polynomial
series = -value * polynomial
direct = tl.log(tl.maximum(1.0 - value, 5.960464477539063e-08))
return tl.where(value < 0.25, series, direct)
@triton.jit
def gumbel_noised_argmax(
logits,
@@ -117,14 +208,15 @@ def gumbel_noised_argmax(
if temp != 0.0:
if IS_DRAFTING:
pos = pos + _DRAFT_NOISE_SALT
gumbel_seed = tl.randint(seed, pos)
if USE_FP64:
u = tl_rand64(gumbel_seed, keys, includes_zero=False)
u = murmur3_uniform64(seed, pos, keys)
gumbel_noise = -tl.log(-tl.log(u))
else:
u = tl_rand32(gumbel_seed, keys, includes_zero=False)
# log1p keeps the winning tail at u -> 0, where fp32 resolves it.
gumbel_noise = -tl.log(-tldevice.log1p(-u))
u = murmur3_uniform32(seed, pos, keys)
# Draw the large-noise tail (which decides the argmax winner) from
# u -> 0, where fp32 has fine resolution. Avoid backend-specific
# log1p while preserving precision in the winning tail.
gumbel_noise = -tl.log(-_log1p_neg_stable(u))
logits = tl.where(mask, logits + gumbel_noise, float("-inf"))
return tl.max(logits, axis=0, return_indices=True)