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

3
import asyncio
4
from collections.abc import Iterable
5
from dataclasses import dataclass
Robert Shaw's avatar
Robert Shaw committed
6
from typing import Any, Optional, Union
7

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


20
21
22
23
24
25
26
27
28
29
30
class RequestOutputCollector:
    """
    Collects streamed RequestOutputs per individual request,
    for hand-off to the consuming asyncio generate task.

    When streaming deltas, RequestOutputs are merged if the
    producer gets ahead of the consumer.
    """

    def __init__(self, output_kind: RequestOutputKind):
        self.aggregate = output_kind == RequestOutputKind.DELTA
31
        self.output: Optional[Union[RequestOutput, Exception]] = None
32
33
        self.ready = asyncio.Event()

34
35
36
    def put(self, output: Union[RequestOutput, Exception]) -> None:
        """Non-blocking put operation."""
        if self.output is None or isinstance(output, Exception):
37
38
            self.output = output
            self.ready.set()
39
        elif isinstance(self.output, RequestOutput):
40
41
42
            # This ensures that request outputs with different request indexes
            # (if n > 1) do not override each other.
            self.output.add(output, aggregate=self.aggregate)
43
44

    async def get(self) -> RequestOutput:
45
        """Get operation blocks on put event."""
46
47
48
49
        while (output := self.output) is None:
            await self.ready.wait()
        self.output = None
        self.ready.clear()
50
51
        if isinstance(output, Exception):
            raise output
52
53
54
        return output

    def get_nowait(self) -> Optional[RequestOutput]:
55
        """Non-blocking get operation."""
56
57
58
59
        output = self.output
        if output is not None:
            self.output = None
            self.ready.clear()
60
61
        if isinstance(output, Exception):
            raise output
62
63
64
        return output


65
66
67
@dataclass
class OutputProcessorOutput:

68
69
    request_outputs: list[RequestOutput]
    reqs_to_abort: list[str]
70
71
72
73
74
75
76


class RequestState:

    def __init__(
        self,
        request_id: str,
77
78
        parent_req: Optional[ParentRequest],
        request_index: int,
79
        lora_name: Optional[str],
80
        output_kind: RequestOutputKind,
81
        prompt: Optional[str],
82
        prompt_token_ids: list[int],
83
        logprobs_processor: LogprobsProcessor,
84
        detokenizer: IncrementalDetokenizer,
85
        max_tokens_param: Optional[int],
86
        arrival_time: float,
87
        queue: Optional[RequestOutputCollector],
88
        log_stats: bool,
89
90
    ):
        self.request_id = request_id
91
92
        self.parent_req = parent_req
        self.request_index = request_index
93
        self.lora_name = lora_name
94
        self.output_kind = output_kind
95
96
97
        self.prompt = prompt
        self.prompt_token_ids = prompt_token_ids
        self.prompt_len = len(prompt_token_ids)
98
        self.logprobs_processor = logprobs_processor
99
        self.detokenizer = detokenizer
100
        self.max_tokens_param = max_tokens_param
101
102
103
        self.is_prefilling = True
        self.queue = queue

104
105
        self.stats = RequestStateStats(
            arrival_time=arrival_time) if log_stats else None
106

107
108
109
110
111
    @classmethod
    def from_new_request(
        cls,
        tokenizer: AnyTokenizer,
        request: EngineCoreRequest,
112
        prompt: Optional[str],
113
114
        parent_req: Optional[ParentRequest],
        request_index: int,
115
        queue: Optional[RequestOutputCollector],
116
        log_stats: bool,
117
    ) -> "RequestState":
118
119
        if not request.sampling_params.detokenize:
            tokenizer = None
