sampler.py 5.7 KB
Newer Older
1
2
3
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project

4
import numpy as np
5
6
import torch

7
import vllm.envs as envs
8
from vllm.config.model import LogprobsMode
9
from vllm.sampling_params import SamplingParams
10
from vllm.v1.worker.gpu.metrics.logits import get_num_nans
11
from vllm.v1.worker.gpu.sample.bad_words import BadWordsState
12
from vllm.v1.worker.gpu.sample.gumbel import gumbel_sample
13
from vllm.v1.worker.gpu.sample.logit_bias import LogitBiasState
14
from vllm.v1.worker.gpu.sample.logprob import compute_topk_logprobs
15
from vllm.v1.worker.gpu.sample.output import SamplerOutput
16
17
from vllm.v1.worker.gpu.sample.penalties import PenaltiesState
from vllm.v1.worker.gpu.sample.states import NO_LOGPROBS, SamplingStates
18
from vllm.v1.worker.gpu.states import RequestState
19
20
21
22
23


class Sampler:
    def __init__(
        self,
24
25
26
        max_num_reqs: int,
        vocab_size: int,
        device: torch.device,
27
        req_states: RequestState,
28
        logprobs_mode: LogprobsMode = "raw_logprobs",
29
        num_speculative_tokens: int = 1,
30
    ):
31
        if logprobs_mode not in ("processed_logprobs", "raw_logprobs"):
32
33
            raise NotImplementedError(f"Unsupported logprobs_mode: {logprobs_mode}")
        self.logprobs_mode = logprobs_mode
34
        self.compute_nans = envs.VLLM_COMPUTE_NANS_IN_LOGITS  # False by default.
35

36
        self.sampling_states = SamplingStates(max_num_reqs, vocab_size)
37
        self.penalties_state = PenaltiesState(req_states)
38
        self.logit_bias_state = LogitBiasState(max_num_reqs, device)
39
        self.bad_words_state = BadWordsState(req_states)
40
        self.num_speculative_tokens = num_speculative_tokens
41
42

    def add_request(
43
        self, req_idx: int, prompt_len: int, sampling_params: SamplingParams
44
45
46
47
    ) -> 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)
48
        self.bad_words_state.add_request(req_idx, sampling_params)
49

50
    def apply_staged_writes(self) -> None:
51
        self.sampling_states.apply_staged_writes()
52
        self.penalties_state.apply_staged_writes()
53
        self.logit_bias_state.apply_staged_writes()
54
        self.bad_words_state.apply_staged_writes()
55

56
57
58
    def __call__(
        self,
        logits: torch.Tensor,
59
60
        idx_mapping: torch.Tensor,
        idx_mapping_np: np.ndarray,
61
        cu_num_logits_np: np.ndarray,
62
        pos: torch.Tensor,
63
64
        input_ids: torch.Tensor,
        expanded_local_pos: torch.Tensor,
65
    ) -> SamplerOutput:
66
67
68
        # NOTE(woosuk): We intentionally compute num_nans before sampling to make clear
        # that num_nans is computed before applying penalties and temperature.
        num_nans = get_num_nans(logits) if self.compute_nans else None
69
        sampled, processed_logits = self.sample(
70
71
72
73
74
75
            logits,
            idx_mapping,
            idx_mapping_np,
            pos,
            input_ids,
            expanded_local_pos,
76
77
78
79
        )

        max_num_logprobs = self.sampling_states.max_num_logprobs(idx_mapping_np)
        if max_num_logprobs != NO_LOGPROBS:
80
81
            if self.logprobs_mode == "processed_logprobs":
                logits = processed_logits
82
83
84
85
86
            expanded_logits = logits.shape[0] != idx_mapping_np.shape[0]
            cu_num_logits = cu_num_logits_np.tolist() if expanded_logits else None
            logprobs_tensors = compute_topk_logprobs(
                logits, max_num_logprobs, sampled, cu_num_logits
            )
87
88
89
90
91
92
93
94
95
96
        else:
            logprobs_tensors = None

        # These are GPU tensors.
        sampler_output = SamplerOutput(
            # The sampled tokens are expanded to 2D tensor with shape
            # [num_requests, 1], where each row represents one generated
            # token per request.
            sampled_token_ids=sampled.view(-1, 1),
            logprobs_tensors=logprobs_tensors,
97
            num_nans=num_nans,
98
99
100
101
102
103
        )
        return sampler_output

    def sample(
        self,
        logits: torch.Tensor,
104
105
106
        idx_mapping: torch.Tensor,
        idx_mapping_np: np.ndarray,
        pos: torch.Tensor,
107
108
        input_ids: torch.Tensor,
        expanded_local_pos: torch.Tensor,
109
110
111
112
    ) -> tuple[torch.Tensor, torch.Tensor]:
        # Copy logits to a new FP32 tensor.
        logits = torch.empty_like(logits, dtype=torch.float32).copy_(logits)

113
        # Apply logit bias (e.g., allowed_token_ids, min_tokens) in place.
114
        self.logit_bias_state.apply_logit_bias(logits, idx_mapping, idx_mapping_np, pos)
115

116
        # Apply penalties in place.
117
118
119
120
121
122
123
124
        self.penalties_state.apply_penalties(
            logits,
            idx_mapping,
            idx_mapping_np,
            input_ids,
            expanded_local_pos,
            self.num_speculative_tokens,
        )
125

126
127
128
129
130
131
132
133
134
        # Apply bad words masking in place.
        self.bad_words_state.apply_bad_words(
            logits,
            idx_mapping,
            idx_mapping_np,
            input_ids,
            expanded_local_pos,
        )

135
        # Apply temperature in place.
136
137
138
139
140
141
142
143
144
        self.sampling_states.apply_temperature(logits, idx_mapping, idx_mapping_np)

        # Apply min_p in place.
        self.sampling_states.apply_min_p(logits, idx_mapping, idx_mapping_np)

        # Apply top_k and/or top_p. This might or might not return a new tensor.
        logits = self.sampling_states.apply_top_k_top_p(
            logits, idx_mapping, idx_mapping_np
        )
145
146

        # Sample the next token.
147
148
        sampled = gumbel_sample(
            logits,
149
150
151
152
            idx_mapping,
            self.sampling_states.temperature.gpu,
            self.sampling_states.seeds.gpu,
            pos,
153
154
            apply_temperature=False,
        )
155
        return sampled, logits