serving_completion.py 14.9 KB
Newer Older
1
import asyncio
2
import time
3
4
5
from typing import (AsyncGenerator, AsyncIterator, Callable, Dict, List,
                    Optional, Tuple)

6
from fastapi import Request
7

8
from vllm.engine.async_llm_engine import AsyncLLMEngine
9
10
11
12
13
14
15
16
from vllm.entrypoints.openai.protocol import (CompletionRequest,
                                              CompletionResponse,
                                              CompletionResponseChoice,
                                              CompletionResponseStreamChoice,
                                              CompletionStreamResponse,
                                              LogProbs, UsageInfo)
from vllm.entrypoints.openai.serving_engine import LoRA, OpenAIServing
from vllm.logger import init_logger
17
18
from vllm.model_executor.guided_decoding import (
    get_guided_decoding_logits_processor)
19
20
from vllm.outputs import RequestOutput
from vllm.utils import random_uuid
21
22
23

logger = init_logger(__name__)

Simon Mo's avatar
Simon Mo committed
24
25
TypeTokenIDs = List[int]
TypeTopLogProbs = List[Optional[Dict[int, float]]]
26
27
28
TypeCreateLogProbsFn = Callable[
    [TypeTokenIDs, TypeTopLogProbs, Optional[int], int], LogProbs]

29

Simon Mo's avatar
Simon Mo committed
30
def parse_prompt_format(prompt) -> Tuple[bool, list]:
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    # get the prompt, openai supports the following
    # "a string, array of strings, array of tokens, or array of token arrays."
    prompt_is_tokens = False
    prompts = [prompt]  # case 1: a string
    if isinstance(prompt, list):
        if len(prompt) == 0:
            raise ValueError("please provide at least one prompt")
        elif isinstance(prompt[0], str):
            prompt_is_tokens = False
            prompts = prompt  # case 2: array of strings
        elif isinstance(prompt[0], int):
            prompt_is_tokens = True
            prompts = [prompt]  # case 3: array of tokens
        elif isinstance(prompt[0], list) and isinstance(prompt[0][0], int):
            prompt_is_tokens = True
            prompts = prompt  # case 4: array of token arrays
        else:
48
49
            raise ValueError("prompt must be a string, array of strings, "
                             "array of tokens, or array of token arrays")
50
51
52
    return prompt_is_tokens, prompts


53
54
55
56
57
58
59
60
61
62
63
64
def merge_async_iterators(*iterators):
    """Merge multiple asynchronous iterators into a single iterator.

    This method handle the case where some iterators finish before others.
    When it yields, it yields a tuple (i, item) where i is the index of the
    iterator that yields the item.
    """
    queue = asyncio.Queue()

    finished = [False] * len(iterators)

    async def producer(i, iterator):
65
66
67
68
69
        try:
            async for item in iterator:
                await queue.put((i, item))
        except Exception as e:
            await queue.put(e)
70
71
72
73
74
75
76
77
78
79
        finished[i] = True

    _tasks = [
        asyncio.create_task(producer(i, iterator))
        for i, iterator in enumerate(iterators)
    ]

    async def consumer():
        while not all(finished) or not queue.empty():
            item = await queue.get()
80
81
            if isinstance(item, Exception):
                raise item
82
83
84
85
86
87
            yield item
        await asyncio.gather(*_tasks)

    return consumer()


88
89
class OpenAIServingCompletion(OpenAIServing):

90
91
92
93
94
95
96
    def __init__(self,
                 engine: AsyncLLMEngine,
                 served_model: str,
                 lora_modules: Optional[List[LoRA]] = None):
        super().__init__(engine=engine,
                         served_model=served_model,
                         lora_modules=lora_modules)
97
98
99
100
101
102
103
104

    async def create_completion(self, request: CompletionRequest,
                                raw_request: Request):
        """Completion API similar to OpenAI's API.

        See https://platform.openai.com/docs/api-reference/completions/create
        for the API specification. This API mimics the OpenAI Completion API.

105
        NOTE: Currently we do not support the following feature:
106
107
108
109
110
111
112
            - suffix (the language models we currently support do not support
            suffix)
        """
        error_check_ret = await self._check_model(request)
        if error_check_ret is not None:
            return error_check_ret

113
        # Return error for unsupported features.
114
115
116
117
118
119
        if request.suffix is not None:
            return self.create_error_response(
                "suffix is not currently supported")

        model_name = request.model
        request_id = f"cmpl-{random_uuid()}"
