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

4
from dataclasses import dataclass
5
from typing import TYPE_CHECKING, Any, Optional, Union
6

7
from vllm.lora.request import LoRARequest
8
from vllm.sequence import Logprob
9

10
11
12
if TYPE_CHECKING:
    from vllm.multimodal import MultiModalDataDict

13
14
15
16
17
18
19
20

@dataclass
class BeamSearchSequence:
    """A sequence for beam search.
    It keeps track of the tokens and the log probability of the sequence.
    The text field is optional and will only be filled when the sequence is
    about to be returned to the user.
    """
21
    # The tokens include the prompt.
22
23
    tokens: list[int]
    logprobs: list[dict[int, Logprob]]
24
    lora_request: Optional[LoRARequest] = None
25
26
    cum_logprob: float = 0.0
    text: Optional[str] = None
27
28
29
    finish_reason: Optional[str] = None
    stop_reason: Union[int, str, None] = None
    multi_modal_data: Optional["MultiModalDataDict"] = None
30
    mm_processor_kwargs: Optional[dict[str, Any]] = None
31
32
33
34
35
36
37
38


@dataclass
class BeamSearchOutput:
    """The output of beam search.
    It contains the list of the best beam search sequences.
    The length of the list is equal to the beam width.
    """
39
    sequences: list[BeamSearchSequence]
40
41
42
43


class BeamSearchInstance:

44
45
46
    def __init__(
        self,
        prompt_tokens: list[int],
47
        lora_request: Optional[LoRARequest] = None,
48
49
50
        logprobs: Optional[list[dict[int, Logprob]]] = None,
        **kwargs,
    ):
51
        self.beams: list[BeamSearchSequence] = [
52
53
54
            BeamSearchSequence(
                tokens=prompt_tokens,
                logprobs=[] if logprobs is None else list(logprobs),
55
                lora_request=lora_request,
56
57
                **kwargs,
            )
58
        ]
59
        self.completed: list[BeamSearchSequence] = []
60
61
62


def get_beam_search_score(
63
    tokens: list[int],
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    cumulative_logprob: float,
    eos_token_id: int,
    length_penalty: float = 1.0,
) -> float:
    """Calculate the beam search score with length penalty.

    Adapted from

    https://github.com/huggingface/transformers/blob/ccb92be23def445f2afdea94c31286f84b89eb5b/src/transformers/generation/beam_search.py#L938
    """
    seq_len = len(tokens)
    if tokens[-1] == eos_token_id:
        seq_len -= 1

    return cumulative_logprob / (seq_len**length_penalty)


def create_sort_beams_key_function(eos_token_id: int, length_penalty: float):

    def sort_beams_key(x: BeamSearchSequence) -> float:
        return get_beam_search_score(x.tokens, x.cum_logprob, eos_token_id,
                                     length_penalty)

    return sort_beams_key