[AuxOutput] Add block-keyed storage for routed-expert outputs (#45635)

Signed-off-by: aoshen02 <aoshen@inferact.ai>
Signed-off-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: aoshen02 <aoshen@inferact.ai>
Co-authored-by: OpenAI Codex <codex@openai.com>
Co-authored-by: Roger Wang <hey@rogerw.io>
Co-authored-by: Nick Hill <nickhill123@gmail.com>
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Hongxin Xu
2026-09-21 10:25:05 +00:00
committed by GitHub
co-authored by aoshen02 OpenAI Codex Roger Wang Nick Hill Codex
parent 0aee727ff6
commit 0b7f11a1ee
32 changed files with 3604 additions and 877 deletions
-127
View File
@@ -61,10 +61,6 @@ from vllm.lora.layers import BaseLayerWithLoRA, LoRAMapping, LoRAMappingType
from vllm.model_executor.layers.attention import Attention
from vllm.model_executor.layers.attention_layer_base import AttentionLayerBase
from vllm.model_executor.layers.fused_moe.all2all_utils import get_ep_all2all_manager
from vllm.model_executor.layers.fused_moe.routed_experts_capturer import (
RoutedExpertsCapturer,
bind_routed_experts_capturer,
)
from vllm.model_executor.layers.mamba.mamba_utils import MambaStateCopyFuncsByType
from vllm.model_executor.layers.mamba.ops.ssu_dispatch import (
initialize_mamba_ssu_backend,
@@ -176,8 +172,6 @@ from vllm.v1.outputs import (
LogprobsTensors,
ModelRunnerOutput,
PoolerOutput,
RoutedExpertsLists,
RoutedExpertsTensors,
SamplerOutput,
make_empty_encoder_model_runner_output,
)
@@ -293,7 +287,6 @@ class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput):
invalid_req_indices: list[int],
async_output_copy_stream: torch.cuda.Stream,
vocab_size: int,
routed_experts: RoutedExpertsTensors | None = None,
check_ep_fault: bool = False,
num_nans: torch.Tensor | None = None,
):
@@ -309,7 +302,6 @@ 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
self._num_nans = num_nans
self._has_fault: torch.Tensor | None = None
@@ -325,11 +317,6 @@ 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._num_nans_cpu = (
self._num_nans.to("cpu", non_blocking=True)
if self._num_nans is not None
@@ -370,10 +357,6 @@ class AsyncGPUModelRunnerOutput(AsyncModelRunnerOutput):
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
if self._num_nans_cpu is not None:
output.num_nans_in_logits = nans_to_dict(
self._num_nans_cpu.tolist(), output.req_id_to_index
@@ -537,9 +520,6 @@ class GPUModelRunner(
# These will be overridden in load_model()
self.is_multimodal_pruning_enabled = False
self.requires_sequential_video_encoding = False
# Set to True after init_routed_experts_capturer() completes.
# Prevents routed experts code from running during profiling/dummy run.
self.routed_experts_initialized = False
self.max_model_len = model_config.max_model_len
# Always set to false after the first forward pass
@@ -2360,18 +2340,6 @@ class GPUModelRunner(
block_table_gid_0 = _get_block_table(0)
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.
slot_mapping_attn = slot_mappings[self.routed_experts_capturer.attn_gid]
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
]
@@ -3745,20 +3713,6 @@ 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,
)
with gpu_sync_allowed():
# Get the valid generated tokens.
max_gen_len = sampled_token_ids.shape[-1]
@@ -4802,39 +4756,14 @@ 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 the next forward overwrites 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 = self.get_routed_experts(
scheduler_output.total_num_scheduled_tokens
)
async_output = AsyncGPUModelRunnerOutput(
model_runner_output=output,
sampled_token_ids=sampler_output.sampled_token_ids,
@@ -4842,7 +4771,6 @@ 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,
check_ep_fault=self.check_ep_fault,
num_nans=num_nans_device,
)
@@ -7468,61 +7396,6 @@ class GPUModelRunner(
kv_transfer_group.register_kv_caches(kv_caches)
kv_transfer_group.set_host_xfer_buffer_ops(copy_kv_blocks)
def get_routed_experts(
self,
num_tokens: int,
) -> RoutedExpertsTensors | None:
if not self.routed_experts_initialized:
return None
device_buffer = self.routed_experts_capturer.get_device_buffer()
return RoutedExpertsTensors(
routing_data=device_buffer[:num_tokens].clone(),
slot_mapping=self.routed_experts_slot_mapping_device[:num_tokens].clone(),
)
def init_routed_experts_capturer(self):
logger.info(
"Initializing routed experts capturer, enable_return_routed_experts: %s",
self.model_config.enable_return_routed_experts,
)
self.routed_experts_capturer = RoutedExpertsCapturer(
max_num_batched_tokens=self.scheduler_config.max_num_batched_tokens,
vllm_config=self.vllm_config,
kv_cache_config=self.kv_cache_config,
)
bind_routed_experts_capturer(self.model, 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=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=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 may_add_encoder_only_layers_to_kv_cache_config(self) -> None:
"""Add encoder-only layers to the KV cache config."""
block_size = self.vllm_config.cache_config.block_size