backend_request_func.py 24.6 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import io
5
6
import json
import os
7
import sys
8
import time
9
10
import traceback
from dataclasses import dataclass, field
11
12

import aiohttp
13
import huggingface_hub.constants
14
from tqdm.asyncio import tqdm
15
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
16

17
18
# NOTE(simon): do not import vLLM here so the benchmark script
# can run without vLLM installed.
19

20
21
22
23
24
25
26
27
28
29
AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=6 * 60 * 60)


@dataclass
class RequestFuncInput:
    prompt: str
    api_url: str
    prompt_len: int
    output_len: int
    model: str
30
31
32
33
    model_name: str | None = None
    logprobs: int | None = None
    extra_body: dict | None = None
    multi_modal_content: dict | list[dict] | None = None
34
    ignore_eos: bool = False
35
36
    language: str | None = None
    request_id: str | None = None
37
38
39
40
41
42


@dataclass
class RequestFuncOutput:
    generated_text: str = ""
    success: bool = False
43
    latency: float = 0.0
44
    output_tokens: int = 0
45
    ttft: float = 0.0  # Time to first token
46
    itl: list[float] = field(default_factory=list)  # list of inter-token latencies
47
    tpot: float = 0.0  # avg next-token latencies
48
    prompt_len: int = 0
49
    error: str = ""
50
51
52
53


async def async_request_tgi(
    request_func_input: RequestFuncInput,
54
    pbar: tqdm | None = None,
55
56
57
58
) -> RequestFuncOutput:
    api_url = request_func_input.api_url
    assert api_url.endswith("generate_stream")

59
60
61
    async with aiohttp.ClientSession(
        trust_env=True, timeout=AIOHTTP_TIMEOUT
    ) as session:
62
63
64
65
66
        params = {
            "max_new_tokens": request_func_input.output_len,
            "do_sample": True,
            "temperature": 0.01,  # TGI does not accept 0.0 temperature.
            "top_p": 0.99,  # TGI does not accept 1.0 top_p.
67
            "truncate": request_func_input.prompt_len,
68
            "ignore_eos_token": request_func_input.ignore_eos,
69
70
71
72
73
        }
        payload = {
            "inputs": request_func_input.prompt,
            "parameters": params,
        }
74
75
76
        headers = None
        if request_func_input.request_id:
            headers = {"x-request-id": request_func_input.request_id}
77
78
        output = RequestFuncOutput()
        output.prompt_len = request_func_input.prompt_len
79
80
81
82
        if request_func_input.ignore_eos:
            output.output_tokens = request_func_input.output_len
        else:
            output.output_tokens = None
83

84
        ttft = 0.0
85
        st = time.perf_counter()
86
        most_recent_timestamp = st
87
        try:
88
89
90
            async with session.post(
                url=api_url, json=payload, headers=headers
            ) as response:
91
                if response.status == 200:
92
93
94
                    async for chunk_bytes in response.content:
                        chunk_bytes = chunk_bytes.strip()
                        if not chunk_bytes:
95
                            continue
96
                        chunk_bytes = chunk_bytes.decode("utf-8")
97

98
                        # NOTE: Sometimes TGI returns a ping response without
99
100
101
                        # any data, we should skip it.
                        if chunk_bytes.startswith(":"):
                            continue
102
                        chunk = chunk_bytes.removeprefix("data:")
103

104
105
106
                        data = json.loads(chunk)
                        timestamp = time.perf_counter()
                        # First token
107
                        if ttft == 0.0:
108
109
110
                            ttft = time.perf_counter() - st
                            output.ttft = ttft

111
112
                        # Decoding phase
                        else:
113
                            output.itl.append(timestamp - most_recent_timestamp)
114

115
116
117
118
119
                        most_recent_timestamp = timestamp

                    output.latency = most_recent_timestamp - st
                    output.success = True
                    output.generated_text = data["generated_text"]
120
121
122
                else:
                    output.error = response.reason or ""
                    output.success = False
123
        except Exception:
124
            output.success = False
125
126
            exc_info = sys.exc_info()
            output.error = "".join(traceback.format_exception(*exc_info))
127
128
129
130
131
132
133
134

        if pbar:
            pbar.update(1)
        return output


async def async_request_trt_llm(
    request_func_input: RequestFuncInput,
135
    pbar: tqdm | None = None,
136
137
138
139
) -> RequestFuncOutput:
    api_url = request_func_input.api_url
    assert api_url.endswith("generate_stream")

140
141
142
    async with aiohttp.ClientSession(
        trust_env=True, timeout=AIOHTTP_TIMEOUT
    ) as session:
143
144
145
146
147
148
149
150
        payload = {
            "accumulate_tokens": True,
            "text_input": request_func_input.prompt,
            "temperature": 0.0,
            "top_p": 1.0,
            "max_tokens": request_func_input.output_len,
            "stream": True,
        }
151
152
        if request_func_input.ignore_eos:
            payload["min_length"] = request_func_input.output_len
153
154
155
        headers = None
        if request_func_input.request_id:
            headers = {"x-request-id": request_func_input.request_id}
156
157
158
        output = RequestFuncOutput()
        output.prompt_len = request_func_input.prompt_len

159
        ttft = 0.0
160
        st = time.perf_counter()
161
        most_recent_timestamp = st
162
        try:
163
164
165
            async with session.post(
                url=api_url, json=payload, headers=headers
            ) as response:
166
                if response.status == 200:
167
168
169
                    async for chunk_bytes in response.content:
                        chunk_bytes = chunk_bytes.strip()
                        if not chunk_bytes:
170
171
                            continue

172
                        chunk = chunk_bytes.decode("utf-8").removeprefix("data:")
173
174

                        data = json.loads(chunk)
175
                        output.generated_text += data["text_output"]
176
177
                        timestamp = time.perf_counter()
                        # First token
178
                        if ttft == 0.0:
179
                            ttft = timestamp - st
180
181
                            output.ttft = ttft

182
183
                        # Decoding phase
                        else:
184
                            output.itl.append(timestamp - most_recent_timestamp)
185
186
187
188

                        most_recent_timestamp = timestamp

                    output.latency = most_recent_timestamp - st
189
190
191
                    output.success = True

                else:
192
                    output.error = response.reason or ""
193
                    output.success = False
194
        except Exception:
195
            output.success = False
196
197
            exc_info = sys.exc_info()
            output.error = "".join(traceback.format_exception(*exc_info))
198
199
200
201
202
203
204
205

        if pbar:
            pbar.update(1)
        return output


async def async_request_deepspeed_mii(
    request_func_input: RequestFuncInput,
206
    pbar: tqdm | None = None,
207
) -> RequestFuncOutput:
208
209
210
211
212
    api_url = request_func_input.api_url
    assert api_url.endswith(("completions", "profile")), (
        "OpenAI Completions API URL must end with 'completions' or 'profile'."
    )

213
214
215
    async with aiohttp.ClientSession(
        trust_env=True, timeout=AIOHTTP_TIMEOUT
    ) as session:
216
        payload = {
217
            "model": request_func_input.model,
218
219
220
            "prompt": request_func_input.prompt,
            "max_tokens": request_func_input.output_len,
            "temperature": 0.01,  # deepspeed-mii does not accept 0.0 temp.
221
222
            "top_p": 1.0,
        }
223
        headers = {"Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}"}
224
225
        if request_func_input.request_id:
            headers["x-request-id"] = request_func_input.request_id
226

227
228
229
        output = RequestFuncOutput()
        output.prompt_len = request_func_input.prompt_len

230
        # NOTE: DeepSpeed-MII doesn't support streaming as of Jan 28 2024,
231
        # will use 0 as placeholder.
232
        # See https://github.com/microsoft/DeepSpeed-MII/pull/311
233
234
235
236
        output.ttft = 0

        st = time.perf_counter()
        try:
237
            async with session.post(
238
                url=api_url, json=payload, headers=headers
239
            ) as response:
240
241
                if response.status == 200:
                    parsed_resp = await response.json()
242
                    output.latency = time.perf_counter() - st
243
                    if "choices" in parsed_resp:
244
                        output.generated_text = parsed_resp["choices"][0]["text"]
245
246
247
                    elif "text" in parsed_resp:
                        output.generated_text = parsed_resp["text"][0]
                    else:
248
249
250
251
                        output.error = (
                            "Unexpected response format: "
                            "neither 'choices' nor 'text' found"
                        )
252
                        output.success = False
253
254
                    output.success = True
                else:
255
                    output.error = response.reason or ""
256
                    output.success = False
257
        except Exception:
258
            output.success = False
259
260
            exc_info = sys.exc_info()
            output.error = "".join(traceback.format_exception(*exc_info))
261
262
263
264
265
266
267
268

        if pbar:
            pbar.update(1)
        return output


async def async_request_openai_completions(
    request_func_input: RequestFuncInput,
269
    pbar: tqdm | None = None,
270
271
) -> RequestFuncOutput:
    api_url = request_func_input.api_url
272
273
274
    assert api_url.endswith(("completions", "profile")), (
        "OpenAI Completions API URL must end with 'completions' or 'profile'."
    )
