request.py 6.12 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
import enum
4
from typing import TYPE_CHECKING, List, Optional, Union
5
6
7

from vllm.lora.request import LoRARequest
from vllm.sampling_params import SamplingParams
8
9
from vllm.v1.engine import (EngineCoreEvent, EngineCoreEventType,
                            EngineCoreRequest, FinishReason)
10
from vllm.v1.utils import ConstantList
11

12
if TYPE_CHECKING:
13
14
    from vllm.multimodal import MultiModalKwargs
    from vllm.multimodal.inputs import PlaceholderRange
15

16
17
18
19
20
21

class Request:

    def __init__(
        self,
        request_id: str,
22
23
24
25
26
        prompt: Optional[str],
        prompt_token_ids: List[int],
        multi_modal_inputs: Optional[List["MultiModalKwargs"]],
        multi_modal_hashes: Optional[List[str]],
        multi_modal_placeholders: Optional[List["PlaceholderRange"]],
27
28
29
30
31
32
33
34
35
36
37
38
        sampling_params: SamplingParams,
        eos_token_id: Optional[int],
        arrival_time: float,
        lora_request: Optional[LoRARequest] = None,
    ) -> None:
        self.request_id = request_id
        self.sampling_params = sampling_params
        # Because of LoRA, the eos token id can be different for each request.
        self.eos_token_id = eos_token_id
        self.lora_request = lora_request

        self.status = RequestStatus.WAITING
39
        self.events: List[EngineCoreEvent] = []
40
41
42
43
        self.stop_reason: Union[int, str, None] = None
        assert sampling_params.max_tokens is not None
        self.max_tokens = sampling_params.max_tokens

44
45
        self.prompt = prompt
        self.prompt_token_ids = prompt_token_ids
46
        self.num_prompt_tokens = len(self.prompt_token_ids)
47
48
        self._output_token_ids: List[int] = []
        self._all_token_ids: List[int] = self.prompt_token_ids.copy()
49
        self.spec_token_ids: List[int] = []
50
51
        self.num_computed_tokens = 0

52
53
54
55
        # Multi-modal related
        self.mm_positions = multi_modal_placeholders or []
        self.mm_inputs = multi_modal_inputs or []
        self.mm_hashes: List[str] = multi_modal_hashes or []
56

57
58
        # Sanity check
        assert len(self.mm_inputs) == len(self.mm_positions)
59
60
        if self.mm_hashes:
            assert len(self.mm_inputs) == len(self.mm_hashes)
61

62
63
64
65
66
67
        # Read-only views
        # Prevent directly appending to the these lists since
        # they should also be updated simultaneously.
        self.output_token_ids = ConstantList(self._output_token_ids)
        self.all_token_ids = ConstantList(self._all_token_ids)

68
69
70
71
    @classmethod
    def from_engine_core_request(cls, request: EngineCoreRequest) -> "Request":
        return cls(
            request_id=request.request_id,
72
73
74
75
76
            prompt=request.prompt,
            prompt_token_ids=request.prompt_token_ids,
            multi_modal_inputs=request.mm_inputs,
            multi_modal_hashes=request.mm_hashes,
            multi_modal_placeholders=request.mm_placeholders,
77
78
79
80
81
82
            sampling_params=request.sampling_params,
            eos_token_id=request.eos_token_id,
            arrival_time=request.arrival_time,
            lora_request=request.lora_request,
        )

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
    def queued(self, timestamp: Optional[float] = None) -> None:
        self.events.append(
            EngineCoreEvent.new_event(EngineCoreEventType.QUEUED, timestamp))

    def scheduled(self, timestamp: Optional[float] = None) -> None:
        self.events.append(
            EngineCoreEvent.new_event(EngineCoreEventType.SCHEDULED,
                                      timestamp))

    def take_events(self) -> Optional[List[EngineCoreEvent]]:
        if not self.events:
            return None
        events, self.events = self.events, []
        return events

98
99
100
101
102
103
104
105
106
    def append_output_token_ids(
        self,
        token_ids: Union[int, List[int]],
    ) -> None:
        if isinstance(token_ids, int):
            token_ids = [token_ids]
        self._output_token_ids.extend(token_ids)
        self._all_token_ids.extend(token_ids)

107
108
109
110
111
112
113
114
115
116
117
118
    def append_spec_token_ids(
        self,
        token_ids: Union[int, List[int]],
    ) -> None:
        if isinstance(token_ids, int):
            self.spec_token_ids.append(token_ids)
        else:
            self.spec_token_ids.extend(token_ids)

    def clear_spec_tokens(self) -> None:
        self.spec_token_ids.clear()

119
120
    @property
    def num_tokens(self) -> int:
121
        return len(self._all_token_ids)
122

123
124
125
126
    @property
    def num_tokens_with_spec(self) -> int:
        return len(self._all_token_ids) + len(self.spec_token_ids)

127
128
    @property
    def num_output_tokens(self) -> int:
129
        return len(self._output_token_ids)
130
131
132
133

    def is_finished(self) -> bool:
        return RequestStatus.is_finished(self.status)

134
    def get_finished_reason(self) -> Union[FinishReason, None]:
135
136
        return RequestStatus.get_finished_reason(self.status)

137
    def has_encoder_inputs(self) -> bool:
138
        return len(self.mm_inputs) > 0
139
140
141
142
143
144
145
146
147
148

    @property
    def num_encoder_inputs(self) -> int:
        return len(self.mm_positions)

    def get_num_encoder_tokens(self, input_id: int) -> int:
        assert input_id < len(self.mm_positions)
        num_tokens = self.mm_positions[input_id]["length"]
        return num_tokens

149
150

class RequestStatus(enum.IntEnum):
151
    """Status of a request."""
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    WAITING = 0
    RUNNING = 1
    PREEMPTED = 2
    # Note: anything after PREEMPTED (2) will be considered
    # as a finished status.
    FINISHED_STOPPED = 3
    FINISHED_LENGTH_CAPPED = 4
    FINISHED_ABORTED = 5
    FINISHED_IGNORED = 6

    @staticmethod
    def is_finished(status: "RequestStatus") -> bool:
        return status > RequestStatus.PREEMPTED

    @staticmethod
167
    def get_finished_reason(
168
            status: "RequestStatus") -> Union[FinishReason, None]:
169
170
171
172
        return _FINISHED_REASON_MAP.get(status)


# Mapping of finished statuses to their finish reasons.
173
# NOTE: The ignored requests are the requests whose prompt lengths
174
175
176
# are longer than the model's length cap. Therefore, the stop
# reason should also be "length" as in OpenAI API.
_FINISHED_REASON_MAP = {
177
178
179
180
    RequestStatus.FINISHED_STOPPED: FinishReason.STOP,
    RequestStatus.FINISHED_LENGTH_CAPPED: FinishReason.LENGTH,
    RequestStatus.FINISHED_ABORTED: FinishReason.ABORT,
    RequestStatus.FINISHED_IGNORED: FinishReason.LENGTH,
181
}