penalties.py 2.17 KB
Newer Older
1
2
3
4
from typing import List, Set, Tuple

import torch

Woosuk Kwon's avatar
Woosuk Kwon committed
5
from vllm.model_executor.layers.utils import apply_penalties
6
7
8
9
10
11
12
13
14
15
16
17
18
from vllm.utils import is_pin_memory_available, make_tensor_with_pad


def apply_min_token_penalties(logits: torch.Tensor,
                              output_token_ids: List[List[int]],
                              stop_token_ids: List[Set[int]],
                              min_tokens: List[int]) -> None:
    """
    Applies minimum token penalty by setting the logits of the stop tokens
    to -inf.
    """
    min_tokens_logits_to_penalize: List[Tuple[int, int]] = []
    for index, min_token in enumerate(min_tokens):
Woosuk Kwon's avatar
Woosuk Kwon committed
19
        if len(output_token_ids[index]) < min_token:
20
21
22
23
24
25
            for stop_token_id in stop_token_ids[index]:
                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
32
33
def apply_all_penalties(
    logits: torch.Tensor,
    prompt_token_ids: torch.Tensor,
    presence_penalties: torch.Tensor,
    frequency_penalties: torch.Tensor,
    repetition_penalties: torch.Tensor,
    output_token_ids: List[List[int]],
) -> 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59


def _convert_to_tensors(output_token_ids: List[List[int]], vocab_size: int,
                        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)