120
121
        return cls(
            request_id=request.request_id,
122
123
            parent_req=parent_req,
            request_index=request_index,
124
125
            lora_name=(request.lora_request.name
                       if request.lora_request is not None else None),
126
            output_kind=request.sampling_params.output_kind,
127
            prompt=prompt,
128
            prompt_token_ids=request.prompt_token_ids,
129
130
131
132
            logprobs_processor=LogprobsProcessor.from_new_request(
                tokenizer=tokenizer,
                request=request,
            ),
133
134
135
136
            detokenizer=IncrementalDetokenizer.from_new_request(
                tokenizer=tokenizer,
                request=request,
            ),
137
138
            max_tokens_param=(request.sampling_params.max_tokens if
                              request.sampling_params is not None else None),
139
            arrival_time=request.arrival_time,
140
            queue=queue,
141
            log_stats=log_stats,
142
143
        )

144
145
146
147
148
    def make_request_output(
        self,
        new_token_ids: list[int],
        finish_reason: Optional[FinishReason],
        stop_reason: Union[int, str, None],
Robert Shaw's avatar
Robert Shaw committed
149
        kv_transfer_params: Optional[dict[str, Any]] = None,
150
        num_cached_tokens: int = 0,
151
152
153
    ) -> Optional[RequestOutput]:

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

156
        if not finished and final_only:
157
158
159
160
161
162
            # Only the final output is required in FINAL_ONLY mode.
            return None

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

163
164
165
166
167
168
169
170
        request_id = self.request_id
        if self.parent_req is None:
            outputs = [completion_output]
        else:
            request_id, outputs, finished = self.parent_req.get_outputs(
                request_id, completion_output)
            if not outputs:
                return None
171

Robert Shaw's avatar
Robert Shaw committed
172
        return self._new_request_output(request_id, outputs, finished,
173
                                        kv_transfer_params, num_cached_tokens)
174
175
176
177

    def _new_request_output(
        self,
        request_id: str,
178
        outputs: list[CompletionOutput],
179
        finished: bool,
Robert Shaw's avatar
Robert Shaw committed
180
        kv_transfer_params: Optional[dict[str, Any]] = None,
181
        num_cached_tokens: int = 0,
182
183
184
185
186
187
188
189
190
191
192
193
194
    ) -> 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,
195
            outputs=outputs,
196
            finished=finished,
Robert Shaw's avatar
Robert Shaw committed
197
            kv_transfer_params=kv_transfer_params,
198
            num_cached_tokens=num_cached_tokens,
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
        )

    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)

230
231
232
233
234
235

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

    def __init__(
        self,
236
        tokenizer: TokenizerGroup,
237
238
239
240
        log_stats: bool,
    ):
        self.log_stats = log_stats
        self.tokenizer = tokenizer
241
        self.request_states: dict[str, RequestState] = {}
242
        self.parent_requests: dict[str, ParentRequest] = {}
243
        self.lora_states = LoRARequestStates()
244
245
246
247
248
249
250

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

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

251
252
253
254
255
256
257
    def propagate_error(self, e: Exception):
        """Propagate error to all generate() tasks."""

        for _, state in self.request_states.items():
            assert state.queue is not None
            state.queue.put(e)

258
259
    def abort_requests(
        self,
260
261
262
        request_ids: Iterable[str],
    ) -> list[str]:
        request_ids_to_abort = []
263
        for request_id in request_ids:
264
265
266
            req_state = self.request_states.pop(request_id, None)
            if req_state is not None:
                self.lora_states.abort_request(req_state)
267
268
269
270
271
272
273
                request_ids_to_abort.append(request_id)
            else:
                parent = self.parent_requests.pop(request_id, None)
                if parent and parent.child_requests:
                    self.abort_requests(parent.child_requests)
                    request_ids_to_abort.extend(parent.child_requests)
        return request_ids_to_abort
274
275
276
277

    def add_request(
        self,
        request: EngineCoreRequest,
278
        prompt: Optional[str],
279
280
        parent_req: Optional[ParentRequest] = None,
        request_index: int = 0,
281
        queue: Optional[RequestOutputCollector] = None,
282
283
284
285
286
    ) -> None:
        request_id = request.request_id
        if request_id in self.request_states:
            raise ValueError(f"Request id {request_id} already running.")

