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

4
from typing import Optional
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

import torch
import torch.nn as nn

from vllm import envs
from vllm.logger import init_logger
from vllm.platforms import current_platform

logger = init_logger(__name__)

try:
    import flashinfer.sampling
    is_flashinfer_available = True
except ImportError:
    is_flashinfer_available = False


class TopKTopPSampler(nn.Module):
23
24
25
26
27
28
    """
    Module that performs optional top-k and top-p filtering followed by
    weighted random sampling of logits.

    Implementations may update the logits tensor in-place.
    """
29
30
31

    def __init__(self):
        super().__init__()
32
        if current_platform.is_cuda():
33
            if is_flashinfer_available:
34
                flashinfer_version = flashinfer.__version__
35
36
37
38
                if flashinfer_version < "0.2.3":
                    logger.warning(
                        "FlashInfer version >= 0.2.3 required. "
                        "Falling back to default sampling implementation.")
39
40
                    self.forward = self.forward_native
                elif envs.VLLM_USE_FLASHINFER_SAMPLER is not False:
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
                    # NOTE(woosuk): The V0 sampler doesn't use FlashInfer for
                    # sampling unless VLLM_USE_FLASHINFER_SAMPLER=1 (i.e., by
                    # default it is unused). For backward compatibility, we set
                    # `VLLM_USE_FLASHINFER_SAMPLER` as None by default and
                    # interpret it differently in V0 and V1 samplers: In V0,
                    # None means False, while in V1, None means True. This is
                    # why we use the condition
                    # `envs.VLLM_USE_FLASHINFER_SAMPLER is not False` here.
                    logger.info("Using FlashInfer for top-p & top-k sampling.")
                    self.forward = self.forward_cuda
                else:
                    logger.warning(
                        "FlashInfer is available, but it is not enabled. "
                        "Falling back to the PyTorch-native implementation of "
                        "top-p & top-k sampling. For the best performance, "
                        "please set VLLM_USE_FLASHINFER_SAMPLER=1.")
                    self.forward = self.forward_native
            else:
                logger.warning(
                    "FlashInfer is not available. Falling back to the PyTorch-"
                    "native implementation of top-p & top-k sampling. For the "
Kazuhiro Serizawa's avatar
Kazuhiro Serizawa committed
62
                    "best performance, please install FlashInfer.")
63
                self.forward = self.forward_native
64
        elif current_platform.is_tpu():
65
            self.forward = self.forward_tpu
66
67
68
69
70
71
        else:
            self.forward = self.forward_native

    def forward_native(
        self,
        logits: torch.Tensor,
72
        generators: dict[int, torch.Generator],
73
74
        k: Optional[torch.Tensor],
        p: Optional[torch.Tensor],
75
76
77
        *,
        max_top_k: Optional[int] = None,
        has_any_no_top_k: bool = False,
78
    ) -> torch.Tensor:
79
80
81
82
83
        """
        PyTorch-native implementation of top-k and top-p sampling.

        The logits tensor may be updated in-place.
        """
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        # Fast path: when top-k is enabled, avoid full-vocab sort/softmax by
        # sampling only from the top-k candidates (and applying top-p within
        # that set). This is especially important on ROCm where the PyTorch
        # native sort path can be very expensive.
        #
        # NOTE: Do not branch on device tensors here; doing so triggers
        # `aten::is_nonzero` and synchronizes the CPU with GPU.
        if (envs.VLLM_V1_USE_REDUCED_TOPK_TOPP_SAMPLER and k is not None
                and max_top_k is not None and not has_any_no_top_k
                and max_top_k <= 4096):
            try:
                return sample_top_k_top_p_reduced(logits,
                                                  generators,
                                                  k,
                                                  p,
                                                  max_top_k=max_top_k)
            except Exception:
                # Fall back to the reference implementation for safety.
                pass
103
        logits = apply_top_k_top_p(logits, k, p)
104
105
106
107
108
109
        probs = logits.softmax(dim=-1, dtype=torch.float32)
        return random_sample(probs, generators)

    def forward_cuda(
        self,
        logits: torch.Tensor,
110
        generators: dict[int, torch.Generator],
111
112
        k: Optional[torch.Tensor],
        p: Optional[torch.Tensor],
113
114
115
        *,
        max_top_k: Optional[int] = None,
        has_any_no_top_k: bool = False,
116
117
    ) -> torch.Tensor:
        """More optimized implementation for top-k and top-p sampling."""
118
        if k is None and p is None:
119
120
121
            # We prefer `random_sample` over `flashinfer_sample` when sorting is
            # not needed. This is because `random_sample` does not require
            # CPU-GPU synchronization while `flashinfer_sample` does.
122
            probs = logits.softmax(dim=-1, dtype=torch.float32)
123
            return random_sample(probs, generators)
124
125
126
127
        if generators:
            logger.warning("FlashInfer 0.2.3+ does not support "
                           "per-request generators. Falling back to "
                           "PyTorch-native implementation.")
128
129
130
131
132
133
            return self.forward_native(logits,
                                       generators,
                                       k,
                                       p,
                                       max_top_k=max_top_k,
                                       has_any_no_top_k=has_any_no_top_k)
