[Perf][GLM-5.2] Blackwell decode optimizations (#48597)
Signed-off-by: Peiyuan Zhou <peiyuanzhou1994@gmail.com> Signed-off-by: zhou <zhou@zhoudeMacBook-Pro.local> Signed-off-by: Stefan Koncarevic <stefan.koncarevic@amd.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Giancarlo Delfin <32987265+TheEpicDolphin@users.noreply.github.com> Co-authored-by: Thien Tran <gau.nernst@yahoo.com.sg> Co-authored-by: OpenAI Codex <codex@openai.com> Co-authored-by: zhou <zhou@zhoudeMacBook-Pro.local> Co-authored-by: stefankoncarevic <Stefan.Koncarevic@amd.com>
This commit is contained in:
co-authored by
Claude
Giancarlo Delfin
Thien Tran
OpenAI Codex
zhou
stefankoncarevic
parent
0d77325b10
commit
dd72658e7d
@@ -28,6 +28,7 @@ from vllm.v1.attention.backend import (
|
||||
MultipleOf,
|
||||
)
|
||||
from vllm.v1.attention.backends.mla.sparse_utils import (
|
||||
phys_shadow,
|
||||
triton_convert_req_index_to_global_index,
|
||||
triton_filter_and_convert_dcp_index,
|
||||
)
|
||||
@@ -404,6 +405,36 @@ class FlashInferMLASparseImpl(SparseMLACommonImpl[FlashInferMLASparseMetadata]):
|
||||
NUM_TOPK_TOKENS=topk_indices.shape[1],
|
||||
return_valid_counts=True,
|
||||
)
|
||||
elif (shadow := phys_shadow(self.topk_indices_buffer)) is not None:
|
||||
# skip_topk layers reuse the previous fresh layer's PHYSICAL
|
||||
# indices: the logical top-k indices are shared (one buffer for
|
||||
# the whole forward) and block_table/req_id are per-step constant,
|
||||
# so re-converting them per layer produces identical output. This
|
||||
# covers both the backbone (index_topk_freq > 1) and MTP draft
|
||||
# steps 1+ (index_share_for_mtp_iteration sets skip_topk; the
|
||||
# draft compact re-arranges the shadow together with the logical
|
||||
# buffer). The fresh/skip split is fixed per captured graph, so
|
||||
# the branch is cudagraph-safe.
|
||||
phys_buf, seq_buf = shadow
|
||||
wrote_fresh = getattr(layer, "indexer", None) is not None and not getattr(
|
||||
layer, "skip_topk", False
|
||||
)
|
||||
if wrote_fresh:
|
||||
topk_indices_physical, seq_lens = (
|
||||
triton_convert_req_index_to_global_index(
|
||||
attn_metadata.req_id_per_token[:num_actual_toks],
|
||||
attn_metadata.block_table,
|
||||
topk_indices,
|
||||
BLOCK_SIZE=attn_metadata.block_size,
|
||||
NUM_TOPK_TOKENS=topk_indices.shape[1],
|
||||
return_valid_counts=True,
|
||||
out=phys_buf[:num_actual_toks],
|
||||
valid_counts_out=seq_buf[:num_actual_toks],
|
||||
)
|
||||
)
|
||||
else:
|
||||
topk_indices_physical = phys_buf[:num_actual_toks]
|
||||
seq_lens = seq_buf[:num_actual_toks]
|
||||
else:
|
||||
topk_indices_physical, seq_lens = triton_convert_req_index_to_global_index(
|
||||
attn_metadata.req_id_per_token[:num_actual_toks],
|
||||
|
||||
@@ -128,6 +128,8 @@ def triton_convert_req_index_to_global_index(
|
||||
prefill_workspace_request_ids: torch.Tensor | None = None,
|
||||
prefill_workspace_starts: torch.Tensor | None = None,
|
||||
return_valid_counts: bool = False,
|
||||
out: torch.Tensor | None = None,
|
||||
valid_counts_out: torch.Tensor | None = None,
|
||||
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
||||
"""
|
||||
out[token_id, indice_id] =
|
||||
@@ -178,14 +180,20 @@ def triton_convert_req_index_to_global_index(
|
||||
req_id_c = req_id.contiguous()
|
||||
block_table_c = block_table.contiguous()
|
||||
token_indices_c = token_indices.contiguous()
|
||||
out = torch.empty_like(token_indices_c)
|
||||
# `out`/`valid_counts_out` allow writing into a stable pre-allocated buffer
|
||||
# (used by the shared-physical-index cache to stay cudagraph-safe).
|
||||
out = torch.empty_like(token_indices_c) if out is None else out
|
||||
|
||||
# Allocate valid count buffer if needed (must be zero-initialized for atomics)
|
||||
valid_counts: torch.Tensor | None = None
|
||||
if return_valid_counts:
|
||||
valid_counts = torch.zeros(
|
||||
num_tokens, dtype=torch.int32, device=token_indices.device
|
||||
)
|
||||
if valid_counts_out is None:
|
||||
valid_counts = torch.zeros(
|
||||
num_tokens, dtype=torch.int32, device=token_indices.device
|
||||
)
|
||||
else:
|
||||
valid_counts = valid_counts_out
|
||||
valid_counts.zero_()
|
||||
|
||||
# Strides in elements
|
||||
bt_stride0, bt_stride1 = block_table_c.stride()
|
||||
@@ -341,3 +349,47 @@ def triton_filter_and_convert_dcp_index(
|
||||
assert valid_counts is not None
|
||||
return out, valid_counts
|
||||
return out
|
||||
|
||||
|
||||
# --- Physical-index shadow (DSA index_topk_freq > 1) -------------------------
|
||||
# GLM-5.2 uses index_topk_freq=4: only ~1/4 of layers write a fresh top-k into
|
||||
# the single shared topk_indices_buffer; the rest reuse it. Since block_table
|
||||
# and req_id_per_token are constant within a decode step, the physical indices
|
||||
# (block_table lookup of the logical top-k) are identical across a freq-group.
|
||||
# Fresh layers convert once into a STABLE shadow of the logical buffer and
|
||||
# skip layers read it -- eliminating ~3/4 of the per-layer convert kernels.
|
||||
#
|
||||
# Invariant: shadow[j] == convert(logical[j]) row-wise. Whoever re-arranges
|
||||
# the logical buffer (e.g. the MTP draft compact between the multi-token
|
||||
# step-0 layout and the single-token steps-1+ layout) must apply the same
|
||||
# gather to the shadow.
|
||||
#
|
||||
# Shadows are registered ONLY at buffer creation time (model init, never
|
||||
# inside cudagraph capture) via register_phys_shadow; every other access is
|
||||
# the read-only phys_shadow lookup, so addresses are stable across graph
|
||||
# replays and no allocation can happen during capture.
|
||||
import weakref as _weakref # noqa: E402
|
||||
|
||||
_PHYS_SHADOWS: dict[int, tuple[torch.Tensor, torch.Tensor]] = {}
|
||||
|
||||
|
||||
def register_phys_shadow(topk_buf: torch.Tensor) -> None:
|
||||
"""Allocate the (physical-index, valid-count) shadow for a logical top-k
|
||||
buffer. Call once where the buffer is created. The finalizer drops the
|
||||
entry with the owning buffer, so a recycled id can never alias a stale
|
||||
shadow."""
|
||||
key = id(topk_buf)
|
||||
if key not in _PHYS_SHADOWS:
|
||||
_PHYS_SHADOWS[key] = (
|
||||
torch.empty_like(topk_buf),
|
||||
torch.empty(topk_buf.shape[0], dtype=torch.int32, device=topk_buf.device),
|
||||
)
|
||||
_weakref.finalize(topk_buf, _PHYS_SHADOWS.pop, key, None)
|
||||
|
||||
|
||||
def phys_shadow(
|
||||
topk_buf: torch.Tensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor] | None:
|
||||
"""The registered shadow for this buffer, or None if it was never
|
||||
registered. Never allocates; capture-safe."""
|
||||
return _PHYS_SHADOWS.get(id(topk_buf))
|
||||
|
||||
@@ -1009,8 +1009,9 @@ class SpecDecodeBaseProposer:
|
||||
# DeepSeek-family MTP (deepseek_mtp.py) recycles the post-final-
|
||||
# norm hidden, so its forward returns (logit_hidden,
|
||||
# recycle_hidden). Other MTP families return a single tensor.
|
||||
return "DeepSeekMTPModel" in (
|
||||
self.draft_model_config.hf_config.architectures or []
|
||||
return bool(
|
||||
{"DeepSeekMTPModel", "DeepseekV32MTPModel"}
|
||||
& set(self.draft_model_config.hf_config.architectures or [])
|
||||
)
|
||||
return self.method not in ("mtp", "draft_model", "dflash")
|
||||
|
||||
|
||||
@@ -48,6 +48,18 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
self.prefill_cudagraph_manager: SpeculatorCudaGraphManager | None = None
|
||||
self.decode_cudagraph_manager: SpeculatorCudaGraphManager | None = None
|
||||
|
||||
# Lifecycle hooks for model-specific optimizations. Subclasses override
|
||||
# the ones they need. These fire in both `capture` and `propose` so that
|
||||
# any state they toggle (e.g. attention flags baked into a CUDA graph) is
|
||||
# identical at capture time and replay time.
|
||||
def on_prefill_begin(self, num_reqs: int, num_tokens: int) -> None: ...
|
||||
|
||||
def on_prefill_end(self, num_reqs: int, num_tokens: int) -> None: ...
|
||||
|
||||
def on_multi_step_decode_begin(self, num_reqs: int) -> None: ...
|
||||
|
||||
def on_multi_step_decode_end(self, num_reqs: int) -> None: ...
|
||||
|
||||
@property
|
||||
def advance_draft_positions(self) -> bool:
|
||||
"""
|
||||
@@ -98,6 +110,9 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
assert self.prefill_cudagraph_manager is not None
|
||||
if self.prefill_cudagraph_manager.use_breakable_cg:
|
||||
self.prefill_cudagraph_manager.init_breakable_cg_runner(self.model)
|
||||
|
||||
self.on_prefill_begin(self.max_num_reqs, self.max_num_tokens)
|
||||
|
||||
self.prefill_cudagraph_manager.capture(
|
||||
self._prefill,
|
||||
self.model_state,
|
||||
@@ -108,9 +123,13 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
progress_bar_desc="Capturing prefill CUDA graphs",
|
||||
)
|
||||
|
||||
self.on_prefill_end(self.max_num_reqs, self.max_num_tokens)
|
||||
|
||||
if self.num_speculative_steps == 1:
|
||||
return
|
||||
|
||||
self.on_multi_step_decode_begin(self.max_num_reqs)
|
||||
|
||||
# Capture the decode draft generation routine (model forward +
|
||||
# sample + update_draft_inputs) for a single
|
||||
# step.
|
||||
@@ -125,6 +144,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
progress_bar_desc="Capturing decode CUDA graphs",
|
||||
)
|
||||
|
||||
self.on_multi_step_decode_end(self.max_num_reqs)
|
||||
|
||||
@torch.inference_mode()
|
||||
def propose(
|
||||
self,
|
||||
@@ -153,7 +174,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
mm_inputs: tuple[list[torch.Tensor], torch.Tensor] | None = None,
|
||||
is_profile: bool = False,
|
||||
) -> torch.Tensor:
|
||||
num_tokens = input_batch.num_tokens_after_padding
|
||||
num_tokens = input_batch.num_tokens
|
||||
num_tokens_padded = input_batch.num_tokens_after_padding
|
||||
num_reqs = input_batch.num_reqs
|
||||
max_query_len = input_batch.num_scheduled_tokens.max()
|
||||
max_seq_len = input_batch.seq_lens_cpu_upper_bound[:num_reqs].max().item()
|
||||
@@ -174,7 +196,7 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
)
|
||||
else:
|
||||
hidden_states = last_hidden_states
|
||||
self.hidden_states[:num_tokens].copy_(hidden_states)
|
||||
self.hidden_states[:num_tokens_padded].copy_(hidden_states)
|
||||
|
||||
self._copy_request_inputs(
|
||||
num_reqs,
|
||||
@@ -202,20 +224,22 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
num_reqs,
|
||||
# Use the actual number of tokens without padding added by
|
||||
# the target model during FULL cudagraph.
|
||||
input_batch.num_tokens,
|
||||
num_tokens,
|
||||
max_query_len,
|
||||
)
|
||||
prefill_batch_desc, num_tokens_across_dp = dispatch_cg_and_sync_dp(
|
||||
self.prefill_cudagraph_manager,
|
||||
num_reqs,
|
||||
num_tokens,
|
||||
num_tokens_padded,
|
||||
uniform_token_count,
|
||||
dp_size=self.dp_size,
|
||||
dp_rank=self.dp_rank,
|
||||
need_eager=is_profile,
|
||||
)
|
||||
|
||||
self._prepare_eplb_forward(input_batch.num_tokens)
|
||||
self._prepare_eplb_forward(num_tokens)
|
||||
|
||||
self.on_prefill_begin(num_reqs, num_tokens)
|
||||
|
||||
if prefill_batch_desc.cg_mode == CUDAGraphMode.FULL:
|
||||
# Replay the full graph for draft prefill.
|
||||
@@ -235,6 +259,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
mm_inputs=mm_inputs,
|
||||
)
|
||||
|
||||
self.on_prefill_end(num_reqs, num_tokens)
|
||||
|
||||
if self.num_speculative_steps == 1:
|
||||
# Early exit.
|
||||
return self.draft_tokens[:num_reqs, :1]
|
||||
@@ -262,6 +288,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
need_eager=is_profile,
|
||||
)
|
||||
|
||||
self.on_multi_step_decode_begin(num_reqs)
|
||||
|
||||
# Generate the remaining num_speculative_steps - 1 draft tokens.
|
||||
self._multi_step_decode(
|
||||
num_reqs,
|
||||
@@ -271,6 +299,8 @@ class AutoRegressiveSpeculator(DraftModelSpeculator):
|
||||
input_batch.seq_lens_cpu_upper_bound,
|
||||
)
|
||||
|
||||
self.on_multi_step_decode_end(num_reqs)
|
||||
|
||||
return self.draft_tokens[:num_reqs]
|
||||
|
||||
@torch.inference_mode()
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.v1.worker.gpu.spec_decode.autoregressive.speculator import (
|
||||
AutoRegressiveSpeculator,
|
||||
)
|
||||
@@ -10,9 +12,46 @@ from vllm.v1.worker.gpu.spec_decode.eagle.utils import load_eagle_model
|
||||
|
||||
|
||||
class MTPSpeculator(AutoRegressiveSpeculator):
|
||||
def __init__(self, vllm_config: VllmConfig, device: torch.device):
|
||||
super().__init__(vllm_config, device)
|
||||
|
||||
spec_config = vllm_config.speculative_config
|
||||
draft_hf_config = (
|
||||
spec_config.draft_model_config.hf_config
|
||||
if spec_config is not None
|
||||
else None
|
||||
)
|
||||
# Detect index_share_for_mtp_iteration. When True, the proposer
|
||||
# toggles skip_topk so step 0 computes MTP's own indices and
|
||||
# steps 1+ reuse them.
|
||||
self.share_mtp_topk_indices = getattr(
|
||||
draft_hf_config, "index_share_for_mtp_iteration", False
|
||||
)
|
||||
|
||||
def load_draft_model(
|
||||
self,
|
||||
target_model: nn.Module,
|
||||
target_attn_layer_names: set[str],
|
||||
) -> nn.Module:
|
||||
return load_eagle_model(target_model, self.vllm_config)
|
||||
draft_model = load_eagle_model(target_model, self.vllm_config)
|
||||
self.share_mtp_topk_indices = self.share_mtp_topk_indices and hasattr(
|
||||
draft_model.model, "set_skip_topk"
|
||||
)
|
||||
return draft_model
|
||||
|
||||
def on_prefill_end(self, num_reqs: int, num_tokens: int) -> None:
|
||||
# Step 0 (prefill) wrote topk indices for every query token in the
|
||||
# multi-token batch. Compact them down to each request's last token so
|
||||
# steps 1+ can reuse them from the shared buffer.
|
||||
if self.share_mtp_topk_indices and self.num_speculative_steps > 1:
|
||||
self.model.model.compact_topk_indices(self.last_token_indices[:num_reqs])
|
||||
|
||||
def on_multi_step_decode_begin(self, num_reqs: int) -> None:
|
||||
# Switch to reuse mode so draft steps 1+ skip the indexer op and read
|
||||
# the indices that step 0 wrote into the shared buffer.
|
||||
if self.share_mtp_topk_indices:
|
||||
self.model.model.set_skip_topk(True)
|
||||
|
||||
def on_multi_step_decode_end(self, num_reqs: int) -> None:
|
||||
if self.share_mtp_topk_indices:
|
||||
self.model.model.set_skip_topk(False)
|
||||
|
||||
Reference in New Issue
Block a user