[Feature] Add fixed-token prefill scoring (#54335)

Signed-off-by: aoshen02 <aoshen@inferact.ai>
Signed-off-by: aoshen02 <aoshen02@users.noreply.github.com>
Co-authored-by: aoshen02 <aoshen02@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
aoshen02
2026-09-28 07:50:09 -07:00
committed by GitHub
co-authored by aoshen02 Claude Opus 5
parent a7ff44355c
commit b721a4c709
36 changed files with 768 additions and 8 deletions
@@ -381,6 +381,7 @@ class GenerateResponse(BaseModel):
choices: list[GenerateResponseChoice]
usage: UsageInfo | None = Field(default=None)
prompt_logprobs: list[dict[int, Logprob] | None] | None = None
prompt_token_id_logprobs: str | None = None
prompt_token_ids: list[int] | None = None
mm_placeholders: dict[str, list[PlaceholderRangeInfo]] | None = None
metrics: PerRequestMetrics | None = None
@@ -138,6 +138,11 @@ class ServingTokens(GenerateBaseServing):
f"sampling_params.n must be at most the server's max_num_seqs "
f"({max_num_seqs}), got {sampling_params.n}."
)
# The stream schema has no field for the scores.
if request.stream and sampling_params.prompt_logprob_token_ids is not None:
return self.create_error_response(
"prompt_logprob_token_ids are not available when stream=true."
)
if self.force_no_detokenize and sampling_params.stop:
# SamplingParams rejects stop with detokenize=False at request
# validation, but this server forces detokenize=False afterwards,
@@ -389,6 +394,11 @@ class ServingTokens(GenerateBaseServing):
choices=choices,
usage=usage,
prompt_logprobs=clamp_prompt_logprobs(final_res.prompt_logprobs),
prompt_token_id_logprobs=(
numpy2base64(final_res.prompt_token_id_logprobs)
if final_res.prompt_token_id_logprobs is not None
else None
),
prompt_token_ids=(
final_res.prompt_token_ids if request.return_token_ids else None
),
+7
View File
@@ -117,6 +117,10 @@ class RequestOutput:
For encoder/decoder models, this is the
decoder input prompt token ids.
prompt_logprobs: The log probabilities to return per prompt token.
prompt_token_id_logprobs: Logprobs of prompt_logprob_token_ids, shaped
[max(prompt_len - 1 - prompt_logprob_start, 0),
len(prompt_logprob_token_ids)]; row i scores them as predictions of
prompt token prompt_logprob_start + i + 1.
outputs: The output sequences of the request.
finished: Whether the whole request is finished.
metrics: Metrics associated with the request.
@@ -148,6 +152,7 @@ class RequestOutput:
num_cached_tokens: int | None = None,
num_cache_creation_tokens: int | None = None,
*,
prompt_token_id_logprobs: np.ndarray | None = None,
kv_transfer_params: dict[str, Any] | None = None,
ec_transfer_params: dict[str, Any] | None = None,
# Forward compatibility, code that uses args added in new release can
@@ -162,6 +167,7 @@ class RequestOutput:
self.prompt = prompt
self.prompt_token_ids = prompt_token_ids
self.prompt_logprobs = prompt_logprobs
self.prompt_token_id_logprobs = prompt_token_id_logprobs
self.outputs = outputs
self.finished = finished
self.metrics = metrics
@@ -215,6 +221,7 @@ class RequestOutput:
f"encoder_prompt={self.encoder_prompt!r}, "
f"encoder_prompt_token_ids={self.encoder_prompt_token_ids}, "
f"prompt_logprobs={self.prompt_logprobs}, "
f"prompt_token_id_logprobs={self.prompt_token_id_logprobs}, "
f"outputs={self.outputs}, "
f"finished={self.finished}, "
f"metrics={self.metrics}, "
+68 -1
View File
@@ -289,6 +289,12 @@ class SamplingParams(
prompt_logprobs: int | None = None
"""Number of log probabilities to return per prompt token.
When set to -1, return all `vocab_size` log probabilities."""
prompt_logprob_token_ids: list[int] | None = None
"""Token IDs to score at each scored causal prompt row, where row i scores
them as predictions of prompt token i + 1. The last prompt row is excluded,
so the result has `max(prompt_len - 1 - prompt_logprob_start, 0)` rows."""
prompt_logprob_start: int | None = None
"""First causal prompt row to score; defaults to the first row."""
logprob_token_ids: list[int] | None = None
"""Specific token IDs to return logprobs for. More efficient than
logprobs=-1 when you only need logprobs for a small set of tokens.
@@ -398,6 +404,8 @@ class SamplingParams(
min_tokens: int = 0,
logprobs: int | None = None,
prompt_logprobs: int | None = None,
prompt_logprob_token_ids: list[int] | None = None,
prompt_logprob_start: int | None = None,
detokenize: bool = True,
skip_special_tokens: bool = True,
spaces_between_special_tokens: bool = True,
@@ -464,6 +472,8 @@ class SamplingParams(
min_tokens=min_tokens,
logprobs=logprobs,
prompt_logprobs=prompt_logprobs,
prompt_logprob_token_ids=prompt_logprob_token_ids,
prompt_logprob_start=prompt_logprob_start,
logprob_token_ids=logprob_token_ids,
detokenize=detokenize,
skip_special_tokens=skip_special_tokens,
@@ -550,7 +560,10 @@ class SamplingParams(
# If prefix caching is enabled,
# the output of prompt logprobs may less than n_prompt_tokens,
# we need to skip reading cache at this request.
self.skip_reading_prefix_cache = self.prompt_logprobs is not None
self.skip_reading_prefix_cache = (
self.prompt_logprobs is not None
or self.prompt_logprob_token_ids is not None
)
def _verify_args(self) -> None:
_verify_num_sequences(self.n, "n")
@@ -902,6 +915,56 @@ class SamplingParams(
value=num_prompt_logprobs,
)
# Validate prompt_logprob_token_ids.
if self.prompt_logprob_token_ids is not None:
n = len(self.prompt_logprob_token_ids)
if n == 0:
raise VLLMValidationError(
"prompt_logprob_token_ids must not be empty.",
parameter="prompt_logprob_token_ids",
value=n,
)
if n > max_logprobs:
raise VLLMValidationError(
f"Requested prompt_logprob_token_ids of length {n}, "
f"which is greater than max allowed: {max_logprobs}. "
f"Set max_logprobs (--max-logprobs) to at least {n}.",
parameter="prompt_logprob_token_ids",
value=n,
)
vocab_size = model_config.get_vocab_size()
invalid_token_ids = [
token_id
for token_id in self.prompt_logprob_token_ids
if token_id < 0 or token_id >= vocab_size
]
if invalid_token_ids:
raise VLLMValidationError(
f"token_id(s) {invalid_token_ids} in "
f"prompt_logprob_token_ids contain out-of-vocab token ids. "
f"Vocabulary size: {vocab_size}",
parameter="prompt_logprob_token_ids",
value=invalid_token_ids,
)
if len(set(self.prompt_logprob_token_ids)) != n:
raise VLLMValidationError(
"prompt_logprob_token_ids must not contain duplicates.",
parameter="prompt_logprob_token_ids",
value=self.prompt_logprob_token_ids,
)
if self.prompt_logprob_start is not None and self.prompt_logprob_start < 0:
raise VLLMValidationError(
"prompt_logprob_start must be non-negative.",
parameter="prompt_logprob_start",
value=self.prompt_logprob_start,
)
elif self.prompt_logprob_start is not None:
raise VLLMValidationError(
"prompt_logprob_start requires prompt_logprob_token_ids.",
parameter="prompt_logprob_start",
value=self.prompt_logprob_start,
)
def _validate_stop_token_ids(self, model_config: ModelConfig) -> None:
"""Validate stop_token_ids are within vocabulary range."""
if not self.stop_token_ids:
@@ -969,6 +1032,10 @@ class SamplingParams(
raise ValueError(
"trace_decode_token_ids is not supported with prompt_logprobs."
)
if self.prompt_logprob_token_ids is not None:
raise ValueError(
"trace_decode_token_ids is not supported with prompt_logprob_token_ids."
)
if speculative_config is not None:
raise ValueError(
"trace_decode_token_ids is not supported with speculative decoding."
+6
View File
@@ -1972,6 +1972,9 @@ class Scheduler(SchedulerInterface):
sampled_token_ids = model_runner_output.sampled_token_ids
logprobs = model_runner_output.logprobs
prompt_logprobs_dict = model_runner_output.prompt_logprobs_dict
prompt_token_id_logprobs_dict = (
model_runner_output.prompt_token_id_logprobs_dict
)
num_scheduled_tokens = scheduler_output.num_scheduled_tokens
pooler_outputs = model_runner_output.pooler_output
num_nans_in_logits = model_runner_output.num_nans_in_logits
@@ -2194,6 +2197,7 @@ class Scheduler(SchedulerInterface):
# Get prompt logprobs for this request.
prompt_logprobs_tensors = prompt_logprobs_dict.get(req_id)
prompt_token_id_logprobs = prompt_token_id_logprobs_dict.get(req_id)
if should_emit_output:
# Add EngineCoreOutput for this Request.
outputs[request.client_index].append(
@@ -2204,6 +2208,7 @@ class Scheduler(SchedulerInterface):
new_logprobs=new_logprobs,
new_sampling_mask=new_sampling_mask,
new_prompt_logprobs_tensors=prompt_logprobs_tensors,
prompt_token_id_logprobs=prompt_token_id_logprobs,
pooling_output=pooler_output,
stop_reason=request.stop_reason,
events=request.take_events(),
@@ -2223,6 +2228,7 @@ class Scheduler(SchedulerInterface):
else:
# Invariant: EngineCore returns no partial prefill outputs.
assert not prompt_logprobs_tensors
assert prompt_token_id_logprobs is None
# Remove the stopped requests from the running and waiting queues.
if stopped_running_reqs:
+3
View File
@@ -236,6 +236,9 @@ class EngineCoreOutput(
# Appended last so `array_like` positional serialization stays compatible.
spec_decode_metrics: RequestSpecDecodeMetrics | None = None
# [num_scored_rows, num_token_ids]; appended last for array_like compatibility.
prompt_token_id_logprobs: torch.Tensor | None = None
@property
def finished(self) -> bool:
return self.finish_reason is not None
+13
View File
@@ -131,6 +131,19 @@ class InputProcessor:
self.structured_outputs_config,
self.tokenizer,
)
if params.prompt_logprob_token_ids is not None:
if not self.vllm_config.use_v2_model_runner:
raise VLLMValidationError(
"prompt_logprob_token_ids requires the V2 model runner "
"(VLLM_USE_V2_MODEL_RUNNER=1).",
parameter="prompt_logprob_token_ids",
)
if self.vllm_config.cache_config.kv_sharing_fast_prefill:
raise VLLMValidationError(
"prompt_logprob_token_ids is incorrect with "
"--kv-sharing-fast-prefill; disable it for scoring.",
parameter="prompt_logprob_token_ids",
)
self.validate_logits_processors_params(params)
+12
View File
@@ -5,6 +5,8 @@ import itertools
from collections.abc import Iterable
from dataclasses import dataclass
import numpy as np
from vllm.logger import init_logger
from vllm.logprobs import (
FlatLogprobs,
@@ -38,6 +40,8 @@ class LogprobsProcessor:
cumulative_logprob: float | None
num_logprobs: int | None
num_prompt_logprobs: int | None
# [num_scored_rows, num_token_ids], set once on the final prefill chunk.
prompt_token_id_logprobs: np.ndarray | None = None
@classmethod
def from_new_request(
@@ -204,6 +208,12 @@ class LogprobsProcessor:
self.prompt_logprobs = []
return plp
def pop_prompt_token_id_logprobs(self) -> np.ndarray | None:
"""Pop and return the fixed-ID prompt scores."""
scores = self.prompt_token_id_logprobs
self.prompt_token_id_logprobs = None
return scores
@staticmethod
def _get_sampled_context_ids(
logprobs_source: SampleLogprobs | PromptLogprobs | None,
@@ -352,3 +362,5 @@ class LogprobsProcessor:
self._update_sample_logprobs(output.new_logprobs)
if output.new_prompt_logprobs_tensors is not None:
self._update_prompt_logprobs(output.new_prompt_logprobs_tensors)
if output.prompt_token_id_logprobs is not None:
self.prompt_token_id_logprobs = output.prompt_token_id_logprobs.numpy()
+5
View File
@@ -390,8 +390,12 @@ class RequestState:
if self.output_kind == RequestOutputKind.DELTA:
# Side effect: logprobs processor forgets prompt logprobs
prompt_logprobs = self.logprobs_processor.pop_prompt_logprobs()
prompt_token_id_logprobs = (
self.logprobs_processor.pop_prompt_token_id_logprobs()
)
else:
prompt_logprobs = self.logprobs_processor.prompt_logprobs
prompt_token_id_logprobs = self.logprobs_processor.prompt_token_id_logprobs
return RequestOutput(
request_id=external_req_id, # request_id is what was provided externally
@@ -399,6 +403,7 @@ class RequestState:
prompt=self.prompt,
prompt_token_ids=prompt_token_ids,
prompt_logprobs=prompt_logprobs,
prompt_token_id_logprobs=prompt_token_id_logprobs,
outputs=cast(list[CompletionOutput], outputs),
finished=finished,
kv_transfer_params=kv_transfer_params,
+3
View File
@@ -283,6 +283,9 @@ class ModelRunnerOutput:
default_factory=dict
)
# req_id -> [num_scored_rows, num_token_ids] prompt_logprob_token_ids scores.
prompt_token_id_logprobs_dict: dict[str, torch.Tensor] = field(default_factory=dict)
# [num_reqs, hidden_size]
pooler_output: list[torch.Tensor | None] | None = None
+7
View File
@@ -156,6 +156,10 @@ class AsyncOutput(AsyncModelRunnerOutput):
k: v.to_cpu_nonblocking() if v is not None else None
for k, v in self.model_runner_output.prompt_logprobs_dict.items()
}
token_id_logprobs = self.model_runner_output.prompt_token_id_logprobs_dict
self.prompt_token_id_logprobs_dict = {
k: v.to("cpu", non_blocking=True) for k, v in token_id_logprobs.items()
}
if self.pending_aux_output is not None:
self.pending_aux_output.enqueue_cpu_copy(
num_sampled=self.num_sampled_tokens_np,
@@ -194,6 +198,9 @@ class AsyncOutput(AsyncModelRunnerOutput):
if self.logprobs_tensors is not None:
self.model_runner_output.logprobs = self.logprobs_tensors.tolists()
self.model_runner_output.prompt_logprobs_dict = self.prompt_logprobs_dict
self.model_runner_output.prompt_token_id_logprobs_dict = (
self.prompt_token_id_logprobs_dict
)
if self.pending_aux_output is not None:
self.model_runner_output.aux_output_connector_output = (
self.pending_aux_output.process_output()
+12 -1
View File
@@ -494,7 +494,9 @@ class GPUModelRunner(LoRAModelRunnerMixin):
),
)
self.prompt_logprobs_worker = PromptLogprobsWorker(
self.max_num_reqs, logprobs_mode=self.model_config.logprobs_mode
self.max_num_reqs,
self.device,
logprobs_mode=self.model_config.logprobs_mode,
)
self.structured_outputs_worker = StructuredOutputsWorker(
max_num_logits=self.max_num_reqs * self.decode_query_len,
@@ -2063,6 +2065,14 @@ class GPUModelRunner(LoRAModelRunnerMixin):
self.req_states.num_computed_tokens.gpu,
self.req_states.prompt_len.np,
)
prompt_token_id_logprobs_dict = (
self.prompt_logprobs_worker.compute_prompt_token_id_logprobs(
self.model.compute_logits,
hidden_states,
input_batch,
self.req_states.prompt_len.np,
)
)
# Prepare the model runner output.
model_runner_output = ModelRunnerOutput(
@@ -2072,6 +2082,7 @@ class GPUModelRunner(LoRAModelRunnerMixin):
req_id_to_index={req_id: i for i, req_id in enumerate(input_batch.req_ids)},
sampled_token_ids=None, # type: ignore
prompt_logprobs_dict=prompt_logprobs_dict, # type: ignore[arg-type]
prompt_token_id_logprobs_dict=prompt_token_id_logprobs_dict,
cudagraph_stats=cudagraph_stats,
)
pending_aux_output = None
+3 -1
View File
@@ -19,6 +19,7 @@ def _topk_log_softmax_kernel(
logits_ptr,
logits_stride,
topk_ids_ptr,
topk_ids_stride,
topk,
vocab_size,
BLOCK_SIZE: tl.constexpr,
@@ -49,7 +50,7 @@ def _topk_log_softmax_kernel(
k_offset = j + tl.arange(0, TOPK_BLOCK_SIZE)
k_mask = k_offset < topk
topk_ids = tl.load(
topk_ids_ptr + req_idx * topk + k_offset, mask=k_mask, other=0
topk_ids_ptr + req_idx * topk_ids_stride + k_offset, mask=k_mask, other=0
)
logits = tl.load(row_ptr + topk_ids, mask=k_mask)
logits = logits.to(tl.float32)
@@ -98,6 +99,7 @@ def compute_token_logprobs(
logits,
logits.stride(0),
token_ids,
token_ids.stride(0),
num_logprobs,
vocab_size,
BLOCK_SIZE=1024, # type: ignore
+84 -3
View File
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
from collections.abc import Callable
from dataclasses import dataclass
import numpy as np
import torch
@@ -8,20 +9,41 @@ import torch
from vllm.config.model import LogprobsMode
from vllm.sampling_params import SamplingParams
from vllm.triton_utils import tl, triton
from vllm.utils.torch_utils import async_tensor_h2d
from vllm.v1.outputs import LogprobsTensors
from vllm.v1.worker.gpu.input_batch import InputBatch
from vllm.v1.worker.gpu.sample.logprob import compute_topk_scores
from vllm.v1.worker.gpu.sample.logprob import (
compute_token_logprobs,
compute_topk_scores,
)
CHUNK_SIZE = 1024
@dataclass
class _TokenIdScores:
token_ids: torch.Tensor # [num_ids], on device
start: int # first prompt row to score
scores: torch.Tensor | None = None # [num_rows, num_ids], filled per chunk
class PromptLogprobsWorker:
def __init__(self, max_num_reqs: int, logprobs_mode: LogprobsMode = "raw_logprobs"):
def __init__(
self,
max_num_reqs: int,
device: torch.device,
logprobs_mode: LogprobsMode = "raw_logprobs",
):
self.max_num_reqs = max_num_reqs
self.device = device
self.logprobs_mode = logprobs_mode
self.uses_prompt_logprobs = np.zeros(self.max_num_reqs, dtype=bool)
self.num_prompt_logprobs = np.zeros(self.max_num_reqs, dtype=np.int32)
# req_idx -> list of in-progress LogprobsTensors
self.in_progress_prompt_logprobs: dict[str, list[LogprobsTensors]] = {}
# req_id -> fixed-ID scoring state
self.token_id_scores: dict[str, _TokenIdScores] = {}
def add_request(self, req_id: str, req_idx: int, sampling_params: SamplingParams):
uses_prompt_logprobs = sampling_params.prompt_logprobs is not None
@@ -29,9 +51,69 @@ class PromptLogprobsWorker:
self.num_prompt_logprobs[req_idx] = sampling_params.prompt_logprobs or 0
if uses_prompt_logprobs:
self.in_progress_prompt_logprobs[req_id] = []
if sampling_params.prompt_logprob_token_ids is not None:
self.token_id_scores[req_id] = _TokenIdScores(
async_tensor_h2d(
sampling_params.prompt_logprob_token_ids, self.device, torch.int64
),
sampling_params.prompt_logprob_start or 0,
)
def remove_request(self, req_id: str) -> None:
self.in_progress_prompt_logprobs.pop(req_id, None)
self.token_id_scores.pop(req_id, None)
def compute_prompt_token_id_logprobs(
self,
logits_fn: Callable[[torch.Tensor], torch.Tensor],
hidden_states: torch.Tensor,
input_batch: InputBatch,
prompt_lens: np.ndarray,
) -> dict[str, torch.Tensor]:
"""Fill scores row (prompt row - req.start) per chunk; emit on the last."""
if not self.token_id_scores:
return {}
logits_mode = self.logprobs_mode in ("raw_logits", "processed_logits")
out: dict[str, torch.Tensor] = {}
for i, req_id in enumerate(input_batch.req_ids):
req = self.token_id_scores.get(req_id)
if req is None:
continue
prompt_len = int(prompt_lens[input_batch.idx_mapping_np[i]])
chunk_start = int(input_batch.num_computed_prefill_tokens_np[i])
chunk_end = chunk_start + int(input_batch.num_scheduled_tokens[i])
# Skip decode steps and, as compute_prompt_logprobs does, requests
# resumed after preemption: their scores were already emitted.
if chunk_start >= prompt_len or prompt_len < input_batch.prefill_len_np[i]:
continue
if req.scores is None:
if chunk_start > req.start:
# This prefill starts past the first scored row, so those
# rows will never be written; drop the request instead of
# emitting a buffer with unwritten rows.
self.token_id_scores.pop(req_id, None)
continue
req.scores = hidden_states.new_empty(
(max(prompt_len - 1 - req.start, 0), len(req.token_ids)),
dtype=torch.float32,
)
# The last prompt row predicts the first decode token; skip it.
lo = max(req.start, chunk_start)
hi = min(chunk_end, prompt_len - 1)
base = int(input_batch.query_start_loc_np[i]) - chunk_start
for a in range(lo, hi, CHUNK_SIZE):
b = min(a + CHUNK_SIZE, hi)
logits = logits_fn(hidden_states[base + a : base + b])
ids = req.token_ids.expand(b - a, -1)
req.scores[a - req.start : b - req.start] = (
logits.gather(-1, ids)
if logits_mode
else compute_token_logprobs(logits, ids)
)
if chunk_end >= prompt_len:
out[req_id] = req.scores
req.scores = None
return out
def compute_prompt_logprobs(
self,
@@ -205,7 +287,6 @@ def compute_prompt_logprobs_with_chunking(
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
# Since materializing the full prompt logits can take too much memory,
# we compute it in chunks.
CHUNK_SIZE = 1024
token_ids = []
scores = []
ranks = []