[Feature][Spec Decode] Support sampling mask replay for MRV2 MTP (#59359)

Signed-off-by: Cuiping Cheng <chengcuipingswu@163.com>
Signed-off-by: aoshen02 <aoshen@inferact.ai>
Co-authored-by: Cuiping Cheng <chengcuipingswu@163.com>
Co-authored-by: aoshen02 <aoshen@inferact.ai>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vx120
2026-10-01 13:51:39 +08:00
committed by GitHub
co-authored by Cuiping Cheng aoshen02 Claude Opus 5.5
parent 37cecc8141
commit 70be6aae19
13 changed files with 583 additions and 68 deletions
+8 -2
View File
@@ -1265,9 +1265,15 @@ class VllmConfig:
return
if not self.use_v2_model_runner:
raise ValueError("sampling distribution replay requires Model Runner V2")
if self.speculative_config is not None:
speculative_config = self.speculative_config
if (
speculative_config is not None
and speculative_config.enable_adaptive_verification
):
raise ValueError(
"sampling distribution replay does not support speculative decoding"
"sampling distribution replay with speculative decoding "
"requires fixed verification boundaries; disable adaptive "
"verification"
)
if model_config.is_diffusion:
raise ValueError(
+5 -1
View File
@@ -441,7 +441,11 @@ class RequestState:
sampling_mask = None
if finished and self.sampling_mask_chunks:
sampling_mask = SamplingMask(
[chunk.token_ids.tolist() for chunk in self.sampling_mask_chunks]
[
position
for chunk in self.sampling_mask_chunks
for position in chunk.to_nested_list()
]
)
# Concatenate routed experts on finish
+10 -4
View File
@@ -57,19 +57,25 @@ class LogprobsLists(NamedTuple):
class SamplingMaskLists(NamedTuple):
"""CSR sampling masks; a step slice holds one position (``offsets=None``)."""
"""CSR sampling masks; a request slice may contain multiple positions."""
# [num_kept_tokens]
token_ids: np.ndarray
# [num_positions + 1], or None for a single position
offsets: np.ndarray | None = None
# Unused with one position per request; kept for the wire layout.
# [num_requests + 1] for multi-position request batches.
cu_num_generated_tokens: list[int] | None = None
def slice_request(self, req_idx: int, num_positions: int) -> "SamplingMaskLists":
assert num_positions == 1 and self.offsets is not None
assert self.offsets is not None
cu = self.cu_num_generated_tokens
start = req_idx if cu is None else cu[req_idx]
end = start + num_positions
lo, hi = self.offsets[start], self.offsets[end]
if num_positions == 1:
return SamplingMaskLists(self.token_ids[lo:hi])
return SamplingMaskLists(
self.token_ids[self.offsets[req_idx] : self.offsets[req_idx + 1]]
self.token_ids[lo:hi], self.offsets[start : end + 1] - lo
)
def to_nested_list(self) -> list[list[int]]:
+1 -1
View File
@@ -185,7 +185,7 @@ class AsyncOutput(AsyncModelRunnerOutput):
if self.sampling_mask_tensors is not None:
self.model_runner_output.sampling_masks = (
self.sampling_mask_tensors.tolists()
self.sampling_mask_tensors.tolists(self.num_sampled_tokens_np)
)
if self.num_nans is not None:
+70 -21
View File
@@ -2,6 +2,7 @@
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from __future__ import annotations
from collections.abc import Sequence
from dataclasses import dataclass
from typing import NamedTuple
@@ -27,6 +28,7 @@ def _compact_sampling_mask_kernel(
logits_ptr,
logits_row_stride,
logits_col_stride,
cu_num_logits_ptr,
num_sampled_tokens_ptr,
token_ids_ptr,
token_ids_row_stride,
@@ -35,25 +37,32 @@ def _compact_sampling_mask_kernel(
counts_ptr,
vocab_size,
max_num_kept,
ROWS_PER_REQUEST: tl.constexpr,
BLOCK_SIZE: tl.constexpr,
):
"""Per row: first ``max_num_kept`` finite-logit ids, the full count, the bitmask."""
req_idx = tl.program_id(0)
is_active = tl.load(num_sampled_tokens_ptr + req_idx) > 0
output_row = tl.program_id(0)
req_idx = output_row // ROWS_PER_REQUEST
slot_idx = output_row % ROWS_PER_REQUEST
if slot_idx >= tl.load(num_sampled_tokens_ptr + req_idx):
tl.store(counts_ptr + output_row, 0)
return
source_row = tl.load(cu_num_logits_ptr + req_idx) + slot_idx
count = tl.zeros((), dtype=tl.int32)
for start_idx in range(0, vocab_size, BLOCK_SIZE):
offsets = start_idx + tl.arange(0, BLOCK_SIZE)
logits = tl.load(
logits_ptr + req_idx * logits_row_stride + offsets * logits_col_stride,
logits_ptr + source_row * logits_row_stride + offsets * logits_col_stride,
mask=offsets < vocab_size,
other=-float("inf"),
)
keep = (logits > -float("inf")) & (logits < float("inf")) & is_active
keep = (logits > -float("inf")) & (logits < float("inf"))
keep_i32 = keep.to(tl.int32)
pos = count + tl.cumsum(keep_i32, axis=0) - keep_i32
tl.store(
token_ids_ptr + req_idx * token_ids_row_stride + pos,
token_ids_ptr + output_row * token_ids_row_stride + pos,
offsets.to(tl.int32),
mask=keep & (pos < max_num_kept),
)
@@ -62,12 +71,12 @@ def _compact_sampling_mask_kernel(
bits = tl.reshape(keep_i32, (BLOCK_SIZE // 8, 8)) << tl.arange(0, 8)[None, :]
byte_offsets = start_idx // 8 + tl.arange(0, BLOCK_SIZE // 8)
tl.store(
packed_mask_ptr + req_idx * packed_mask_row_stride + byte_offsets,
packed_mask_ptr + output_row * packed_mask_row_stride + byte_offsets,
tl.sum(bits, axis=1).to(tl.uint8),
mask=byte_offsets < tl.cdiv(vocab_size, 8),
)
tl.store(counts_ptr + req_idx, count)
tl.store(counts_ptr + output_row, count)
# Bounds the [num_reqs, width] int32 buffer; wider rows use the bitmask instead.
@@ -78,37 +87,46 @@ class SamplingMaskTensors(NamedTuple):
"""Device-side masks pending async D2H: compact ids, plus the bitmask as
the exact fallback for rows wider than ``max_num_kept``."""
# [num_requests, max_num_kept]
# [num_requests * rows_per_request, max_num_kept]
token_ids: torch.Tensor
# [num_requests, ceil(vocab_size / 8)]
# [num_requests * rows_per_request, ceil(vocab_size / 8)]
packed_mask: torch.Tensor
# [num_requests]
# [num_requests * rows_per_request]
counts: torch.Tensor
vocab_size: int
# Fixed request-major output slots. Ordinary sampling has one slot.
rows_per_request: int = 1
@classmethod
def from_logits(
cls,
logits: torch.Tensor,
cu_num_logits: torch.Tensor,
num_sampled_tokens: torch.Tensor,
max_num_kept: int,
rows_per_request: int = 1,
) -> SamplingMaskTensors:
"""Capture the finite-logit support of every row with a sampled token."""
num_reqs, vocab_size = logits.shape
"""Capture committed target supports in fixed request-major slots."""
num_reqs = num_sampled_tokens.shape[0]
vocab_size = logits.shape[1]
max_num_kept = min(max_num_kept, vocab_size, MAX_COMPACT_SUPPORT)
num_output_rows = num_reqs * rows_per_request
device = logits.device
token_ids = torch.empty(
(num_reqs, max_num_kept), dtype=torch.int32, device=device
(num_output_rows, max_num_kept), dtype=torch.int32, device=device
)
packed_mask = torch.empty(
(num_reqs, (vocab_size + 7) // 8), dtype=torch.uint8, device=device
(num_output_rows, (vocab_size + 7) // 8),
dtype=torch.uint8,
device=device,
)
counts = torch.empty(num_reqs, dtype=torch.int32, device=device)
_compact_sampling_mask_kernel[(num_reqs,)](
counts = torch.empty(num_output_rows, dtype=torch.int32, device=device)
_compact_sampling_mask_kernel[(num_output_rows,)](
logits,
logits.stride(0),
logits.stride(1),
cu_num_logits,
num_sampled_tokens,
token_ids,
token_ids.stride(0),
@@ -117,9 +135,23 @@ class SamplingMaskTensors(NamedTuple):
counts,
vocab_size,
max_num_kept,
ROWS_PER_REQUEST=rows_per_request,
BLOCK_SIZE=8192,
)
return cls(token_ids, packed_mask, counts, vocab_size)
return cls(token_ids, packed_mask, counts, vocab_size, rows_per_request)
@classmethod
def cat(cls, chunks: Sequence[SamplingMaskTensors]) -> SamplingMaskTensors:
"""Join request-contiguous chunks that share one output layout."""
first = chunks[0]
assert len({(c.vocab_size, c.rows_per_request) for c in chunks}) == 1
return cls(
torch.cat([chunk.token_ids for chunk in chunks]),
torch.cat([chunk.packed_mask for chunk in chunks]),
torch.cat([chunk.counts for chunk in chunks]),
first.vocab_size,
first.rows_per_request,
)
def to_cpu_nonblocking(self) -> SamplingMaskTensors:
if self.token_ids.device.type == "cpu":
@@ -129,15 +161,31 @@ class SamplingMaskTensors(NamedTuple):
self.packed_mask.to("cpu", non_blocking=True),
self.counts.to("cpu", non_blocking=True),
self.vocab_size,
self.rows_per_request,
)
def tolists(self) -> SamplingMaskLists:
"""CSR over all requests; rows without a sampled token are empty."""
def tolists(
self, num_sampled_tokens: np.ndarray | None = None
) -> SamplingMaskLists:
"""Convert fixed output rows to the scheduler's CSR representation."""
counts = self.counts.cpu().numpy()
token_ids = self.token_ids.cpu().numpy()
packed_mask = self.packed_mask.cpu().numpy()
width = token_ids.shape[1]
cu_num_generated_tokens = None
if self.rows_per_request == 1:
sampled_rows = np.arange(len(counts))
else:
assert num_sampled_tokens is not None
active_slots = (
np.arange(self.rows_per_request)[None, :] < num_sampled_tokens[:, None]
)
sampled_rows = np.flatnonzero(active_slots)
cu_num_generated_tokens = np.cumsum(
np.concatenate(([0], num_sampled_tokens))
).tolist()
def support(row: int) -> np.ndarray:
if counts[row] <= width:
return token_ids[row, : counts[row]]
@@ -147,7 +195,8 @@ class SamplingMaskTensors(NamedTuple):
)
return np.flatnonzero(bits).astype(np.int32, copy=False)
supports = [support(row) for row in range(len(counts))]
supports = [support(row) for row in sampled_rows]
offsets = np.zeros(len(supports) + 1, dtype=np.int64)
np.cumsum([len(s) for s in supports], out=offsets[1:])
return SamplingMaskLists(np.concatenate(supports), offsets)
flat = np.concatenate([np.empty(0, dtype=np.int32), *supports])
return SamplingMaskLists(flat, offsets, cu_num_generated_tokens)
+4 -1
View File
@@ -203,7 +203,10 @@ class Sampler:
# Size by the validated top_k batch max; wider supports use the bitmask.
max_num_kept = int(np.max(self.sampling_states.top_k.np[idx_mapping_np]))
sampling_mask_tensors = SamplingMaskTensors.from_logits(
processed_logits, num_sampled, max_num_kept
processed_logits,
input_batch.cu_num_logits,
num_sampled,
max_num_kept,
)
# These are GPU tensors.
@@ -18,7 +18,7 @@ from vllm.v1.worker.gpu.input_batch import (
)
from vllm.v1.worker.gpu.metrics.logits import get_num_nans
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
from vllm.v1.worker.gpu.sample.output import SamplerOutput
from vllm.v1.worker.gpu.sample.output import SamplerOutput, SamplingMaskTensors
from vllm.v1.worker.gpu.sample.sampler import Sampler
from vllm.v1.worker.gpu.sample.states import NO_LOGPROBS
from vllm.v1.worker.gpu.spec_decode.rejection_sampler_utils import (
@@ -296,7 +296,12 @@ class RejectionSampler:
max_chunk_logits: int,
max_num_logprobs: int,
verify_draft_sampled: torch.Tensor | None = None,
) -> tuple[torch.Tensor, torch.Tensor, LogprobsTensors | None]:
) -> tuple[
torch.Tensor,
torch.Tensor,
LogprobsTensors | None,
SamplingMaskTensors | None,
]:
if verify_draft_sampled is None:
verify_draft_sampled = draft_sampled
cu_num_logits_np = input_batch.cu_num_logits_np
@@ -316,6 +321,14 @@ class RejectionSampler:
sampled_chunks: list[torch.Tensor] = []
num_sampled_chunks: list[torch.Tensor] = []
logprobs_chunks: list[LogprobsTensors] = []
sampling_mask_chunks: list[SamplingMaskTensors] = []
max_num_kept = None
if self.sampler.return_sampling_mask:
max_num_kept = int(
np.max(
self.sampler.sampling_states.top_k.np[input_batch.idx_mapping_np]
)
)
for start, end in request_chunks:
lo = int(cu_num_logits_np[start])
@@ -346,13 +359,31 @@ class RejectionSampler:
)
if chunk_logprobs is not None:
logprobs_chunks.append(chunk_logprobs)
if max_num_kept is not None:
sampling_mask_chunks.append(
SamplingMaskTensors.from_logits(
processed_logits,
chunk_cu_num_logits,
num_sampled,
max_num_kept,
self.num_speculative_steps + 1,
)
)
del processed_logits
sampled_chunks.append(sampled)
num_sampled_chunks.append(num_sampled)
if len(sampled_chunks) == 1:
logprobs_tensors = logprobs_chunks[0] if logprobs_chunks else None
return sampled_chunks[0], num_sampled_chunks[0], logprobs_tensors
sampling_mask_tensors = (
sampling_mask_chunks[0] if sampling_mask_chunks else None
)
return (
sampled_chunks[0],
num_sampled_chunks[0],
logprobs_tensors,
sampling_mask_tensors,
)
logprobs_tensors = None
if logprobs_chunks:
@@ -366,7 +397,12 @@ class RejectionSampler:
sampled = torch.cat(sampled_chunks)
num_sampled = torch.cat(num_sampled_chunks)
return sampled, num_sampled, logprobs_tensors
sampling_mask_tensors = (
SamplingMaskTensors.cat(sampling_mask_chunks)
if sampling_mask_chunks
else None
)
return sampled, num_sampled, logprobs_tensors, sampling_mask_tensors
def __call__(
self,
@@ -400,7 +436,12 @@ class RejectionSampler:
input_batch.idx_mapping_np
)
chunk_logit_limit = get_max_chunk_logits(logits.shape[1])
sampled, num_sampled, logprobs_tensors = self._verify_in_chunks(
(
sampled,
num_sampled,
logprobs_tensors,
sampling_mask_tensors,
) = self._verify_in_chunks(
logits,
input_batch,
draft_logits,
@@ -425,4 +466,5 @@ class RejectionSampler:
num_nans=num_nans,
num_sampled=num_sampled,
num_rejected=num_rejected,
sampling_mask_tensors=sampling_mask_tensors,
)