134
135
136
137
        # flashinfer sampling functions expect contiguous logits.
        # In flex_attn/triton_attn fp32 inference, logits can be non-contiguous
        # because of slicing operation in logits_processor.
        return flashinfer_sample(logits.contiguous(), k, p, generators)
138

139
140
141
142
143
144
145
    def forward_tpu(
        self,
        logits: torch.Tensor,
        generators: dict[int, torch.Generator],
        k: Optional[torch.Tensor],
        p: Optional[torch.Tensor],
    ) -> torch.Tensor:
146
        logits = apply_top_k_top_p_tpu(logits, k, p)
147
148
149
        probs = logits.softmax(dim=-1, dtype=torch.float32)
        return random_sample(probs, generators)

150

151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def apply_top_k_top_p_tpu(
    logits: torch.Tensor,
    k: torch.Tensor,
    p: torch.Tensor,
) -> torch.Tensor:
    """
    Apply top-k and top-p optimized for TPU.

    This algorithm avoids using torch.scatter which is extremely slow on TPU.
    This is achieved by finding a "cut-off" element in the original logit, and
    after thresholding the logit using this cut-off, the remaining elements
    shall constitute the top-p set.

    Note: in the case of tie (i.e. multipple cut-off elements present in the
    logit), all tie elements are included in the top-p set. In other words,
    this function does not break ties. Instead, these tie tokens have equal
    chance of being chosen during final sampling, so we can consider the tie
    being broken then.
    """
170
171
172
    probs = logits.softmax(dim=-1)
    probs_sort, _ = probs.sort(dim=-1, descending=False)

173
    if k is not None:
174
175
176
177
178
179
180
181
182
183
        top_k_count = probs_sort.size(1) - k.to(torch.long)  # shape: (batch, )
        top_k_count = top_k_count.unsqueeze(dim=1)
        top_k_cutoff = probs_sort.gather(-1, top_k_count)

        # Make sure the no top-k rows are no-op.
        no_top_k_mask = (k == logits.shape[1]).unsqueeze(dim=1)
        top_k_cutoff.masked_fill_(no_top_k_mask, -float("inf"))

        elements_to_discard = probs < top_k_cutoff
        logits.masked_fill_(elements_to_discard, -float("inf"))
184
185
186
187
188
189
190
191
192
193
194
195
196
197

    if p is not None:
        cumprob = torch.cumsum(probs_sort, dim=-1)
        top_p_mask = cumprob <= 1 - p.unsqueeze(dim=1)
        top_p_mask[:, -1] = False  # at least one

        top_p_count = top_p_mask.sum(dim=-1).unsqueeze(1)
        top_p_cutoff = probs_sort.gather(-1, top_p_count)
        elements_to_discard = probs < top_p_cutoff
        logits.masked_fill_(elements_to_discard, -float("inf"))

    return logits


198
199
def apply_top_k_top_p(
    logits: torch.Tensor,
200
201
    k: Optional[torch.Tensor],
    p: Optional[torch.Tensor],
202
203
204
) -> torch.Tensor:
    """Apply top-k and top-p masks to the logits.

205
206
207
208
    If a top-p is used, this function will sort the logits tensor,
    which can be slow for large batches.

    The logits tensor may be updated in-place.
209
    """
210
211
212
213
214
215
216
    if p is None:
        if k is None:
            return logits

        # Avoid sorting vocab for top-k only case.
        return apply_top_k_only(logits, k)

217
218
    logits_sort, logits_idx = logits.sort(dim=-1, descending=False)

219
    if k is not None:
220
        # Apply top-k.
221
        top_k_mask = logits_sort.size(1) - k.to(torch.long)  # shape: B
222
223
224
225
226
        # Get all the top_k values.
        top_k_mask = logits_sort.gather(1, top_k_mask.unsqueeze(dim=1))
        top_k_mask = logits_sort < top_k_mask
        logits_sort.masked_fill_(top_k_mask, -float("inf"))

227
    if p is not None:
228
229
        # Apply top-p.
        probs_sort = logits_sort.softmax(dim=-1)
230
        probs_sum = torch.cumsum(probs_sort, dim=-1, out=probs_sort)
231
232
233
234
235
236
237
238
239
240
        top_p_mask = probs_sum <= 1 - p.unsqueeze(dim=1)
        # at least one
        top_p_mask[:, -1] = False
        logits_sort.masked_fill_(top_p_mask, -float("inf"))

    # Re-sort the probabilities.
    logits = logits_sort.scatter(dim=-1, index=logits_idx, src=logits_sort)
    return logits


241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def apply_top_k_only(
    logits: torch.Tensor,
    k: torch.Tensor,
) -> torch.Tensor:
    """
    Apply top-k mask to the logits.

    This implementation doesn't involve sorting the entire vocab.

    The logits tensor may be updated in-place.
    """
    no_top_k_mask = k == logits.shape[1]
    # Set non-top-k rows to 1 so that we can gather.
    k = k.masked_fill(no_top_k_mask, 1)
    max_top_k = k.max()
    # topk.values tensor has shape [batch_size, max_top_k].
    # Convert top k to 0-based index in range [0, max_top_k).