120
        created_time = int(time.time())
121

122
        # Schedule the request and get the result generator.
123
        generators = []
124
125
        try:
            sampling_params = request.to_sampling_params()
126
            lora_request = self._maybe_get_lora(request)
127
128
            guided_decode_logit_processor = (
                await get_guided_decoding_logits_processor(
129
                    request, await self.engine.get_tokenizer()))
130
131
132
133
134
            if guided_decode_logit_processor is not None:
                if sampling_params.logits_processors is None:
                    sampling_params.logits_processors = []
                sampling_params.logits_processors.append(
                    guided_decode_logit_processor)
135
            prompt_is_tokens, prompts = parse_prompt_format(request.prompt)
136

137
138
139
140
141
142
143
144
145
            for i, prompt in enumerate(prompts):
                if prompt_is_tokens:
                    input_ids = self._validate_prompt_and_tokenize(
                        request, prompt_ids=prompt)
                else:
                    input_ids = self._validate_prompt_and_tokenize(
                        request, prompt=prompt)

                generators.append(
146
                    self.engine.generate(prompt,
147
148
                                         sampling_params,
                                         f"{request_id}-{i}",
149
150
                                         prompt_token_ids=input_ids,
                                         lora_request=lora_request))
151
        except ValueError as e:
152
            # TODO: Use a vllm-specific Validation Error
153
            return self.create_error_response(str(e))
154

Simon Mo's avatar
Simon Mo committed
155
        result_generator: AsyncIterator[Tuple[
156
157
            int, RequestOutput]] = merge_async_iterators(*generators)

158
        # Similar to the OpenAI API, when n != best_of, we do not stream the
159
160
        # results. In addition, we do not stream the results when use
        # beam search.
161
162
163
164
165
166
        stream = (request.stream
                  and (request.best_of is None or request.n == request.best_of)
                  and not request.use_beam_search)

        # Streaming response
        if stream:
167
168
169
170
171
172
173
            return self.completion_stream_generator(request,
                                                    raw_request,
                                                    result_generator,
                                                    request_id,
                                                    created_time,
                                                    model_name,
                                                    num_prompts=len(prompts))
174
175

        # Non-streaming response
176
        final_res_batch: RequestOutput = [None] * len(prompts)
177
178
179
180
181
182
183
184
185
186
187
188
        try:
            async for i, res in result_generator:
                if await raw_request.is_disconnected():
                    # Abort the request if the client disconnects.
                    await self.engine.abort(f"{request_id}-{i}")
                    return self.create_error_response("Client disconnected")
                final_res_batch[i] = res
            response = self.request_output_to_completion_response(
                final_res_batch, request, request_id, created_time, model_name)
        except ValueError as e:
            # TODO: Use a vllm-specific Validation Error
            return self.create_error_response(str(e))
189

190
191
        # When user requests streaming but we don't stream, we still need to
        # return a streaming response with a single event.
192
        if request.stream:
193
            response_json = response.model_dump_json()
194
195
196
197
198
199
200
201

            async def fake_stream_generator() -> AsyncGenerator[str, None]:
                yield f"data: {response_json}\n\n"
                yield "data: [DONE]\n\n"

            return fake_stream_generator()

        return response
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

    async def completion_stream_generator(
        self,
        request: CompletionRequest,
        raw_request: Request,
        result_generator: AsyncIterator[Tuple[int, RequestOutput]],
        request_id: str,
        created_time: int,
        model_name: str,
        num_prompts: int,
    ) -> AsyncGenerator[str, None]:
        previous_texts = [""] * request.n * num_prompts
        previous_num_tokens = [0] * request.n * num_prompts
        has_echoed = [False] * request.n * num_prompts

        try:
            async for prompt_idx, res in result_generator:

                # Abort the request if the client disconnects.
                if await raw_request.is_disconnected():
                    await self.engine.abort(f"{request_id}-{prompt_idx}")
                    raise StopAsyncIteration()

                for output in res.outputs:
                    i = output.index + prompt_idx * request.n
227
228
                    # TODO(simon): optimize the performance by avoiding full
                    # text O(n^2) sending.
229
230
231
232
233
234
235

                    if request.echo and request.max_tokens == 0:
                        # only return the prompt
                        delta_text = res.prompt
                        delta_token_ids = res.prompt_token_ids
                        top_logprobs = res.prompt_logprobs
                        has_echoed[i] = True
