|
| 1 | +# |
| 2 | +# Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. |
| 3 | +# This file is a part of the vllm-ascend project. |
| 4 | +# Adapted from vllm/tests/entrypoints/llm/test_guided_generate.py |
| 5 | +# Copyright 2023 The vLLM team. |
| 6 | +# |
| 7 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | +# you may not use this file except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, software |
| 14 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | +# See the License for the specific language governing permissions and |
| 17 | +# limitations under the License. |
| 18 | +# |
| 19 | +from typing import Optional |
| 20 | + |
| 21 | +import torch |
| 22 | + |
| 23 | +from vllm.v1.sample.ops.topk_topp_sampler import \ |
| 24 | + apply_top_k_top_p # noqa: F401 |
| 25 | +from vllm.v1.sample.sampler import Sampler # noqa: F401 |
| 26 | + |
| 27 | +# Set tolerance to 1 for quant ops |
| 28 | +DEFAULT_ATOL = 1e-3 |
| 29 | +DEFAULT_RTOL = 1e-3 |
| 30 | + |
| 31 | + |
| 32 | +def apply_min_p_new( |
| 33 | + logits: torch.Tensor, |
| 34 | + min_p: torch.Tensor, |
| 35 | +) -> torch.Tensor: |
| 36 | + """ |
| 37 | + Filters logits using adaptive probability thresholding. |
| 38 | + """ |
| 39 | + if min_p == 0: |
| 40 | + return logits |
| 41 | + # Convert logits to probability distribution |
| 42 | + probability_values = torch.nn.functional.softmax(logits, dim=-1) |
| 43 | + # Calculate maximum probabilities per sequence |
| 44 | + max_probabilities = torch.amax(probability_values, dim=-1, keepdim=True) |
| 45 | + # Reshape min_p for broadcasting |
| 46 | + adjusted_min_p = min_p.unsqueeze(1) * max_probabilities |
| 47 | + # Identify valid tokens using threshold comparison |
| 48 | + # Apply mask using boolean indexing |
| 49 | + logits = logits.masked_fill(probability_values < adjusted_min_p, |
| 50 | + -float('inf')) |
| 51 | + return logits |
| 52 | + |
| 53 | + |
| 54 | +def apply_top_k_top_p_new( |
| 55 | + logits: torch.Tensor, |
| 56 | + k: Optional[torch.Tensor], |
| 57 | + p: Optional[torch.Tensor], |
| 58 | +) -> torch.Tensor: |
| 59 | + batch_size, vocab_size = logits.shape |
| 60 | + logits_sort, logits_idx = logits.sort(dim=-1, descending=False) |
| 61 | + |
| 62 | + # Apply top-k. |
| 63 | + boundary = logits_sort.gather(1, (vocab_size - k).unsqueeze(dim=1)) |
| 64 | + top_k_mask = logits_sort < boundary |
| 65 | + logits_sort.masked_fill_(top_k_mask, -float("inf")) |
| 66 | + |
| 67 | + if p is not None: |
| 68 | + # Apply top-p. |
| 69 | + cutoff = top_k_mask.sum(dim=-1).min() |
| 70 | + probs_sort = logits_sort.softmax(dim=-1)[:, cutoff:] |
| 71 | + probs_sum = probs_sort.cumsum(dim=-1) |
| 72 | + top_p_mask = probs_sum > 1 - p.unsqueeze(dim=1) |
| 73 | + top_p_mask[:, -1] = True |
| 74 | + strides = torch.arange(0, |
| 75 | + batch_size * vocab_size, |
| 76 | + vocab_size, |
| 77 | + device=logits.device) |
| 78 | + flatten_idx = logits_idx[:, cutoff:] + strides.unsqueeze(dim=1) |
| 79 | + valid_idx = torch.masked_select(flatten_idx, top_p_mask) |
| 80 | + logits_flatten = logits.flatten() |
| 81 | + valid_logits = torch.index_select(logits_flatten, 0, valid_idx) |
| 82 | + logits = torch.empty_like(logits_flatten).fill_(-float("inf")) |
| 83 | + logits[valid_idx] = valid_logits |
| 84 | + return logits.reshape(batch_size, vocab_size) |
| 85 | + |
| 86 | + |
| 87 | +# test with leading dimension and merge seqlen and batch_size as num_tokens |
| 88 | +@torch.inference_mode() |
| 89 | +def test_apply_min_p() -> None: |
| 90 | + logits = torch.randn((128, 7168)).npu() |
| 91 | + min_p = torch.Tensor([0.01]).npu() |
| 92 | + logits_new = apply_min_p_new(logits, min_p) |
| 93 | + sampler = Sampler() |
| 94 | + logits_old = sampler.apply_min_p(logits, min_p) |
| 95 | + # Compare the results. |
| 96 | + torch.testing.assert_close(logits_new, |
| 97 | + logits_old, |
| 98 | + atol=DEFAULT_ATOL, |
| 99 | + rtol=DEFAULT_RTOL) |
| 100 | + |
| 101 | + |
| 102 | +# test with leading dimension and merge seqlen and batch_size as num_tokens |
| 103 | +@torch.inference_mode() |
| 104 | +def test_apply_top_k_top_p() -> None: |
| 105 | + logits = torch.randn((128, 7168)).npu() |
| 106 | + k = torch.Tensor([-1]).int().npu() |
| 107 | + p = torch.Tensor([1]).int().npu() |
| 108 | + logits_new = apply_top_k_top_p_new(logits, k, p) |
| 109 | + logits_old = apply_top_k_top_p(logits, k, p) |
| 110 | + # Compare the results. |
| 111 | + torch.testing.assert_close(logits_new, |
| 112 | + logits_old, |
| 113 | + atol=DEFAULT_ATOL, |
| 114 | + rtol=DEFAULT_RTOL) |
0 commit comments