258
    k_index = k.sub_(1).unsqueeze(1)
259
    top_k_mask = logits.topk(max_top_k, dim=1).values.gather(1, k_index.long())
260
261
262
263
264
265
    # Handle non-topk rows.
    top_k_mask.masked_fill_(no_top_k_mask.unsqueeze(1), -float("inf"))
    logits.masked_fill_(logits < top_k_mask, -float("inf"))
    return logits


266
267
def random_sample(
    probs: torch.Tensor,
268
    generators: dict[int, torch.Generator],
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
) -> torch.Tensor:
    """Randomly sample from the probabilities.

    We use this function instead of torch.multinomial because torch.multinomial
    causes CPU-GPU synchronization.
    """
    q = torch.empty_like(probs)
    # NOTE(woosuk): To batch-process the requests without their own seeds,
    # which is the common case, we first assume that every request does
    # not have its own seed. Then, we overwrite the values for the requests
    # that have their own seeds.
    if len(generators) != probs.shape[0]:
        q.exponential_()
    if generators:
        # TODO(woosuk): This can be slow because we handle each request
        # one by one. Optimize this.
        for i, generator in generators.items():
            q[i].exponential_(generator=generator)
    return probs.div_(q).argmax(dim=-1).view(-1)


290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
def sample_top_k_top_p_reduced(
    logits: torch.Tensor,
    generators: dict[int, torch.Generator],
    k: torch.Tensor,
    p: Optional[torch.Tensor],
    *,
    max_top_k: int,
) -> torch.Tensor:
    """Sample from logits using only the top-k candidates.

    This avoids full-vocab sorting and full-vocab softmax/exponential kernels.
    Semantics match applying top-k then top-p (if provided) and sampling from
    the resulting distribution.
    """
    vocab_size = logits.shape[-1]
    # Cap for safety; very large top-k values may be expensive or defeat the
    # purpose of the reduced path.
    if max_top_k <= 0 or max_top_k >= vocab_size:
        masked_logits = apply_top_k_top_p(logits, k, p)
        probs = masked_logits.softmax(dim=-1, dtype=torch.float32)
        return random_sample(probs, generators)

    topk = logits.topk(max_top_k, dim=-1)
    topk_logits = topk.values
    topk_indices = topk.indices

    # Apply per-row top-k (some rows may have smaller k).
    # topk_logits is sorted descending by default.
    k = k.to(torch.long)
    arange_k = torch.arange(max_top_k, device=logits.device).unsqueeze(0)
    keep_k = arange_k < k.unsqueeze(1)
    topk_logits = topk_logits.masked_fill(~keep_k, -float("inf"))

    # Convert to probabilities over the reduced candidate set.
    probs = topk_logits.softmax(dim=-1, dtype=torch.float32)

    if p is not None:
        # Apply top-p within the reduced set. Since candidates are already
        # sorted by descending logit, we can do cumulative top-p on this order.
        # Keep tokens until cumprob exceeds p, inclusive of the boundary token.
        cumprob = torch.cumsum(probs, dim=-1)
        cumprob_prev = cumprob - probs
        keep_p = cumprob_prev <= p.unsqueeze(1)
        probs = probs * keep_p

    # Sample a position within the reduced set and map it back to vocab ids.
    pos = random_sample(probs, generators)
    return topk_indices.gather(1, pos.unsqueeze(1)).squeeze(1)


340
def flashinfer_sample(
341
    logits: torch.Tensor,
342
343
    k: Optional[torch.Tensor],
    p: Optional[torch.Tensor],
344
    generators: dict[int, torch.Generator],
345
) -> torch.Tensor:
346
    """Sample from the logits using FlashInfer.
347
348
349
350

    Statistically, this function is equivalent to the `random_sample` function.
    However, this function is faster because it avoids sorting the logits tensor
    via rejection sampling.
351

352
353
354
355
356
357
358
359
    NOTE: The outputs of this function do not necessarily match the outputs of
    the `random_sample` function. It only guarantees that the outputs are
    statistically equivalent.

    NOTE: This function includes CPU-GPU synchronization, while `random_sample`
    does not. Call this function at the end of the forward pass to minimize
    the synchronization overhead.
    """
360
361
    assert not (k is None and p is None)
    if k is None:
362
        # Top-p only.
363
        probs = logits.softmax(dim=-1, dtype=torch.float32)
364
365
        next_token_ids = flashinfer.sampling.top_p_sampling_from_probs(
            probs, p, deterministic=True)
366
    elif p is None:
367
        # Top-k only.
368
        probs = logits.softmax(dim=-1, dtype=torch.float32)
369
370
        next_token_ids = flashinfer.sampling.top_k_sampling_from_probs(
            probs, k, deterministic=True)
371
372
    else:
        # Both top-k and top-p.
373
374
        next_token_ids = flashinfer.sampling.top_k_top_p_sampling_from_logits(
            logits, k, p, deterministic=True)
375

376
    return next_token_ids.view(-1)