[RFC] Replace shared-memory routed experts with ModelRunnerOutput transfer and HTTP support (#39568)
Signed-off-by: xhx1022 <1737006628@qq.com> Signed-off-by: arlenxu <arlenxu@tencent.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Co-authored-by: arlenxu <arlenxu@tencent.com> Co-authored-by: Junjie Zhang <junj.jay.zhang@gmail.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
arlenxu
Junjie Zhang
parent
2317682f95
commit
c7560af424
@@ -7,8 +7,6 @@ from collections.abc import Iterable
|
||||
from dataclasses import replace
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
from vllm import envs
|
||||
from vllm.compilation.cuda_graph import CUDAGraphStat
|
||||
from vllm.config import VllmConfig
|
||||
@@ -28,7 +26,7 @@ from vllm.distributed.kv_transfer.kv_connector.v1.base import KVConnectorMetadat
|
||||
from vllm.distributed.kv_transfer.kv_connector.v1.metrics import KVConnectorStats
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
|
||||
RoutedExpertsReader,
|
||||
RoutedExpertsManager,
|
||||
)
|
||||
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
|
||||
from vllm.multimodal.encoder_budget import MultiModalBudget
|
||||
@@ -52,7 +50,7 @@ from vllm.v1.core.sched.request_queue import (
|
||||
)
|
||||
from vllm.v1.core.sched.utils import check_stop, remove_all
|
||||
from vllm.v1.engine import EngineCoreEventType, EngineCoreOutput, EngineCoreOutputs
|
||||
from vllm.v1.kv_cache_interface import AttentionSpec, KVCacheConfig
|
||||
from vllm.v1.kv_cache_interface import KVCacheConfig
|
||||
from vllm.v1.metrics.perf import ModelMetrics, PerfStats
|
||||
from vllm.v1.metrics.stats import PrefixCacheStats, SchedulerStats
|
||||
from vllm.v1.outputs import DraftTokenIds, KVConnectorOutput, ModelRunnerOutput
|
||||
@@ -258,42 +256,24 @@ class Scheduler(SchedulerInterface):
|
||||
if self.log_stats and vllm_config.observability_config.enable_mfu_metrics:
|
||||
self.perf_metrics = ModelMetrics(vllm_config)
|
||||
|
||||
if self.vllm_config.model_config.enable_return_routed_experts:
|
||||
self.enable_return_routed_experts = (
|
||||
vllm_config.model_config.enable_return_routed_experts
|
||||
)
|
||||
|
||||
if self.enable_return_routed_experts:
|
||||
assert self.dcp_world_size == 1 and self.pcp_world_size == 1, (
|
||||
"enable_return_routed_experts does not support context parallelism "
|
||||
"(dcp_world_size > 1 or pcp_world_size > 1)"
|
||||
)
|
||||
|
||||
self.routed_experts_reader = RoutedExpertsReader.create()
|
||||
|
||||
assert len(kv_cache_config.kv_cache_groups) > 0, (
|
||||
"enable_return_routed_experts requires at least one kv cache group"
|
||||
)
|
||||
# Find the attention group for routed experts indexing.
|
||||
self.routed_experts_attn_gid = 0
|
||||
for gid, group in enumerate(kv_cache_config.kv_cache_groups):
|
||||
if isinstance(group.kv_cache_spec, AttentionSpec):
|
||||
self.routed_experts_attn_gid = gid
|
||||
break
|
||||
min_block_size = min(
|
||||
[
|
||||
group.kv_cache_spec.block_size
|
||||
for group in kv_cache_config.kv_cache_groups
|
||||
]
|
||||
)
|
||||
num_groups = len(kv_cache_config.kv_cache_groups)
|
||||
self.max_num_kv_tokens = (
|
||||
kv_cache_config.num_blocks // num_groups
|
||||
) * min_block_size
|
||||
dcp_size = self.vllm_config.parallel_config.decode_context_parallel_size
|
||||
pcp_size = self.vllm_config.parallel_config.prefill_context_parallel_size
|
||||
if pcp_size * dcp_size > 1:
|
||||
self.max_num_kv_tokens *= pcp_size * dcp_size
|
||||
|
||||
self.routed_experts_reader.attach_buffer(
|
||||
max_num_kv_tokens=self.max_num_kv_tokens,
|
||||
vllm_config=self.vllm_config,
|
||||
self.routed_experts_mgr = RoutedExpertsManager(
|
||||
vllm_config=vllm_config,
|
||||
kv_cache_config=kv_cache_config,
|
||||
)
|
||||
# Block-ID snapshot taken at schedule time (before forward),
|
||||
# so update_from_output can read slot data even if a later
|
||||
# schedule() frees the blocks (async scheduling race).
|
||||
self._re_block_ids: dict[str, list[int]] = {}
|
||||
|
||||
self._pause_state: PauseState = PauseState.UNPAUSED
|
||||
|
||||
@@ -990,6 +970,22 @@ class Scheduler(SchedulerInterface):
|
||||
request.use_structured_output and not request.is_prefill_chunk
|
||||
)
|
||||
|
||||
# Snapshot block IDs for routed experts before forward starts.
|
||||
# A concurrent schedule() may preempt requests and free blocks
|
||||
# before update_from_output runs; the snapshot survives that.
|
||||
# Use update() to preserve entries from the previous step that
|
||||
# have not yet been consumed by update_from_output (async
|
||||
# scheduling may call _update_after_schedule again before the
|
||||
# prior update_from_output runs).
|
||||
if self.enable_return_routed_experts:
|
||||
gid = self.routed_experts_mgr.attn_gid
|
||||
self._re_block_ids.update(
|
||||
{
|
||||
rid: self.kv_cache_manager.get_blocks(rid).get_block_ids()[gid]
|
||||
for rid in num_scheduled_tokens
|
||||
}
|
||||
)
|
||||
|
||||
# Clear the finished request IDs.
|
||||
# NOTE: We shouldn't do self.finished_req_ids.clear() here because
|
||||
# it will also affect the scheduler output.
|
||||
@@ -1323,6 +1319,27 @@ class Scheduler(SchedulerInterface):
|
||||
num_scheduled_tokens,
|
||||
)
|
||||
|
||||
# Persist per-step routed experts into the scheduler-side slot
|
||||
# buffer (CPU->CPU fancy-index assign; ~few MB per step).
|
||||
# MUST precede the per-request routing reads below: stopped
|
||||
# requests may terminate on tokens generated in this very step,
|
||||
# whose routing was just D2H'd into model_runner_output.
|
||||
routing_data = None
|
||||
routing_offsets: dict[str, int] = {}
|
||||
if model_runner_output.routed_experts is not None:
|
||||
re = model_runner_output.routed_experts
|
||||
self.routed_experts_mgr.store_batch(re.routing_data, re.slot_mapping)
|
||||
routing_data = re.routing_data.astype(
|
||||
self.routed_experts_mgr.routed_experts_by_slot.dtype,
|
||||
copy=False,
|
||||
)
|
||||
# Build offset map using model runner's request order
|
||||
# (input_batch ordering), NOT scheduler dict order.
|
||||
offset = 0
|
||||
for rid in model_runner_output.req_ids:
|
||||
routing_offsets[rid] = offset
|
||||
offset += num_scheduled_tokens[rid]
|
||||
|
||||
# NOTE(woosuk): As len(num_scheduled_tokens) can be up to 1K or more,
|
||||
# the below loop can be a performance bottleneck. We should do our best
|
||||
# to avoid expensive operations inside the loop.
|
||||
@@ -1385,6 +1402,7 @@ class Scheduler(SchedulerInterface):
|
||||
pooler_output = pooler_outputs[req_index] if pooler_outputs else None
|
||||
kv_transfer_params = None
|
||||
status_before_stop = request.status
|
||||
num_output_tokens_before = len(request._output_token_ids)
|
||||
|
||||
# Check for stop and update request status.
|
||||
if new_token_ids:
|
||||
@@ -1414,10 +1432,47 @@ class Scheduler(SchedulerInterface):
|
||||
stopped = True
|
||||
|
||||
routed_experts = None
|
||||
if (
|
||||
self.enable_return_routed_experts
|
||||
and routing_data is not None
|
||||
and new_token_ids
|
||||
):
|
||||
req_offset = routing_offsets[req_id]
|
||||
end = req_offset + num_tokens_scheduled
|
||||
block_ids = self._re_block_ids.pop(req_id, [])
|
||||
if num_output_tokens_before == 0:
|
||||
# Prefill completed: read full prompt routing from
|
||||
# slot buffer using the block-ID snapshot taken at
|
||||
# schedule time (immune to async preemption).
|
||||
if (
|
||||
request.sampling_params is not None
|
||||
and request.sampling_params.routed_experts_prompt_start
|
||||
is not None
|
||||
):
|
||||
prompt_start = (
|
||||
request.sampling_params.routed_experts_prompt_start
|
||||
)
|
||||
assert prompt_start < request.num_prompt_tokens
|
||||
else:
|
||||
prompt_start = 0
|
||||
routed_experts = self.routed_experts_mgr.get(
|
||||
block_ids,
|
||||
request.num_prompt_tokens,
|
||||
token_start=prompt_start,
|
||||
)
|
||||
else:
|
||||
if scheduled_spec_token_ids:
|
||||
# Spec decode: accepted tokens at the START of
|
||||
# the scheduled range, rejected at the end.
|
||||
routed_experts = routing_data[
|
||||
req_offset : req_offset + len(new_token_ids)
|
||||
]
|
||||
else:
|
||||
# Normal decode / re-prefill: token(s) at the END.
|
||||
routed_experts = routing_data[end - len(new_token_ids) : end]
|
||||
|
||||
finish_reason = None
|
||||
if stopped:
|
||||
routed_experts = self._get_routed_experts(request)
|
||||
|
||||
# Capture finish_reason BEFORE _handle_stopped_request, which may
|
||||
# reset the status to WAITING for streaming requests that continue.
|
||||
finish_reason = request.get_finished_reason()
|
||||
@@ -1592,31 +1647,6 @@ class Scheduler(SchedulerInterface):
|
||||
self._enqueue_waiting_request(request)
|
||||
return False
|
||||
|
||||
def _get_routed_experts(self, request: Request) -> np.ndarray | None:
|
||||
if not self.vllm_config.model_config.enable_return_routed_experts:
|
||||
return None
|
||||
|
||||
kv_blocks = self.kv_cache_manager.get_blocks(request.request_id)
|
||||
block_ids = kv_blocks.get_block_ids()[self.routed_experts_attn_gid]
|
||||
num_tokens = request.num_tokens - 1
|
||||
|
||||
# compute slot mapping using attention group's block_size
|
||||
block_ids_array = np.array(block_ids, dtype=np.int32)
|
||||
num_blocks = len(block_ids)
|
||||
attn_group = self.kv_cache_config.kv_cache_groups[self.routed_experts_attn_gid]
|
||||
block_size = attn_group.kv_cache_spec.block_size
|
||||
|
||||
# generate block offsets
|
||||
block_offsets = np.arange(0, block_size)
|
||||
|
||||
# compute slot mapping: slot = block_id * block_size + offset
|
||||
slot_mapping = (
|
||||
block_offsets.reshape((1, block_size))
|
||||
+ block_ids_array.reshape((num_blocks, 1)) * block_size
|
||||
).flatten()[:num_tokens]
|
||||
|
||||
return self.routed_experts_reader.get_routed_experts(indices=slot_mapping)
|
||||
|
||||
def _update_request_with_output(
|
||||
self, request: Request, new_token_ids: list[int]
|
||||
) -> tuple[list[int], bool]:
|
||||
|
||||
@@ -175,6 +175,9 @@ class RequestState:
|
||||
|
||||
self.stats = RequestStateStats(arrival_time=arrival_time) if log_stats else None
|
||||
|
||||
# Routed experts accumulation (prompt + sample chunks)
|
||||
self.routed_experts_chunks: list[np.ndarray] = []
|
||||
|
||||
# Stream Interval
|
||||
self.stream_interval = stream_interval
|
||||
self.sent_tokens_offset = 0 # Offset of sent tokens
|
||||
@@ -273,7 +276,6 @@ class RequestState:
|
||||
finish_reason: FinishReason | None,
|
||||
stop_reason: int | str | None,
|
||||
kv_transfer_params: dict[str, Any] | None = None,
|
||||
routed_experts: np.ndarray | None = None,
|
||||
) -> RequestOutput | PoolingRequestOutput | None:
|
||||
finished = finish_reason is not None
|
||||
final_only = self.output_kind == RequestOutputKind.FINAL_ONLY
|
||||
@@ -314,9 +316,7 @@ class RequestState:
|
||||
finished,
|
||||
)
|
||||
|
||||
output = self._new_completion_output(
|
||||
new_token_ids, finish_reason, stop_reason, routed_experts
|
||||
)
|
||||
output = self._new_completion_output(new_token_ids, finish_reason, stop_reason)
|
||||
|
||||
if self.parent_req is None:
|
||||
outputs = [output]
|
||||
@@ -378,7 +378,6 @@ class RequestState:
|
||||
token_ids: list[int],
|
||||
finish_reason: FinishReason | None,
|
||||
stop_reason: int | str | None,
|
||||
routed_experts: np.ndarray | None = None,
|
||||
) -> CompletionOutput:
|
||||
assert self.detokenizer is not None
|
||||
assert self.logprobs_processor is not None
|
||||
@@ -395,6 +394,11 @@ class RequestState:
|
||||
if delta and logprobs:
|
||||
logprobs = logprobs[-len(token_ids) :]
|
||||
|
||||
# Concatenate routed experts on finish
|
||||
routed_experts = None
|
||||
if finished and self.routed_experts_chunks:
|
||||
routed_experts = np.concatenate(self.routed_experts_chunks, axis=0)
|
||||
|
||||
return CompletionOutput(
|
||||
index=self.request_index,
|
||||
text=text,
|
||||
@@ -616,7 +620,10 @@ class OutputProcessor:
|
||||
finish_reason = engine_core_output.finish_reason
|
||||
stop_reason = engine_core_output.stop_reason
|
||||
kv_transfer_params = engine_core_output.kv_transfer_params
|
||||
routed_experts = engine_core_output.routed_experts
|
||||
if engine_core_output.routed_experts is not None:
|
||||
req_state.routed_experts_chunks.append(
|
||||
engine_core_output.routed_experts
|
||||
)
|
||||
|
||||
if req_state.is_prefilling:
|
||||
if engine_core_output.prefill_stats is not None:
|
||||
@@ -647,7 +654,6 @@ class OutputProcessor:
|
||||
finish_reason,
|
||||
stop_reason,
|
||||
kv_transfer_params,
|
||||
routed_experts,
|
||||
):
|
||||
if req_state.streaming_input:
|
||||
request_output.finished = False
|
||||
|
||||
@@ -109,6 +109,73 @@ class LogprobsTensors(NamedTuple):
|
||||
)
|
||||
|
||||
|
||||
class RoutedExpertsTensors(NamedTuple):
|
||||
"""Device-side snapshot of routed experts data, pending async D2H.
|
||||
|
||||
Produced by :class:`GPUModelRunner` at the end of each async-scheduled
|
||||
step. The copy stream waits on the default stream, then issues
|
||||
non-blocking D2H via :meth:`to_cpu_nonblocking` into a pinned CPU
|
||||
buffer; :class:`AsyncGPUModelRunnerOutput.get_output` synchronizes
|
||||
the copy before the scheduler reads it.
|
||||
|
||||
Sliced to ``total_num_scheduled_tokens`` (step-level, across all
|
||||
requests — NOT per-request). Both ``routing_data`` and
|
||||
``slot_mapping`` must be private clones when sourced from shared
|
||||
capturer / prepare-input buffers, so the next forward pass /
|
||||
``_prepare_inputs`` on the default stream does not race with a
|
||||
D2H still pending on the copy stream.
|
||||
"""
|
||||
|
||||
# (num_scheduled_tokens, num_layers, num_experts_per_tok)
|
||||
routing_data: torch.Tensor
|
||||
# (num_scheduled_tokens,)
|
||||
slot_mapping: torch.Tensor
|
||||
|
||||
def to_cpu_nonblocking(self) -> "RoutedExpertsTensors":
|
||||
"""Issue non-blocking D2H on the current stream.
|
||||
|
||||
NOTE: ``non_blocking=True`` only delivers true overlap when the
|
||||
CPU target is pinned. The current fallback here allocates a
|
||||
new pageable CPU tensor per call, which silently degrades to a
|
||||
synchronous copy; acceptable because the sync happens on the
|
||||
dedicated copy stream, not the default stream.
|
||||
"""
|
||||
if self.routing_data.device.type == "cpu":
|
||||
return self
|
||||
return RoutedExpertsTensors(
|
||||
self.routing_data.to("cpu", non_blocking=True),
|
||||
self.slot_mapping.to("cpu", non_blocking=True),
|
||||
)
|
||||
|
||||
def tolists(self) -> "RoutedExpertsLists":
|
||||
"""Convert to the numpy-backed form consumed by the scheduler.
|
||||
|
||||
``.cpu()`` is a no-op when the tensor is already on CPU, so this
|
||||
is cheap for the post-D2H case; for raw device tensors it will
|
||||
synchronously block, which is only reached in tests.
|
||||
"""
|
||||
return RoutedExpertsLists(
|
||||
self.routing_data.cpu().numpy(),
|
||||
self.slot_mapping.cpu().numpy(),
|
||||
)
|
||||
|
||||
|
||||
class RoutedExpertsLists(NamedTuple):
|
||||
"""CPU-side routed experts, the form :meth:`RoutedExpertsManager.store_batch`
|
||||
consumes.
|
||||
|
||||
Batched per scheduler step: the leading dim is the number of tokens
|
||||
scheduled across all requests in this step (``total_num_scheduled_tokens``),
|
||||
not per-request tokens. ``slot_mapping[i]`` tells the scheduler which
|
||||
physical KV-cache slot row ``i`` of ``routing_data`` belongs to.
|
||||
"""
|
||||
|
||||
# (num_scheduled_tokens, num_layers, num_experts_per_tok)
|
||||
routing_data: np.ndarray
|
||||
# (num_scheduled_tokens,)
|
||||
slot_mapping: np.ndarray
|
||||
|
||||
|
||||
# [num_reqs, <dynamic>]
|
||||
# The shape of each element depends on the pooler used
|
||||
PoolerOutput: TypeAlias = torch.Tensor | list[torch.Tensor] | list[torch.Tensor | None]
|
||||
@@ -201,6 +268,17 @@ class ModelRunnerOutput:
|
||||
# information related to cudagraph execution
|
||||
cudagraph_stats: CUDAGraphStat | None = None
|
||||
|
||||
# Per-step routed experts data captured by the worker.
|
||||
# ``routing_data`` shape: (num_scheduled_tokens, num_layers,
|
||||
# num_experts_per_tok); expert IDs as uint8/uint16.
|
||||
# ``slot_mapping`` shape: (num_scheduled_tokens,); physical KV-cache
|
||||
# slot for each row of routing_data.
|
||||
# ``num_scheduled_tokens`` is step-level (total across all requests
|
||||
# in this step), not per-request. The scheduler persists this into
|
||||
# its slot buffer via ``slot_buffer[slot_mapping] = routing_data``.
|
||||
# ``None`` when ``enable_return_routed_experts`` is off.
|
||||
routed_experts: RoutedExpertsLists | None = None
|
||||
|
||||
|
||||
# ModelRunnerOutput wrapper for async scheduling.
|
||||
class AsyncModelRunnerOutput(ABC):
|
||||
|
||||
@@ -157,6 +157,8 @@ from vllm.v1.outputs import (
|
||||
LogprobsTensors,
|
||||
ModelRunnerOutput,
|
||||
PoolerOutput,
|
||||
RoutedExpertsLists,
|
||||
RoutedExpertsTensors,
|
||||
SamplerOutput,
|
||||
make_empty_encoder_model_runner_output,
|
||||
)
|
||||
@@ -236,6 +238,7 @@ class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput):
|
||||
invalid_req_indices: list[int],
|
||||
async_output_copy_stream: torch.cuda.Stream,
|
||||
vocab_size: int,
|
||||
routed_experts: RoutedExpertsTensors | None = None,
|
||||
):
|
||||
self._model_runner_output = model_runner_output
|
||||
self._invalid_req_indices = invalid_req_indices
|
||||
@@ -248,6 +251,7 @@ class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput):
|
||||
self._sampled_token_ids = sampled_token_ids
|
||||
self.vocab_size = vocab_size
|
||||
self._logprobs_tensors = logprobs_tensors
|
||||
self._routed_experts = routed_experts
|
||||
|
||||
# Initiate the copy on a separate stream, but do not synchronize it.
|
||||
default_stream = torch.cuda.current_stream()
|
||||
@@ -261,6 +265,11 @@ class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput):
|
||||
if self._logprobs_tensors
|
||||
else None
|
||||
)
|
||||
self._routed_experts_cpu = (
|
||||
self._routed_experts.to_cpu_nonblocking()
|
||||
if self._routed_experts is not None
|
||||
else None
|
||||
)
|
||||
self.async_copy_ready_event.record()
|
||||
|
||||
def get_output(self) -> ModelRunnerOutput:
|
||||
@@ -292,6 +301,11 @@ class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput):
|
||||
output = self._model_runner_output
|
||||
output.sampled_token_ids = valid_sampled_token_ids
|
||||
output.logprobs = logprobs_lists
|
||||
|
||||
if self._routed_experts_cpu is not None:
|
||||
output.routed_experts = self._routed_experts_cpu.tolists()
|
||||
del self._routed_experts
|
||||
|
||||
return output
|
||||
|
||||
|
||||
@@ -2192,9 +2206,18 @@ class GPUModelRunner(
|
||||
slot_mapping_gid_0 = slot_mappings[0]
|
||||
|
||||
if self.routed_experts_initialized:
|
||||
# Copy this step's attention slot_mapping into our private
|
||||
# device buffer. The shared ``slot_mappings[attn_gid]`` is
|
||||
# owned by the attention block table and will be overwritten
|
||||
# by the next ``_prepare_inputs``; we need a stable snapshot
|
||||
# because the async D2H may still be in flight on the copy
|
||||
# stream when the next step runs.
|
||||
attn_gid = self.routed_experts_attn_gid
|
||||
slot_mapping_attn = slot_mappings[attn_gid]
|
||||
self.slot_mapping = slot_mapping_attn[:num_tokens].cpu().numpy()
|
||||
self.routed_experts_slot_mapping_device[:num_tokens].copy_(
|
||||
slot_mapping_attn[:num_tokens]
|
||||
)
|
||||
|
||||
num_computed_tokens_cpu = self.input_batch.num_computed_tokens_cpu_tensor[
|
||||
:num_reqs_padded
|
||||
]
|
||||
@@ -3478,6 +3501,21 @@ class GPUModelRunner(
|
||||
invalid_req_indices = []
|
||||
logprobs_lists = None
|
||||
if not self.use_async_scheduling:
|
||||
# Sync scheduling: issue routed experts D2H into the pinned
|
||||
# CPU buffer BEFORE ``_to_list`` below. ``_to_list`` does
|
||||
# ``event.synchronize()`` on the async copy stream which
|
||||
# waits for every D2H queued on the default stream since
|
||||
# the last sync, so this enqueue is naturally covered
|
||||
# without requiring its own synchronize.
|
||||
if self.routed_experts_initialized:
|
||||
buf = self.routed_experts_capturer.get_device_buffer()
|
||||
total = scheduler_output.total_num_scheduled_tokens
|
||||
self.routed_experts_cpu[:total].copy_(buf[:total], non_blocking=True)
|
||||
self.routed_experts_slot_mapping_cpu[:total].copy_(
|
||||
self.routed_experts_slot_mapping_device[:total],
|
||||
non_blocking=True,
|
||||
)
|
||||
|
||||
# Get the valid generated tokens.
|
||||
max_gen_len = sampled_token_ids.shape[-1]
|
||||
if max_gen_len == 1:
|
||||
@@ -3878,11 +3916,7 @@ class GPUModelRunner(
|
||||
)
|
||||
|
||||
if self.routed_experts_initialized:
|
||||
capturer = RoutedExpertsCapturer.get_instance()
|
||||
if capturer is not None:
|
||||
capturer.clear_buffer() # noqa
|
||||
else:
|
||||
logger.error("RoutedExpertsCapturer not initialized.")
|
||||
self.routed_experts_capturer.clear_buffer()
|
||||
|
||||
# If ngram_gpu is used, we need to copy the scheduler_output to avoid
|
||||
# the modification has influence on the scheduler_output in engine core process.
|
||||
@@ -4415,13 +4449,6 @@ class GPUModelRunner(
|
||||
self.kv_connector_output = None
|
||||
|
||||
with record_function_or_nullcontext("gpu_model_runner: ModelRunnerOutput"):
|
||||
if self.routed_experts_initialized:
|
||||
capturer = RoutedExpertsCapturer.get_instance()
|
||||
if capturer is not None:
|
||||
capturer.save_captured_experts(indices=self.slot_mapping) # noqa
|
||||
else:
|
||||
logger.error("RoutedExpertsCapturer not initialized.")
|
||||
|
||||
output = ModelRunnerOutput(
|
||||
req_ids=req_ids_output_copy,
|
||||
req_id_to_index=req_id_to_index_output_copy,
|
||||
@@ -4434,14 +4461,47 @@ class GPUModelRunner(
|
||||
else None,
|
||||
num_nans_in_logits=num_nans_in_logits,
|
||||
cudagraph_stats=cudagraph_stats,
|
||||
routed_experts=None,
|
||||
)
|
||||
|
||||
if not self.use_async_scheduling:
|
||||
if self.routed_experts_initialized:
|
||||
# Sync path: D2H was issued in ``_bookkeeping_sync`` and
|
||||
# synchronized by ``_to_list``'s event.synchronize(), so
|
||||
# the pinned buffers are ready to be wrapped as numpy.
|
||||
total = scheduler_output.total_num_scheduled_tokens
|
||||
output.routed_experts = RoutedExpertsLists(
|
||||
routing_data=self.routed_experts_cpu[:total].numpy(),
|
||||
slot_mapping=self.routed_experts_slot_mapping_cpu[:total].numpy(),
|
||||
)
|
||||
return output
|
||||
|
||||
with record_function_or_nullcontext(
|
||||
"gpu_model_runner: AsyncGPUModelRunnerOutput"
|
||||
):
|
||||
# Async path: produce a device-side snapshot that the async
|
||||
# copy stream can D2H later. Both tensors must be private
|
||||
# clones because:
|
||||
# - ``routing_data`` source is the shared capturer buffer,
|
||||
# which is ``clear_buffer()``-ed at the start of the
|
||||
# next step on the default stream.
|
||||
# - ``slot_mapping`` source is our own
|
||||
# ``routed_experts_slot_mapping_device``, which the
|
||||
# next ``_prepare_inputs`` overwrites on the default
|
||||
# stream while the D2H is still pending on the copy
|
||||
# stream.
|
||||
# Without clones, the copy stream would read torn data.
|
||||
routed_experts_snapshot = None
|
||||
if self.routed_experts_initialized:
|
||||
buf = self.routed_experts_capturer.get_device_buffer()
|
||||
total = scheduler_output.total_num_scheduled_tokens
|
||||
routed_experts_snapshot = RoutedExpertsTensors(
|
||||
routing_data=buf[:total].clone(),
|
||||
slot_mapping=self.routed_experts_slot_mapping_device[
|
||||
:total
|
||||
].clone(),
|
||||
)
|
||||
|
||||
async_output = AsyncGPUModelRunnerOutput(
|
||||
model_runner_output=output,
|
||||
sampled_token_ids=sampler_output.sampled_token_ids,
|
||||
@@ -4449,6 +4509,7 @@ class GPUModelRunner(
|
||||
invalid_req_indices=invalid_req_indices,
|
||||
async_output_copy_stream=self._get_or_create_async_output_copy_stream(),
|
||||
vocab_size=self.input_batch.vocab_size,
|
||||
routed_experts=routed_experts_snapshot,
|
||||
)
|
||||
with record_function_or_nullcontext(
|
||||
"gpu_model_runner: set_async_sampled_token_ids"
|
||||
@@ -7042,9 +7103,16 @@ class GPUModelRunner(
|
||||
kv_transfer_group.set_host_xfer_buffer_ops(copy_kv_blocks)
|
||||
|
||||
def _get_attention_kv_cache_gid(self) -> int:
|
||||
"""Find the KV cache group index for attention layers."""
|
||||
"""Find the KV cache group index for attention layers.
|
||||
|
||||
Must match :attr:`RoutedExpertsManager.attn_gid` in the scheduler:
|
||||
both pick the first ``FullAttentionSpec`` group so hybrid models
|
||||
(Mamba / linear-attention layers that use other AttentionSpec
|
||||
subclasses) end up indexing the same slot layout on both sides.
|
||||
Falls back to 0 only for legacy single-group configs.
|
||||
"""
|
||||
for gid, group in enumerate(self.kv_cache_config.kv_cache_groups):
|
||||
if isinstance(group.kv_cache_spec, AttentionSpec):
|
||||
if isinstance(group.kv_cache_spec, FullAttentionSpec):
|
||||
return gid
|
||||
return 0
|
||||
|
||||
@@ -7053,29 +7121,41 @@ class GPUModelRunner(
|
||||
"Initializing routed experts capturer, enable_return_routed_experts: %s",
|
||||
self.model_config.enable_return_routed_experts,
|
||||
)
|
||||
routed_experts_capturer = RoutedExpertsCapturer.create()
|
||||
self.routed_experts_attn_gid = self._get_attention_kv_cache_gid()
|
||||
min_block_size = min(
|
||||
[
|
||||
group.kv_cache_spec.block_size
|
||||
for group in self.kv_cache_config.kv_cache_groups
|
||||
]
|
||||
)
|
||||
num_groups = len(self.kv_cache_config.kv_cache_groups)
|
||||
self.max_num_kv_tokens = (
|
||||
self.kv_cache_config.num_blocks // num_groups
|
||||
) * min_block_size
|
||||
dcp_size = self.vllm_config.parallel_config.decode_context_parallel_size
|
||||
pcp_size = self.vllm_config.parallel_config.prefill_context_parallel_size
|
||||
if pcp_size * dcp_size > 1:
|
||||
self.max_num_kv_tokens *= pcp_size * dcp_size
|
||||
|
||||
routed_experts_capturer.init_buffer(
|
||||
self.routed_experts_capturer = RoutedExpertsCapturer(
|
||||
max_num_batched_tokens=self.scheduler_config.max_num_batched_tokens,
|
||||
max_num_kv_tokens=self.max_num_kv_tokens,
|
||||
vllm_config=self.vllm_config,
|
||||
)
|
||||
self._bind_routed_experts_capturer(routed_experts_capturer)
|
||||
self.routed_experts_attn_gid = self._get_attention_kv_cache_gid()
|
||||
self._bind_routed_experts_capturer(self.routed_experts_capturer)
|
||||
|
||||
# Pinned CPU buffer for non-blocking D2H of ``routing_data`` on
|
||||
# the sync scheduling path. Shape / dtype mirror the device
|
||||
# capturer exactly so ``copy_`` is a straight memcpy.
|
||||
self.routed_experts_cpu = torch.empty(
|
||||
self.routed_experts_capturer.device_buffer.shape,
|
||||
dtype=self.routed_experts_capturer.device_buffer.dtype,
|
||||
device="cpu",
|
||||
pin_memory=self.pin_memory,
|
||||
)
|
||||
# ``slot_mapping`` dtype is fixed to int64 by
|
||||
# ``block_table.slot_mapping``; we mirror that here.
|
||||
max_tokens = self.scheduler_config.max_num_batched_tokens
|
||||
self.routed_experts_slot_mapping_cpu = torch.empty(
|
||||
(max_tokens,),
|
||||
dtype=torch.int64,
|
||||
device="cpu",
|
||||
pin_memory=self.pin_memory,
|
||||
)
|
||||
# Private device buffer so the shared ``block_table.slot_mapping``
|
||||
# can be overwritten by the next ``_prepare_inputs`` while the
|
||||
# D2H is still pending on the copy stream. Written in
|
||||
# ``_prepare_inputs``, read in ``_bookkeeping_sync`` (sync path)
|
||||
# or cloned into a snapshot (async path).
|
||||
self.routed_experts_slot_mapping_device = torch.empty(
|
||||
(max_tokens,),
|
||||
dtype=torch.int64,
|
||||
device=self.device,
|
||||
)
|
||||
self.routed_experts_initialized = True
|
||||
|
||||
def _bind_routed_experts_capturer(self, capturer: RoutedExpertsCapturer) -> None:
|
||||
|
||||
Reference in New Issue
Block a user