"vllm/vscode:/vscode.git/clone" did not exist on "2cbda7439420e71567395758dc079d3f47c42bed"
__init__.py 7.85 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import enum
5
import time
6
from collections.abc import Mapping
7
from typing import Any, Literal
8
9

import msgspec
10
import numpy as np
11
import torch
12

13
from vllm.lora.request import LoRARequest
14
from vllm.multimodal.inputs import MultiModalFeatureSpec
15
from vllm.pooling_params import PoolingParams
16
from vllm.sampling_params import SamplingParams
17
from vllm.v1.metrics.stats import SchedulerStats
18
from vllm.v1.outputs import LogprobsLists, LogprobsTensors
19
from vllm.v1.serial_utils import UtilityResult
20

21
22
23
24
25
26
# Type for pause_generation mode parameter.
# - "abort": Abort all in-flight requests immediately (default).
# - "wait": Wait for in-flight requests to complete before pausing.
# - "keep": Freeze requests in queue; they resume on resume_generation().
PauseMode = Literal["abort", "wait", "keep"]

27
28
# These are possible values of RequestOutput.finish_reason,
# so form part of the external API.
29
FINISH_REASON_STRINGS = ("stop", "length", "abort", "error", "repetition")
30

31
32
33
34
35
36
37
38
39
EEP_NOTIFICATION_CALL_ID = -1


class EEPNotificationType(enum.Enum):
    NEW_CORE_ENGINES_INIT_READY = "NEW_CORE_ENGINES_INIT_READY"
    NEW_CORE_ENGINES_WEIGHTS_INIT_READY = "NEW_CORE_ENGINES_WEIGHTS_INIT_READY"
    RECONFIGURE_FINISHED = "RECONFIGURE_FINISHED"
    SHUTDOWN_COMPLETE = "SHUTDOWN_COMPLETE"

40
41

class FinishReason(enum.IntEnum):
42
    """
43
    Reason a request finished - stop, length, abort, error, or repetition.
44

45
46
    Int rather than Str for more compact serialization.

47
48
    stop - a stop string was emitted
    length - max_tokens was consumed, or max_model_len was reached
49
50
51
    abort - aborted by client
    error - retryable request-level internal error (e.g., KV load failure).
            Invariant: always converted to 500 Internal Server Error.
52
    repetition - repetitive token pattern detected (hallucination)
53
54

    """
55

56
57
58
    STOP = 0
    LENGTH = 1
    ABORT = 2
59
    ERROR = 3
60
    REPETITION = 4
61
62

    def __str__(self):
63
        return FINISH_REASON_STRINGS[self.value]
64
65


66
class EngineCoreRequest(
67
68
69
70
71
    msgspec.Struct,
    array_like=True,  # type: ignore[call-arg]
    omit_defaults=True,  # type: ignore[call-arg]
    gc=False,
):  # type: ignore[call-arg]
72
    request_id: str
73
74
75
76
    prompt_token_ids: list[int] | None
    mm_features: list[MultiModalFeatureSpec] | None
    sampling_params: SamplingParams | None
    pooling_params: PoolingParams | None
77
    arrival_time: float
78
79
80
81
    lora_request: LoRARequest | None
    cache_salt: str | None
    data_parallel_rank: int | None
    prompt_embeds: torch.Tensor | None = None
82

83
84
85
86
    # Index of the client, used to ensure outputs are sent back to the same
    # client for this request when scaling out the front-end.
    client_index: int = 0

87
88
89
90
    # Used in DP case to indicate which wave of requests this is expected to
    # belong to, to cover a race condition where the request is sent before
    # a wave finished notification is received.
    current_wave: int = 0
91
    priority: int = 0
92

93
    trace_headers: Mapping[str, str] | None = None
94
    resumable: bool = False
95

96
97
98
99
100
101
    # The user-provided request ID. This field is set internally,
    # copied from the provided request_id that's originally assigned
    # to the request_id field, see InputProcessor.assign_request_id().
    # Used in outputs and to support abort(req_id, internal=False).
    external_req_id: str | None = None

102
103
    reasoning_ended: bool | None = None

104
105
106
107
108
109
110
111
    @property
    def params(self) -> SamplingParams | PoolingParams:
        """Return the processed params (sampling or pooling)."""
        if self.sampling_params is not None:
            return self.sampling_params
        assert self.pooling_params is not None
        return self.pooling_params

112

113
114
class EngineCoreEventType(enum.IntEnum):
    """The type of engine core request event."""
115

116
117
    QUEUED = 1
    SCHEDULED = 2
118
    PREEMPTED = 3
119
120
121
122
123
124
125
126
127