275

276
277
278
    async with aiohttp.ClientSession(
        trust_env=True, timeout=AIOHTTP_TIMEOUT
    ) as session:
279
        payload = {
280
281
282
            "model": request_func_input.model_name
            if request_func_input.model_name
            else request_func_input.model,
283
284
            "prompt": request_func_input.prompt,
            "temperature": 0.0,
285
            "repetition_penalty": 1.0,
286
            "max_tokens": request_func_input.output_len,
287
            "logprobs": request_func_input.logprobs,
288
            "stream": True,
289
290
291
            "stream_options": {
                "include_usage": True,
            },
292
        }
293
294
        if request_func_input.ignore_eos:
            payload["ignore_eos"] = request_func_input.ignore_eos
295
296
        if request_func_input.extra_body:
            payload.update(request_func_input.extra_body)
297
        headers = {"Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}"}
298
299
        if request_func_input.request_id:
            headers["x-request-id"] = request_func_input.request_id
300
301
302
303
304
305

        output = RequestFuncOutput()
        output.prompt_len = request_func_input.prompt_len

        generated_text = ""
        st = time.perf_counter()
306
        most_recent_timestamp = st
307
        try:
308
309
310
            async with session.post(
                url=api_url, json=payload, headers=headers
            ) as response:
311
                if response.status == 200:
312
                    first_chunk_received = False
313
314
315
                    async for chunk_bytes in response.content:
                        chunk_bytes = chunk_bytes.strip()
                        if not chunk_bytes:
316
317
                            continue

318
                        chunk = chunk_bytes.decode("utf-8").removeprefix("data: ")
319
                        if chunk != "[DONE]":
320
321
                            data = json.loads(chunk)

322
323
324
                            # NOTE: Some completion API might have a last
                            # usage summary response without a token so we
                            # want to check a token was generated
325
326
327
328
                            if choices := data.get("choices"):
                                # Note that text could be empty here
                                # e.g. for special tokens
                                text = choices[0].get("text")
329
330
                                timestamp = time.perf_counter()
                                # First token
331
                                if not first_chunk_received:
332
                                    first_chunk_received = True
333
334
335
336
                                    ttft = time.perf_counter() - st
                                    output.ttft = ttft

                                # Decoding phase
337
                                else:
338
                                    output.itl.append(timestamp - most_recent_timestamp)
339
340

                                most_recent_timestamp = timestamp
341
                                generated_text += text or ""
342
                            if usage := data.get("usage"):
343
                                output.output_tokens = usage.get("completion_tokens")
344
345
346
347
348
349
                    if first_chunk_received:
                        output.success = True
                    else:
                        output.success = False
                        output.error = (
                            "Never received a valid chunk to calculate TTFT."
350
351
                            "This response will be marked as failed!"
                        )
352
                    output.generated_text = generated_text
353
                    output.latency = most_recent_timestamp - st
354
355
356
                else:
                    output.error = response.reason or ""
                    output.success = False
357
        except Exception:
358
            output.success = False
359
360
            exc_info = sys.exc_info()
            output.error = "".join(traceback.format_exception(*exc_info))
361
362
363
364
365
366

    if pbar:
        pbar.update(1)
    return output


367
368
async def async_request_openai_chat_completions(
    request_func_input: RequestFuncInput,
369
    pbar: tqdm | None = None,
370
371
) -> RequestFuncOutput:
    api_url = request_func_input.api_url
372
373
374
    assert api_url.endswith(("chat/completions", "profile")), (
        "OpenAI Chat Completions API URL must end with 'chat/completions'."
    )
375

376
377
378
    async with aiohttp.ClientSession(
        trust_env=True, timeout=AIOHTTP_TIMEOUT
    ) as session:
379
380
        content = [{"type": "text", "text": request_func_input.prompt}]
        if request_func_input.multi_modal_content:
381
382
383
384
385
386
387
388
389
            mm_content = request_func_input.multi_modal_content
            if isinstance(mm_content, list):
                content.extend(mm_content)
            elif isinstance(mm_content, dict):
                content.append(mm_content)
            else:
                raise TypeError(
                    "multi_modal_content must be a dict or list[dict] for openai-chat"
                )
390
        payload = {
391
392
393
            "model": request_func_input.model_name
            if request_func_input.model_name
            else request_func_input.model,
394
            "messages": [
395
                {"role": "user", "content": content},
396
397
            ],
            "temperature": 0.0,
398
            "max_completion_tokens": request_func_input.output_len,
399
            "stream": True,
400
401
402
            "stream_options": {
                "include_usage": True,
            },
403
        }