287
        req_state = RequestState.from_new_request(
288
289
            tokenizer=self.tokenizer.get_lora_tokenizer(request.lora_request),
            request=request,
290
            prompt=prompt,
291
292
            parent_req=parent_req,
            request_index=request_index,
293
294
            queue=queue,
            log_stats=self.log_stats)
295
296
        self.request_states[request_id] = req_state
        self.lora_states.add_request(req_state)
297
298
        if parent_req:
            self.parent_requests[parent_req.request_id] = parent_req
299
300
301

    def process_outputs(
        self,
302
        engine_core_outputs: list[EngineCoreOutput],
303
        engine_core_timestamp: Optional[float] = None,
304
        iteration_stats: Optional[IterationStats] = None,
305
306
307
308
309
310
311
312
313
314
315
316
317
    ) -> 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.

318
        NOTE FOR DEVELOPERS
319

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

324
325
        If you need to touch every element of the batch, do it from
        within the loop below.
326
327
        """

328
329
        request_outputs: list[RequestOutput] = []
        reqs_to_abort: list[str] = []
330
331
332
333
334
335
336
337
        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.
338
339
340
            self._update_stats_from_output(req_state, engine_core_output,
                                           engine_core_timestamp,
                                           iteration_stats)
341

342
343
            new_token_ids = engine_core_output.new_token_ids
            finish_reason = engine_core_output.finish_reason
344
            stop_reason = engine_core_output.stop_reason
Robert Shaw's avatar
Robert Shaw committed
345
            kv_transfer_params = engine_core_output.kv_transfer_params
346
            num_cached_tokens = engine_core_output.num_cached_tokens
347
            req_state.is_prefilling = False
348

349
350
351
            # 2) Detokenize the token ids into text and perform stop checks.
            stop_string = req_state.detokenizer.update(
                new_token_ids, finish_reason == FinishReason.STOP)
352
            if stop_string:
353
                finish_reason = FinishReason.STOP
354
                stop_reason = stop_string
355

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

            # 4) Create and handle RequestOutput objects.
360
            if request_output := req_state.make_request_output(
Robert Shaw's avatar
Robert Shaw committed
361
                    new_token_ids, finish_reason, stop_reason,
362
                    kv_transfer_params, num_cached_tokens):
363
364
                if req_state.queue is not None:
                    # AsyncLLM: put into queue for handling by generate().
365
                    req_state.queue.put(request_output)
366
367
368
369
                else:
                    # LLMEngine: return list of RequestOutputs.
                    request_outputs.append(request_output)

370
371
372
            # Free completed requests.
            if finish_reason is not None:
                self.request_states.pop(req_id)
373
374
375
376
                # Remove parent request if applicable.
                parent_req = req_state.parent_req
                if parent_req and not parent_req.child_requests:
                    self.parent_requests.pop(parent_req.request_id, None)
377
378
379
380
                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)
381

382
383
384
                # Track per-request stats
                self._update_stats_from_finished(req_state, finish_reason,
                                                 iteration_stats)
385

386
387
        self.lora_states.update_iteration_stats(iteration_stats)

388
389
390
391
392
        return OutputProcessorOutput(
            request_outputs=request_outputs,
            reqs_to_abort=reqs_to_abort,
        )

393
394
395
396
397
398
399
    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

400
401
        lora_stats = self.lora_states.get_stats(req_state)

402
403
404
405
406
407
        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,
408
                                           req_state.stats, lora_stats)
409
410
411
412
413
414
415
416
417

    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
418
419
420
        iteration_stats.update_from_finished_request(
            finish_reason=finish_reason,
            num_prompt_tokens=len(req_state.prompt_token_ids),
421
            max_tokens_param=req_state.max_tokens_param,
422
            req_stats=req_state.stats)
423
        self.lora_states.finish_request(req_state)
424
425
426
427

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