[Model Runner V2] Support custom logits processors (#56497)
Signed-off-by: David Cheung <d7cheung@gmail.com> Signed-off-by: Nick Hill <nickhill123@gmail.com> Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: Nick Hill <nickhill123@gmail.com>
This commit is contained in:
co-authored by
Claude
Nick Hill
parent
751f6807d9
commit
5302d1fe40
@@ -1,43 +1,47 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
import numpy as np
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.worker.gpu.buffer_utils import StagedWriteTensor, UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.interface import (
|
||||
LogitsContext,
|
||||
LogitsProcessor,
|
||||
LogitsProcRequestState,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
|
||||
class BadWordsState:
|
||||
def __init__(self, req_states: RequestState):
|
||||
class BadWordsState(LogitsProcessor):
|
||||
def __init__(self, vllm_config: "VllmConfig", req_states: LogitsProcRequestState):
|
||||
self.req_states = req_states
|
||||
self.max_num_reqs = req_states.max_num_reqs
|
||||
self.device = req_states.device
|
||||
max_num_reqs = req_states.max_num_reqs
|
||||
device = req_states.device
|
||||
|
||||
max_total_tokens = envs.VLLM_MAX_BAD_WORDS_TOTAL_TOKENS
|
||||
max_num_bad_words = envs.VLLM_MAX_NUM_BAD_WORDS
|
||||
# flattened bad word tokens: [max_num_reqs, VLLM_MAX_BAD_WORDS_TOTAL_TOKENS]
|
||||
self.bad_word_token_ids = StagedWriteTensor(
|
||||
(self.max_num_reqs, max_total_tokens),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
(max_num_reqs, max_total_tokens), dtype=torch.int32, device=device
|
||||
)
|
||||
# cumulative offsets of bad words: [max_num_reqs, VLLM_MAX_NUM_BAD_WORDS + 1]
|
||||
self.bad_word_offsets = StagedWriteTensor(
|
||||
(self.max_num_reqs, max_num_bad_words + 1),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
(max_num_reqs, max_num_bad_words + 1), dtype=torch.int32, device=device
|
||||
)
|
||||
# number of bad words per request
|
||||
self.num_bad_words = UvaBackedTensor(self.max_num_reqs, dtype=torch.int32)
|
||||
self.num_bad_words = UvaBackedTensor(max_num_reqs, dtype=torch.int32)
|
||||
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> None:
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> bool:
|
||||
bad_words_token_ids = sampling_params.bad_words_token_ids
|
||||
if not bad_words_token_ids:
|
||||
self.num_bad_words.np[req_idx] = 0
|
||||
return
|
||||
return False
|
||||
|
||||
num_bad_words = len(bad_words_token_ids)
|
||||
max_num_bad_words = envs.VLLM_MAX_NUM_BAD_WORDS
|
||||
@@ -65,38 +69,33 @@ class BadWordsState:
|
||||
self.bad_word_token_ids.stage_write(req_idx, 0, flattened_tokens)
|
||||
self.bad_word_offsets.stage_write(req_idx, 0, offsets)
|
||||
self.num_bad_words.np[req_idx] = num_bad_words
|
||||
return True
|
||||
|
||||
def apply_staged_writes(self) -> None:
|
||||
self.num_bad_words.copy_to_uva()
|
||||
self.bad_word_token_ids.apply_write()
|
||||
self.bad_word_offsets.apply_write()
|
||||
|
||||
def apply_bad_words(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
idx_mapping_np: np.ndarray,
|
||||
input_ids: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
) -> None:
|
||||
max_num_bad_words = int(self.num_bad_words.np[idx_mapping_np].max())
|
||||
def apply(self, logits: torch.Tensor, ctx: LogitsContext) -> torch.Tensor:
|
||||
max_num_bad_words = int(self.num_bad_words.np[ctx.idx_mapping_np].max())
|
||||
if max_num_bad_words == 0:
|
||||
# No request uses bad words. Skip the kernel launch.
|
||||
return
|
||||
return logits
|
||||
|
||||
apply_bad_words(
|
||||
logits,
|
||||
expanded_idx_mapping,
|
||||
ctx.expanded_idx_mapping,
|
||||
self.bad_word_token_ids.gpu,
|
||||
self.bad_word_offsets.gpu,
|
||||
self.num_bad_words.gpu,
|
||||
self.req_states.all_token_ids.gpu,
|
||||
self.req_states.prompt_len.gpu,
|
||||
self.req_states.total_len.gpu,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
ctx.input_ids,
|
||||
ctx.expanded_local_pos,
|
||||
max_num_bad_words,
|
||||
)
|
||||
return logits
|
||||
|
||||
|
||||
@triton.jit
|
||||
|
||||
@@ -200,6 +200,9 @@ class BatchSharder:
|
||||
num_logits_per_req_np[local_req_indices_np], out=local_cu_num_logits_np[1:]
|
||||
)
|
||||
max_num_logits_per_req = int(num_logits_per_req_np.max()) if num_reqs else 1
|
||||
local_seq_lens_cpu_upper_bound = input_batch.seq_lens_cpu_upper_bound[
|
||||
torch.from_numpy(local_req_indices_np)
|
||||
]
|
||||
|
||||
# Shard the input batch GPU tensors.
|
||||
sorted_logits_indices = torch.empty(
|
||||
@@ -269,6 +272,7 @@ class BatchSharder:
|
||||
expanded_idx_mapping=local_expanded_idx_mapping,
|
||||
expanded_local_pos=local_expanded_local_pos,
|
||||
seq_lens=local_seq_lens,
|
||||
seq_lens_cpu_upper_bound=local_seq_lens_cpu_upper_bound,
|
||||
logits_indices=local_logits_indices,
|
||||
cu_num_logits=local_cu_num_logits,
|
||||
cu_num_logits_np=local_cu_num_logits_np,
|
||||
|
||||
@@ -1,60 +1,61 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.triton_utils import tl, triton
|
||||
from vllm.v1.worker.gpu.buffer_utils import StagedWriteTensor, UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.interface import (
|
||||
LogitsContext,
|
||||
LogitsProcessor,
|
||||
LogitsProcRequestState,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
MAX_NUM_ALLOWED_TOKEN_IDS = 1024
|
||||
MAX_NUM_LOGIT_BIAS_TOKENS = 1024
|
||||
MAX_NUM_STOP_TOKEN_IDS = 128
|
||||
|
||||
|
||||
class LogitBiasState:
|
||||
def __init__(self, max_num_reqs: int, device: torch.device):
|
||||
self.max_num_reqs = max_num_reqs
|
||||
class LogitBiasState(LogitsProcessor):
|
||||
def __init__(self, vllm_config: "VllmConfig", req_states: LogitsProcRequestState):
|
||||
self.prompt_len_np = req_states.prompt_len.np
|
||||
max_num_reqs = req_states.max_num_reqs
|
||||
device = req_states.device
|
||||
|
||||
# Allowed token IDs.
|
||||
self.num_allowed_token_ids = UvaBackedTensor(
|
||||
self.max_num_reqs, dtype=torch.int32
|
||||
)
|
||||
self.num_allowed_token_ids = UvaBackedTensor(max_num_reqs, dtype=torch.int32)
|
||||
self.allowed_token_ids = StagedWriteTensor(
|
||||
(self.max_num_reqs, MAX_NUM_ALLOWED_TOKEN_IDS),
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
(max_num_reqs, MAX_NUM_ALLOWED_TOKEN_IDS), dtype=torch.int32, device=device
|
||||
)
|
||||
# Logit bias.
|
||||
self.num_logit_bias = UvaBackedTensor(self.max_num_reqs, dtype=torch.int32)
|
||||
self.num_logit_bias = UvaBackedTensor(max_num_reqs, dtype=torch.int32)
|
||||
self.logit_bias_token_ids = StagedWriteTensor(
|
||||
(self.max_num_reqs, MAX_NUM_LOGIT_BIAS_TOKENS),
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
(max_num_reqs, MAX_NUM_LOGIT_BIAS_TOKENS), dtype=torch.int32, device=device
|
||||
)
|
||||
self.logit_bias = StagedWriteTensor(
|
||||
(self.max_num_reqs, MAX_NUM_LOGIT_BIAS_TOKENS),
|
||||
(max_num_reqs, MAX_NUM_LOGIT_BIAS_TOKENS),
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
)
|
||||
# Min tokens.
|
||||
self.min_lens = UvaBackedTensor(self.max_num_reqs, dtype=torch.int32)
|
||||
self.num_stop_token_ids = UvaBackedTensor(self.max_num_reqs, dtype=torch.int32)
|
||||
self.restore_when_all_masked = UvaBackedTensor(
|
||||
self.max_num_reqs, dtype=torch.int32
|
||||
)
|
||||
self.min_lens = UvaBackedTensor(max_num_reqs, dtype=torch.int32)
|
||||
self.num_stop_token_ids = UvaBackedTensor(max_num_reqs, dtype=torch.int32)
|
||||
self.restore_when_all_masked = UvaBackedTensor(max_num_reqs, dtype=torch.int32)
|
||||
self.stop_token_ids = StagedWriteTensor(
|
||||
(self.max_num_reqs, MAX_NUM_STOP_TOKEN_IDS),
|
||||
dtype=torch.int32,
|
||||
device=device,
|
||||
(max_num_reqs, MAX_NUM_STOP_TOKEN_IDS), dtype=torch.int32, device=device
|
||||
)
|
||||
|
||||
# Using any of the above.
|
||||
self.use_logit_bias = np.zeros(max_num_reqs, dtype=bool)
|
||||
|
||||
def add_request(
|
||||
self, req_idx: int, prompt_len: int, sampling_params: SamplingParams
|
||||
) -> None:
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> bool:
|
||||
prompt_len = int(self.prompt_len_np[req_idx])
|
||||
# Using any logit bias.
|
||||
use_logit_bias = False
|
||||
|
||||
@@ -112,6 +113,7 @@ class LogitBiasState:
|
||||
self.restore_when_all_masked.np[req_idx] = 0
|
||||
|
||||
self.use_logit_bias[req_idx] = use_logit_bias
|
||||
return use_logit_bias
|
||||
|
||||
def apply_staged_writes(self) -> None:
|
||||
self.num_allowed_token_ids.copy_to_uva()
|
||||
@@ -126,25 +128,19 @@ class LogitBiasState:
|
||||
self.restore_when_all_masked.copy_to_uva()
|
||||
self.stop_token_ids.apply_write()
|
||||
|
||||
def apply_logit_bias(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
idx_mapping_np: np.ndarray,
|
||||
pos: torch.Tensor,
|
||||
) -> None:
|
||||
if not np.any(self.use_logit_bias[idx_mapping_np]):
|
||||
def apply(self, logits: torch.Tensor, ctx: LogitsContext) -> torch.Tensor:
|
||||
if not np.any(self.use_logit_bias[ctx.idx_mapping_np]):
|
||||
# No request uses logit bias. Skip the kernel launch.
|
||||
return
|
||||
return logits
|
||||
|
||||
enable_stop_token_restore = bool(
|
||||
np.any(self.restore_when_all_masked.np[idx_mapping_np])
|
||||
np.any(self.restore_when_all_masked.np[ctx.idx_mapping_np])
|
||||
)
|
||||
|
||||
apply_logit_bias(
|
||||
logits,
|
||||
expanded_idx_mapping,
|
||||
pos,
|
||||
ctx.expanded_idx_mapping,
|
||||
ctx.pos,
|
||||
self.num_allowed_token_ids.gpu,
|
||||
self.allowed_token_ids.gpu,
|
||||
self.num_logit_bias.gpu,
|
||||
@@ -156,6 +152,7 @@ class LogitBiasState:
|
||||
self.stop_token_ids.gpu,
|
||||
enable_stop_token_restore,
|
||||
)
|
||||
return logits
|
||||
|
||||
|
||||
@triton.jit
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Custom logits processors for the V2 model runner.
|
||||
|
||||
Kept import-light: the frontend process imports this package to validate
|
||||
per-request params, so nothing here may pull in model-runner side modules
|
||||
(torch, triton, worker state) at import time.
|
||||
"""
|
||||
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.interface import (
|
||||
LogitsContext,
|
||||
LogitsProcessor,
|
||||
LogitsProcRequestState,
|
||||
)
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.loader import (
|
||||
build_custom_logits_processors,
|
||||
build_custom_logits_processors_params_validator,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"LogitsProcRequestState",
|
||||
"LogitsContext",
|
||||
"LogitsProcessor",
|
||||
"build_custom_logits_processors",
|
||||
"build_custom_logits_processors_params_validator",
|
||||
]
|
||||
@@ -0,0 +1,158 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""V2 logits processor interface.
|
||||
|
||||
Import-light by design: custom processor classes are also loaded in the
|
||||
frontend process (to validate per-request params), so this module must not
|
||||
pull in model-runner side modules (torch, triton, worker state) at import
|
||||
time. Heavy imports live under TYPE_CHECKING; annotations are deferred.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.worker.gpu.buffer_utils import StagedWriteTensor, UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogitsProcRequestState:
|
||||
"""State associated with active requests, shared with logits processors.
|
||||
|
||||
Wraps the model runner's per-slot buffers, which are mutated in place,
|
||||
so reads always see current values. Processors must treat every field
|
||||
as read-only.
|
||||
"""
|
||||
|
||||
device: torch.device
|
||||
max_num_reqs: int
|
||||
vocab_size: int
|
||||
|
||||
# [max_num_reqs, max_model_len] committed token ids per request slot.
|
||||
all_token_ids: StagedWriteTensor
|
||||
# [max_num_reqs] tokens in the user-provided prompt.
|
||||
prompt_len: UvaBackedTensor
|
||||
# [max_num_reqs] tokens fed at the latest (re)fill: the prompt plus any
|
||||
# partial output on resumption after preemption.
|
||||
prefill_len: UvaBackedTensor
|
||||
# [max_num_reqs] prompt_len + output_len; grows as the request progresses.
|
||||
total_len: StagedWriteTensor
|
||||
|
||||
@classmethod
|
||||
def from_request_state(cls, req_states: RequestState) -> LogitsProcRequestState:
|
||||
return cls(
|
||||
device=req_states.device,
|
||||
max_num_reqs=req_states.max_num_reqs,
|
||||
vocab_size=req_states.vocab_size,
|
||||
all_token_ids=req_states.all_token_ids,
|
||||
prompt_len=req_states.prompt_len,
|
||||
prefill_len=req_states.prefill_len,
|
||||
total_len=req_states.total_len,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogitsContext:
|
||||
"""The current step's batch layout, passed to every ``apply()`` call.
|
||||
|
||||
A row is a logits row, not a request: rows are reordered every step, and
|
||||
under speculative decoding a request owns one row per draft token.
|
||||
Committed tokens live in ``req_states.all_token_ids`` (valid up to
|
||||
``total_len``); this step's draft tokens are only in ``input_ids``.
|
||||
"""
|
||||
|
||||
# [num_logits_rows] row -> persistent request slot.
|
||||
expanded_idx_mapping: torch.Tensor
|
||||
# [num_reqs] batch position -> persistent request slot.
|
||||
idx_mapping: torch.Tensor
|
||||
# [num_reqs] batch position -> persistent request slot, on the host, for
|
||||
# skipping work without a device sync.
|
||||
idx_mapping_np: np.ndarray
|
||||
# [num_logits_rows] row -> its offset among the rows of its own request.
|
||||
expanded_local_pos: torch.Tensor
|
||||
# [num_logits_rows] token fed to the model at each row's input position.
|
||||
input_ids: torch.Tensor
|
||||
# [num_logits_rows] position of each row within its sequence.
|
||||
pos: torch.Tensor
|
||||
# [num_reqs] batch position -> upper bound of tokens visible to the token
|
||||
# being sampled this step, on the host. Exact when spec decoding isn't in use.
|
||||
# Exact per-row lengths on device are `pos + 1`.
|
||||
seq_lens_upper_bound_np: np.ndarray
|
||||
|
||||
|
||||
class LogitsProcessor(ABC):
|
||||
"""Custom logits processor for Model Runner V2.
|
||||
|
||||
Per-request state is keyed by the request slot index; slots are recycled
|
||||
through a free list, so per-slot state must be fully (re)initialized in
|
||||
``add_request()``.
|
||||
|
||||
``apply()`` runs after the built-in bias, penalty, bad-words and grammar
|
||||
stages and before temperature, min_p and top-k/top-p, so it sees unscaled
|
||||
logits and must not re-inflate grammar-masked tokens. Thinking-budget
|
||||
forcing runs after ``apply()`` and wins over its edits for requests whose
|
||||
budget is exhausted.
|
||||
|
||||
State that is constant for a request belongs in ``__init__()`` or
|
||||
``add_request()``; ``apply()`` receives only what changes per step.
|
||||
"""
|
||||
|
||||
def __init__( # noqa: B027
|
||||
self, vllm_config: VllmConfig, req_states: LogitsProcRequestState
|
||||
):
|
||||
"""Capture what stays constant for the processor's lifetime.
|
||||
|
||||
``req_states`` exposes the on-device token history and batch constants a
|
||||
processor may read. Treat it as read-only.
|
||||
"""
|
||||
|
||||
@classmethod # noqa: B027
|
||||
def validate_params(cls, sampling_params: SamplingParams) -> None:
|
||||
"""Raise ``ValueError`` for invalid per-request arguments.
|
||||
|
||||
Runs at request admission, so invalid arguments fail the request
|
||||
with an error instead of reaching the sampler.
|
||||
"""
|
||||
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> bool:
|
||||
"""Initialize per-slot state for a request entering the batch.
|
||||
|
||||
The slot may hold a previous occupant's state; overwrite or
|
||||
neutralize all of it here.
|
||||
|
||||
Returns whether this processor modifies logits for the request.
|
||||
"""
|
||||
return True
|
||||
|
||||
def apply_staged_writes(self) -> None: # noqa: B027
|
||||
"""Flush any host-side writes staged by ``add_request()`` to the device.
|
||||
|
||||
Called once per step before the forward pass, after the model runner
|
||||
has flushed ``req_states``, so a processor that stages writes here can
|
||||
read the request's tokens back on device.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def apply(self, logits: torch.Tensor, ctx: LogitsContext) -> torch.Tensor:
|
||||
"""Modify logits in place or return a new tensor. In-place modification
|
||||
is preferred for efficiency.
|
||||
|
||||
``apply()`` is called once for the whole batch, including rows of
|
||||
requests this processor declined in ``add_request()``, so filter rows
|
||||
via ``ctx.expanded_idx_mapping``.
|
||||
|
||||
Args:
|
||||
logits: [num_logits_rows, vocab_size] float32 tensor.
|
||||
ctx: this step's batch layout.
|
||||
|
||||
"""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,211 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Loading of custom logits processor classes for the V2 model runner.
|
||||
|
||||
This module is deliberately import-light: the frontend process uses it to
|
||||
validate per-request params, so importing it must not pull in model-runner
|
||||
side modules (torch, triton, worker state). Imports needed to instantiate
|
||||
processors are deferred to ``build_custom_logits_processors``.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
from collections.abc import Callable, Sequence
|
||||
from functools import lru_cache
|
||||
from importlib.metadata import entry_points
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from vllm.exceptions import VLLMValidationError
|
||||
from vllm.logger import init_logger
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.interface import (
|
||||
LogitsProcessor,
|
||||
LogitsProcRequestState,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
# Same entry-points group as
|
||||
# vllm.v1.sample.logits_processor.LOGITSPROCS_GROUP; duplicated here so this
|
||||
# module stays importable without the V1 sampler machinery.
|
||||
LOGITSPROCS_GROUP = "vllm.logits_processors"
|
||||
|
||||
|
||||
def _load_v2_logitsprocs_plugins() -> list[type[LogitsProcessor]]:
|
||||
"""Load installed logits processor plugins.
|
||||
|
||||
Plugins registered under ``LOGITSPROCS_GROUP`` ship V1-interface
|
||||
processors today; those crash under the V2 sampler, so reject them at
|
||||
load time.
|
||||
"""
|
||||
from vllm.utils.torch_utils import guard_cuda_initialization
|
||||
|
||||
installed_logitsprocs_plugins = entry_points(group=LOGITSPROCS_GROUP)
|
||||
if len(installed_logitsprocs_plugins) == 0:
|
||||
logger.debug("No logitsprocs plugins installed (group %s).", LOGITSPROCS_GROUP)
|
||||
return []
|
||||
|
||||
logger.debug("Loading installed logitsprocs plugins (group %s):", LOGITSPROCS_GROUP)
|
||||
classes: list[type[LogitsProcessor]] = []
|
||||
for entrypoint in installed_logitsprocs_plugins:
|
||||
try:
|
||||
logger.debug(
|
||||
"- Loading logitproc plugin entrypoint=%s target=%s",
|
||||
entrypoint.name,
|
||||
entrypoint.value,
|
||||
)
|
||||
with guard_cuda_initialization():
|
||||
cls = entrypoint.load()
|
||||
except Exception as e:
|
||||
logger.error("Failed to load LogitsProcessor plugin %s: %s", entrypoint, e)
|
||||
raise RuntimeError(
|
||||
f"Failed to load LogitsProcessor plugin {entrypoint}"
|
||||
) from e
|
||||
if not (isinstance(cls, type) and issubclass(cls, LogitsProcessor)):
|
||||
raise ValueError(
|
||||
f"LogitsProcessor plugin {entrypoint.name} is not a subclass of "
|
||||
"vllm.v1.worker.gpu.sample.logits_processor.LogitsProcessor; "
|
||||
"V1-interface plugins are not supported by the V2 model runner."
|
||||
)
|
||||
classes.append(cls)
|
||||
return classes
|
||||
|
||||
|
||||
def _load_v2_logitsprocs_by_fqcns(
|
||||
logits_processors: Sequence[str | type],
|
||||
) -> list[type[LogitsProcessor]]:
|
||||
"""Resolve a mixed list of processor types and FQCN strings into types.
|
||||
|
||||
FQCN syntax is <module>:<type> i.e. x.y.z:CustomLogitProc.
|
||||
"""
|
||||
from vllm.utils.torch_utils import guard_cuda_initialization
|
||||
|
||||
classes: list[type[LogitsProcessor]] = []
|
||||
for ldx, logitproc in enumerate(logits_processors):
|
||||
if isinstance(logitproc, type):
|
||||
logger.debug(" - Already-loaded logit processor: %s", logitproc.__name__)
|
||||
if not issubclass(logitproc, LogitsProcessor):
|
||||
raise ValueError(
|
||||
f"{logitproc.__name__} is not a subclass of "
|
||||
"vllm.v1.worker.gpu.sample.logits_processor.LogitsProcessor"
|
||||
)
|
||||
classes.append(logitproc)
|
||||
continue
|
||||
|
||||
logger.debug("- Loading logits processor %s", logitproc)
|
||||
parts = logitproc.split(":")
|
||||
if len(parts) != 2:
|
||||
raise ValueError(
|
||||
f"Invalid logits processor FQCN {logitproc!r}. "
|
||||
"Expected format: '<module>:<type>'"
|
||||
)
|
||||
module_path, qualname = parts
|
||||
|
||||
try:
|
||||
with guard_cuda_initialization():
|
||||
module = importlib.import_module(module_path)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"Failed to load %sth LogitsProcessor plugin %s: %s",
|
||||
ldx,
|
||||
logitproc,
|
||||
e,
|
||||
)
|
||||
raise RuntimeError(
|
||||
f"Failed to load {ldx}th LogitsProcessor plugin {logitproc}"
|
||||
) from e
|
||||
|
||||
obj = module
|
||||
for attr in qualname.split("."):
|
||||
obj = getattr(obj, attr)
|
||||
if not isinstance(obj, type):
|
||||
raise ValueError("Loaded logit processor must be a type.")
|
||||
if not issubclass(obj, LogitsProcessor):
|
||||
raise ValueError(
|
||||
f"{obj.__name__} is not a subclass of "
|
||||
"vllm.v1.worker.gpu.sample.logits_processor.LogitsProcessor"
|
||||
)
|
||||
classes.append(obj)
|
||||
|
||||
return classes
|
||||
|
||||
|
||||
def _load_v2_logitsprocs(
|
||||
logits_processors: Sequence[str | type] | None,
|
||||
) -> list[type[LogitsProcessor]]:
|
||||
"""Load all custom logits processors for the V2 model runner.
|
||||
|
||||
Combines installed plugins (validated as V2 processors) with the
|
||||
user-specified list of processor types and FQCN strings.
|
||||
"""
|
||||
return _load_v2_logitsprocs_plugins() + _load_v2_logitsprocs_by_fqcns(
|
||||
logits_processors or ()
|
||||
)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def _cached_load_v2_logitsprocs(
|
||||
custom_logitsprocs: tuple[str | type, ...],
|
||||
) -> list[type[LogitsProcessor]]:
|
||||
return _load_v2_logitsprocs(list(custom_logitsprocs))
|
||||
|
||||
|
||||
def build_custom_logits_processors(
|
||||
vllm_config: "VllmConfig",
|
||||
req_states: "RequestState",
|
||||
is_pooling_model: bool,
|
||||
custom_logitsprocs: Sequence[str | type] = (),
|
||||
) -> list[LogitsProcessor]:
|
||||
"""Load and instantiate custom logits processors, entrypoint plugins first.
|
||||
|
||||
Raises:
|
||||
ValueError: if a pooling model specifies custom processors, or a
|
||||
loaded class does not implement the V2 interface.
|
||||
RuntimeError: if an FQCN fails to import.
|
||||
|
||||
"""
|
||||
from vllm.v1.sample.logits_processor import STR_POOLING_REJECTS_LOGITSPROCS
|
||||
|
||||
if is_pooling_model:
|
||||
if custom_logitsprocs:
|
||||
raise ValueError(STR_POOLING_REJECTS_LOGITSPROCS)
|
||||
logger.debug(
|
||||
"Skipping logits processor loading because pooling models"
|
||||
" do not support logits processors."
|
||||
)
|
||||
return []
|
||||
|
||||
custom_logitsprocs_classes = _load_v2_logitsprocs(custom_logitsprocs)
|
||||
lp_req_state = LogitsProcRequestState.from_request_state(req_states)
|
||||
return [ctor(vllm_config, lp_req_state) for ctor in custom_logitsprocs_classes]
|
||||
|
||||
|
||||
def build_custom_logits_processors_params_validator(
|
||||
custom_logitsprocs: Sequence[str | type] | None,
|
||||
) -> "Callable[[SamplingParams], None]":
|
||||
"""Load custom processor classes once and return a params validator.
|
||||
|
||||
Called from the frontend at startup. The returned callable runs each
|
||||
processor's ``validate_params`` at request admission.
|
||||
|
||||
Raises:
|
||||
ValueError: if a loaded class does not implement the V2 interface.
|
||||
RuntimeError: if an FQCN fails to import.
|
||||
|
||||
"""
|
||||
if not custom_logitsprocs:
|
||||
return lambda _: None
|
||||
|
||||
classes = _cached_load_v2_logitsprocs(tuple(custom_logitsprocs))
|
||||
|
||||
def validate_params(sampling_params: "SamplingParams") -> None:
|
||||
for cls in classes:
|
||||
try:
|
||||
cls.validate_params(sampling_params)
|
||||
except ValueError as e:
|
||||
raise VLLMValidationError(str(e)) from e
|
||||
|
||||
return validate_params
|
||||
@@ -1,5 +1,7 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
@@ -8,16 +10,22 @@ from vllm.triton_utils import tl, triton
|
||||
from vllm.utils.math_utils import cdiv
|
||||
from vllm.utils.torch_utils import async_tensor_h2d
|
||||
from vllm.v1.worker.gpu.buffer_utils import UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.interface import (
|
||||
LogitsContext,
|
||||
LogitsProcessor,
|
||||
LogitsProcRequestState,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm.config import VllmConfig
|
||||
|
||||
|
||||
class PenaltiesState:
|
||||
def __init__(self, req_states: RequestState):
|
||||
class PenaltiesState(LogitsProcessor):
|
||||
def __init__(self, vllm_config: "VllmConfig", req_states: LogitsProcRequestState):
|
||||
self.req_states = req_states
|
||||
|
||||
max_num_reqs = req_states.max_num_reqs
|
||||
self.vocab_size = req_states.vocab_size
|
||||
self.device = req_states.device
|
||||
max_num_reqs = req_states.max_num_reqs
|
||||
vocab_size = req_states.vocab_size
|
||||
|
||||
self.repetition_penalty = UvaBackedTensor(max_num_reqs, dtype=torch.float32)
|
||||
self.frequency_penalty = UvaBackedTensor(max_num_reqs, dtype=torch.float32)
|
||||
@@ -30,20 +38,17 @@ class PenaltiesState:
|
||||
|
||||
# Statistics for penalties.
|
||||
self.prompt_bin_mask = torch.zeros(
|
||||
max_num_reqs,
|
||||
cdiv(self.vocab_size, 32),
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
max_num_reqs, cdiv(vocab_size, 32), dtype=torch.int32, device=self.device
|
||||
)
|
||||
# TODO(woosuk): This tensor is rarely used but can be very large, taking up
|
||||
# GBs of GPU memory. Optimize the memory usage.
|
||||
self.output_bin_counts = torch.zeros(
|
||||
max_num_reqs, self.vocab_size, dtype=torch.int32, device=self.device
|
||||
max_num_reqs, vocab_size, dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
self._new_penalties_reqs: list[int] = []
|
||||
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> None:
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> bool:
|
||||
self.repetition_penalty.np[req_idx] = sampling_params.repetition_penalty
|
||||
self.frequency_penalty.np[req_idx] = sampling_params.frequency_penalty
|
||||
self.presence_penalty.np[req_idx] = sampling_params.presence_penalty
|
||||
@@ -52,13 +57,12 @@ class PenaltiesState:
|
||||
self.use_penalty[req_idx] = do_penalty
|
||||
if do_penalty:
|
||||
self._new_penalties_reqs.append(req_idx)
|
||||
return do_penalty
|
||||
|
||||
def apply_staged_writes(self) -> None:
|
||||
if self._new_penalties_reqs:
|
||||
idx_mapping = async_tensor_h2d(
|
||||
self._new_penalties_reqs,
|
||||
dtype=torch.int32,
|
||||
device=self.device,
|
||||
self._new_penalties_reqs, dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
prefill_lens = self.req_states.prefill_len.np[self._new_penalties_reqs]
|
||||
@@ -78,29 +82,23 @@ class PenaltiesState:
|
||||
self.frequency_penalty.copy_to_uva()
|
||||
self.presence_penalty.copy_to_uva()
|
||||
|
||||
def apply_penalties(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
idx_mapping_np: np.ndarray,
|
||||
input_ids: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
) -> None:
|
||||
if not np.any(self.use_penalty[idx_mapping_np]):
|
||||
def apply(self, logits: torch.Tensor, ctx: LogitsContext) -> torch.Tensor:
|
||||
if not np.any(self.use_penalty[ctx.idx_mapping_np]):
|
||||
# No request uses penalties. Skip the kernel launch.
|
||||
return
|
||||
return logits
|
||||
|
||||
apply_penalties(
|
||||
logits,
|
||||
expanded_idx_mapping,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
ctx.expanded_idx_mapping,
|
||||
ctx.input_ids,
|
||||
ctx.expanded_local_pos,
|
||||
self.repetition_penalty.gpu,
|
||||
self.frequency_penalty.gpu,
|
||||
self.presence_penalty.gpu,
|
||||
self.prompt_bin_mask,
|
||||
self.output_bin_counts,
|
||||
)
|
||||
return logits
|
||||
|
||||
|
||||
@triton.jit
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
import vllm.envs as envs
|
||||
from vllm.config import VllmConfig
|
||||
from vllm.config.model import PROCESSED_LOGPROBS_MODES, LogprobsMode
|
||||
from vllm.config.reasoning import ReasoningConfig
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.v1.sample.ops.topk_topp_sampler import (
|
||||
apply_top_k_top_p,
|
||||
@@ -18,6 +20,11 @@ from vllm.v1.worker.gpu.metrics.logits import get_num_nans
|
||||
from vllm.v1.worker.gpu.sample.bad_words import BadWordsState
|
||||
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
|
||||
from vllm.v1.worker.gpu.sample.logit_bias import LogitBiasState
|
||||
from vllm.v1.worker.gpu.sample.logits_processor.interface import (
|
||||
LogitsContext,
|
||||
LogitsProcessor,
|
||||
LogitsProcRequestState,
|
||||
)
|
||||
from vllm.v1.worker.gpu.sample.logprob import (
|
||||
LogprobTokenIdsState,
|
||||
compute_topk_scores,
|
||||
@@ -33,6 +40,7 @@ from vllm.v1.worker.gpu.states import RequestState
|
||||
class Sampler:
|
||||
def __init__(
|
||||
self,
|
||||
vllm_config: VllmConfig,
|
||||
max_num_reqs: int,
|
||||
vocab_size: int,
|
||||
device: torch.device,
|
||||
@@ -41,8 +49,8 @@ class Sampler:
|
||||
num_speculative_tokens: int = 1,
|
||||
use_fp64_gumbel: bool = False,
|
||||
enable_trace_replay: bool = False,
|
||||
reasoning_config: ReasoningConfig | None = None,
|
||||
return_sampling_mask: bool = False,
|
||||
custom_logits_processors: Sequence[LogitsProcessor] = (),
|
||||
):
|
||||
self.logprobs_mode = logprobs_mode
|
||||
self.compute_nans = envs.VLLM_COMPUTE_NANS_IN_LOGITS # False by default.
|
||||
@@ -50,11 +58,25 @@ class Sampler:
|
||||
|
||||
self.req_states = req_states
|
||||
self.sampling_states = SamplingStates(max_num_reqs, vocab_size)
|
||||
self.penalties_state = PenaltiesState(req_states)
|
||||
self.logit_bias_state = LogitBiasState(max_num_reqs, device)
|
||||
self.bad_words_state = BadWordsState(req_states)
|
||||
|
||||
lp_req_state = LogitsProcRequestState.from_request_state(req_states)
|
||||
self.penalties_state = PenaltiesState(vllm_config, lp_req_state)
|
||||
logit_bias_state = LogitBiasState(vllm_config, lp_req_state)
|
||||
bad_words_state = BadWordsState(vllm_config, lp_req_state)
|
||||
|
||||
# List order is pipeline order: bias adds, penalties scale, so the
|
||||
# two do not commute.
|
||||
self.logits_processors: list[LogitsProcessor] = [
|
||||
logit_bias_state,
|
||||
self.penalties_state,
|
||||
bad_words_state,
|
||||
*custom_logits_processors,
|
||||
]
|
||||
|
||||
self.logprob_token_ids_state = LogprobTokenIdsState(max_num_reqs, device)
|
||||
self.thinking_budget_state = ThinkingBudgetState(req_states, reasoning_config)
|
||||
self.thinking_budget_state = ThinkingBudgetState(
|
||||
req_states, vllm_config.reasoning_config
|
||||
)
|
||||
self.trace_replay_state = (
|
||||
TraceReplayState(req_states) if enable_trace_replay else None
|
||||
)
|
||||
@@ -65,41 +87,25 @@ class Sampler:
|
||||
not return_sampling_mask and flashinfer_sampler_supported()
|
||||
)
|
||||
|
||||
def add_request(
|
||||
self, req_idx: int, prompt_len: int, sampling_params: SamplingParams
|
||||
) -> None:
|
||||
self.sampling_states.add_request(req_idx, sampling_params)
|
||||
self.penalties_state.add_request(req_idx, sampling_params)
|
||||
self.logit_bias_state.add_request(req_idx, prompt_len, sampling_params)
|
||||
self.bad_words_state.add_request(req_idx, sampling_params)
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> None:
|
||||
needs_processing = self.sampling_states.add_request(req_idx, sampling_params)
|
||||
needs_processing |= self.thinking_budget_state.add_request(
|
||||
req_idx, sampling_params
|
||||
)
|
||||
for processor in self.logits_processors:
|
||||
needs_processing |= processor.add_request(req_idx, sampling_params)
|
||||
self.needs_logits_processing[req_idx] = needs_processing
|
||||
|
||||
self.logprob_token_ids_state.add_request(req_idx, sampling_params)
|
||||
self.thinking_budget_state.add_request(req_idx, sampling_params)
|
||||
if self.trace_replay_state is not None:
|
||||
self.trace_replay_state.add_request(req_idx, sampling_params)
|
||||
|
||||
states = self.sampling_states
|
||||
temperature = states.temperature.np[req_idx]
|
||||
self.needs_logits_processing[req_idx] = (
|
||||
self.logit_bias_state.use_logit_bias[req_idx]
|
||||
or self.penalties_state.use_penalty[req_idx]
|
||||
or self.bad_words_state.num_bad_words.np[req_idx] > 0
|
||||
or (
|
||||
self.thinking_budget_state.enabled
|
||||
and self.thinking_budget_state.use_thinking_budget[req_idx]
|
||||
)
|
||||
or (temperature != 0.0 and temperature != 1.0)
|
||||
or states.min_p.np[req_idx] != 0.0
|
||||
or states.top_k.np[req_idx] != states.vocab_size
|
||||
or states.top_p.np[req_idx] != 1.0
|
||||
)
|
||||
|
||||
def apply_staged_writes(self) -> None:
|
||||
self.sampling_states.apply_staged_writes()
|
||||
self.penalties_state.apply_staged_writes()
|
||||
self.logit_bias_state.apply_staged_writes()
|
||||
self.bad_words_state.apply_staged_writes()
|
||||
self.logprob_token_ids_state.apply_staged_writes()
|
||||
for processor in self.logits_processors:
|
||||
processor.apply_staged_writes()
|
||||
self.thinking_budget_state.apply_staged_writes()
|
||||
self.logprob_token_ids_state.apply_staged_writes()
|
||||
if self.trace_replay_state is not None:
|
||||
self.trace_replay_state.apply_staged_writes()
|
||||
|
||||
@@ -131,6 +137,7 @@ class Sampler:
|
||||
expanded_local_pos = input_batch.expanded_local_pos
|
||||
pos = input_batch.positions[input_batch.logits_indices]
|
||||
input_ids = input_batch.input_ids[input_batch.logits_indices]
|
||||
seq_lens_upper_bound_np = input_batch.seq_lens_cpu_upper_bound.numpy()
|
||||
|
||||
# NOTE(woosuk): We intentionally compute num_nans before sampling to make clear
|
||||
# that num_nans is computed before applying penalties and temperature.
|
||||
@@ -146,6 +153,7 @@ class Sampler:
|
||||
pos,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
seq_lens_upper_bound_np,
|
||||
return_logprobs=logprobs_dims is not None,
|
||||
)
|
||||
|
||||
@@ -215,6 +223,7 @@ class Sampler:
|
||||
pos: torch.Tensor,
|
||||
input_ids: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
seq_lens_upper_bound_np: np.ndarray,
|
||||
skip_top_k_top_p: bool = False,
|
||||
) -> torch.Tensor:
|
||||
if not np.any(self.needs_logits_processing[idx_mapping_np]):
|
||||
@@ -223,39 +232,23 @@ class Sampler:
|
||||
# Copy logits to a new FP32 tensor.
|
||||
logits = torch.empty_like(logits, dtype=torch.float32).copy_(logits)
|
||||
|
||||
# Apply logit bias (e.g., allowed_token_ids, min_tokens) in place.
|
||||
self.logit_bias_state.apply_logit_bias(
|
||||
logits, expanded_idx_mapping, idx_mapping_np, pos
|
||||
ctx = LogitsContext(
|
||||
expanded_idx_mapping=expanded_idx_mapping,
|
||||
idx_mapping=idx_mapping,
|
||||
idx_mapping_np=idx_mapping_np,
|
||||
expanded_local_pos=expanded_local_pos,
|
||||
input_ids=input_ids,
|
||||
pos=pos,
|
||||
seq_lens_upper_bound_np=seq_lens_upper_bound_np,
|
||||
)
|
||||
|
||||
# Apply penalties in place.
|
||||
self.penalties_state.apply_penalties(
|
||||
logits,
|
||||
expanded_idx_mapping,
|
||||
idx_mapping_np,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
)
|
||||
# Apply logits processors (native + any custom).
|
||||
for processor in self.logits_processors:
|
||||
logits = processor.apply(logits, ctx)
|
||||
|
||||
# Apply bad words masking in place.
|
||||
self.bad_words_state.apply_bad_words(
|
||||
logits,
|
||||
expanded_idx_mapping,
|
||||
idx_mapping_np,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
)
|
||||
|
||||
# Force the reasoning end marker once a request's thinking budget is
|
||||
# reached; applied before temperature so the forced token is always kept.
|
||||
self.thinking_budget_state.apply(
|
||||
logits,
|
||||
expanded_idx_mapping,
|
||||
idx_mapping,
|
||||
idx_mapping_np,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
)
|
||||
# Forcing runs last so no stage can overwrite the forced end marker
|
||||
# or weaken it by scaling.
|
||||
self.thinking_budget_state.apply(logits, ctx)
|
||||
|
||||
# Apply temperature in place.
|
||||
self.sampling_states.apply_temperature(
|
||||
@@ -282,6 +275,7 @@ class Sampler:
|
||||
pos: torch.Tensor,
|
||||
input_ids: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
seq_lens_upper_bound_np: np.ndarray,
|
||||
return_logprobs: bool = False,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
processed_logits = self.apply_sampling_params(
|
||||
@@ -292,6 +286,7 @@ class Sampler:
|
||||
pos,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
seq_lens_upper_bound_np,
|
||||
skip_top_k_top_p=True,
|
||||
)
|
||||
top_k, top_p = self.sampling_states.get_top_k_top_p(
|
||||
|
||||
@@ -38,14 +38,18 @@ class SamplingStates:
|
||||
# -1 means no logprobs are requested.
|
||||
self.num_logprobs.fill(NO_LOGPROBS)
|
||||
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> None:
|
||||
self.temperature.np[req_idx] = sampling_params.temperature
|
||||
self.top_p.np[req_idx] = sampling_params.top_p
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> bool:
|
||||
temperature = sampling_params.temperature
|
||||
top_k = sampling_params.top_k
|
||||
top_p = sampling_params.top_p
|
||||
min_p = sampling_params.min_p
|
||||
|
||||
self.temperature.np[req_idx] = temperature
|
||||
self.top_p.np[req_idx] = top_p
|
||||
if top_k <= 0 or top_k > self.vocab_size:
|
||||
top_k = self.vocab_size
|
||||
self.top_k.np[req_idx] = top_k
|
||||
self.min_p.np[req_idx] = sampling_params.min_p
|
||||
self.min_p.np[req_idx] = min_p
|
||||
|
||||
seed = sampling_params.seed
|
||||
self.seeds_set[req_idx] = seed is not None
|
||||
@@ -60,6 +64,13 @@ class SamplingStates:
|
||||
num_logprobs = self.vocab_size
|
||||
self.num_logprobs[req_idx] = num_logprobs
|
||||
|
||||
return temperature != 0.0 and (
|
||||
temperature != 1.0
|
||||
or min_p != 0.0
|
||||
or top_k != self.vocab_size
|
||||
or top_p != 1.0
|
||||
)
|
||||
|
||||
def apply_staged_writes(self) -> None:
|
||||
self.temperature.copy_to_uva()
|
||||
self.top_p.copy_to_uva()
|
||||
|
||||
@@ -9,6 +9,7 @@ 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.worker.gpu.buffer_utils import UvaBackedTensor
|
||||
from vllm.v1.worker.gpu.sample.logits_processor import LogitsContext
|
||||
from vllm.v1.worker.gpu.states import RequestState
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -78,11 +79,12 @@ class ThinkingBudgetState:
|
||||
end_ids, dtype=torch.int32, device=self.device
|
||||
)
|
||||
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> None:
|
||||
def add_request(self, req_idx: int, sampling_params: SamplingParams) -> bool:
|
||||
if not self.enabled:
|
||||
return
|
||||
return False
|
||||
budget = sampling_params.thinking_token_budget
|
||||
self.use_thinking_budget[req_idx] = budget is not None
|
||||
use_thinking_budget = budget is not None
|
||||
self.use_thinking_budget[req_idx] = use_thinking_budget
|
||||
if budget is None:
|
||||
budget = -1
|
||||
else:
|
||||
@@ -91,6 +93,7 @@ class ThinkingBudgetState:
|
||||
if self.thinking_token_budget.np[req_idx] != budget:
|
||||
self.thinking_token_budget.np[req_idx] = budget
|
||||
self._budget_dirty = True
|
||||
return use_thinking_budget
|
||||
|
||||
def apply_staged_writes(self) -> None:
|
||||
if not self.enabled:
|
||||
@@ -107,27 +110,20 @@ class ThinkingBudgetState:
|
||||
self.thinking_token_budget.copy_to_uva()
|
||||
self._budget_dirty = False
|
||||
|
||||
def apply(
|
||||
self,
|
||||
logits: torch.Tensor,
|
||||
expanded_idx_mapping: torch.Tensor,
|
||||
idx_mapping: torch.Tensor,
|
||||
idx_mapping_np: np.ndarray,
|
||||
input_ids: torch.Tensor,
|
||||
expanded_local_pos: torch.Tensor,
|
||||
) -> None:
|
||||
def apply(self, logits: torch.Tensor, ctx: LogitsContext) -> None:
|
||||
idx_mapping_np = ctx.idx_mapping_np
|
||||
if not self.enabled or not np.any(self.use_thinking_budget[idx_mapping_np]):
|
||||
return
|
||||
|
||||
apply_thinking_budget(
|
||||
logits,
|
||||
idx_mapping,
|
||||
expanded_idx_mapping,
|
||||
ctx.idx_mapping,
|
||||
ctx.expanded_idx_mapping,
|
||||
self.thinking_token_budget.gpu,
|
||||
self.req_states.all_token_ids.gpu,
|
||||
self.req_states.total_len.gpu,
|
||||
input_ids,
|
||||
expanded_local_pos,
|
||||
ctx.input_ids,
|
||||
ctx.expanded_local_pos,
|
||||
self.cached_last_start,
|
||||
self.cached_last_end,
|
||||
self.cached_scan_pos,
|
||||
|
||||
Reference in New Issue
Block a user