404
405
        if request_func_input.ignore_eos:
            payload["ignore_eos"] = request_func_input.ignore_eos
406
407
        if request_func_input.extra_body:
            payload.update(request_func_input.extra_body)
408
409
        headers = {
            "Content-Type": "application/json",
410
            "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
411
        }
412
413
        if request_func_input.request_id:
            headers["x-request-id"] = request_func_input.request_id
414
415
416
417
418

        output = RequestFuncOutput()
        output.prompt_len = request_func_input.prompt_len

        generated_text = ""
419
        ttft = 0.0
420
        st = time.perf_counter()
421
        most_recent_timestamp = st
422
        try:
423
424
425
            async with session.post(
                url=api_url, json=payload, headers=headers
            ) as response:
426
                if response.status == 200:
427
428
429
                    async for chunk_bytes in response.content:
                        chunk_bytes = chunk_bytes.strip()
                        if not chunk_bytes:
430
                            continue
431
432
433
434
435
436
437
                        chunk_bytes = chunk_bytes.decode("utf-8")
                        # NOTE: SSE comments (often used as pings) start with a colon.
                        # These are not JSON data payload and should be skipped.
                        if chunk_bytes.startswith(":"):
                            continue

                        chunk = chunk_bytes.removeprefix("data: ")
438

439
                        if chunk != "[DONE]":
440
441
442
                            timestamp = time.perf_counter()
                            data = json.loads(chunk)

443
444
                            if choices := data.get("choices"):
                                content = choices[0]["delta"].get("content")
445
                                # First token
446
                                if ttft == 0.0:
447
                                    ttft = timestamp - st
448
449
450
451
                                    output.ttft = ttft

                                # Decoding phase
                                else:
452
                                    output.itl.append(timestamp - most_recent_timestamp)
453

454
                                generated_text += content or ""
455
                            elif usage := data.get("usage"):
456
                                output.output_tokens = usage.get("completion_tokens")
457

458
459
                            most_recent_timestamp = timestamp

460
461
                    output.generated_text = generated_text
                    output.success = True
462
                    output.latency = most_recent_timestamp - st
463
                else:
464
                    output.error = response.reason or ""
465
                    output.success = False
466
        except Exception:
467
            output.success = False
468
469
            exc_info = sys.exc_info()
            output.error = "".join(traceback.format_exception(*exc_info))
470
471
472
473
474
475

    if pbar:
        pbar.update(1)
    return output


476
477
async def async_request_openai_audio(
    request_func_input: RequestFuncInput,
478
    pbar: tqdm | None = None,
479
480
481
) -> RequestFuncOutput:
    # Lazy import without PlaceholderModule to avoid vllm dep.
    import soundfile
482

483
    api_url = request_func_input.api_url
484
485
486
    assert api_url.endswith(("transcriptions", "translations")), (
        "OpenAI Chat Completions API URL must end with 'transcriptions' "
    )
487
488
    "or `translations`."

489
490
491
    async with aiohttp.ClientSession(
        trust_env=True, timeout=AIOHTTP_TIMEOUT
    ) as session:
492
493
        content = [{"type": "text", "text": request_func_input.prompt}]
        payload = {
494
495
496
            "model": request_func_input.model_name
            if request_func_input.model_name
            else request_func_input.model,
497
498
499
500
501
502
            "temperature": 0.0,
            "max_completion_tokens": request_func_input.output_len,
            "stream": True,
            "language": "en",
            # Flattened due to multipart/form-data
            "stream_include_usage": True,
503
            "stream_continuous_usage_stats": True,
504
505
506
507
508
509
        }
        if request_func_input.extra_body:
            payload.update(request_func_input.extra_body)
        headers = {
            "Authorization": f"Bearer {os.environ.get('OPENAI_API_KEY')}",
        }
510
511
        if request_func_input.request_id:
            headers["x-request-id"] = request_func_input.request_id
512
513
514
515
516
517
518
519

        # Send audio file
        def to_bytes(y, sr):
            buffer = io.BytesIO()
            soundfile.write(buffer, y, sr, format="WAV")
            buffer.seek(0)
            return buffer

520
521
522
523
        mm_audio = request_func_input.multi_modal_content
        if not isinstance(mm_audio, dict) or "audio" not in mm_audio:
            raise TypeError("multi_modal_content must be a dict containing 'audio'")
        with to_bytes(*mm_audio["audio"]) as f:
524
            form = aiohttp.FormData()
525
            form.add_field("file", f, content_type="audio/wav")
