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

4
5
import torch

Woosuk Kwon's avatar
Woosuk Kwon committed
6
from vllm.model_executor.layers.utils import apply_penalties
7
8
9
from vllm.utils import is_pin_memory_available, make_tensor_with_pad


10
def apply_min_token_penalties(
11
12
        logits: torch.Tensor, output_token_ids: list[list[int]],
        min_tokens: dict[int, tuple[int, set[int]]]) -> None:
13
14
15
16
    """
    Applies minimum token penalty by setting the logits of the stop tokens
    to -inf.
    """
17
    min_tokens_logits_to_penalize: list[tuple[int, int]] = []
18
    for index, (min_token, stop_token_ids) in min_tokens.items():
Woosuk Kwon's avatar
Woosuk Kwon committed
19
        if len(output_token_ids[index]) < min_token:
20
            for stop_token_id in stop_token_ids:
21
22
23
24
25
                min_tokens_logits_to_penalize.append((index, stop_token_id))
    if min_tokens_logits_to_penalize:
        logits[tuple(zip(*min_tokens_logits_to_penalize))] = -float("inf")


Woosuk Kwon's avatar
Woosuk Kwon committed
26
27
28
29
30
31
def apply_all_penalties(
    logits: torch.Tensor,
    prompt_token_ids: torch.Tensor,
    presence_penalties: torch.Tensor,
    frequency_penalties: torch.Tensor,
    repetition_penalties: torch.Tensor,
32
    output_token_ids: list[list[int]],
Woosuk Kwon's avatar
Woosuk Kwon committed
33
) -> torch.Tensor:
34
35
36
37
38
39
    """
    Applies presence, frequency and repetition penalties to the logits.
    """
    _, vocab_size = logits.shape
    output_tokens_t = _convert_to_tensors(output_token_ids, vocab_size,
                                          logits.device)
Woosuk Kwon's avatar
Woosuk Kwon committed
40
41
42
    return apply_penalties(logits, prompt_token_ids, output_tokens_t,
                           presence_penalties, frequency_penalties,
                           repetition_penalties)
43
44


45
def _convert_to_tensors(output_token_ids: list[list[int]], vocab_size: int,
46
47
48
49
50
51
52
53
54
55
56
57
58
59
                        device: torch.device) -> torch.Tensor:
    """
    Convert the different list data structures to tensors.
    """
    output_tokens_tensor = make_tensor_with_pad(
        output_token_ids,
        # Use the value of vocab_size as a pad since we don't have a
        # token_id of this value.
        pad=vocab_size,
        device="cpu",
        dtype=torch.int64,
        pin_memory=is_pin_memory_available(),
    )
    return output_tokens_tensor.to(device, non_blocking=True)