Merge remote-tracking branch 'upstream/main' into patches
This commit is contained in:
@@ -34,9 +34,9 @@ from typing import Any, ClassVar, TypeVar
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.compilation.cudagraph_pool import capture_pool
|
||||
from vllm.compilation.monitor import validate_cudagraph_capturing_enabled
|
||||
from vllm.config import CUDAGraphMode, VllmConfig
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id
|
||||
from vllm.forward_context import (
|
||||
BatchDescriptor,
|
||||
get_forward_context,
|
||||
@@ -370,11 +370,6 @@ class BreakableCUDAGraphWrapper:
|
||||
|
||||
entry.input_addresses = self._collect_tensor_addresses(args, kwargs)
|
||||
|
||||
if self.graph_pool is not None:
|
||||
set_graph_pool_id(self.graph_pool)
|
||||
else:
|
||||
set_graph_pool_id(current_platform.graph_pool_handle())
|
||||
|
||||
# Match torch.cuda.graph()'s pre-capture cleanup, which we bypass.
|
||||
# Skip it when gc is disabled: bulk capture runs under
|
||||
# freeze_gc_for_cudagraph_capture, which already did this cleanup,
|
||||
@@ -386,8 +381,10 @@ class BreakableCUDAGraphWrapper:
|
||||
# pre-capture prefetches are complete and don't leak into the graph.
|
||||
get_offloader().sync_prev_onload()
|
||||
|
||||
capture = BreakableCUDAGraphCapture(pool=self.graph_pool)
|
||||
with capture:
|
||||
with (
|
||||
capture_pool(self.graph_pool, self.vllm_config) as pool,
|
||||
BreakableCUDAGraphCapture(pool=pool) as capture,
|
||||
):
|
||||
output = self.runnable(*args, **kwargs)
|
||||
# Join the offloader's copy stream while we still hold the last
|
||||
# segment open, so the join is captured into the graph (otherwise
|
||||
|
||||
@@ -13,9 +13,9 @@ from unittest.mock import patch
|
||||
import torch
|
||||
|
||||
from vllm.compilation.counter import compilation_counter
|
||||
from vllm.compilation.cudagraph_pool import capture_pool
|
||||
from vllm.compilation.monitor import validate_cudagraph_capturing_enabled
|
||||
from vllm.config import CUDAGraphMode, VllmConfig
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id
|
||||
from vllm.forward_context import (
|
||||
BatchDescriptor,
|
||||
get_forward_context,
|
||||
@@ -302,10 +302,9 @@ class CUDAGraphWrapper:
|
||||
)
|
||||
)
|
||||
|
||||
if self.graph_pool is not None:
|
||||
set_graph_pool_id(self.graph_pool)
|
||||
else:
|
||||
set_graph_pool_id(current_platform.graph_pool_handle())
|
||||
graph_pool = stack.enter_context(
|
||||
capture_pool(self.graph_pool, self.vllm_config)
|
||||
)
|
||||
|
||||
# Sync offloader's copy stream before capture.
|
||||
# Ensure any pre-capture prefetches from offloader are complete.
|
||||
@@ -314,7 +313,7 @@ class CUDAGraphWrapper:
|
||||
# mind-exploding: carefully manage the reference and memory.
|
||||
with torch.cuda.graph(
|
||||
cudagraph,
|
||||
pool=self.graph_pool,
|
||||
pool=graph_pool,
|
||||
stream=current_stream(),
|
||||
):
|
||||
# `output` is managed by pytorch's cudagraph pool
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Graph pool routing for CUDA graph capture under sleep mode."""
|
||||
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from typing import TYPE_CHECKING, cast
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.device_allocator import get_mem_allocator_instance
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.device_allocator.cumem import CuMemAllocator
|
||||
|
||||
_outside_cumem: ContextVar[bool] = ContextVar("capture_outside_cumem", default=False)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def capture_outside_cumem_pool() -> Iterator[None]:
|
||||
"""CUDA graphs captured here stay out of cuMem, so that memory profiling can
|
||||
free its throwaway graphs normally."""
|
||||
token = _outside_cumem.set(True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_outside_cumem.reset(token)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def capture_pool(
|
||||
pool: tuple[int, int] | None, vllm_config: VllmConfig
|
||||
) -> Iterator[tuple[int, int] | None]:
|
||||
"""Yield the pool to capture into, the cuMem graph pool when sleep offloads
|
||||
graph memory, and point NCCL's graph allocator at it."""
|
||||
if vllm_config.use_cumem_cudagraph_pool and not _outside_cumem.get():
|
||||
allocator = cast("CuMemAllocator", get_mem_allocator_instance())
|
||||
with allocator.cudagraph_pool() as cumem_pool:
|
||||
set_graph_pool_id(cumem_pool)
|
||||
yield cumem_pool
|
||||
else:
|
||||
set_graph_pool_id(pool or current_platform.graph_pool_handle())
|
||||
yield pool
|
||||
@@ -111,6 +111,8 @@ LayerBlockType = Literal["attention", "linear_attention", "mamba"]
|
||||
_ATTENTION_LAYER_TYPES = frozenset(
|
||||
{
|
||||
"full_attention",
|
||||
"indexed_attention",
|
||||
# TODO: Delete below once Transformers 5.18.0 is the minimum required version.
|
||||
"deepseek_sparse_attention",
|
||||
"qwen_sparse_attention",
|
||||
}
|
||||
@@ -376,6 +378,9 @@ class ModelConfig:
|
||||
(default) uses the built-in ``CuMemAllocator`` and is behavior-compatible
|
||||
with prior releases. Additional backends (CUDA checkpoint, CRIU, durable
|
||||
snapshot) may be registered in-tree or by plugins (RFC #34303)."""
|
||||
sleep_mode_offload_cudagraph: bool = False
|
||||
"""Back up CUDA graph memory to CPU during sleep, restored in place on wake.
|
||||
Takes effect with enable_sleep_mode, the cumem backend and CUDA graphs."""
|
||||
enable_nccl_comm_suspend: bool = False
|
||||
"""Enable releasing NCCL communicator memory during sleep mode
|
||||
(``ncclCommSuspend``/``ncclCommResume``). Experimental; when disabled
|
||||
|
||||
@@ -960,7 +960,7 @@ class SpeculativeConfig:
|
||||
"architectures": [architecture],
|
||||
}
|
||||
)
|
||||
if hf_config.model_type in ("longcat_flash", "longcat_flash_ngram"):
|
||||
if hf_config.model_type == "longcat_flash":
|
||||
hf_config.model_type = "longcat_flash_mtp"
|
||||
n_predict = getattr(hf_config, "num_nextn_predict_layers", 1)
|
||||
hf_config.update(
|
||||
|
||||
@@ -704,6 +704,21 @@ class VllmConfig:
|
||||
"""
|
||||
return 1 + self.num_speculative_tokens
|
||||
|
||||
@property
|
||||
def use_cumem_cudagraph_pool(self) -> bool:
|
||||
"""Whether CUDA graphs go to the cuMem pool that sleep offloads."""
|
||||
from vllm.platforms import current_platform
|
||||
|
||||
model_config = self.model_config
|
||||
return (
|
||||
model_config is not None
|
||||
and model_config.sleep_mode_offload_cudagraph
|
||||
and model_config.enable_sleep_mode
|
||||
and model_config.sleep_mode_backend == "cumem"
|
||||
and self.compilation_config.cudagraph_mode != CUDAGraphMode.NONE
|
||||
and current_platform.is_cuda()
|
||||
)
|
||||
|
||||
@property
|
||||
def use_v2_model_runner(self) -> bool:
|
||||
if self.attention_config.hisparse_config is not None:
|
||||
@@ -2328,6 +2343,14 @@ class VllmConfig:
|
||||
custom_ops.append("+quant_fp8")
|
||||
|
||||
self._verify_kv_transfer_compat()
|
||||
if self.use_cumem_cudagraph_pool:
|
||||
# NCCL graph registration pins the offloaded pool; workers inherit this.
|
||||
value = os.environ.setdefault("NCCL_GRAPH_REGISTER", "0")
|
||||
if value != "0":
|
||||
logger.warning(
|
||||
"NCCL_GRAPH_REGISTER=%s pins the CUDA graph pool during sleep.",
|
||||
value,
|
||||
)
|
||||
# Log the custom passes that are enabled
|
||||
self.compilation_config.pass_config.log_enabled_passes()
|
||||
|
||||
|
||||
@@ -430,6 +430,23 @@ class CuMemAllocator:
|
||||
if allocation["allocated_size"] == 0 and data and not data.is_asleep:
|
||||
unmap_and_release(self._python_free_callback(allocation["address"]))
|
||||
|
||||
@contextmanager
|
||||
def cudagraph_pool(self) -> Iterator[tuple[int, int]]:
|
||||
"""Tag CUDA graph capture allocations and yield the graph pool id."""
|
||||
if "cudagraph" not in self.allocator_and_pools:
|
||||
allocator = get_pluggable_allocator(
|
||||
self.python_malloc_callback, self.python_free_callback
|
||||
)
|
||||
mem_pool = torch.cuda.memory.MemPool(allocator._allocator)
|
||||
self.allocator_and_pools["cudagraph"] = [(mem_pool, allocator)]
|
||||
old_tag = self.current_tag
|
||||
self.current_tag = "cudagraph"
|
||||
try:
|
||||
# capture_begin routes allocations to this pool; no use_mem_pool.
|
||||
yield self.allocator_and_pools["cudagraph"][0][0].id
|
||||
finally:
|
||||
self.current_tag = old_tag
|
||||
|
||||
def get_current_usage(self) -> int:
|
||||
"""Get the total number of bytes allocated in the memory pool."""
|
||||
sum_bytes: int = 0
|
||||
|
||||
@@ -129,8 +129,11 @@ class CuMemBackend(SleepModeBackend):
|
||||
|
||||
self._state = "SUSPENDED"
|
||||
allocator = get_mem_allocator_instance()
|
||||
# Runtime state is kept at every level; weights only at level 1.
|
||||
offload_tags = ("weights", "runtime") if level == 1 else ("runtime",)
|
||||
# Runtime state and graph pools are kept at every level; weights only
|
||||
# at level 1.
|
||||
offload_tags: tuple[str, ...] = ("runtime", "cudagraph")
|
||||
if level == 1:
|
||||
offload_tags = ("weights", *offload_tags)
|
||||
allocator.sleep(offload_tags=offload_tags)
|
||||
|
||||
def resume(self, tags: list[str] | None = None) -> None:
|
||||
|
||||
@@ -7,6 +7,7 @@ from torch.distributed import ProcessGroup
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm._aiter_ops import rocm_aiter_ops
|
||||
from vllm.config import get_current_vllm_config_or_none
|
||||
from vllm.distributed.device_communicators.all_reduce_utils import (
|
||||
NCCL_SYMM_MEM_ALL_REDUCE_CONFIG,
|
||||
should_nccl_symm_mem_ag_rs,
|
||||
@@ -114,6 +115,10 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
self.aiter_ar_comm: AiterCustomAllreduce | None = None
|
||||
self.use_aiter_ag_rs: bool = False
|
||||
|
||||
# cuMem graph buffers cannot be IPC-registered; capture copies them instead.
|
||||
config = get_current_vllm_config_or_none()
|
||||
register = config is None or not config.use_cumem_cudagraph_pool
|
||||
|
||||
if use_torch_symm_mem and current_platform.is_cuda():
|
||||
self.symm_mem_comm = SymmMemCommunicator(
|
||||
group=self.cpu_group,
|
||||
@@ -151,6 +156,7 @@ class CudaCommunicator(DeviceCommunicatorBase):
|
||||
symm_mem_enabled=(
|
||||
self.symm_mem_comm is not None and not self.symm_mem_comm.disabled
|
||||
),
|
||||
register_graph_buffers=register,
|
||||
)
|
||||
|
||||
# AITER custom all-gather/reduce-scatter DP-attention dispatch/combine
|
||||
|
||||
@@ -147,18 +147,22 @@ class CustomAllreduce:
|
||||
_DEFAULT_MNNVL_MULTIMEM_REDUCE_SCATTER_MAX_SIZE
|
||||
),
|
||||
symm_mem_enabled=False,
|
||||
*,
|
||||
register_graph_buffers: bool = True,
|
||||
) -> None:
|
||||
"""Args:
|
||||
group: the process group to work on. If None, it will use the
|
||||
default process group.
|
||||
device: the device to bind the CustomAllreduce to. If None,
|
||||
it will be bound to f"cuda:{local_rank}".
|
||||
register_graph_buffers: whether graph capture IPC-registers its buffers.
|
||||
It is the caller's responsibility to make sure each communicator
|
||||
is bind to a unique device, and all communicators in this group
|
||||
are in the same node.
|
||||
|
||||
"""
|
||||
self._IS_CAPTURING = False
|
||||
self._capture_registered = register_graph_buffers
|
||||
self._ptr = 0
|
||||
self.disabled = True
|
||||
self.mnnvl_buffer = None
|
||||
@@ -549,7 +553,7 @@ class CustomAllreduce:
|
||||
return None
|
||||
if self._IS_CAPTURING:
|
||||
if torch.cuda.is_current_stream_capturing():
|
||||
return self.all_reduce(input, registered=True)
|
||||
return self.all_reduce(input, registered=self._capture_registered)
|
||||
else:
|
||||
# If warm up, mimic the allocation pattern since custom
|
||||
# allreduce is out-of-place.
|
||||
|
||||
@@ -17,7 +17,7 @@ from vllm.config.compilation import PassConfig
|
||||
from vllm.distributed.device_communicators.all_reduce_utils import (
|
||||
FI_MNNVL_ALLREDUCE_MAX_SIZE_MB,
|
||||
)
|
||||
from vllm.distributed.parallel_state import _node_count, get_node_count
|
||||
from vllm.distributed.parallel_state import _node_count
|
||||
from vllm.logger import init_logger
|
||||
from vllm.platforms import current_platform
|
||||
from vllm.utils.gpu_sync_debug import gpu_sync_allowed
|
||||
@@ -140,14 +140,13 @@ def _create_workspace(
|
||||
return workspace
|
||||
|
||||
|
||||
def _resolve_fi_ar_backend() -> tuple[str, bool]:
|
||||
def _resolve_fi_ar_backend(group: ProcessGroup) -> tuple[str | None, bool]:
|
||||
"""Resolve the flashinfer allreduce backend for the current setup.
|
||||
|
||||
Returns:
|
||||
A ``(backend, allow_trtllm_fallback)`` tuple. ``allow_trtllm_fallback``
|
||||
is True only when ``auto`` selects mnnvl for a single node, so that
|
||||
workspace creation can fall back to trtllm on single-node topologies
|
||||
without NVSwitch multicast support (where mnnvl is unavailable).
|
||||
A ``(backend, allow_trtllm_fallback)`` tuple. ``backend`` is ``None``
|
||||
when automatic selection has no supported backend for the process
|
||||
group.
|
||||
|
||||
"""
|
||||
backend = envs.VLLM_FLASHINFER_ALLREDUCE_BACKEND
|
||||
@@ -155,15 +154,23 @@ def _resolve_fi_ar_backend() -> tuple[str, bool]:
|
||||
logger.debug_once("Using flashinfer allreduce backend: %s", backend)
|
||||
return backend, False
|
||||
|
||||
# Default to mnnvl for both single- and multi-node setups. The mnnvl
|
||||
# cudagraph hang that previously forced single-node to trtllm
|
||||
# (https://github.com/vllm-project/vllm/issues/35772) was fixed upstream in
|
||||
# FlashInfer (>= 0.6.12, vLLM pins 0.6.15), so mnnvl is safe here. trtllm
|
||||
# does not support multi-node allreduce, so mnnvl is required there anyway.
|
||||
# mnnvl needs NVSwitch multicast; on single-node topologies without it,
|
||||
# fall back to trtllm so fused allreduce stays enabled.
|
||||
backend = "mnnvl"
|
||||
allow_trtllm_fallback = get_node_count() == 1
|
||||
node_count = _node_count(group)
|
||||
if node_count == 1:
|
||||
# TRTLLM supports single-node allreduce on Hopper and Blackwell. Do not
|
||||
# create an MNNVL workspace when the process group is node-local.
|
||||
backend = "trtllm"
|
||||
allow_trtllm_fallback = False
|
||||
elif current_platform.has_device_capability(100):
|
||||
# MNNVL requires Blackwell-class GPUs and is the only supported
|
||||
# FlashInfer backend for a multi-node allreduce process group.
|
||||
backend = "mnnvl"
|
||||
allow_trtllm_fallback = False
|
||||
else:
|
||||
logger.debug_once(
|
||||
"FlashInfer allreduce fusion is disabled: multi-node process groups "
|
||||
"require an MNNVL-capable Blackwell system."
|
||||
)
|
||||
return None, False
|
||||
|
||||
logger.debug_once("Auto-selected flashinfer allreduce backend: %s", backend)
|
||||
return backend, allow_trtllm_fallback
|
||||
@@ -187,9 +194,12 @@ def get_fi_ar_workspace(
|
||||
if _fi_ar_workspace is not None or _fi_ar_workspace_failed:
|
||||
return _fi_ar_workspace
|
||||
|
||||
backend, allow_trtllm_fallback = _resolve_fi_ar_backend()
|
||||
backend, allow_trtllm_fallback = _resolve_fi_ar_backend(group)
|
||||
|
||||
if get_node_count() > 1 and backend == "trtllm":
|
||||
if backend is None:
|
||||
return None
|
||||
|
||||
if backend == "trtllm" and _node_count(group) > 1:
|
||||
raise ValueError(
|
||||
"Flashinfer allreduce is not supported for multi-node allreduce with "
|
||||
"'trtllm' backend. Please use 'mnnvl' backend instead."
|
||||
@@ -253,9 +263,12 @@ def get_fi_ar_quant_workspace(
|
||||
if _fi_ar_quant_workspace is not None or _fi_ar_quant_workspace_failed:
|
||||
return _fi_ar_quant_workspace
|
||||
|
||||
backend, allow_trtllm_fallback = _resolve_fi_ar_backend()
|
||||
backend, allow_trtllm_fallback = _resolve_fi_ar_backend(group)
|
||||
|
||||
if get_node_count() > 1 and backend == "trtllm":
|
||||
if backend is None:
|
||||
return None
|
||||
|
||||
if backend == "trtllm" and _node_count(group) > 1:
|
||||
raise ValueError(
|
||||
"Flashinfer allreduce quantization fusion is not supported for "
|
||||
"multi-node allreduce with 'trtllm' backend. Please use 'mnnvl' "
|
||||
@@ -397,7 +410,13 @@ class FlashInferAllReduce:
|
||||
self.world_size,
|
||||
)
|
||||
return
|
||||
backend, _ = _resolve_fi_ar_backend()
|
||||
backend, _ = _resolve_fi_ar_backend(self.group)
|
||||
if backend is None:
|
||||
logger.info(
|
||||
"FlashInfer All Reduce is disabled because no supported backend "
|
||||
"is available for this process group."
|
||||
)
|
||||
return
|
||||
tuned_max_size = _get_tuned_standalone_max_size(
|
||||
self.world_size,
|
||||
backend,
|
||||
|
||||
@@ -770,6 +770,7 @@ class EngineArgs:
|
||||
|
||||
generation_config: str = ModelConfig.generation_config
|
||||
enable_sleep_mode: bool = ModelConfig.enable_sleep_mode
|
||||
sleep_mode_offload_cudagraph: bool = ModelConfig.sleep_mode_offload_cudagraph
|
||||
sleep_preserve_parameter_names: list[str] = get_field(
|
||||
ModelConfig, "sleep_preserve_parameter_names"
|
||||
)
|
||||
@@ -1007,6 +1008,10 @@ class EngineArgs:
|
||||
model_group.add_argument(
|
||||
"--enable-sleep-mode", **model_kwargs["enable_sleep_mode"]
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--sleep-mode-offload-cudagraph",
|
||||
**model_kwargs["sleep_mode_offload_cudagraph"],
|
||||
)
|
||||
model_group.add_argument(
|
||||
"--sleep-preserve-parameter-names",
|
||||
**model_kwargs["sleep_preserve_parameter_names"],
|
||||
@@ -1984,6 +1989,7 @@ class EngineArgs:
|
||||
generation_config=self.generation_config,
|
||||
override_generation_config=self.override_generation_config,
|
||||
enable_sleep_mode=self.enable_sleep_mode,
|
||||
sleep_mode_offload_cudagraph=self.sleep_mode_offload_cudagraph,
|
||||
sleep_preserve_parameter_names=self.sleep_preserve_parameter_names,
|
||||
enable_cumem_allocator=self.enable_cumem_allocator,
|
||||
enable_nccl_comm_suspend=self.enable_nccl_comm_suspend,
|
||||
|
||||
@@ -631,6 +631,8 @@ class OpenAIServingChat(GenerateBaseServing):
|
||||
if finish_reason_sent[i]:
|
||||
continue
|
||||
|
||||
self._raise_if_error(output.finish_reason, request_id)
|
||||
|
||||
if request.logprobs and (
|
||||
request.top_logprobs is not None or request.logprob_token_ids
|
||||
):
|
||||
@@ -758,10 +760,6 @@ class OpenAIServingChat(GenerateBaseServing):
|
||||
|
||||
# if the model is finished generating
|
||||
else:
|
||||
# check for error finish reason and abort streaming
|
||||
# finish_reason='error' indicates a retryable error
|
||||
self._raise_if_error(output.finish_reason, request_id)
|
||||
|
||||
# Send the finish response for each request.n only once
|
||||
# In OpenAI's API, when a tool is called, the
|
||||
# finish_reason is:
|
||||
|
||||
@@ -326,6 +326,8 @@ class OpenAIServingCompletion(GenerateBaseServing):
|
||||
|
||||
for output in res.outputs:
|
||||
i = output.index + prompt_idx * num_choices
|
||||
finish_reason = output.finish_reason
|
||||
self._raise_if_error(finish_reason, request_id)
|
||||
|
||||
# Useful when request.return_token_ids is True
|
||||
# Returning prompt token IDs shares the same logic
|
||||
@@ -392,11 +394,8 @@ class OpenAIServingCompletion(GenerateBaseServing):
|
||||
|
||||
previous_text_lens[i] += len(delta_text)
|
||||
previous_num_tokens[i] += len(output.token_ids)
|
||||
finish_reason = output.finish_reason
|
||||
stop_reason = output.stop_reason
|
||||
|
||||
self._raise_if_error(finish_reason, request_id)
|
||||
|
||||
chunk = CompletionStreamResponse(
|
||||
id=request_id,
|
||||
object="text_completion",
|
||||
|
||||
@@ -656,6 +656,11 @@ class HarmonyContext(ConversationContext):
|
||||
|
||||
self.last_append_segments: list[Segment] = []
|
||||
self.last_append_flush_status: bool = False
|
||||
# Each completed message with the items sent for it in
|
||||
# output_item.done events, so the final response can reuse their ids.
|
||||
self.streamed_items_by_message: list[
|
||||
tuple[Message, list[ResponseOutputItem]]
|
||||
] = []
|
||||
|
||||
# Turn tracking - replaces multiple individual tracking variables
|
||||
self.current_turn_metrics = TurnMetrics()
|
||||
|
||||
@@ -12,6 +12,7 @@ from typing import Any, Final, cast
|
||||
from fastapi import Request
|
||||
from openai.types.responses import (
|
||||
ResponseOutputItem,
|
||||
ResponseOutputItemDoneEvent,
|
||||
ResponseOutputMessage,
|
||||
ResponseOutputText,
|
||||
ResponseStatus,
|
||||
@@ -68,6 +69,7 @@ from vllm.entrypoints.openai.responses.utils import (
|
||||
build_response_output_items,
|
||||
extract_function_tool_names,
|
||||
extract_tool_types,
|
||||
reuse_streamed_item_ids,
|
||||
)
|
||||
from vllm.entrypoints.serve.engine.protocol import ErrorResponse
|
||||
from vllm.entrypoints.serve.utils.api_utils import get_max_tokens
|
||||
@@ -781,17 +783,21 @@ class OpenAIServingResponses(GenerateBaseServing):
|
||||
assert isinstance(context, HarmonyContext)
|
||||
output = []
|
||||
harmony_msgs = context.messages[context.num_init_messages :]
|
||||
if harmony_msgs:
|
||||
fn_names = context.function_tool_names
|
||||
for msg in harmony_msgs[:-1]:
|
||||
output.extend(harmony_to_response_output(msg, fn_names))
|
||||
output.extend(
|
||||
harmony_to_response_output(
|
||||
harmony_msgs[-1],
|
||||
fn_names,
|
||||
incomplete=context.last_append_flush_status,
|
||||
)
|
||||
# Streamed messages are a subsequence of harmony_msgs, in order.
|
||||
streamed = iter(context.streamed_items_by_message)
|
||||
next_streamed = next(streamed, None)
|
||||
for i, msg in enumerate(harmony_msgs):
|
||||
items = harmony_to_response_output(
|
||||
msg,
|
||||
context.function_tool_names,
|
||||
incomplete=(
|
||||
i == len(harmony_msgs) - 1 and context.last_append_flush_status
|
||||
),
|
||||
)
|
||||
if next_streamed is not None and next_streamed[0] is msg:
|
||||
reuse_streamed_item_ids(items, next_streamed[1])
|
||||
next_streamed = next(streamed, None)
|
||||
output.extend(items)
|
||||
|
||||
if request.enable_response_messages:
|
||||
input_messages = context.messages[: context.num_init_messages]
|
||||
@@ -1291,16 +1297,24 @@ class OpenAIServingResponses(GenerateBaseServing):
|
||||
yield _increment_sequence_number_and_return(event)
|
||||
|
||||
elif completed_message := segment.completed_message:
|
||||
done_items: list[ResponseOutputItem] = []
|
||||
# TODO: Fix browser emitted as MCP calls
|
||||
for event in emit_previous_item_done_events(
|
||||
completed_message, state, ctx.function_tool_names
|
||||
):
|
||||
if isinstance(event, ResponseOutputItemDoneEvent):
|
||||
done_items.append(event.item)
|
||||
yield _increment_sequence_number_and_return(event)
|
||||
|
||||
for event in emit_tool_action_events(
|
||||
completed_message, state, self.tool_server
|
||||
):
|
||||
if isinstance(event, ResponseOutputItemDoneEvent):
|
||||
done_items.append(event.item)
|
||||
yield _increment_sequence_number_and_return(event)
|
||||
ctx.streamed_items_by_message.append(
|
||||
(completed_message, done_items)
|
||||
)
|
||||
state.reset_for_new_item()
|
||||
|
||||
async def responses_stream_generator(
|
||||
|
||||
@@ -202,7 +202,7 @@ def emit_reasoning_delta_events(
|
||||
events: list[StreamingResponsesResponse] = []
|
||||
if not state.sent_output_item_added:
|
||||
state.sent_output_item_added = True
|
||||
state.current_item_id = f"msg_{random_uuid()}"
|
||||
state.current_item_id = f"rs_{random_uuid()}"
|
||||
events.append(
|
||||
ResponseOutputItemAddedEvent(
|
||||
type="response.output_item.added",
|
||||
|
||||
@@ -112,6 +112,28 @@ def build_response_output_items(
|
||||
return outputs
|
||||
|
||||
|
||||
def reuse_streamed_item_ids(
|
||||
items: list[ResponseOutputItem],
|
||||
streamed_items: list[ResponseOutputItem],
|
||||
) -> None:
|
||||
"""Give rebuilt output items the ids already streamed for the same message.
|
||||
|
||||
Items are paired by type in order; an item without a streamed counterpart
|
||||
keeps its own id.
|
||||
"""
|
||||
remaining = list(streamed_items)
|
||||
for item in items:
|
||||
for i, streamed in enumerate(remaining):
|
||||
if streamed.type != item.type:
|
||||
continue
|
||||
item.id = streamed.id
|
||||
if isinstance(item, ResponseFunctionToolCall):
|
||||
assert isinstance(streamed, ResponseFunctionToolCall)
|
||||
item.call_id = streamed.call_id
|
||||
del remaining[i]
|
||||
break
|
||||
|
||||
|
||||
def should_continue_final_message(
|
||||
request_input: str | list[ResponseInputOutputItem],
|
||||
) -> bool:
|
||||
|
||||
@@ -516,11 +516,12 @@ class ServingTokens(GenerateBaseServing):
|
||||
request_metadata: RequestResponseMetadata,
|
||||
) -> AsyncGenerator[str, None]:
|
||||
num_prompt_tokens = 0
|
||||
num_generated_tokens: list[int] = []
|
||||
first_iteration = True
|
||||
prompt_token_ids: list[int] | None = None
|
||||
num_cached_tokens = None
|
||||
sampling_params: SamplingParams = request.sampling_params
|
||||
# With n > 1, the first output may not include every choice yet.
|
||||
num_generated_tokens = [0] * sampling_params.n
|
||||
last_res: RequestOutput | None = None
|
||||
text_mode = request.output_mode == "text"
|
||||
tokenizer = self._logprobs_tokenizer(text_mode)
|
||||
@@ -540,7 +541,6 @@ class ServingTokens(GenerateBaseServing):
|
||||
if res.encoder_prompt_token_ids is not None:
|
||||
num_prompt_tokens += len(res.encoder_prompt_token_ids)
|
||||
num_cached_tokens = res.num_cached_tokens
|
||||
num_generated_tokens = [0] * len(res.outputs)
|
||||
first_iteration = False
|
||||
|
||||
for output in res.outputs:
|
||||
@@ -551,21 +551,15 @@ class ServingTokens(GenerateBaseServing):
|
||||
finish_reason = output.finish_reason
|
||||
self._raise_if_error(finish_reason, request_id)
|
||||
|
||||
if text_mode:
|
||||
# Text held back for stop string matching is flushed
|
||||
# with the final output, and the abort output has no
|
||||
# new token IDs, so text or a finish reason is enough.
|
||||
emit = bool(
|
||||
delta_token_ids or output.text or finish_reason is not None
|
||||
)
|
||||
else:
|
||||
# Still emit a terminal empty chunk while prompt
|
||||
# metadata is pending, so zero-token completions
|
||||
# deliver it.
|
||||
emit = bool(delta_token_ids) or (
|
||||
finish_reason is not None and prompt_token_ids is not None
|
||||
)
|
||||
if not emit:
|
||||
# Terminal outputs are always emitted so the client sees
|
||||
# the finish reason, e.g. an abort, which has no new
|
||||
# tokens. Text mode also emits text held back for stop
|
||||
# string matching, which can arrive without token IDs.
|
||||
if not (
|
||||
delta_token_ids
|
||||
or finish_reason is not None
|
||||
or (text_mode and output.text)
|
||||
):
|
||||
continue
|
||||
|
||||
if sampling_params.logprobs is not None:
|
||||
|
||||
@@ -63,8 +63,12 @@ class BaseServing:
|
||||
):
|
||||
error_response = load_result
|
||||
|
||||
served_names = ", ".join(model.name for model in self.models.base_model_paths)
|
||||
return error_response or self.create_error_response(
|
||||
message=f"The model `{request.model}` does not exist.",
|
||||
message=(
|
||||
f"The model `{request.model}` does not exist. "
|
||||
f"Valid aliases: {served_names}."
|
||||
),
|
||||
err_type="NotFoundError",
|
||||
status_code=HTTPStatus.NOT_FOUND,
|
||||
param="model",
|
||||
|
||||
@@ -257,6 +257,7 @@ def do_shrink_kernel(
|
||||
output_d0_stride,
|
||||
output_d1_stride,
|
||||
output_d2_stride,
|
||||
output_split_stride,
|
||||
scaling,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
@@ -265,6 +266,7 @@ def do_shrink_kernel(
|
||||
SPLIT_K: tl.constexpr,
|
||||
SLICE_NUM: tl.constexpr,
|
||||
USE_GDC: tl.constexpr,
|
||||
STORE_PARTIALS: tl.constexpr,
|
||||
):
|
||||
"""Given an array of integers that identifies the rows of A, ram,
|
||||
a lora index that identifies which LoRA to use from lora_ptr, lora_index,
|
||||
@@ -324,17 +326,31 @@ def do_shrink_kernel(
|
||||
# Identify the C output pointers to store the results of the accumulator.
|
||||
offset_cn = tl.arange(0, BLOCK_N) + pid_n * BLOCK_N
|
||||
offset_cm = tl.arange(0, BLOCK_M)
|
||||
cur_out_ptr = out_ptr if SLICE_NUM == 1 else out_ptr + slice_id * output_d0_stride
|
||||
if STORE_PARTIALS:
|
||||
cur_out_ptr = (
|
||||
out_ptr
|
||||
+ slice_id.to(tl.int64) * output_d0_stride
|
||||
+ pid_sk.to(tl.int64) * output_split_stride
|
||||
)
|
||||
else:
|
||||
cur_out_ptr = (
|
||||
out_ptr if SLICE_NUM == 1 else out_ptr + slice_id * output_d0_stride
|
||||
)
|
||||
c_ptr = (
|
||||
cur_out_ptr
|
||||
+ ram[:, None] * output_d1_stride
|
||||
+ offset_cn[None, :] * output_d2_stride
|
||||
)
|
||||
c_mask = (offset_cm[:, None] < M_LEN) & (offset_cn[None, :] < N)
|
||||
accumulator *= scaling
|
||||
|
||||
# handles write-back with reduction-splitting
|
||||
if SPLIT_K == 1:
|
||||
if STORE_PARTIALS:
|
||||
# Unscaled FP32 partial per K split; the reducer adds the splits in a
|
||||
# fixed order and applies scaling once.
|
||||
tl.store(c_ptr, accumulator, mask=c_mask)
|
||||
else:
|
||||
tl.atomic_add(c_ptr, accumulator, mask=c_mask, sem="relaxed")
|
||||
accumulator *= scaling
|
||||
# handles write-back with reduction-splitting
|
||||
if SPLIT_K == 1:
|
||||
tl.store(c_ptr, accumulator, mask=c_mask)
|
||||
else:
|
||||
tl.atomic_add(c_ptr, accumulator, mask=c_mask, sem="relaxed")
|
||||
|
||||
@@ -13,11 +13,90 @@ from vllm.lora.ops.triton_ops.kernel_utils import do_shrink_kernel
|
||||
from vllm.lora.ops.triton_ops.utils import (
|
||||
_get_lora_a_ptr,
|
||||
get_lora_op_configs,
|
||||
is_batch_invariant,
|
||||
supports_pdl,
|
||||
)
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.torch_utils import direct_register_custom_op
|
||||
|
||||
# Batch-invariant shrink splits K into this many fixed partials (no atomics).
|
||||
_BI_SPLIT_K = 8
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _lora_shrink_reduce_kernel(
|
||||
partial_ptr,
|
||||
out_ptr,
|
||||
M,
|
||||
N: tl.constexpr,
|
||||
token_indices_sorted_by_lora_ids,
|
||||
num_tokens_per_lora,
|
||||
lora_token_start_loc,
|
||||
lora_ids,
|
||||
scaling,
|
||||
partial_d0_stride,
|
||||
partial_d1_stride,
|
||||
partial_d2_stride,
|
||||
partial_d3_stride,
|
||||
output_d0_stride,
|
||||
output_d1_stride,
|
||||
output_d2_stride,
|
||||
BLOCK_M: tl.constexpr,
|
||||
BLOCK_N: tl.constexpr,
|
||||
SPLIT_K: tl.constexpr,
|
||||
GROUP_SIZE_M: tl.constexpr,
|
||||
):
|
||||
cta_n_num = tl.cdiv(N, BLOCK_N)
|
||||
cta_m_num = tl.cdiv(M, BLOCK_M)
|
||||
pid_m_n = tl.program_id(axis=0)
|
||||
num_pid_in_group = GROUP_SIZE_M * cta_n_num
|
||||
group_id = pid_m_n // num_pid_in_group
|
||||
first_pid_m = group_id * GROUP_SIZE_M
|
||||
group_size_m = min(cta_m_num - first_pid_m, GROUP_SIZE_M)
|
||||
pid_m = first_pid_m + ((pid_m_n % num_pid_in_group) % group_size_m)
|
||||
pid_n = (pid_m_n % num_pid_in_group) // group_size_m
|
||||
|
||||
slice_id = tl.program_id(axis=1)
|
||||
lora_idx = tl.program_id(axis=2)
|
||||
lora_id = tl.load(lora_ids + lora_idx)
|
||||
if lora_id == -1:
|
||||
return
|
||||
|
||||
lora_m_size = tl.load(num_tokens_per_lora + lora_idx)
|
||||
cta_m_offset = pid_m * BLOCK_M
|
||||
if cta_m_offset >= lora_m_size:
|
||||
return
|
||||
|
||||
cta_m_len = min(BLOCK_M, lora_m_size - cta_m_offset)
|
||||
lora_m_indices_start = tl.load(lora_token_start_loc + lora_idx)
|
||||
cta_lora_seq_indices = (
|
||||
token_indices_sorted_by_lora_ids + lora_m_indices_start + cta_m_offset
|
||||
)
|
||||
offset_m = tl.arange(0, BLOCK_M) % cta_m_len
|
||||
ram = tl.load(cta_lora_seq_indices + offset_m)
|
||||
offset_n = tl.arange(0, BLOCK_N) + pid_n * BLOCK_N
|
||||
offset_cm = tl.arange(0, BLOCK_M)
|
||||
mask = (offset_cm[:, None] < cta_m_len) & (offset_n[None, :] < N)
|
||||
|
||||
accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
|
||||
for split_id in range(SPLIT_K):
|
||||
partial_in = (
|
||||
partial_ptr
|
||||
+ slice_id.to(tl.int64) * partial_d0_stride
|
||||
+ tl.cast(split_id, tl.int64) * partial_d1_stride
|
||||
+ ram[:, None] * partial_d2_stride
|
||||
+ offset_n[None, :] * partial_d3_stride
|
||||
)
|
||||
accumulator += tl.load(partial_in, mask=mask, other=0.0)
|
||||
|
||||
output = (
|
||||
out_ptr
|
||||
+ slice_id * output_d0_stride
|
||||
+ ram[:, None] * output_d1_stride
|
||||
+ offset_n[None, :] * output_d2_stride
|
||||
)
|
||||
tl.store(output, accumulator * scaling, mask=mask)
|
||||
|
||||
|
||||
@triton.jit
|
||||
def _lora_shrink_kernel(
|
||||
@@ -49,7 +128,15 @@ def _lora_shrink_kernel(
|
||||
SLICE_NUM: tl.constexpr,
|
||||
USE_GDC: tl.constexpr,
|
||||
launch_pdl: tl.constexpr,
|
||||
STORE_PARTIALS: tl.constexpr = False,
|
||||
output_split_stride=0,
|
||||
PARTIAL_N: tl.constexpr = 0,
|
||||
PARTIAL_K: tl.constexpr = 0,
|
||||
):
|
||||
if STORE_PARTIALS:
|
||||
# The split-K partial stage specializes on N and K.
|
||||
N = PARTIAL_N
|
||||
K = PARTIAL_K
|
||||
cta_n_num = tl.cdiv(N, BLOCK_N)
|
||||
cta_m_num = tl.cdiv(M, BLOCK_M)
|
||||
|
||||
@@ -116,6 +203,7 @@ def _lora_shrink_kernel(
|
||||
output_d0_stride,
|
||||
output_d1_stride,
|
||||
output_d2_stride,
|
||||
output_split_stride,
|
||||
scaling,
|
||||
BLOCK_M,
|
||||
BLOCK_N,
|
||||
@@ -124,6 +212,7 @@ def _lora_shrink_kernel(
|
||||
SPLIT_K,
|
||||
SLICE_NUM,
|
||||
USE_GDC,
|
||||
STORE_PARTIALS,
|
||||
)
|
||||
|
||||
|
||||
@@ -167,6 +256,23 @@ def _lora_shrink(
|
||||
|
||||
"""
|
||||
assert no_lora_flag_cpu.numel() == 1
|
||||
if inputs.size(0) == 0:
|
||||
# An empty first call has no work to do.
|
||||
return
|
||||
partials: torch.Tensor | None = None
|
||||
if is_batch_invariant:
|
||||
# Allocated before the no-LoRA return so profiling sees the scratch.
|
||||
# Per-call allocation keeps each CUDA graph's scratch in its own pool.
|
||||
partials = torch.empty(
|
||||
(
|
||||
output_tensor.size(0),
|
||||
_BI_SPLIT_K,
|
||||
inputs.size(0),
|
||||
output_tensor.size(-1),
|
||||
),
|
||||
dtype=torch.float32,
|
||||
device=output_tensor.device,
|
||||
)
|
||||
if no_lora_flag_cpu.item():
|
||||
# None of the inputs require LoRA.
|
||||
return
|
||||
@@ -213,6 +319,11 @@ def _lora_shrink(
|
||||
NUM_STAGES = kernel_config["num_stages"]
|
||||
NUM_CTAS = kernel_config["num_ctas"]
|
||||
GROUP_SIZE_M = kernel_config.get("group_size_m", 8)
|
||||
|
||||
# Every M must keep the same K partition for batch invariance.
|
||||
if partials is not None:
|
||||
BLOCK_K = 256
|
||||
SPLIT_K = _BI_SPLIT_K
|
||||
EVEN_K = K % (BLOCK_K * SPLIT_K) == 0 # type: ignore
|
||||
|
||||
# TODO (varun): This grid formulation maximizes parallelization at the
|
||||
@@ -225,11 +336,24 @@ def _lora_shrink(
|
||||
)
|
||||
|
||||
# PDL only works when dual-stream is being used.
|
||||
use_gdc = supports_pdl(inputs.device) and envs.VLLM_LORA_ENABLE_DUAL_STREAM
|
||||
use_gdc = (
|
||||
supports_pdl(inputs.device)
|
||||
and envs.VLLM_LORA_ENABLE_DUAL_STREAM
|
||||
and partials is None
|
||||
)
|
||||
first_out = output_tensor if partials is None else partials
|
||||
partial_args = {}
|
||||
if partials is not None:
|
||||
partial_args = dict(
|
||||
STORE_PARTIALS=True,
|
||||
output_split_stride=partials.stride(1),
|
||||
PARTIAL_N=N,
|
||||
PARTIAL_K=K,
|
||||
)
|
||||
_lora_shrink_kernel[grid](
|
||||
inputs,
|
||||
lora_ptr_tensor,
|
||||
output_tensor,
|
||||
first_out,
|
||||
M,
|
||||
N,
|
||||
K,
|
||||
@@ -243,9 +367,9 @@ def _lora_shrink(
|
||||
lora_strides_d0,
|
||||
lora_strides_d1,
|
||||
lora_strides_d2,
|
||||
output_tensor.stride(0),
|
||||
output_tensor.stride(1),
|
||||
output_tensor.stride(2),
|
||||
first_out.stride(0),
|
||||
first_out.stride(-2),
|
||||
first_out.stride(-1),
|
||||
BLOCK_M,
|
||||
BLOCK_N,
|
||||
BLOCK_K,
|
||||
@@ -258,7 +382,28 @@ def _lora_shrink(
|
||||
num_ctas=NUM_CTAS,
|
||||
num_stages=NUM_STAGES,
|
||||
launch_pdl=use_gdc,
|
||||
**partial_args,
|
||||
)
|
||||
if partials is not None:
|
||||
_lora_shrink_reduce_kernel[(grid[0] // SPLIT_K, *grid[1:])](
|
||||
partials,
|
||||
output_tensor,
|
||||
M,
|
||||
N,
|
||||
token_indices_sorted_by_lora_ids,
|
||||
num_tokens_per_lora,
|
||||
lora_token_start_loc,
|
||||
lora_ids,
|
||||
scaling,
|
||||
*partials.stride(),
|
||||
*output_tensor.stride(),
|
||||
BLOCK_M,
|
||||
BLOCK_N,
|
||||
SPLIT_K,
|
||||
GROUP_SIZE_M,
|
||||
num_warps=NUM_WARPS,
|
||||
num_stages=NUM_STAGES,
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
@@ -918,7 +918,7 @@ def mean_batch_invariant(input, dim, keepdim=False, dtype: torch.dtype | None =
|
||||
for d in sorted_dims:
|
||||
result = result.squeeze(d)
|
||||
|
||||
return result
|
||||
return result if dtype is not None else result.to(input.dtype)
|
||||
|
||||
|
||||
@triton.jit
|
||||
|
||||
@@ -50,6 +50,19 @@ class LightOnOCRMultiModalProcessor(BaseMultiModalProcessor[LightOnOCRProcessing
|
||||
def _get_hf_mm_text(self, mm_counts: Mapping[str, int]) -> str:
|
||||
return self.dummy_inputs.get_dummy_text(mm_counts)
|
||||
|
||||
def _call_hf_processor(
|
||||
self,
|
||||
hf_data: Mapping[str, object],
|
||||
hf_kwargs: Mapping[str, object],
|
||||
) -> BatchFeature:
|
||||
# The checkpoint sets `do_pad: null`, which disables padding since
|
||||
# Transformers v5.18, so images of different sizes cannot be stacked.
|
||||
return self.info.ctx.call_hf_processor(
|
||||
self.info.get_hf_processor(**hf_kwargs),
|
||||
hf_data,
|
||||
{**hf_kwargs, "do_pad": True},
|
||||
)
|
||||
|
||||
def _postprocess_hf_mm_data(
|
||||
self,
|
||||
mm_data: Mapping[str, object],
|
||||
|
||||
@@ -39,7 +39,7 @@ from itertools import islice
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers import PreTrainedConfig
|
||||
from transformers import LongcatFlashConfig
|
||||
|
||||
from vllm.compilation.decorators import support_torch_compile
|
||||
from vllm.config import CacheConfig, VllmConfig
|
||||
@@ -80,121 +80,6 @@ from .utils import (
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class FlashConfig(PreTrainedConfig):
|
||||
"""Flash model configuration."""
|
||||
|
||||
moe_intermediate_size: int
|
||||
|
||||
model_type = "longcat_flash"
|
||||
keys_to_ignore_at_inference = ["past_key_values"]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
vocab_size=131072,
|
||||
hidden_size=4096,
|
||||
intermediate_size=8192,
|
||||
num_layers=28,
|
||||
num_hidden_layers=None,
|
||||
num_attention_heads=96,
|
||||
num_key_value_heads=128,
|
||||
ep_size=1,
|
||||
kv_lora_rank=512,
|
||||
q_lora_rank=1536,
|
||||
qk_rope_head_dim=64,
|
||||
v_head_dim=128,
|
||||
qk_nope_head_dim=128,
|
||||
num_experts_per_tok=None,
|
||||
norm_topk_prob=False,
|
||||
max_position_embeddings=8192,
|
||||
initializer_range=0.02,
|
||||
rms_norm_eps=1e-05,
|
||||
use_cache=True,
|
||||
pad_token_id=None,
|
||||
bos_token_id=100000,
|
||||
eos_token_id=100001,
|
||||
pretraining_tp=1,
|
||||
tie_word_embeddings=False,
|
||||
rope_parameters=None,
|
||||
attention_bias=False,
|
||||
attention_dropout=0.0,
|
||||
mla_scale_q_lora=False,
|
||||
mla_scale_kv_lora=False,
|
||||
dtype="bfloat16",
|
||||
params_dtype="bfloat16",
|
||||
router_dtype="float32",
|
||||
router_bias=False,
|
||||
topk_method=None,
|
||||
routed_scaling_factor=1.0,
|
||||
zero_expert_num=0,
|
||||
zero_expert_type=None,
|
||||
nextn_use_scmoe=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
pad_token_id=pad_token_id,
|
||||
bos_token_id=bos_token_id,
|
||||
eos_token_id=eos_token_id,
|
||||
tie_word_embeddings=tie_word_embeddings,
|
||||
dtype=dtype,
|
||||
params_dtype=params_dtype,
|
||||
router_dtype=router_dtype,
|
||||
topk_method=topk_method,
|
||||
router_bias=router_bias,
|
||||
nextn_use_scmoe=nextn_use_scmoe,
|
||||
**kwargs,
|
||||
)
|
||||
self.vocab_size = vocab_size
|
||||
self.max_position_embeddings = max_position_embeddings
|
||||
self.hidden_size = hidden_size
|
||||
self.num_hidden_layers = (
|
||||
num_hidden_layers if num_hidden_layers is not None else num_layers
|
||||
)
|
||||
self.num_attention_heads = num_attention_heads
|
||||
self.ep_size = ep_size
|
||||
self.kv_lora_rank = kv_lora_rank
|
||||
self.q_lora_rank = q_lora_rank
|
||||
self.qk_rope_head_dim = qk_rope_head_dim
|
||||
self.v_head_dim = v_head_dim
|
||||
self.qk_nope_head_dim = qk_nope_head_dim
|
||||
self.num_experts_per_tok = num_experts_per_tok
|
||||
self.norm_topk_prob = norm_topk_prob
|
||||
# for backward compatibility
|
||||
if num_key_value_heads is None:
|
||||
num_key_value_heads = num_attention_heads
|
||||
|
||||
self.num_key_value_heads = num_key_value_heads
|
||||
self.initializer_range = initializer_range
|
||||
self.rms_norm_eps = rms_norm_eps
|
||||
self.pretraining_tp = pretraining_tp
|
||||
self.use_cache = use_cache
|
||||
# Try to set `rope_scaling` if available, otherwise use `rope_parameters`
|
||||
rope_scaling = kwargs.pop("rope_scaling", None)
|
||||
rope_parameters = rope_scaling or rope_parameters or {"rope_type": "default"}
|
||||
rope_theta = kwargs.pop("rope_theta", 1000000.0)
|
||||
if "rope_theta" not in rope_parameters:
|
||||
rope_parameters["rope_theta"] = rope_theta
|
||||
self.rope_parameters = rope_parameters
|
||||
self.attention_bias = attention_bias
|
||||
self.attention_dropout = attention_dropout
|
||||
self.mla_scale_q_lora = mla_scale_q_lora
|
||||
self.mla_scale_kv_lora = mla_scale_kv_lora
|
||||
self.zero_expert_num = zero_expert_num
|
||||
self.zero_expert_type = zero_expert_type
|
||||
self.routed_scaling_factor = routed_scaling_factor
|
||||
self.hidden_act = "silu"
|
||||
self.intermediate_size = (
|
||||
self.ffn_hidden_size
|
||||
if hasattr(self, "ffn_hidden_size")
|
||||
else intermediate_size
|
||||
)
|
||||
if hasattr(self, "moe_intermediate_size"):
|
||||
self.moe_intermediate_size = self.moe_intermediate_size
|
||||
elif hasattr(self, "expert_ffn_hidden_size"):
|
||||
self.moe_intermediate_size = self.expert_ffn_hidden_size
|
||||
else:
|
||||
self.moe_intermediate_size = self.intermediate_size
|
||||
|
||||
|
||||
class FlashMLP(nn.Module):
|
||||
"""Flash MLP layer."""
|
||||
|
||||
@@ -242,22 +127,17 @@ class FlashMLP(nn.Module):
|
||||
class LongcatRouter(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config: FlashConfig,
|
||||
config: LongcatFlashConfig,
|
||||
zero_expert_num: int,
|
||||
router_params_dtype: torch.dtype,
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
self.n_routed_experts = (
|
||||
config.n_routed_experts
|
||||
if hasattr(config, "n_routed_experts")
|
||||
else config.num_experts[0]
|
||||
)
|
||||
self.n_routed_experts = self.n_routed_experts + zero_expert_num
|
||||
self.n_routed_experts = config.n_routed_experts + zero_expert_num
|
||||
self.classifier = GateLinear(
|
||||
config.hidden_size,
|
||||
self.n_routed_experts,
|
||||
bias=config.router_bias,
|
||||
bias=False,
|
||||
out_dtype=router_params_dtype,
|
||||
params_dtype=router_params_dtype,
|
||||
prefix=f"{prefix}.classifier",
|
||||
@@ -274,7 +154,7 @@ class LongcatRouter(nn.Module):
|
||||
class LongcatMoe(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config: FlashConfig,
|
||||
config: LongcatFlashConfig,
|
||||
num_experts: int,
|
||||
top_k: int,
|
||||
hidden_size: int,
|
||||
@@ -286,10 +166,7 @@ class LongcatMoe(nn.Module):
|
||||
):
|
||||
super().__init__()
|
||||
self.hidden_size = hidden_size
|
||||
# Gate always runs at half / full precision for now.
|
||||
self.router_params_dtype = params_dtype
|
||||
if config.router_dtype == "float32":
|
||||
self.router_params_dtype = torch.float32
|
||||
self.router_params_dtype = torch.float32
|
||||
|
||||
self.router = LongcatRouter(
|
||||
config=config,
|
||||
@@ -354,7 +231,7 @@ class FlashDecoderLayer(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
config: FlashConfig,
|
||||
config: LongcatFlashConfig,
|
||||
cache_config: CacheConfig | None = None,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
prefix: str = "",
|
||||
@@ -376,9 +253,7 @@ class FlashDecoderLayer(nn.Module):
|
||||
qk_nope_head_dim=config.qk_nope_head_dim,
|
||||
qk_rope_head_dim=config.qk_rope_head_dim,
|
||||
v_head_dim=config.v_head_dim,
|
||||
q_lora_rank=(
|
||||
config.q_lora_rank if hasattr(config, "q_lora_rank") else None
|
||||
),
|
||||
q_lora_rank=config.q_lora_rank,
|
||||
kv_lora_rank=config.kv_lora_rank,
|
||||
max_position_embeddings=max_position_embeddings,
|
||||
cache_config=cache_config,
|
||||
@@ -415,12 +290,8 @@ class FlashDecoderLayer(nn.Module):
|
||||
|
||||
self.mlp = LongcatMoe(
|
||||
config=config,
|
||||
num_experts=config.n_routed_experts
|
||||
if hasattr(config, "n_routed_experts")
|
||||
else config.num_experts[self.layer_idx],
|
||||
top_k=config.moe_topk
|
||||
if hasattr(config, "moe_topk")
|
||||
else config.num_experts_per_tok,
|
||||
num_experts=config.n_routed_experts,
|
||||
top_k=config.moe_topk,
|
||||
hidden_size=config.hidden_size,
|
||||
intermediate_size=config.moe_intermediate_size,
|
||||
quant_config=quant_config,
|
||||
@@ -482,7 +353,7 @@ class FlashModel(nn.Module):
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
|
||||
config = vllm_config.model_config.hf_config
|
||||
cache_config = vllm_config.cache_config
|
||||
quant_config = vllm_config.quant_config
|
||||
self.config = config
|
||||
@@ -499,7 +370,7 @@ class FlashModel(nn.Module):
|
||||
else:
|
||||
self.embed_tokens = PPMissingLayer()
|
||||
self.start_layer, self.end_layer, self.layers = make_layers(
|
||||
config.num_hidden_layers,
|
||||
config.num_layers,
|
||||
lambda prefix: FlashDecoderLayer(
|
||||
vllm_config,
|
||||
config,
|
||||
@@ -561,9 +432,7 @@ class FlashModel(nn.Module):
|
||||
ckpt_gate_proj_name="gate_proj",
|
||||
ckpt_down_proj_name="down_proj",
|
||||
ckpt_up_proj_name="up_proj",
|
||||
num_experts=self.config.n_routed_experts
|
||||
if hasattr(self.config, "n_routed_experts")
|
||||
else self.config.num_experts[0],
|
||||
num_experts=self.config.n_routed_experts,
|
||||
)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
@@ -659,7 +528,7 @@ class FlashModel(nn.Module):
|
||||
)
|
||||
weight_loader(param, loaded_weight)
|
||||
loaded_params.add(name)
|
||||
for layer_id in range(self.config.num_hidden_layers):
|
||||
for layer_id in range(self.config.num_layers):
|
||||
for i in range(2):
|
||||
if isinstance(self.layers[layer_id], PPMissingLayer):
|
||||
continue
|
||||
@@ -727,15 +596,10 @@ class LongcatFlashForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
|
||||
super().__init__()
|
||||
config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
|
||||
config = vllm_config.model_config.hf_config
|
||||
quant_config = vllm_config.quant_config
|
||||
|
||||
self.config = config
|
||||
config.intermediate_size = (
|
||||
config.ffn_hidden_size
|
||||
if hasattr(config, "ffn_hidden_size")
|
||||
else config.intermediate_size
|
||||
)
|
||||
|
||||
self.quant_config = quant_config
|
||||
|
||||
|
||||
@@ -20,7 +20,6 @@ from vllm.model_executor.layers.vocab_parallel_embedding import (
|
||||
VocabParallelEmbedding,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
from vllm.model_executor.models.longcat_flash import FlashConfig
|
||||
from vllm.sequence import IntermediateTensors
|
||||
|
||||
from .deepseek_v2 import DeepseekV2DecoderLayer
|
||||
@@ -80,9 +79,9 @@ class LongCatMultiTokenPredictor(nn.Module):
|
||||
prefix: str = "",
|
||||
):
|
||||
super().__init__()
|
||||
config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
|
||||
vllm_config.model_config.hf_config.intermediate_size = config.intermediate_size
|
||||
self.mtp_start_layer_idx = config.num_hidden_layers * 2
|
||||
config = vllm_config.model_config.hf_config
|
||||
# TODO: Use `num_hidden_layers` once Transformers 5.18.0 is the minimum
|
||||
self.mtp_start_layer_idx = config.num_layers * 2
|
||||
self.num_mtp_layers = 1
|
||||
self.layers = torch.nn.ModuleDict(
|
||||
{
|
||||
@@ -130,7 +129,7 @@ class LongCatFlashMTP(nn.Module):
|
||||
# builds a dense MLP. object.__setattr__ bypasses the ngram remote
|
||||
# config's strict validation (it rejects setting the int field to None).
|
||||
object.__setattr__(vllm_config.model_config.hf_config, "n_routed_experts", None)
|
||||
self.config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
|
||||
self.config = vllm_config.model_config.hf_config
|
||||
self.quant_config = (
|
||||
None
|
||||
if "mtp" in getattr(self.config, "disable_quant_module", [])
|
||||
@@ -264,7 +263,7 @@ class LongCatFlashMTP(nn.Module):
|
||||
weight_loader = getattr(param, "weight_loader", default_weight_loader)
|
||||
weight_loader(param, loaded_weight)
|
||||
loaded_params.add(name)
|
||||
spec_layer_id = self.config.num_hidden_layers * 2
|
||||
spec_layer_id = self.model.mtp_start_layer_idx
|
||||
self_attn = self.model.layers[str(spec_layer_id)].mtp_block.self_attn
|
||||
if (
|
||||
self.quant_config is not None
|
||||
@@ -356,5 +355,5 @@ class LongCatFlashMTP(nn.Module):
|
||||
self, config: PreTrainedConfig, weight_name: str
|
||||
) -> int | None:
|
||||
if "model.mtp" in weight_name:
|
||||
return config.num_hidden_layers * 2
|
||||
return self.model.mtp_start_layer_idx
|
||||
return None
|
||||
|
||||
@@ -15,6 +15,7 @@ from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from transformers import LongcatFlashConfig
|
||||
|
||||
from vllm import _custom_ops as ops
|
||||
from vllm.config import VllmConfig
|
||||
@@ -30,15 +31,15 @@ from vllm.v1.worker.gpu.model_states.default import DefaultModelState
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
from .interfaces import SupportsLoRA, SupportsPP
|
||||
from .longcat_flash import FlashConfig, FlashModel
|
||||
from .longcat_flash import FlashModel
|
||||
from .utils import AutoWeightsLoader, PPMissingLayer, WeightsMapper, maybe_prefix
|
||||
|
||||
|
||||
def uses_ngram_embedding(config: FlashConfig) -> bool:
|
||||
def uses_ngram_embedding(config: LongcatFlashConfig) -> bool:
|
||||
return getattr(config, "ngram_vocab_size_ratio", None) is not None
|
||||
|
||||
|
||||
def _config_dtype(config: FlashConfig) -> torch.dtype:
|
||||
def _config_dtype(config: LongcatFlashConfig) -> torch.dtype:
|
||||
dt = getattr(config, "torch_dtype", None) or getattr(config, "dtype", None)
|
||||
if isinstance(dt, torch.dtype):
|
||||
return dt
|
||||
@@ -54,7 +55,7 @@ class NgramEmbedding(nn.Module):
|
||||
single ``bmm``. Hashing math is ported from the HF reference.
|
||||
"""
|
||||
|
||||
def __init__(self, config: FlashConfig, base_embeddings: nn.Module) -> None:
|
||||
def __init__(self, config: LongcatFlashConfig, base_embeddings: nn.Module) -> None:
|
||||
super().__init__()
|
||||
self.config = config
|
||||
self.word_embeddings = base_embeddings
|
||||
@@ -170,14 +171,6 @@ class FlashNgramModel(FlashModel):
|
||||
"""FlashModel whose input embedding is an :class:`NgramEmbedding`."""
|
||||
|
||||
def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
|
||||
# Each FlashDecoderLayer is a *dual* layer (2 attentions), so the number
|
||||
# of decoder layers is ``num_layers``. The ngram HF config sets
|
||||
# ``num_hidden_layers`` to a multiple of that (attention-module count),
|
||||
# which FlashModel would otherwise build as too many (dead) layers.
|
||||
hf = vllm_config.model_config.hf_config
|
||||
num_layers = getattr(hf, "num_layers", None)
|
||||
if num_layers is not None and hf.num_hidden_layers != num_layers:
|
||||
hf.num_hidden_layers = num_layers
|
||||
super().__init__(vllm_config=vllm_config, prefix=prefix)
|
||||
self.ngram_embeddings: NgramEmbedding | None
|
||||
if get_pp_group().is_first_rank and uses_ngram_embedding(self.config):
|
||||
@@ -222,10 +215,7 @@ class LongcatFlashNgramForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
|
||||
"V2 model runner for its n-gram embedding state; it is selected "
|
||||
"automatically unless VLLM_USE_V2_MODEL_RUNNER=0 is set."
|
||||
)
|
||||
config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
|
||||
config.intermediate_size = getattr(
|
||||
config, "ffn_hidden_size", config.intermediate_size
|
||||
)
|
||||
config = vllm_config.model_config.hf_config
|
||||
self.config = config
|
||||
self.quant_config = vllm_config.quant_config
|
||||
|
||||
|
||||
@@ -166,8 +166,7 @@ def xpu_sparse_decode_fp8(
|
||||
num_tokens = q.shape[0]
|
||||
device = q.device
|
||||
|
||||
# Determine max topk and swa widths
|
||||
if not swa_only and topk_indices is not None:
|
||||
if not swa_only and topk_indices is not None and kv_cache is not None:
|
||||
topk_idx_2d = (
|
||||
topk_indices.squeeze(1) if topk_indices.dim() == 3 else topk_indices
|
||||
)
|
||||
@@ -176,109 +175,57 @@ def xpu_sparse_decode_fp8(
|
||||
topk_idx_2d = None
|
||||
max_topk = 0
|
||||
|
||||
use_topk = topk_idx_2d is not None
|
||||
swa_idx_2d = swa_indices.squeeze(1) if swa_indices.dim() == 3 else swa_indices
|
||||
max_swa = swa_idx_2d.shape[1]
|
||||
|
||||
K_total = max_topk + max_swa
|
||||
|
||||
# Allocate flat workspace: [num_tokens * K_total, 512] bf16
|
||||
# Topk rows precede SWA rows in the flat workspace.
|
||||
n_topk_rows = num_tokens * max_topk
|
||||
workspace = torch.empty(
|
||||
(num_tokens * K_total, OUTPUT_DIM), dtype=torch.bfloat16, device=device
|
||||
)
|
||||
ws_3d = workspace.view(num_tokens, K_total, OUTPUT_DIM)
|
||||
|
||||
# Dequant+gather topk slots from compressed cache
|
||||
if not swa_only and topk_idx_2d is not None and kv_cache is not None:
|
||||
topk_flat = topk_idx_2d.reshape(-1).to(torch.int32)
|
||||
topk_buf = torch.empty(
|
||||
(num_tokens * max_topk, OUTPUT_DIM), dtype=torch.bfloat16, device=device
|
||||
if topk_idx_2d is not None and kv_cache is not None and n_topk_rows > 0:
|
||||
dequant_gather_slots(
|
||||
workspace[:n_topk_rows],
|
||||
kv_cache,
|
||||
topk_idx_2d.reshape(-1).to(torch.int32),
|
||||
kv_cache.shape[1],
|
||||
)
|
||||
compressed_block_size = kv_cache.shape[1]
|
||||
dequant_gather_slots(topk_buf, kv_cache, topk_flat, compressed_block_size)
|
||||
ws_3d[:, :max_topk, :] = topk_buf.view(num_tokens, max_topk, OUTPUT_DIM)
|
||||
|
||||
# Dequant+gather SWA slots
|
||||
swa_flat = swa_idx_2d.reshape(-1).to(torch.int32)
|
||||
swa_buf = torch.empty(
|
||||
(num_tokens * max_swa, OUTPUT_DIM), dtype=torch.bfloat16, device=device
|
||||
dequant_gather_slots(
|
||||
workspace[n_topk_rows:],
|
||||
swa_kv_cache,
|
||||
swa_idx_2d.reshape(-1).to(torch.int32),
|
||||
swa_kv_cache.shape[1],
|
||||
)
|
||||
swa_block_size = swa_kv_cache.shape[1]
|
||||
dequant_gather_slots(swa_buf, swa_kv_cache, swa_flat, swa_block_size)
|
||||
|
||||
ws_3d[:, max_topk:, :] = swa_buf.view(num_tokens, max_swa, OUTPUT_DIM)
|
||||
|
||||
# Build combined indices into the flat workspace and combined lengths.
|
||||
# Workspace layout per token t: [topk_0..topk_{max_topk-1}, swa_0..swa_{max_swa-1}]
|
||||
# Flat index for token t, position p = t * K_total + p
|
||||
#
|
||||
# IMPORTANT: The attention kernel uses combined_lens as a position cutoff —
|
||||
# it only reads indices[0..combined_lens-1]. So indices must be PACKED
|
||||
# contiguously: [valid_topk_indices..., valid_swa_indices..., -1 padding...]
|
||||
if not swa_only and topk_lens is not None:
|
||||
combined_lens = (topk_lens + swa_lens).to(torch.int32)
|
||||
else:
|
||||
combined_lens = swa_lens.to(torch.int32)
|
||||
|
||||
max_combined = int(combined_lens.max().item()) if combined_lens.numel() > 0 else 0
|
||||
# Round up to BLOCK_N=16 alignment for kernel efficiency
|
||||
# Use a shape-derived width so replay accepts changing lens without host sync.
|
||||
_BLOCK_N = 16
|
||||
max_combined_padded = ((max_combined + _BLOCK_N - 1) // _BLOCK_N) * _BLOCK_N
|
||||
width = max(_BLOCK_N, ((K_total + _BLOCK_N - 1) // _BLOCK_N) * _BLOCK_N)
|
||||
|
||||
# Build packed index table: [num_tokens, max_combined_padded]
|
||||
# Each token t: [topk_0..topk_{tlen-1}, swa_0..swa_{slen-1}, -1 padding]
|
||||
# Vectorized: for each token, topk indices are t*K_total + 0..tlen-1,
|
||||
# swa indices are t*K_total + max_topk + 0..slen-1
|
||||
combined_indices = torch.full(
|
||||
(num_tokens, max_combined_padded),
|
||||
fill_value=-1,
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
pos = torch.arange(width, device=device, dtype=torch.int32).unsqueeze(0)
|
||||
tok = torch.arange(num_tokens, device=device, dtype=torch.int32).unsqueeze(1)
|
||||
|
||||
slen = swa_lens.reshape(-1, 1).to(torch.int32).clamp(min=0, max=max_swa)
|
||||
if use_topk and topk_lens is not None:
|
||||
tlen = topk_lens.reshape(-1, 1).to(torch.int32).clamp(min=0, max=max_topk)
|
||||
else:
|
||||
tlen = torch.zeros_like(slen)
|
||||
|
||||
in_topk = pos < tlen
|
||||
in_swa = (pos >= tlen) & (pos < tlen + slen)
|
||||
|
||||
topk_ws = tok * max_topk + pos
|
||||
swa_ws = n_topk_rows + tok * max_swa + (pos - tlen)
|
||||
|
||||
combined_indices = torch.where(
|
||||
in_topk,
|
||||
topk_ws,
|
||||
torch.where(in_swa, swa_ws, torch.full_like(topk_ws, -1)),
|
||||
)
|
||||
|
||||
token_offsets = (
|
||||
torch.arange(num_tokens, device=device, dtype=torch.int32) * K_total
|
||||
) # [B]
|
||||
|
||||
if not swa_only and topk_lens is not None:
|
||||
# Pack topk: for each token, write t*K_total + 0..tlen-1 at positions 0..tlen-1
|
||||
max_tlen = int(topk_lens.max().item())
|
||||
topk_range = torch.arange(max_tlen, device=device, dtype=torch.int32).unsqueeze(
|
||||
0
|
||||
)
|
||||
topk_valid = topk_range < topk_lens.unsqueeze(1)
|
||||
topk_ws_indices = token_offsets.unsqueeze(1) + topk_range
|
||||
combined_indices[:, :max_tlen] = torch.where(
|
||||
topk_valid,
|
||||
topk_ws_indices,
|
||||
torch.tensor(-1, dtype=torch.int32, device=device),
|
||||
)
|
||||
# Pack swa after topk: positions tlen..tlen+slen-1
|
||||
# Since tlen varies per token, we need per-token offset
|
||||
swa_range = torch.arange(max_swa, device=device, dtype=torch.int32).unsqueeze(0)
|
||||
swa_valid = swa_range < swa_lens.unsqueeze(1)
|
||||
swa_ws_indices = token_offsets.unsqueeze(1) + max_topk + swa_range
|
||||
# Write at position topk_lens[t] + swa_pos for each token
|
||||
for t_idx in range(num_tokens):
|
||||
tlen = int(topk_lens[t_idx].item())
|
||||
slen = int(swa_lens[t_idx].item())
|
||||
combined_indices[t_idx, tlen : tlen + slen] = swa_ws_indices[t_idx, :slen]
|
||||
else:
|
||||
# SWA-only: pack swa indices at positions 0..slen-1
|
||||
# Use min(max_swa, max_combined_padded) because combined_indices only
|
||||
# has max_combined_padded columns, and all valid entries fit within it.
|
||||
effective_swa = min(max_swa, max_combined_padded)
|
||||
swa_range = torch.arange(
|
||||
effective_swa, device=device, dtype=torch.int32
|
||||
).unsqueeze(0)
|
||||
swa_valid = swa_range < swa_lens.unsqueeze(1)
|
||||
swa_ws_indices = token_offsets.unsqueeze(1) + swa_range # max_topk=0
|
||||
combined_indices[:, :effective_swa] = torch.where(
|
||||
swa_valid,
|
||||
swa_ws_indices,
|
||||
torch.tensor(-1, dtype=torch.int32, device=device),
|
||||
)
|
||||
|
||||
# Call BF16 sparse MLA kernel
|
||||
out_attn, _, _ = triton_bf16_mla_sparse_interface(
|
||||
q=q,
|
||||
kv=workspace.unsqueeze(1),
|
||||
|
||||
@@ -75,8 +75,12 @@ def _ring_slot_mapping_kernel(
|
||||
block = tl.load(block_table_ptr + req * block_table_stride, mask=valid, other=0)
|
||||
pos = tl.load(positions_ptr + offsets, mask=valid, other=0)
|
||||
slot = block.to(tl.int64) * CAPACITY + pos % CAPACITY
|
||||
# Block 0 is the null block. A request without a ring block (dummy or padding
|
||||
# rows, which the runners fill with the null block) must not write.
|
||||
tl.store(
|
||||
slot_mapping_ptr + offsets, tl.where(valid, slot, -1), mask=offsets < num_tokens
|
||||
slot_mapping_ptr + offsets,
|
||||
tl.where(valid & (block != 0), slot, -1),
|
||||
mask=offsets < num_tokens,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -47,7 +47,13 @@ from vllm.v1.attention.selector import get_attn_backend
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
_SPARSE_LAYER_TYPES = ("sparse_attention", "sparse", "deepseek_sparse_attention")
|
||||
_SPARSE_LAYER_TYPES = (
|
||||
"sparse_attention",
|
||||
"sparse",
|
||||
"indexed_attention",
|
||||
# TODO: Delete below once Transformers 5.18.0 is the minimum required version.
|
||||
"deepseek_sparse_attention",
|
||||
)
|
||||
_WEIGHT_LAYER_INDEX_RE = re.compile(r"(?:^|\.)layers\.(\d+)(?:\.|$)")
|
||||
|
||||
|
||||
|
||||
@@ -80,6 +80,10 @@ from .low_latency_gemm import enable_qwen4_exp_low_latency_gemm
|
||||
from .ple_layer import Qwen4ExpPLELayer
|
||||
from .qsa import Qwen4ExpQSAAttention
|
||||
|
||||
# Transformers v5.18 renamed `qwen_sparse_attention` to `indexed_attention`
|
||||
# TODO: Delete qwen_... once Transformers 5.18.0 is the minimum required version.
|
||||
_QSA_LAYER_TYPES = ("qwen_sparse_attention", "indexed_attention")
|
||||
|
||||
|
||||
def without_modelopt_fp4(
|
||||
quant_config: QuantizationConfig | None,
|
||||
@@ -208,7 +212,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
prefix=f"{prefix}.linear_attn",
|
||||
gqa_interleaved_layout=False,
|
||||
)
|
||||
elif layer_type == "qwen_sparse_attention":
|
||||
elif layer_type in _QSA_LAYER_TYPES:
|
||||
use_qsa = getattr(config, "indexer_n_heads", None) is not None
|
||||
if not use_qsa:
|
||||
self.self_attn = Qwen3NextAttention(
|
||||
@@ -290,7 +294,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
attn_out = self.linear_attn(hidden_states=block_input)
|
||||
elif self.layer_type == "qwen_sparse_attention":
|
||||
elif self.layer_type in _QSA_LAYER_TYPES:
|
||||
attn_out = self.self_attn(
|
||||
hidden_states=block_input,
|
||||
positions=positions,
|
||||
@@ -381,7 +385,7 @@ class Qwen4ExpModel(nn.Module):
|
||||
self._qsa_layer_ids = frozenset(
|
||||
layer_idx
|
||||
for layer_idx, layer_type in enumerate(config.layer_types)
|
||||
if layer_type == "qwen_sparse_attention"
|
||||
if layer_type in _QSA_LAYER_TYPES
|
||||
and getattr(config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, config.hidden_size)
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm.model_executor.layers.quantization.compressed_tensors.compressed_tenso
|
||||
CompressedTensorsConfig,
|
||||
)
|
||||
from vllm.model_executor.layers.quantization.fp8 import Fp8Config
|
||||
from vllm.model_executor.layers.quantization.inc import INCConfig
|
||||
from vllm.model_executor.layers.quantization.modelopt import (
|
||||
ModelOptMixedPrecisionConfig,
|
||||
ModelOptQuantConfigBase,
|
||||
@@ -190,6 +191,11 @@ class Qwen4ExpPLEEmbeddingMethod(QuantizeMethodBase):
|
||||
and quant_config.get_scheme_dict(None, layer_name=prefix) is None
|
||||
):
|
||||
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
|
||||
if (
|
||||
isinstance(quant_config, INCConfig)
|
||||
and not quant_config.config_parser.resolve(None, prefix).quantized
|
||||
):
|
||||
return Qwen4ExpPLEUnquantizedEmbeddingMethod()
|
||||
if not isinstance(quant_config, Fp8Config):
|
||||
raise NotImplementedError(
|
||||
"Qwen4Exp PLE embedding does not support quantization config "
|
||||
|
||||
@@ -82,6 +82,10 @@ from .ops.cute_dsl.hc_down_silu import request_hc_down_silu_warmup
|
||||
from .ple_layer import Qwen4ExpPLELayer
|
||||
from .qsa import Qwen4ExpQSAAttention
|
||||
|
||||
# Transformers v5.18 renamed `qwen_sparse_attention` to `indexed_attention`
|
||||
# TODO: Delete qwen_... once Transformers 5.18.0 is the minimum required version.
|
||||
_QSA_LAYER_TYPES = ("qwen_sparse_attention", "indexed_attention")
|
||||
|
||||
|
||||
def without_modelopt_fp4(
|
||||
quant_config: QuantizationConfig | None,
|
||||
@@ -212,7 +216,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
prefix=f"{prefix}.linear_attn",
|
||||
gqa_interleaved_layout=False,
|
||||
)
|
||||
elif layer_type == "qwen_sparse_attention":
|
||||
elif layer_type in _QSA_LAYER_TYPES:
|
||||
use_qsa = getattr(config, "indexer_n_heads", None) is not None
|
||||
if not use_qsa:
|
||||
self.self_attn = Qwen3NextAttention(
|
||||
@@ -296,7 +300,7 @@ class Qwen4ExpDecoderLayer(nn.Module):
|
||||
|
||||
if self.layer_type == "linear_attention":
|
||||
attn_out = self.linear_attn(hidden_states=block_input)
|
||||
elif self.layer_type == "qwen_sparse_attention":
|
||||
elif self.layer_type in _QSA_LAYER_TYPES:
|
||||
attn_out = self.self_attn(
|
||||
hidden_states=block_input,
|
||||
positions=positions,
|
||||
@@ -376,7 +380,7 @@ class Qwen4ExpModel(nn.Module):
|
||||
self._qsa_layer_ids = frozenset(
|
||||
layer_idx
|
||||
for layer_idx, layer_type in enumerate(config.layer_types)
|
||||
if layer_type == "qwen_sparse_attention"
|
||||
if layer_type in _QSA_LAYER_TYPES
|
||||
and getattr(config, "indexer_n_heads", None) is not None
|
||||
)
|
||||
self.embed_tokens = VocabParallelEmbedding(self.vocab_size, config.hidden_size)
|
||||
|
||||
@@ -146,7 +146,7 @@ def normalize_audio(
|
||||
|
||||
# No reduction needed if already at target
|
||||
if num_channels == spec.target_channels:
|
||||
return audio
|
||||
return audio[0] if num_channels == 1 else audio
|
||||
|
||||
# Cannot expand channels
|
||||
if num_channels < spec.target_channels:
|
||||
|
||||
@@ -523,7 +523,9 @@ class CpuPlatform(Platform):
|
||||
if not backend_classes:
|
||||
return
|
||||
|
||||
pre_block_size = vllm_config.cache_config.block_size
|
||||
cls._align_hybrid_block_size(vllm_config, backend_classes[0])
|
||||
cls._check_aligned_block_size(vllm_config, backend_classes, pre_block_size)
|
||||
|
||||
@classmethod
|
||||
def discover_numa_topology(cls) -> list[list[int]]:
|
||||
|
||||
@@ -698,6 +698,7 @@ class Platform:
|
||||
|
||||
# Phase 2: Align block/mamba sizes for hybrid models
|
||||
# (may override user settings).
|
||||
pre_block_size = cache_config.block_size
|
||||
if model_config.is_hybrid:
|
||||
cls._align_hybrid_block_size(vllm_config, backend_classes[0])
|
||||
|
||||
@@ -706,6 +707,36 @@ class Platform:
|
||||
# May override the user's --block-size.
|
||||
if cache_config.kv_cache_dtype_skip_layers:
|
||||
cls._align_heterogeneous_kv_block_size(vllm_config, backend_classes[0])
|
||||
cls._check_aligned_block_size(vllm_config, backend_classes, pre_block_size)
|
||||
|
||||
@classmethod
|
||||
def _check_aligned_block_size(
|
||||
cls,
|
||||
vllm_config: "VllmConfig",
|
||||
backend_classes: "list[type[AttentionBackend]]",
|
||||
pre_block_size: int,
|
||||
) -> None:
|
||||
"""Fail now, not at worker setup, if alignment left a rejected size.
|
||||
|
||||
Alignment rounds by the first backend's kernel block only, so it can
|
||||
land on a size a sibling backend rejects.
|
||||
"""
|
||||
from vllm.config.vllm import set_current_vllm_config
|
||||
|
||||
block_size = vllm_config.cache_config.block_size
|
||||
if block_size == pre_block_size:
|
||||
return
|
||||
with set_current_vllm_config(vllm_config):
|
||||
rejecting = [
|
||||
b.get_name()
|
||||
for b in backend_classes
|
||||
if not b.supports_block_size(block_size)
|
||||
]
|
||||
if rejecting:
|
||||
raise ValueError(
|
||||
f"Aligned KV cache block size {block_size} is not supported by "
|
||||
f"attention backend(s): {', '.join(rejecting)}."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _align_heterogeneous_kv_block_size(
|
||||
|
||||
@@ -452,6 +452,7 @@ class XPUPlatform(Platform):
|
||||
if new_block_size == cache_config.block_size:
|
||||
return
|
||||
|
||||
pre_block_size = cache_config.block_size
|
||||
if cache_config.mamba_cache_mode == "align":
|
||||
cache_config.mamba_block_size = new_block_size
|
||||
original_mamba_page_size_padded = cache_config.mamba_page_size_padded
|
||||
@@ -474,6 +475,10 @@ class XPUPlatform(Platform):
|
||||
original_mamba_page_size_padded,
|
||||
cache_config.mamba_page_size_padded,
|
||||
)
|
||||
# This rounding runs after super()'s check, so check its result too.
|
||||
cls._check_aligned_block_size(
|
||||
vllm_config, cls._find_non_ssm_backends(vllm_config), pre_block_size
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def support_hybrid_kv_cache(cls) -> bool:
|
||||
|
||||
@@ -147,6 +147,12 @@ _CONFIG_REGISTRY: dict[str, type[PreTrainedConfig]] = LazyConfigDict(
|
||||
|
||||
_SPECULATIVE_DECODING_CONFIGS: set[str] = {"eagle", "speculators", "medusa"}
|
||||
|
||||
# Checkpoints whose config.json has no model_type, only remote code in auto_map
|
||||
_ARCHITECTURE_TO_MODEL_TYPE: dict[str, str] = {
|
||||
"LongcatFlashForCausalLM": "longcat_flash",
|
||||
"LongcatFlashNgramForCausalLM": "longcat_flash",
|
||||
}
|
||||
|
||||
_PATCH_HF_VALIDATE_ROPE: set[str] = {"sarvam_mla"}
|
||||
|
||||
# Model types whose checkpoints carry shared RoPE parameters alongside the
|
||||
@@ -352,6 +358,8 @@ class HFConfigParser(ConfigParserBase):
|
||||
if config_dict.get("speculators_config") is not None
|
||||
else model_type
|
||||
)
|
||||
if model_type is None and (architectures := config_dict.get("architectures")):
|
||||
model_type = _ARCHITECTURE_TO_MODEL_TYPE.get(architectures[0])
|
||||
# Allow hf_overrides to override model_type before checking _CONFIG_REGISTRY
|
||||
if (hf_overrides := kwargs.pop("hf_overrides", None)) is not None:
|
||||
if isinstance(hf_overrides, dict) and "model_type" in hf_overrides:
|
||||
@@ -374,6 +382,15 @@ class HFConfigParser(ConfigParserBase):
|
||||
if extra_layer_types := _PATCH_HF_ALLOWED_LAYER_TYPES.get(model_type):
|
||||
_patch_hf_transformers_allowed_layer_types(extra_layer_types)
|
||||
|
||||
if model_type == "vlm":
|
||||
# HyperCLOVAX remote code registers this alias in a bare
|
||||
# `try/except` that fails silently since transformers 5.18
|
||||
from transformers import CONFIG_MAPPING, Qwen2_5_VLVisionConfig
|
||||
|
||||
CONFIG_MAPPING.register(
|
||||
"qwen2_5_vl_visual", Qwen2_5_VLVisionConfig, exist_ok=True
|
||||
)
|
||||
|
||||
rope_parameters = config_dict.get("rope_parameters") or {}
|
||||
if model_type == "gemma4_text" and "full_attention" in rope_parameters:
|
||||
from transformers import Gemma4TextConfig
|
||||
@@ -387,6 +404,11 @@ class HFConfigParser(ConfigParserBase):
|
||||
}
|
||||
kwargs.setdefault("name_or_path", str(model))
|
||||
config = Gemma4TextConfig.from_dict(config_dict, **kwargs)
|
||||
elif model_type in _ARCHITECTURE_TO_MODEL_TYPE.values():
|
||||
from transformers import CONFIG_MAPPING
|
||||
|
||||
kwargs.setdefault("name_or_path", str(model))
|
||||
config = CONFIG_MAPPING[model_type].from_dict(config_dict, **kwargs)
|
||||
elif model_type in _SPECULATIVE_DECODING_CONFIGS:
|
||||
config_class = _CONFIG_REGISTRY[model_type]
|
||||
config = config_class.from_pretrained(
|
||||
|
||||
@@ -329,7 +329,6 @@ class ModelArchConfigConvertorBase:
|
||||
"kimi_k2",
|
||||
"kimi_linear",
|
||||
"longcat_flash",
|
||||
"longcat_flash_ngram",
|
||||
"pangu_ultra_moe",
|
||||
"pangu_ultra_moe_mtp",
|
||||
"bailing_hybrid",
|
||||
@@ -714,6 +713,12 @@ class PanguUltraMoeMTPModelArchConfigConvertor(ModelArchConfigConvertorBase):
|
||||
return getattr(self.hf_text_config, "num_nextn_predict_layers", 0)
|
||||
|
||||
|
||||
class LongCatFlashModelArchConfigConvertor(ModelArchConfigConvertorBase):
|
||||
def get_num_hidden_layers(self) -> int:
|
||||
# `num_hidden_layers` counts attention sublayers, two per decoder layer
|
||||
return self.hf_text_config.num_layers
|
||||
|
||||
|
||||
class LongCatFlashMTPModelArchConfigConvertor(ModelArchConfigConvertorBase):
|
||||
def get_num_hidden_layers(self) -> int:
|
||||
return getattr(self.hf_text_config, "num_nextn_predict_layers", 1)
|
||||
@@ -825,6 +830,7 @@ MODEL_ARCH_CONFIG_CONVERTORS = {
|
||||
"gemma4_unified_text": Gemma4ModelArchConfigConvertor,
|
||||
"glm4_moe_mtp": GLM4MoeMTPModelArchConfigConvertor,
|
||||
"glm_ocr_mtp": GLM4MoeMTPModelArchConfigConvertor,
|
||||
"longcat_flash": LongCatFlashModelArchConfigConvertor,
|
||||
"longcat_flash_mtp": LongCatFlashMTPModelArchConfigConvertor,
|
||||
"mamba": MambaModelArchConfigConvertor,
|
||||
"medusa": MedusaModelArchConfigConvertor,
|
||||
|
||||
@@ -6,6 +6,7 @@ from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
import torch
|
||||
|
||||
from vllm.config import get_current_vllm_config
|
||||
from vllm.config.cache import CacheDType
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.attention.mla_attention import (
|
||||
@@ -155,6 +156,7 @@ class TokenspeedMLABackend(MLACommonBackend):
|
||||
class TokenspeedMLAImpl(MLACommonImpl[MLACommonMetadata]):
|
||||
can_return_lse_for_decode: bool = True
|
||||
supports_dcp: bool = True
|
||||
supports_mtp_with_cp_non_trivial_interleave_size: bool = True
|
||||
# tokenspeed_mla_decode returns LSE in log2 units; its own DCP test merges
|
||||
# partial outputs with exp2(lse).
|
||||
lse_base_on_e: bool = False
|
||||
@@ -216,6 +218,9 @@ class TokenspeedMLAImpl(MLACommonImpl[MLACommonMetadata]):
|
||||
self._workspace_buffer: torch.Tensor | None = None
|
||||
self.softmax_scale: float | None = None
|
||||
self.output_scale: float | None = None
|
||||
# NIXL resolves interleaving after model construction; retain the config
|
||||
# rather than caching its initial interleave size.
|
||||
self._parallel_config = get_current_vllm_config().parallel_config
|
||||
|
||||
# Pre-JIT BF16 and FP8 prefill kernels here too — decode impl always
|
||||
# runs when tokenspeed is selected, prefill backend may not (user can
|
||||
@@ -311,9 +316,13 @@ class TokenspeedMLAImpl(MLACommonImpl[MLACommonMetadata]):
|
||||
causal_seqs=causal_seqs if self.dcp_world_size > 1 else None,
|
||||
cp_world=self.dcp_world_size,
|
||||
cp_rank=self.dcp_rank,
|
||||
cp_interleave_size=self._parallel_config.cp_kv_cache_interleave_size,
|
||||
)
|
||||
if return_lse:
|
||||
o, lse = kernel_out
|
||||
# DCP ranks with no local KV may return undefined outputs (e.g.,
|
||||
# NaNs). The downstream DCP combine path must mask empty
|
||||
# shards and ignore their outputs when merging partial attention.
|
||||
lse = lse.view(-1, lse.shape[-1])
|
||||
else:
|
||||
o, lse = kernel_out, None
|
||||
|
||||
@@ -481,7 +481,9 @@ class RocmAttentionImpl(AttentionImpl):
|
||||
k_scale=layer._k_scale,
|
||||
v_scale=layer._v_scale,
|
||||
alibi_slopes=self.alibi_slopes,
|
||||
sliding_window=self.sliding_window[0],
|
||||
# self.sliding_window[0] is the FlashAttention-style left span (W - 1).
|
||||
# chunked_prefill_paged_decode expects the full window length W.
|
||||
sliding_window=1 + self.sliding_window[0],
|
||||
sm_scale=self.scale,
|
||||
output_scale=output_scale,
|
||||
sinks=self.sinks,
|
||||
|
||||
@@ -1395,6 +1395,10 @@ class SimpleCPUOffloadScheduler:
|
||||
the transfer finished, then release refs without caching abandoned
|
||||
store results.
|
||||
"""
|
||||
for pending in self._pending_cpu_hits.values():
|
||||
self._free_pending_cpu_hit(pending)
|
||||
self._pending_cpu_hits.clear()
|
||||
|
||||
self._abandoned_store_event_to_blocks.update(self._store_event_to_blocks)
|
||||
for transfer in self._pending_finished_stores:
|
||||
self._release_transfer_refs(transfer)
|
||||
|
||||
@@ -398,10 +398,7 @@ def init_kv_cache(
|
||||
# Dual-attention models (e.g. LongCat-Flash) put two Attention modules per
|
||||
# decoder layer, so a layer name carries two integers (layer + module index).
|
||||
num_attn_module = (
|
||||
2
|
||||
if vllm_config.model_config.hf_config.model_type
|
||||
in ("longcat_flash", "longcat_flash_ngram")
|
||||
else 1
|
||||
2 if vllm_config.model_config.hf_config.model_type == "longcat_flash" else 1
|
||||
)
|
||||
bindable_caches = {
|
||||
name: cache for name, cache in kv_caches.items() if name in forward_context
|
||||
|
||||
@@ -19,10 +19,13 @@ from vllm.compilation.breakable_cudagraph import (
|
||||
)
|
||||
from vllm.compilation.counter import compilation_counter
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat, CUDAGraphWrapper
|
||||
from vllm.compilation.cudagraph_pool import (
|
||||
capture_outside_cumem_pool,
|
||||
capture_pool,
|
||||
)
|
||||
from vllm.compilation.wrapper import TorchCompileWithNoGuardsWrapper
|
||||
from vllm.config import VllmConfig, set_current_vllm_config
|
||||
from vllm.config.compilation import CUDAGraphMode
|
||||
from vllm.distributed.device_communicators.pynccl_allocator import set_graph_pool_id
|
||||
from vllm.distributed.parallel_state import (
|
||||
get_pp_group,
|
||||
graph_capture,
|
||||
@@ -481,15 +484,14 @@ class CudaGraphManager:
|
||||
# Sync offloader's copy stream before capture.
|
||||
# Ensure any pre-capture prefetches from offloader are complete.
|
||||
get_offloader().sync_prev_onload()
|
||||
if self.pool is not None:
|
||||
set_graph_pool_id(self.pool)
|
||||
else:
|
||||
set_graph_pool_id(current_platform.graph_pool_handle())
|
||||
if self._capture_mem_samples is not None:
|
||||
torch.accelerator.synchronize()
|
||||
free_before = torch.accelerator.get_memory_info()[0]
|
||||
with torch.cuda.graph(
|
||||
graph, self.pool, stream=self._capture_stream(desc)
|
||||
with (
|
||||
capture_pool(self.pool, self.vllm_config) as pool,
|
||||
torch.cuda.graph(
|
||||
graph, pool, stream=self._capture_stream(desc)
|
||||
),
|
||||
):
|
||||
forward_fn(CUDAGraphMode.NONE)
|
||||
# Join offloader's copy stream after forward to avoid
|
||||
@@ -941,7 +943,8 @@ def profile_cudagraph_memory(runner: "GPUModelRunner") -> int:
|
||||
mem_samples: list[int] = []
|
||||
manager._capture_mem_samples = mem_samples
|
||||
|
||||
measured = int(runner.capture_model(profile_only=True))
|
||||
with capture_outside_cumem_pool():
|
||||
measured = int(runner.capture_model(profile_only=True))
|
||||
|
||||
# The measured delta covers PIECEWISE, encoder and speculator graphs
|
||||
# plus the sampled FULL graphs; swap the sampled FULL cost for the
|
||||
|
||||
Reference in New Issue
Block a user