output_processor.py 13.9 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
4
import asyncio
from dataclasses import dataclass
5
from typing import Optional, Union
6

7
from vllm.outputs import CompletionOutput, RequestOutput
8
9
from vllm.sampling_params import RequestOutputKind
from vllm.transformers_utils.tokenizer import AnyTokenizer
10
from vllm.transformers_utils.tokenizer_group import BaseTokenizerGroup
11
12
13
from vllm.v1.engine import EngineCoreOutput, EngineCoreRequest, FinishReason
from vllm.v1.engine.detokenizer import IncrementalDetokenizer
from vllm.v1.engine.logprobs import LogprobsProcessor
14
from vllm.v1.engine.parallel_sampling import ParentRequest
15
16
from vllm.v1.metrics.stats import (IterationStats, LoRARequestStates,
                                   RequestStateStats)
17
18
19
20
21


@dataclass
class OutputProcessorOutput:

22
23
    request_outputs: list[RequestOutput]
    reqs_to_abort: list[str]
24
25
26
27
28
29
30


class RequestState:

    def __init__(
        self,
        request_id: str,
31
32
        parent_req: Optional[ParentRequest],
        request_index: int,
33
        lora_name: Optional[str],
34
        output_kind: RequestOutputKind,
35
        prompt: Optional[str],
36
        prompt_token_ids: list[int],
37
        logprobs_processor: LogprobsProcessor,
38
        detokenizer: IncrementalDetokenizer,
39
        max_tokens_param: Optional[int],
40
        arrival_time: float,
41
        queue: Optional[asyncio.Queue[RequestOutput]],
42
        log_stats: bool,
43
44
    ):
        self.request_id = request_id
45
46
        self.parent_req = parent_req
        self.request_index = request_index
47
        self.lora_name = lora_name
48
        self.output_kind = output_kind
49
50
51
        self.prompt = prompt
        self.prompt_token_ids = prompt_token_ids
        self.prompt_len = len(prompt_token_ids)
52
        self.logprobs_processor = logprobs_processor
53
        self.detokenizer = detokenizer
54
        self.max_tokens_param = max_tokens_param
55
56
57
        self.is_prefilling = True
        self.queue = queue

58
59
        self.stats = RequestStateStats(
            arrival_time=arrival_time) if log_stats else None
60

61
62
63
64
65
    @classmethod
    def from_new_request(
        cls,
        tokenizer: AnyTokenizer,
        request: EngineCoreRequest,
66
67
        parent_req: Optional[ParentRequest],
        request_index: int,
68
69
        queue: Optional[asyncio.Queue[RequestOutput]],
        log_stats: bool,
70
71
72
    ) -> "RequestState":
        return cls(
            request_id=request.request_id,
73
74
            parent_req=parent_req,
            request_index=request_index,
75
76
            lora_name=(request.lora_request.name
                       if request.lora_request is not None else None),
77
            output_kind=request.sampling_params.output_kind,
78
79
            prompt=request.prompt,
            prompt_token_ids=request.prompt_token_ids,
80
81
82
83
            logprobs_processor=LogprobsProcessor.from_new_request(
                tokenizer=tokenizer,
                request=request,
            ),
84
85
86
87
            detokenizer=IncrementalDetokenizer.from_new_request(
                tokenizer=tokenizer,
                request=request,
            ),
88
89
            max_tokens_param=(request.sampling_params.max_tokens if
                              request.sampling_params is not None else None),
90
            arrival_time=request.arrival_time,
91
            queue=queue,
92
            log_stats=log_stats,
93
94
        )

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    def make_request_output(
        self,
        new_token_ids: list[int],
        finish_reason: Optional[FinishReason],
        stop_reason: Union[int, str, None],
    ) -> Optional[RequestOutput]:

        finished = finish_reason is not None
        output_kind = self.output_kind
        final_only = output_kind == RequestOutputKind.FINAL_ONLY

        # In follow up, we will switch to invariant where EngineCore
        # does not stream partial prefills.
        if not finished and (self.is_prefilling or final_only):
            # Only the final output is required in FINAL_ONLY mode.
            return None

        def new_request_output(request_id: str) -> RequestOutput:
            return self._new_request_output(request_id, finished)

        completion_output = self._new_completion_output(
            new_token_ids, finish_reason, stop_reason)

        if self.parent_req is not None:
            return self.parent_req.make_request_output(final_only,
                                                       completion_output,
                                                       new_request_output)

        request_output = new_request_output(self.request_id)
        request_output.outputs.append(completion_output)
        return request_output

    def _new_request_output(
        self,
        request_id: str,
        finished: bool,
    ) -> RequestOutput:

        if self.output_kind == RequestOutputKind.DELTA:
            # Side effect: logprobs processor forgets prompt logprobs
            prompt_logprobs = self.logprobs_processor.pop_prompt_logprobs()
        else:
            prompt_logprobs = self.logprobs_processor.prompt_logprobs

        return RequestOutput(
            request_id=request_id,
            prompt=self.prompt,
            prompt_token_ids=self.prompt_token_ids,
            prompt_logprobs=prompt_logprobs,
            outputs=[],
            finished=finished,
        )

    def _new_completion_output(
        self,
        token_ids: list[int],
        finish_reason: Optional[FinishReason],
        stop_reason: Union[int, str, None],
    ) -> CompletionOutput:

        finished = finish_reason is not None
        delta = self.output_kind == RequestOutputKind.DELTA

        # Prepare text and token_ids, based on delta mode
        text = self.detokenizer.get_next_output_text(finished, delta)
        if not delta:
            token_ids = self.detokenizer.output_token_ids

        # Prepare logprobs, based on delta mode
        logprobs = self.logprobs_processor.logprobs
        if delta and logprobs:
            logprobs = logprobs[-len(token_ids):]

        return CompletionOutput(
            index=self.request_index,
            text=text,
            token_ids=token_ids,
            logprobs=logprobs,
            cumulative_logprob=self.logprobs_processor.cumulative_logprob,
            finish_reason=str(finish_reason) if finished else None,
            stop_reason=stop_reason if finished else None)