236
237
                    elif (request.echo and request.max_tokens > 0
                          and not has_echoed[i]):
238
239
                        # echo the prompt and first token
                        delta_text = res.prompt + output.text
240
241
                        delta_token_ids = (res.prompt_token_ids +
                                           output.token_ids)
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
                        top_logprobs = res.prompt_logprobs + (output.logprobs
                                                              or [])
                        has_echoed[i] = True
                    else:
                        # return just the delta
                        delta_text = output.text[len(previous_texts[i]):]
                        delta_token_ids = output.token_ids[
                            previous_num_tokens[i]:]
                        top_logprobs = output.logprobs[previous_num_tokens[
                            i]:] if output.logprobs else None

                    if request.logprobs is not None:
                        logprobs = self._create_logprobs(
                            token_ids=delta_token_ids,
                            top_logprobs=top_logprobs,
                            num_output_top_logprobs=request.logprobs,
                            initial_text_offset=len(previous_texts[i]),
                        )
                    else:
                        logprobs = None

                    previous_texts[i] = output.text
                    previous_num_tokens[i] = len(output.token_ids)
                    finish_reason = output.finish_reason
266
                    stop_reason = output.stop_reason
267
268
269
270
271
272
273
274
275
276
                    if output.finish_reason is not None:  # return final usage
                        prompt_tokens = len(res.prompt_token_ids)
                        completion_tokens = len(output.token_ids)
                        final_usage = UsageInfo(
                            prompt_tokens=prompt_tokens,
                            completion_tokens=completion_tokens,
                            total_tokens=prompt_tokens + completion_tokens,
                        )
                    else:
                        final_usage = None
277
278
279
280
281
282
283
284
285
286
                    response_json = CompletionStreamResponse(
                        id=request_id,
                        created=created_time,
                        model=model_name,
                        choices=[
                            CompletionResponseStreamChoice(
                                index=i,
                                text=delta_text,
                                logprobs=logprobs,
                                finish_reason=finish_reason,
287
                                stop_reason=stop_reason,
288
                            )
289
290
291
                        ],
                        usage=final_usage,
                    ).model_dump_json(exclude_unset=True)
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
                    yield f"data: {response_json}\n\n"
        except ValueError as e:
            # TODO: Use a vllm-specific Validation Error
            data = self.create_streaming_error_response(str(e))
            yield f"data: {data}\n\n"
        yield "data: [DONE]\n\n"

    def request_output_to_completion_response(
        self,
        final_res_batch: List[RequestOutput],
        request: CompletionRequest,
        request_id: str,
        created_time: int,
        model_name: str,
    ) -> CompletionResponse:
        choices = []
        num_prompt_tokens = 0
        num_generated_tokens = 0
        for final_res in final_res_batch:
            assert final_res is not None
            prompt_token_ids = final_res.prompt_token_ids
            prompt_logprobs = final_res.prompt_logprobs
            prompt_text = final_res.prompt

            for output in final_res.outputs:
                if request.echo and request.max_tokens == 0:
                    token_ids = prompt_token_ids
                    top_logprobs = prompt_logprobs
                    output_text = prompt_text
                elif request.echo and request.max_tokens > 0:
                    token_ids = prompt_token_ids + output.token_ids
                    top_logprobs = prompt_logprobs + output.logprobs
                    output_text = prompt_text + output.text
                else:
                    token_ids = output.token_ids
                    top_logprobs = output.logprobs
                    output_text = output.text

                if request.logprobs is not None:
                    logprobs = self._create_logprobs(
                        token_ids=token_ids,
                        top_logprobs=top_logprobs,
                        num_output_top_logprobs=request.logprobs,
                    )
                else:
                    logprobs = None

                choice_data = CompletionResponseChoice(
                    index=len(choices),
                    text=output_text,
                    logprobs=logprobs,
                    finish_reason=output.finish_reason,
344
                    stop_reason=output.stop_reason,
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
                )
                choices.append(choice_data)

            num_prompt_tokens += len(prompt_token_ids)
            num_generated_tokens += sum(
                len(output.token_ids) for output in final_res.outputs)

        usage = UsageInfo(
            prompt_tokens=num_prompt_tokens,
            completion_tokens=num_generated_tokens,
            total_tokens=num_prompt_tokens + num_generated_tokens,
        )

        return CompletionResponse(
            id=request_id,
            created=created_time,
            model=model_name,
            choices=choices,
            usage=usage,
        )