| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import torch |
| 5 | |
| 6 | from vllm.model_executor.layers.utils import apply_penalties |
| 7 | from vllm.utils.torch_utils import PIN_MEMORY, make_tensor_with_pad |
| 8 | |
| 9 | |
| 10 | def apply_all_penalties( |
| 11 | logits: torch.Tensor, |
| 12 | prompt_token_ids: torch.Tensor, |
| 13 | presence_penalties: torch.Tensor, |
| 14 | frequency_penalties: torch.Tensor, |
| 15 | repetition_penalties: torch.Tensor, |
| 16 | output_token_ids: list[list[int]], |
| 17 | ) -> torch.Tensor: |
| 18 | """Applies presence, frequency and repetition penalties to the logits.""" |
| 19 | _, vocab_size = logits.shape |
| 20 | output_tokens_t = _convert_to_tensors(output_token_ids, vocab_size, logits.device) |
| 21 | |
| 22 | # In the async scheduling case, rows that won't have penalties applied may contain |
| 23 | # -1 placeholder token ids. We must replace these with valid token ids so that the |
| 24 | # scatter done in apply_penalties is valid. |
| 25 | # NOTE(nick): The penalties implementation is currently quite inefficient and |
| 26 | # will be reworked anyhow. |
| 27 | output_tokens_t.masked_fill_(output_tokens_t == -1, vocab_size) |
| 28 | |
| 29 | return apply_penalties( |
| 30 | logits, |
| 31 | prompt_token_ids, |
| 32 | output_tokens_t, |
| 33 | presence_penalties, |
| 34 | frequency_penalties, |
| 35 | repetition_penalties, |
| 36 | ) |
| 37 | |
| 38 | |
| 39 | def _convert_to_tensors( |
| 40 | output_token_ids: list[list[int]], vocab_size: int, device: torch.device |
| 41 | ) -> torch.Tensor: |
| 42 | """Convert the different list data structures to tensors.""" |
| 43 | output_tokens_tensor = make_tensor_with_pad( |
| 44 | output_token_ids, |
| 45 | # Use the value of vocab_size as a pad since we don't have a |
| 46 | # token_id of this value. |
| 47 | pad=vocab_size, |
| 48 | device="cpu", |
| 49 | dtype=torch.int64, |
| 50 | pin_memory=PIN_MEMORY, |
| 51 | ) |
| 52 | return output_tokens_tensor.to(device, non_blocking=True) |