526
527
528
529
530
531
532
533
534
535
536
            for key, value in payload.items():
                form.add_field(key, str(value))

            output = RequestFuncOutput()
            output.prompt_len = request_func_input.prompt_len

            generated_text = ""
            ttft = 0.0
            st = time.perf_counter()
            most_recent_timestamp = st
            try:
537
538
539
                async with session.post(
                    url=api_url, data=form, headers=headers
                ) as response:
540
541
542
543
544
545
                    if response.status == 200:
                        async for chunk_bytes in response.content:
                            chunk_bytes = chunk_bytes.strip()
                            if not chunk_bytes:
                                continue

546
                            chunk = chunk_bytes.decode("utf-8").removeprefix("data: ")
547
548
549
550
551
                            if chunk != "[DONE]":
                                timestamp = time.perf_counter()
                                data = json.loads(chunk)

                                if choices := data.get("choices"):
552
                                    content = choices[0]["delta"].get("content")
553
554
555
556
557
558
559
560
                                    # First token
                                    if ttft == 0.0:
                                        ttft = timestamp - st
                                        output.ttft = ttft

                                    # Decoding phase
                                    else:
                                        output.itl.append(
561
562
                                            timestamp - most_recent_timestamp
                                        )
563
564
565
566

                                    generated_text += content or ""
                                elif usage := data.get("usage"):
                                    output.output_tokens = usage.get(
567
568
                                        "completion_tokens"
                                    )
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

                                most_recent_timestamp = timestamp

                        output.generated_text = generated_text
                        output.success = True
                        output.latency = most_recent_timestamp - st
                    else:
                        output.error = response.reason or ""
                        output.success = False
            except Exception:
                output.success = False
                exc_info = sys.exc_info()
                output.error = "".join(traceback.format_exception(*exc_info))

        if pbar:
            pbar.update(1)
        return output


588
def get_model(pretrained_model_name_or_path: str) -> str:
589
    if os.getenv("VLLM_USE_MODELSCOPE", "False").lower() == "true":
590
        from modelscope import snapshot_download
591

592
593
        from vllm.model_executor.model_loader.weight_utils import get_lock

594
595
596
597
598
599
        # Use file lock to prevent multiple processes from
        # downloading the same model weights at the same time.
        with get_lock(pretrained_model_name_or_path):
            model_path = snapshot_download(
                model_id=pretrained_model_name_or_path,
                local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
600
601
                ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"],
            )
602

603
            return model_path
604
    return pretrained_model_name_or_path
605
606
607


def get_tokenizer(
608
609
610
611
    pretrained_model_name_or_path: str,
    tokenizer_mode: str = "auto",
    trust_remote_code: bool = False,
    **kwargs,
612
) -> PreTrainedTokenizer | PreTrainedTokenizerFast:
613
    if pretrained_model_name_or_path is not None and not os.path.exists(
614
615
616
        pretrained_model_name_or_path
    ):
        pretrained_model_name_or_path = get_model(pretrained_model_name_or_path)
617
618
    if tokenizer_mode == "slow":
        if kwargs.get("use_fast", False):
619
            raise ValueError("Cannot use the fast tokenizer in slow tokenizer mode.")
620
621
622
623
624
        kwargs["use_fast"] = False
    if tokenizer_mode == "mistral":
        try:
            from vllm.transformers_utils.tokenizer import MistralTokenizer
        except ImportError as e:
625
626
627
628
629
630
            raise ImportError(
                "MistralTokenizer requires vllm package.\n"
                "Please install it with `pip install vllm` "
                "to use mistral tokenizer mode."
            ) from e
        return MistralTokenizer.from_pretrained(str(pretrained_model_name_or_path))
631
632
633
634
635
636
    else:
        return AutoTokenizer.from_pretrained(
            pretrained_model_name_or_path,
            trust_remote_code=trust_remote_code,
            **kwargs,
        )
637
638


639
640
ASYNC_REQUEST_FUNCS = {
    "tgi": async_request_tgi,
641
642
    "vllm": async_request_openai_completions,
    "lmdeploy": async_request_openai_completions,
643
644
    "deepspeed-mii": async_request_deepspeed_mii,
    "openai": async_request_openai_completions,
645
    "openai-chat": async_request_openai_chat_completions,
646
    "openai-audio": async_request_openai_audio,
647
    "tensorrt-llm": async_request_trt_llm,
648
    "scalellm": async_request_openai_completions,
649
    "sglang": async_request_openai_completions,
650
    "llama.cpp": async_request_openai_completions,
651
}
652
653

OPENAI_COMPATIBLE_BACKENDS = [
654
655
656
    k
    for k, v in ASYNC_REQUEST_FUNCS.items()
    if v in (async_request_openai_completions, async_request_openai_chat_completions)
657
]