177
178
179
180
181
182
183
184
185
186
187

class OutputProcessor:
    """Process EngineCoreOutputs into RequestOutputs."""

    def __init__(
        self,
        tokenizer: BaseTokenizerGroup,
        log_stats: bool,
    ):
        self.log_stats = log_stats
        self.tokenizer = tokenizer
188
        self.request_states: dict[str, RequestState] = {}
189
        self.lora_states = LoRARequestStates()
190
191
192
193
194
195
196
197
198

    def get_num_unfinished_requests(self):
        return len(self.request_states)

    def has_unfinished_requests(self) -> bool:
        return len(self.request_states) > 0

    def abort_requests(
        self,
199
        request_ids: list[str],
200
201
    ) -> None:
        for request_id in request_ids:
202
203
204
            req_state = self.request_states.pop(request_id, None)
            if req_state is not None:
                self.lora_states.abort_request(req_state)
205
206
                if req_state.parent_req is not None:
                    req_state.parent_req.finish_child_request(request_id)
207
208
209
210

    def add_request(
        self,
        request: EngineCoreRequest,
211
212
        parent_req: Optional[ParentRequest] = None,
        request_index: int = 0,
213
214
215
216
217
218
        queue: Optional[asyncio.Queue[RequestOutput]] = None,
    ) -> None:
        request_id = request.request_id
        if request_id in self.request_states:
            raise ValueError(f"Request id {request_id} already running.")

219
        req_state = RequestState.from_new_request(
220
221
            tokenizer=self.tokenizer.get_lora_tokenizer(request.lora_request),
            request=request,
222
223
            parent_req=parent_req,
            request_index=request_index,
224
225
            queue=queue,
            log_stats=self.log_stats)
226
227
        self.request_states[request_id] = req_state
        self.lora_states.add_request(req_state)
228
229
230

    def process_outputs(
        self,
231
        engine_core_outputs: list[EngineCoreOutput],
232
        engine_core_timestamp: Optional[float] = None,
233
        iteration_stats: Optional[IterationStats] = None,
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
    ) -> OutputProcessorOutput:
        """
        Process the EngineCoreOutputs:
        1) Compute stats for logging
        2) Detokenize
        3) Create and handle RequestOutput objects:
            * If there is a queue (for usage with AsyncLLM), 
              put the RequestOutput objects into the queue for
              handling by the per-request generate() tasks.

            * If there is no queue (for usage with LLMEngine), 
              return a list of RequestOutput objects.

        ****************** NOTE FOR DEVELOPERS ******************

        VLLM V1 minimizes the number of python loops over the full
        batch to ensure system overheads are minimized. This is the 
        only function that should loop over EngineCoreOutputs.

253
254
        If you need to touch every element of the batch, do it from
        within the loop below.
255
256
257
258
        
        **********************************************************
        """