class EngineCoreEvent(msgspec.Struct):
    """A timestamped engine core event associated with a request.

    The timestamp is a monotonic timestamps and is used for by the engine
    frontend to calculate intervals between engine core events. These
    timestamps should not be compared with timestamps from other processes.
    """
128

129
130
131
132
    type: EngineCoreEventType
    timestamp: float

    @classmethod
133
    def new_event(
134
        cls, event_type: EngineCoreEventType, timestamp: float | None = None
135
    ) -> "EngineCoreEvent":
136
137
138
139
        timestamp = time.monotonic() if timestamp is None else timestamp
        return cls(event_type, timestamp)


140
class EngineCoreOutput(
141
142
143
144
145
    msgspec.Struct,
    array_like=True,  # type: ignore[call-arg]
    omit_defaults=True,  # type: ignore[call-arg]
    gc=False,
):  # type: ignore[call-arg]
146
    request_id: str
147
    new_token_ids: list[int]
148

149
150
    new_logprobs: LogprobsLists | None = None
    new_prompt_logprobs_tensors: LogprobsTensors | None = None
151

152
    pooling_output: torch.Tensor | None = None
153

154
155
156
157
    finish_reason: FinishReason | None = None
    stop_reason: int | str | None = None
    events: list[EngineCoreEvent] | None = None
    kv_transfer_params: dict[str, Any] | None = None
158

159
    trace_headers: Mapping[str, str] | None = None
160
    # The number of tokens with prefix cache hits (local + external).
161
    num_cached_tokens: int = 0
162
163
    # The number of tokens computed remotely (original count from connector).
    num_external_computed_tokens: int = 0
164
    routed_experts: np.ndarray | None = None
165
166
167
168
    # The number of NaNs in logits.
    # A value greater than 0 indicates that the output is corrupted.
    num_nans_in_logits: int = 0

169
170
171
172
    @property
    def finished(self) -> bool:
        return self.finish_reason is not None

173

174
class UtilityOutput(
175
176
177
178
    msgspec.Struct,
    array_like=True,  # type: ignore[call-arg]
    gc=False,
):  # type: ignore[call-arg]
179
180
181
    call_id: int

    # Non-None implies the call failed, result should be None.
182
183
    failure_message: str | None = None
    result: UtilityResult | None = None
184
185


186
class EngineCoreOutputs(
187
188
189
190
191
    msgspec.Struct,
    array_like=True,  # type: ignore[call-arg]
    omit_defaults=True,  # type: ignore[call-arg]
    gc=False,
):  # type: ignore[call-arg]
192
    # NOTE(Nick): We could consider ways to make this more compact,
193
    # e.g. columnwise layout
194

195
196
    engine_index: int = 0

197
    # [num_reqs]
198
    outputs: list[EngineCoreOutput] = []
199
    scheduler_stats: SchedulerStats | None = None
200
201
    timestamp: float = 0.0

202
203
    utility_output: UtilityOutput | None = None
    finished_requests: set[str] | None = None
204

205
206
    # In DP case, used to signal that the current wave of requests
    # has finished and the engines are paused.
207
    wave_complete: int | None = None
208
209
    # In DP case, used to signal that a request was received for an
    # "old" wave, so the next wave needs to be started in other engines.
210
    start_wave: int | None = None
211

212
213
214
    def __post_init__(self):
        if self.timestamp == 0.0:
            self.timestamp = time.monotonic()
215
216
217
218
219
220
221


class EngineCoreRequestType(enum.Enum):
    """
    Request types defined as hex byte strings, so it can be sent over sockets
    without separate encoding step.
    """
222
223
224
225
226

    ADD = b"\x00"
    ABORT = b"\x01"
    START_DP_WAVE = b"\x02"
    UTILITY = b"\x03"
227
    # Sentinel used within EngineCoreProc.
228
    EXECUTOR_FAILED = b"\x04"
229
230
    # Sentinel to wake up input_queue.get() during shutdown.
    WAKEUP = b"\x05"
231
232
233
234
235
236
237
238


class ReconfigureDistributedRequest(msgspec.Struct):
    new_data_parallel_size: int
    new_data_parallel_rank: int
    new_data_parallel_rank_local: int
    new_data_parallel_master_ip: str
    new_data_parallel_master_port: int
239
240
241
242
243
    new_data_parallel_master_port_list: list[int]
    new_stateless_world_group_port_list: list[list[int]]
    new_stateless_dp_group_port_list: list[list[int]]
    new_stateless_ep_group_port_list: list[list[int]]
    new_stateless_eplb_group_port_list: list[list[int]]
244
245
246
247
248
249


class ReconfigureRankType(enum.IntEnum):
    """
    Rank type for reconfiguring distributed request.
    """
250

251
252
    KEEP_CURRENT_RANK = -1
    SHUTDOWN_CURRENT_RANK = -2