259
260
        request_outputs: list[RequestOutput] = []
        reqs_to_abort: list[str] = []
261
262
263
264
265
266
267
268
        for engine_core_output in engine_core_outputs:
            req_id = engine_core_output.request_id
            req_state = self.request_states.get(req_id)
            if req_state is None:
                # Ignore output for already-aborted request.
                continue

            # 1) Compute stats for this iteration.
269
270
271
            self._update_stats_from_output(req_state, engine_core_output,
                                           engine_core_timestamp,
                                           iteration_stats)
272

273
274
            new_token_ids = engine_core_output.new_token_ids
            finish_reason = engine_core_output.finish_reason
275
            stop_reason = engine_core_output.stop_reason
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292

            # TODO(andy): prompt logprobs + chunked prefill can
            # result in engine core returning an output for a
            # partial prefill (in order to send back partial
            # prompt logprobs.) This breaks the invariant that
            # process_outputs is only operating on engine core
            # outputs associated with non-partial completions.
            # Currently this is handled by having `is_prefilling`
            # check for new decoded tokens, indicating that
            # the completion is not partial.
            #
            # Follow up will aggregate partial prompt logprobs
            # in the EngineCore.
            req_state.is_prefilling = not new_token_ids

            # 2) Detokenize the token ids into text and check for stop
            #    strings.
293
294
            stop_string = req_state.detokenizer.update(new_token_ids)
            if stop_string and finish_reason != FinishReason.STOP:
295
                finish_reason = FinishReason.STOP
296
                stop_reason = stop_string
297
298
299
300
301
302

            # 3) Compute sample and prompt logprobs for request,
            #    if required.
            req_state.logprobs_processor.update_from_output(engine_core_output)

            # 4) Create and handle RequestOutput objects.
303
304
            if request_output := req_state.make_request_output(
                    new_token_ids, finish_reason, stop_reason):
305
306
307
308
309
310
311
                if req_state.queue is not None:
                    # AsyncLLM: put into queue for handling by generate().
                    req_state.queue.put_nowait(request_output)
                else:
                    # LLMEngine: return list of RequestOutputs.
                    request_outputs.append(request_output)

312
313
314
315
316
317
318
            # Free completed requests.
            if finish_reason is not None:
                self.request_states.pop(req_id)
                if not engine_core_output.finished:
                    # If req not finished in EngineCore, but Detokenizer
                    # detected stop string, abort needed in EngineCore.
                    reqs_to_abort.append(req_id)
319
320
                if req_state.parent_req is not None:
                    req_state.parent_req.finish_child_request(req_id)
321

322
323
324
                # Track per-request stats
                self._update_stats_from_finished(req_state, finish_reason,
                                                 iteration_stats)
325

326
327
        self.lora_states.update_iteration_stats(iteration_stats)

328
329
330
331
332
        return OutputProcessorOutput(
            request_outputs=request_outputs,
            reqs_to_abort=reqs_to_abort,
        )

333
334
335
336
337
338
339
    def _update_stats_from_output(self, req_state: RequestState,
                                  engine_core_output: EngineCoreOutput,
                                  engine_core_timestamp: Optional[float],
                                  iteration_stats: Optional[IterationStats]):
        if iteration_stats is None:
            return

340
341
        lora_stats = self.lora_states.get_stats(req_state)

342
343
344
345
346
347
        assert engine_core_timestamp is not None
        assert req_state.stats is not None
        iteration_stats.update_from_output(engine_core_output,
                                           engine_core_timestamp,
                                           req_state.is_prefilling,
                                           req_state.prompt_len,
348
                                           req_state.stats, lora_stats)
349
350
351
352
353
354
355
356
357

    def _update_stats_from_finished(self, req_state: RequestState,
                                    finish_reason: Optional[FinishReason],
                                    iteration_stats: Optional[IterationStats]):
        if iteration_stats is None:
            return

        assert finish_reason is not None
        assert req_state.stats is not None
358
359
360
        iteration_stats.update_from_finished_request(
            finish_reason=finish_reason,
            num_prompt_tokens=len(req_state.prompt_token_ids),
361
            max_tokens_param=req_state.max_tokens_param,
362
            req_stats=req_state.stats)
363
        self.lora_states.finish_request(req_state)
364
365
366
367

        ParentRequest.observe_finished_request(
            req_state.parent_req, iteration_stats,
            req_state.stats.num_generation_tokens)