benchmark_serving_structured_output.py 36 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
r"""Benchmark online serving throughput with structured outputs.
4
5
6
7
8
9

On the server side, run one of the following commands:
    (vLLM OpenAI API server)
    vllm serve <your_model> --disable-log-requests

On the client side, run:
10
    python benchmarks/benchmark_serving_structured_output.py \
11
12
13
        --backend <backend> \
        --model <your_model> \
        --dataset json \
14
        --structured-output-ratio 1.0 \
15
16
17
18
19
20
21
        --request-rate 10 \
        --num-prompts 1000

    when using tgi backend, add
        --endpoint /generate_stream
    to the end of the command above.
"""
22

23
24
import argparse
import asyncio
25
import copy
26
27
28
29
30
import dataclasses
import json
import os
import random
import time
31
import uuid
32
import warnings
33
from collections.abc import AsyncGenerator
34
from dataclasses import dataclass
35
from typing import Optional
36
37
38
39
40
41
42

import datasets
import numpy as np
import pandas as pd
from tqdm.asyncio import tqdm
from transformers import PreTrainedTokenizerBase

43
44
45
46
47
48
from backend_request_func import (
    ASYNC_REQUEST_FUNCS,
    RequestFuncInput,
    RequestFuncOutput,
)

49
50
51
52
53
54
55
56
57
58
try:
    from vllm.transformers_utils.tokenizer import get_tokenizer
except ImportError:
    from backend_request_func import get_tokenizer

try:
    from vllm.utils import FlexibleArgumentParser
except ImportError:
    from argparse import ArgumentParser as FlexibleArgumentParser

59
from vllm.v1.structured_output.backend_xgrammar import (
60
61
    has_xgrammar_unsupported_json_features,
)
62

63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
MILLISECONDS_TO_SECONDS_CONVERSION = 1000


@dataclass
class BenchmarkMetrics:
    completed: int
    total_input: int
    total_output: int
    request_throughput: float
    request_goodput: float
    output_throughput: float
    total_token_throughput: float
    mean_ttft_ms: float
    median_ttft_ms: float
    std_ttft_ms: float
78
    percentiles_ttft_ms: list[tuple[float, float]]
79
80
81
    mean_tpot_ms: float
    median_tpot_ms: float
    std_tpot_ms: float
82
    percentiles_tpot_ms: list[tuple[float, float]]
83
84
85
    mean_itl_ms: float
    median_itl_ms: float
    std_itl_ms: float
86
    percentiles_itl_ms: list[tuple[float, float]]
87
88
89
90
91
92
    # E2EL stands for end-to-end latency per request.
    # It is the time taken on the client side from sending
    # a request to receiving a complete response.
    mean_e2el_ms: float
    median_e2el_ms: float
    std_e2el_ms: float
93
    percentiles_e2el_ms: list[tuple[float, float]]
94
95
96
97
98
99
100
101
102
103
104
105
106


@dataclasses.dataclass
class SampleRequest:
    """A class representing a single inference request for benchmarking.

    Attributes:
        prompt: The input text prompt for the model.
        multi_modal_data: Optional dictionary containing multi-modal data (e.g.
            images).
        prompt_len: The length of the prompt in tokens.
        expected_output_len: The expected length of the output in tokens.
    """
107

108
109
110
111
112
113
114
115
    prompt: str
    prompt_len: int
    expected_output_len: int
    schema: dict
    structure_type: str
    completion: str = None


116
117
118
119
def sample_requests(
    tokenizer: PreTrainedTokenizerBase, args: argparse.Namespace
) -> list[SampleRequest]:
    if args.dataset == "json" or args.dataset == "json-unique":
120
121
        if args.json_schema_path is None:
            dir_path = os.path.dirname(os.path.realpath(__file__))
122
123
124
            args.json_schema_path = os.path.join(
                dir_path, "structured_schemas", "structured_schema_1.json"
            )
125
        json_schemas = []
126
127
        with open(args.json_schema_path) as f:
            schema = json.load(f)
128

129
130
        if args.dataset == "json-unique":
            json_schemas = [copy.deepcopy(schema) for _ in range(args.num_prompts)]
131
            for i in range(len(json_schemas)):
132
133
                if "properties" not in json_schemas[i]:
                    json_schemas[i]["properties"] = {}
134
135
136
137
                json_schemas[i]["properties"][f"__optional_field_{uuid.uuid4()}"] = {
                    "type": "string",
                    "description": "An unique optional field to avoid cached schemas",
                }
138
139
        else:
            json_schemas = [schema] * args.num_prompts
140
141

        def gen_prompt(index: int):
142
            return f"Generate an example of a brief user profile given the following schema: {json.dumps(get_schema(index))}"  # noqa: E501
143
144
145
146

        def get_schema(index: int):
            return json_schemas[index % len(json_schemas)]

147
        requests = [
148
149
150
151
152
153
154
            SampleRequest(
                prompt=gen_prompt(i),
                prompt_len=len(tokenizer(gen_prompt(i)).input_ids),
                expected_output_len=args.output_len,
                schema=get_schema(i),
                structure_type=args.structure_type,
            )
155
            for i in range(args.num_prompts)
156
157
158
159
        ]

    elif args.dataset == "grammar":
        schema = """
Reid's avatar
Reid committed
160
        root ::= select_statement
161

Reid's avatar
Reid committed
162
        select_statement ::= "SELECT " column " from " table " where " condition
163

Reid's avatar
Reid committed
164
        column ::= "col_1 " | "col_2 "
165

Reid's avatar
Reid committed
166
        table ::= "table_1 " | "table_2 "
167

Reid's avatar
Reid committed
168
        condition ::= column "= " number
169

Reid's avatar
Reid committed
170
        number ::= "1 " | "2 "
171
172
173
174
175
176
177
        """
        prompt = "Generate an SQL query to show the 'username' \
            and 'email' from the 'users' table."

        input_len = len(tokenizer(prompt).input_ids)
        print(f"Input length of the prompt: {input_len} tokens")
        requests = [
178
179
180
181
182
183
184
            SampleRequest(
                prompt=prompt,
                prompt_len=input_len,
                expected_output_len=args.output_len,
                schema=schema,
                structure_type=args.structure_type,
            )
185
186
187
188
189
190
191
192
193
194
195
196
197
            for _ in range(args.num_prompts)
        ]

    elif args.dataset == "regex":
        regex = r"\w+@\w+\.com\n"
        args.regex = regex
        prompt = "Generate an email address for Alan Turing, \
            who works in Enigma. End in .com and new line. \
                Example result: alan.turing@enigma.com\n"

        input_len = len(tokenizer(prompt).input_ids)
        print(f"Input length of the prompt: {input_len} tokens")
        requests = [
198
199
200
201
202
203
204
            SampleRequest(
                prompt=prompt,
                prompt_len=input_len,
                expected_output_len=args.output_len,
                schema=regex,
                structure_type=args.structure_type,
            )
205
206
207
208
209
210
211
212
213
214
            for _ in range(args.num_prompts)
        ]

    elif args.dataset == "choice":
        choice = ["Positive", "Negative"]
        args.choice = choice
        prompt = "Classify this sentiment: vLLM is wonderful!"
        input_len = len(tokenizer(prompt).input_ids)
        print(f"Input length of the prompt: {input_len} tokens")
        requests = [
215
216
217
218
219
220
221
            SampleRequest(
                prompt=prompt,
                prompt_len=input_len,
                expected_output_len=args.output_len,
                schema=choice,
                structure_type=args.structure_type,
            )
222
223
224
225
            for _ in range(args.num_prompts)
        ]

    elif args.dataset == "xgrammar_bench":
226
        requests: list[SampleRequest] = []
227
        dataset = datasets.load_dataset("NousResearch/json-mode-eval", split="train")
228
229
230
231
        full_dataset_len = len(dataset)

        def _filter_func(item):
            import json
232

233
234
235
236
237
            schema = json.loads(item["schema"])
            return not has_xgrammar_unsupported_json_features(schema)

        dataset = dataset.filter(_filter_func)
        num_filtered_out = full_dataset_len - len(dataset)
238
239
240
241
        print(
            f"dataset has {len(dataset)} entries after filtering "
            f"out {num_filtered_out} entries with unsupported features"
        )
242
243
244
245
246
247
        len_dataset = len(dataset)
        for data_point_idx in range(args.num_prompts):
            idx = data_point_idx
            while idx >= len_dataset:
                idx -= len_dataset
            schema = dataset["schema"][idx]
248
249
250
            prompt = tokenizer.apply_chat_template(
                dataset["prompt"][idx], tokenize=False, add_generation_prompt=True
            )
251
252
253
254
            input_len = len(tokenizer(prompt).input_ids)
            completion = dataset["completion"][idx]

            requests.append(
255
256
257
258
259
260
261
262
263
                SampleRequest(
                    prompt=prompt,
                    prompt_len=input_len,
                    expected_output_len=args.output_len,
                    schema=schema,
                    structure_type=args.structure_type,
                    completion=completion,
                )
            )
264
265
266
267
268

    return requests


async def get_request(
269
    input_requests: list[SampleRequest],
270
271
    request_rate: float,
    burstiness: float = 1.0,
272
) -> AsyncGenerator[tuple[int, SampleRequest], None]:
273
    """
274
    Asynchronously generates requests at a specified rate
275
    with OPTIONAL burstiness.
276

277
    Args:
278
        input_requests:
279
            A list of input requests, each represented as a tuple.
280
        request_rate:
281
            The rate at which requests are generated (requests/s).
282
283
        burstiness (optional):
            The burstiness factor of the request generation.
284
285
286
            Only takes effect when request_rate is not inf.
            Default value is 1, which follows a Poisson process.
            Otherwise, the request intervals follow a gamma distribution.
287
288
            A lower burstiness value (0 < burstiness < 1) results
            in more bursty requests, while a higher burstiness value
289
290
291
292
293
294
            (burstiness > 1) results in a more uniform arrival of requests.
    """
    input_requests = iter(input_requests)

    # Calculate scale parameter theta to maintain the desired request_rate.
    assert burstiness > 0, (
295
296
        f"A positive burstiness factor is expected, but given {burstiness}."
    )
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    theta = 1.0 / (request_rate * burstiness)

    for i, request in enumerate(input_requests):
        yield i, request

        if request_rate == float("inf"):
            # If the request rate is infinity, then we don't need to wait.
            continue

        # Sample the request interval from the gamma distribution.
        # If burstiness is 1, it follows exponential distribution.
        interval = np.random.gamma(shape=burstiness, scale=theta)
        # The next request will be sent after the interval.
        await asyncio.sleep(interval)


def calculate_metrics(
314
315
    input_requests: list[tuple[str, int, int]],
    outputs: list[RequestFuncOutput],
316
317
    dur_s: float,
    tokenizer: PreTrainedTokenizerBase,
318
319
320
321
322
    selected_percentile_metrics: list[str],
    selected_percentiles: list[float],
    goodput_config_dict: Optional[dict[str, float]] = None,
) -> tuple[BenchmarkMetrics, list[int]]:
    actual_output_lens: list[int] = []
323
324
325
    total_input = 0
    completed = 0
    good_completed = 0
326
327
328
329
330
    itls: list[float] = []
    tpots: list[float] = []
    all_tpots: list[float] = []
    ttfts: list[float] = []
    e2els: list[float] = []
331
332
333
334
335
336
337
    for i in range(len(outputs)):
        if outputs[i].success:
            # We use the tokenizer to count the number of output tokens for all
            # serving backends instead of looking at len(outputs[i].itl) since
            # multiple output tokens may be bundled together
            # Note : this may inflate the output token count slightly
            output_len = len(
338
339
                tokenizer(outputs[i].generated_text, add_special_tokens=False).input_ids
            )
340
341
342
343
            actual_output_lens.append(output_len)
            total_input += input_requests[i].prompt_len
            tpot = 0
            if output_len > 1:
344
345
                latency_minus_ttft = outputs[i].latency - outputs[i].ttft
                tpot = latency_minus_ttft / (output_len - 1)
346
                tpots.append(tpot)
347
            outputs[i].tpot = tpot
348
349
350
351
352
353
354
355
356
            # Note: if output_len <= 1, we regard tpot as 0 for goodput
            all_tpots.append(tpot)
            itls += outputs[i].itl
            ttfts.append(outputs[i].ttft)
            e2els.append(outputs[i].latency)
            completed += 1
        else:
            actual_output_lens.append(0)

357
358
359
360
361
362
    if goodput_config_dict:
        valid_metrics = []
        slo_values = []

        if "ttft" in goodput_config_dict:
            valid_metrics.append(ttfts)
363
364
365
            slo_values.append(
                goodput_config_dict["ttft"] / MILLISECONDS_TO_SECONDS_CONVERSION
            )
366
367
        if "tpot" in goodput_config_dict:
            valid_metrics.append(all_tpots)
368
369
370
            slo_values.append(
                goodput_config_dict["tpot"] / MILLISECONDS_TO_SECONDS_CONVERSION
            )
371
372
        if "e2el" in goodput_config_dict:
            valid_metrics.append(e2els)
373
374
375
            slo_values.append(
                goodput_config_dict["e2el"] / MILLISECONDS_TO_SECONDS_CONVERSION
            )
376
377
378
379
380
381

        for req_metric in zip(*valid_metrics):
            is_good_req = all([s >= r for s, r in zip(slo_values, req_metric)])
            if is_good_req:
                good_completed += 1

382
383
384
385
    if completed == 0:
        warnings.warn(
            "All requests failed. This is likely due to a misconfiguration "
            "on the benchmark arguments.",
386
387
            stacklevel=2,
        )
388
389
390
391
392
393
394
395
    metrics = BenchmarkMetrics(
        completed=completed,
        total_input=total_input,
        total_output=sum(actual_output_lens),
        request_throughput=completed / dur_s,
        request_goodput=good_completed / dur_s,
        output_throughput=sum(actual_output_lens) / dur_s,
        total_token_throughput=(total_input + sum(actual_output_lens)) / dur_s,
396
397
        mean_ttft_ms=np.mean(ttfts or 0)
        * 1000,  # ttfts is empty if streaming is not supported by backend
398
399
        std_ttft_ms=np.std(ttfts or 0) * 1000,
        median_ttft_ms=np.median(ttfts or 0) * 1000,
400
401
402
        percentiles_ttft_ms=[
            (p, np.percentile(ttfts or 0, p) * 1000) for p in selected_percentiles
        ],
403
404
405
        mean_tpot_ms=np.mean(tpots or 0) * 1000,
        std_tpot_ms=np.std(tpots or 0) * 1000,
        median_tpot_ms=np.median(tpots or 0) * 1000,
406
407
408
        percentiles_tpot_ms=[
            (p, np.percentile(tpots or 0, p) * 1000) for p in selected_percentiles
        ],
409
410
411
        mean_itl_ms=np.mean(itls or 0) * 1000,
        std_itl_ms=np.std(itls or 0) * 1000,
        median_itl_ms=np.median(itls or 0) * 1000,
412
413
414
        percentiles_itl_ms=[
            (p, np.percentile(itls or 0, p) * 1000) for p in selected_percentiles
        ],
415
416
417
        mean_e2el_ms=np.mean(e2els or 0) * 1000,
        std_e2el_ms=np.std(e2els or 0) * 1000,
        median_e2el_ms=np.median(e2els or 0) * 1000,
418
419
420
        percentiles_e2el_ms=[
            (p, np.percentile(e2els or 0, p) * 1000) for p in selected_percentiles
        ],
421
422
423
424
425
426
427
428
429
430
431
    )

    return metrics, actual_output_lens


async def benchmark(
    backend: str,
    api_url: str,
    base_url: str,
    model_id: str,
    tokenizer: PreTrainedTokenizerBase,
432
    input_requests: list[SampleRequest],
433
434
435
436
    request_rate: float,
    burstiness: float,
    disable_tqdm: bool,
    profile: bool,
437
438
    selected_percentile_metrics: list[str],
    selected_percentiles: list[str],
439
440
    ignore_eos: bool,
    max_concurrency: Optional[int],
441
    structured_output_ratio: float,
442
    goodput_config_dict: Optional[dict[str, float]] = None,
443
444
445
446
447
448
449
450
451
452
453
454
455
):
    if backend in ASYNC_REQUEST_FUNCS:
        request_func = ASYNC_REQUEST_FUNCS[backend]
    else:
        raise ValueError(f"Unknown backend: {backend}")

    def prepare_extra_body(request) -> dict:
        extra_body = {}
        # Add the schema to the extra_body
        extra_body[request.structure_type] = request.schema
        return extra_body

    print("Starting initial single prompt test run...")
456
    structured_output_req_idx = random.sample(
457
458
        range(len(input_requests)), int(len(input_requests) * structured_output_ratio)
    )
459
460

    test_request = input_requests[0]
461
462
463
    test_req_extra_body = (
        prepare_extra_body(test_request) if 0 in structured_output_req_idx else None
    )
464
465
466
467
468
469
470
    test_input = RequestFuncInput(
        model=model_id,
        prompt=test_request.prompt,
        api_url=api_url,
        prompt_len=test_request.prompt_len,
        output_len=test_request.expected_output_len,
        ignore_eos=ignore_eos,
471
        extra_body=test_req_extra_body,
472
473
474
475
476
    )
    test_output = await request_func(request_func_input=test_input)
    if not test_output.success:
        raise ValueError(
            "Initial test run failed - Please make sure benchmark arguments "
477
478
            f"are correctly specified. Error: {test_output.error}"
        )
479
480
481
482
483
484
485
486
487
488
489
490
    else:
        print("Initial test run completed. Starting main benchmark run...")

    if profile:
        print("Starting profiler...")
        profile_input = RequestFuncInput(
            model=model_id,
            prompt=test_request.prompt,
            api_url=base_url + "/start_profile",
            prompt_len=test_request.prompt_len,
            output_len=test_request.expected_output_len,
            ignore_eos=ignore_eos,
491
            extra_body=test_req_extra_body,
492
493
494
495
496
        )
        profile_output = await request_func(request_func_input=profile_input)
        if profile_output.success:
            print("Profiler started")

497
    distribution = "Poisson process" if burstiness == 1.0 else "Gamma distribution"
498
499
500
501
502
503
504
505
506
507
508

    print(f"Traffic request rate: {request_rate}")
    print(f"Burstiness factor: {burstiness} ({distribution})")
    print(f"Maximum request concurrency: {max_concurrency}")

    pbar = None if disable_tqdm else tqdm(total=len(input_requests))

    # This can be used once the minimum Python version is 3.10 or higher,
    # and it will simplify the code in limited_request_func.
    #    semaphore = (asyncio.Semaphore(max_concurrency)
    #                 if max_concurrency else contextlib.nullcontext())
509
    semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else None
510
511
512

    async def limited_request_func(request_func_input, pbar):
        if semaphore is None:
513
            return await request_func(request_func_input=request_func_input, pbar=pbar)
514
        async with semaphore:
515
            return await request_func(request_func_input=request_func_input, pbar=pbar)
516
517

    benchmark_start_time = time.perf_counter()
518
519
    tasks: list[asyncio.Task] = []
    expected: list[str] = []
520
521
522
523
    async for i, request in get_request(input_requests, request_rate, burstiness):
        extra_body = (
            prepare_extra_body(request) if i in structured_output_req_idx else None
        )
524
525
526
527
528
529
530
531
532
533
534
535
        request_func_input = RequestFuncInput(
            model=model_id,
            prompt=request.prompt,
            api_url=api_url,
            prompt_len=request.prompt_len,
            output_len=request.expected_output_len,
            ignore_eos=ignore_eos,
            extra_body=extra_body,
        )
        expected.append(request.completion)
        tasks.append(
            asyncio.create_task(
536
537
538
                limited_request_func(request_func_input=request_func_input, pbar=pbar)
            )
        )
539
    outputs: list[RequestFuncOutput] = await asyncio.gather(*tasks)
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566

    if profile:
        print("Stopping profiler...")
        profile_input = RequestFuncInput(
            model=model_id,
            prompt=test_request.prompt,
            api_url=base_url + "/stop_profile",
            prompt_len=test_request.prompt_len,
            output_len=test_request.expected_output_len,
            extra_body={test_request.structure_type: test_request.schema},
        )
        profile_output = await request_func(request_func_input=profile_input)
        if profile_output.success:
            print("Profiler stopped")

    if pbar is not None:
        pbar.close()

    benchmark_duration = time.perf_counter() - benchmark_start_time

    metrics, actual_output_lens = calculate_metrics(
        input_requests=input_requests,
        outputs=outputs,
        dur_s=benchmark_duration,
        tokenizer=tokenizer,
        selected_percentile_metrics=selected_percentile_metrics,
        selected_percentiles=selected_percentiles,
567
        goodput_config_dict=goodput_config_dict,
568
569
    )

570
    print("{s:{c}^{n}}".format(s=" Serving Benchmark Result ", n=50, c="="))
571
    print("{:<40} {:<10}".format("Successful requests:", metrics.completed))
572
    print("{:<40} {:<10.2f}".format("Benchmark duration (s):", benchmark_duration))
573
    print("{:<40} {:<10}".format("Total input tokens:", metrics.total_input))
574
575
576
577
578
579
    print("{:<40} {:<10}".format("Total generated tokens:", metrics.total_output))
    print(
        "{:<40} {:<10.2f}".format(
            "Request throughput (req/s):", metrics.request_throughput
        )
    )
580
    if goodput_config_dict:
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
        print(
            "{:<40} {:<10.2f}".format(
                "Request goodput (req/s):", metrics.request_goodput
            )
        )
    print(
        "{:<40} {:<10.2f}".format(
            "Output token throughput (tok/s):", metrics.output_throughput
        )
    )
    print(
        "{:<40} {:<10.2f}".format(
            "Total Token throughput (tok/s):", metrics.total_token_throughput
        )
    )
596
597

    result = {
598
599
600
601
602
603
604
605
606
607
608
609
610
        "duration": benchmark_duration,
        "completed": metrics.completed,
        "total_input_tokens": metrics.total_input,
        "total_output_tokens": metrics.total_output,
        "request_throughput": metrics.request_throughput,
        "output_throughput": metrics.output_throughput,
        "total_token_throughput": metrics.total_token_throughput,
        "ttft_description": pd.Series([output.ttft for output in outputs])
        .describe()
        .to_dict(),
        "tpot_description": pd.Series([output.tpot for output in outputs])
        .describe()
        .to_dict(),
611
        "input_lens": [output.prompt_len for output in outputs],
612
        "output_lens": actual_output_lens,
613
614
615
616
617
        "ttfts": [output.ttft for output in outputs],
        "itls": [output.itl for output in outputs],
        "errors": [output.error for output in outputs],
    }

618
619
620
621
    ret = [
        {"generated": output.generated_text, "expected": gt}
        for output, gt in zip(outputs, expected)
    ]
622
623
624
625
626
627
628
629
630
631
632
633
634

    def process_one_metric(
        # E.g., "ttft"
        metric_attribute_name: str,
        # E.g., "TTFT"
        metric_name: str,
        # E.g., "Time to First Token"
        metric_header: str,
    ):
        # This function prints and adds statistics of the specified
        # metric.
        if metric_attribute_name not in selected_percentile_metrics:
            return
635
636
637
638
639
640
641
642
643
644
645
646
647
        print("{s:{c}^{n}}".format(s=metric_header, n=50, c="-"))
        print(
            "{:<40} {:<10.2f}".format(
                f"Mean {metric_name} (ms):",
                getattr(metrics, f"mean_{metric_attribute_name}_ms"),
            )
        )
        print(
            "{:<40} {:<10.2f}".format(
                f"Median {metric_name} (ms):",
                getattr(metrics, f"median_{metric_attribute_name}_ms"),
            )
        )
648
        result[f"mean_{metric_attribute_name}_ms"] = getattr(
649
650
            metrics, f"mean_{metric_attribute_name}_ms"
        )
651
        result[f"median_{metric_attribute_name}_ms"] = getattr(
652
653
            metrics, f"median_{metric_attribute_name}_ms"
        )
654
        result[f"std_{metric_attribute_name}_ms"] = getattr(
655
656
657
            metrics, f"std_{metric_attribute_name}_ms"
        )
        for p, value in getattr(metrics, f"percentiles_{metric_attribute_name}_ms"):
658
            p_word = str(int(p)) if int(p) == p else str(p)
659
            print("{:<40} {:<10.2f}".format(f"P{p_word} {metric_name} (ms):", value))
660
661
662
            result[f"p{p_word}_{metric_attribute_name}_ms"] = value

    process_one_metric("ttft", "TTFT", "Time to First Token")
663
    process_one_metric("tpot", "TPOT", "Time per Output Token (excl. 1st token)")
664
665
666
667
668
669
670
671
672
673
674
    process_one_metric("itl", "ITL", "Inter-token Latency")
    process_one_metric("e2el", "E2EL", "End-to-end Latency")

    print("=" * 50)

    return result, ret


def evaluate(ret, args):
    def _eval_correctness_json(expected, actual):
        # extract json string from string using regex
675
        import regex as re
676
677

        actual = actual.replace("\n", "").replace(" ", "").strip()
678
        try:
679
            actual = re.search(r"\{.*\}", actual).group()
680
681
682
683
684
685
686
687
688
689
            actual = json.loads(actual)
        except Exception:
            return False

        return True

    def _eval_correctness_choice(expected, actual):
        return actual in args.choice

    def _eval_correctness_regex(expected, actual):
690
        import regex as re
691

692
693
694
        return re.match(args.regex, actual) is not None

    def _eval_correctness(expected, actual):
695
        if args.structure_type == "guided_json":
696
            return _eval_correctness_json(expected, actual)
697
        elif args.structure_type == "guided_regex":
698
            return _eval_correctness_regex(expected, actual)
699
        elif args.structure_type == "guided_choice":
700
701
702
703
704
705
            return _eval_correctness_choice(expected, actual)
        else:
            return None

    scores = []
    for res in ret:
706
707
        score = _eval_correctness(res["expected"], res["generated"])
        res["correctness"] = score
708
709
710
711
        scores.append(score)

    not_none_scores = [score for score in scores if score is not None]

712
713
714
715
716
    return (
        (sum(not_none_scores) / len(not_none_scores) * 100)
        if len(not_none_scores) > 0
        else None
    )
717
718


719
720
721
722
723
724
725
726
727
def parse_goodput(slo_pairs):
    goodput_config_dict = {}
    try:
        for slo_pair in slo_pairs:
            slo_name, slo_val = slo_pair.split(":")
            goodput_config_dict[slo_name] = float(slo_val)
    except ValueError as err:
        raise argparse.ArgumentTypeError(
            "Invalid format found for service level objectives. "
728
            'Specify service level objectives for goodput as "KEY:VALUE" '
729
            "pairs, where the key is a metric name, and the value is a "
730
731
            "number in milliseconds."
        ) from err
732
733
734
735
736
737
738
739
740
741
742
743
744
    return goodput_config_dict


def check_goodput_args(args):
    goodput_config_dict = {}
    VALID_NAMES = ["ttft", "tpot", "e2el"]
    if args.goodput:
        goodput_config_dict = parse_goodput(args.goodput)
        for slo_name, slo_val in goodput_config_dict.items():
            if slo_name not in VALID_NAMES:
                raise ValueError(
                    f"Invalid metric name found, {slo_name}: {slo_val}. "
                    "The service level objective name should be one of "
745
746
                    f"{str(VALID_NAMES)}. "
                )
747
748
749
750
            if slo_val < 0:
                raise ValueError(
                    f"Invalid value found, {slo_name}: {slo_val}. "
                    "The service level objective value should be "
751
752
                    "non-negative."
                )
753
754
755
    return goodput_config_dict


756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
def main(args: argparse.Namespace):
    print(args)
    random.seed(args.seed)
    np.random.seed(args.seed)

    backend = args.backend
    model_id = args.model
    tokenizer_id = args.tokenizer if args.tokenizer is not None else args.model

    if args.base_url is not None:
        api_url = f"{args.base_url}{args.endpoint}"
        base_url = f"{args.base_url}"
    else:
        api_url = f"http://{args.host}:{args.port}{args.endpoint}"
        base_url = f"http://{args.host}:{args.port}"

772
773
774
775
776
    tokenizer = get_tokenizer(
        tokenizer_id,
        trust_remote_code=args.trust_remote_code,
        tokenizer_mode=args.tokenizer_mode,
    )
777

778
779
780
781
782
783
    if args.dataset == "grammar":
        args.structure_type = "guided_grammar"
    elif args.dataset == "regex":
        args.structure_type = "guided_regex"
    elif args.dataset == "choice":
        args.structure_type = "guided_choice"
784
    else:
785
        args.structure_type = "guided_json"
786

787
788
    if args.no_structured_output:
        args.structured_output_ratio = 0
789
    if args.save_results:
790
        result_file_name = f"{args.structured_output_ratio}guided"
791
792
793
794
795
796
797
798
799
800
801
802
        result_file_name += f"_{backend}"
        result_file_name += f"_{args.request_rate}qps"
        result_file_name += f"_{args.model.split('/')[-1]}"
        result_file_name += f"_{args.dataset}"
        result_file_name += f"_{args.num_prompts}"
        result_file_name += f"_out{args.output_len}"
        result_file_name += ".txt"
    else:
        result_file_name = None

    input_requests = sample_requests(tokenizer, args)

803
804
    goodput_config_dict = check_goodput_args(args)

805
806
807
808
809
810
811
812
813
814
815
816
817
    benchmark_result, ret = asyncio.run(
        benchmark(
            backend=backend,
            api_url=api_url,
            base_url=base_url,
            model_id=model_id,
            tokenizer=tokenizer,
            input_requests=input_requests,
            request_rate=args.request_rate,
            burstiness=args.burstiness,
            disable_tqdm=args.disable_tqdm,
            profile=args.profile,
            selected_percentile_metrics=args.percentile_metrics.split(","),
818
            selected_percentiles=[float(p) for p in args.metric_percentiles.split(",")],
819
820
            ignore_eos=args.ignore_eos,
            max_concurrency=args.max_concurrency,
821
            structured_output_ratio=args.structured_output_ratio,
822
            goodput_config_dict=goodput_config_dict,
823
824
        )
    )
825
826
827

    # Save config and results to json
    score = evaluate(ret, args)
828
    print("correct_rate(%)", score, "\n")
829
830
    if args.save_results:
        results = {
831
832
833
834
835
836
837
838
839
840
            "backend": backend,
            "model_id": model_id,
            "tokenizer_id": tokenizer_id,
            "num_prompts": args.num_prompts,
            "request_rate": args.request_rate
            if args.request_rate < float("inf")
            else "inf",
            "burstiness": args.burstiness,
            "max_concurrency": args.max_concurrency,
            "correct_rate(%)": score,
841
842
843
844
845
846
847
848
        }
        results = {"outputs": ret, **results, **benchmark_result}

        # Save to file
        if args.result_filename:
            result_file_name = args.result_filename
        if args.result_dir:
            result_file_name = os.path.join(args.result_dir, result_file_name)
849
        with open(result_file_name, "w", encoding="utf-8") as outfile:
850
851
852
            json.dump(results, outfile, indent=4)


853
def create_argument_parser():
854
    parser = FlexibleArgumentParser(
855
856
        description="Benchmark the online serving throughput."
    )
857
858
859
860
861
862
863
864
865
866
867
868
    parser.add_argument(
        "--backend",
        type=str,
        default="vllm",
        choices=list(ASYNC_REQUEST_FUNCS.keys()),
    )
    parser.add_argument(
        "--base-url",
        type=str,
        default=None,
        help="Server or API base url if not using http host and port.",
    )
869
870
    # Use 127.0.0.1 here instead of localhost to force the use of ipv4
    parser.add_argument("--host", type=str, default="127.0.0.1")
871
872
873
874
875
876
877
    parser.add_argument("--port", type=int, default=8000)
    parser.add_argument(
        "--endpoint",
        type=str,
        default="/v1/completions",
        help="API endpoint.",
    )
878
879
880
881
882
883
884
885
    parser.add_argument(
        "--dataset",
        default="json",
        choices=["json", "json-unique", "grammar", "regex", "choice", "xgrammar_bench"],
    )
    parser.add_argument(
        "--json-schema-path", type=str, default=None, help="Path to json schema."
    )
886
887
888
889
890
891
892
893
894
895
896
    parser.add_argument(
        "--max-concurrency",
        type=int,
        default=None,
        help="Maximum number of concurrent requests. This can be used "
        "to help simulate an environment where a higher level component "
        "is enforcing a maximum number of concurrent requests. While the "
        "--request-rate argument controls the rate at which requests are "
        "initiated, this argument will control how many are actually allowed "
        "to execute at a time. This means that when used in combination, the "
        "actual request rate may be lower than specified with --request-rate, "
897
898
        "if the server is not processing requests fast enough to keep up.",
    )
899
900
901
902
903
904
905
906
907
    parser.add_argument(
        "--model",
        type=str,
        required=True,
        help="Name of the model.",
    )
    parser.add_argument(
        "--tokenizer",
        type=str,
908
        help="Name or path of the tokenizer, if not using the default tokenizer.",  # noqa: E501
909
    )
910
911
912
913
    parser.add_argument(
        "--tokenizer-mode",
        type=str,
        default="auto",
914
        help="Name or path of the tokenizer, if not using the default tokenizer.",  # noqa: E501
915
    )
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
    parser.add_argument(
        "--num-prompts",
        type=int,
        default=1000,
        help="Number of prompts to process.",
    )
    parser.add_argument(
        "--output-len",
        type=int,
        default=128,
        help="Number of output tokens.",
    )
    parser.add_argument(
        "--request-rate",
        type=float,
        default=float("inf"),
        help="Number of requests per second. If this is inf, "
        "then all the requests are sent at time 0. "
        "Otherwise, we use Poisson process or gamma distribution "
        "to synthesize the request arrival times.",
    )
    parser.add_argument(
        "--burstiness",
        type=float,
        default=1.0,
        help="Burstiness factor of the request generation. "
        "Only take effect when request_rate is not inf. "
        "Default value is 1, which follows Poisson process. "
        "Otherwise, the request intervals follow a gamma distribution. "
        "A lower burstiness value (0 < burstiness < 1) results in more "
        "bursty requests. A higher burstiness value (burstiness > 1) "
        "results in a more uniform arrival of requests.",
    )
    parser.add_argument("--seed", type=int, default=0)
    parser.add_argument(
        "--trust-remote-code",
        action="store_true",
        help="Trust remote code from huggingface",
    )
    parser.add_argument(
        "--disable-tqdm",
        action="store_true",
        help="Specify to disable tqdm progress bar.",
    )
    parser.add_argument(
        "--save-results",
        action="store_true",
        help="Specify to save benchmark results to a json file",
    )
    parser.add_argument(
        "--profile",
        action="store_true",
        help="Use Torch Profiler. The endpoint must be launched with "
        "VLLM_TORCH_PROFILER_DIR to enable profiler.",
    )
    parser.add_argument(
        "--result-dir",
        type=str,
        default=None,
        help="Specify directory to save benchmark json results."
        "If not specified, results are saved in the current directory.",
    )
    parser.add_argument(
        "--result-filename",
        type=str,
        default=None,
        help="Specify the filename to save benchmark json results."
        "If not specified, results will be saved in "
        "{backend}-{args.request_rate}qps-{base_model_id}-{current_dt}.json"
        " format.",
    )
    parser.add_argument(
        "--ignore-eos",
        action="store_true",
        help="Set ignore_eos flag when sending the benchmark request."
991
992
        "Warning: ignore_eos is not supported in deepspeed_mii and tgi.",
    )
993
994
995
996
    parser.add_argument(
        "--percentile-metrics",
        type=str,
        default="ttft,tpot,itl",
997
        help="Comma-separated list of selected metrics to report percentils. "
998
        "This argument specifies the metrics to report percentiles. "
999
1000
1001
        'Allowed metric names are "ttft", "tpot", "itl", "e2el". '
        'Default value is "ttft,tpot,itl".',
    )
1002
1003
1004
1005
    parser.add_argument(
        "--metric-percentiles",
        type=str,
        default="99",
1006
        help="Comma-separated list of percentiles for selected metrics. "
1007
1008
1009
        'To report 25-th, 50-th, and 75-th percentiles, use "25,50,75". '
        'Default value is "99". '
        'Use "--percentile-metrics" to select metrics.',
1010
    )
1011
1012
1013
1014
    parser.add_argument(
        "--goodput",
        nargs="+",
        required=False,
1015
        help='Specify service level objectives for goodput as "KEY:VALUE" '
1016
        "pairs, where the key is a metric name, and the value is in "
1017
        'milliseconds. Multiple "KEY:VALUE" pairs can be provided, '
1018
        "separated by spaces. Allowed request level metric names are "
1019
        '"ttft", "tpot", "e2el". For more context on the definition of '
1020
        "goodput, refer to DistServe paper: https://arxiv.org/pdf/2401.09670 "
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
        "and the blog: https://hao-ai-lab.github.io/blogs/distserve",
    )

    parser.add_argument(
        "--no-structured-output",
        action="store_true",
        default=False,
        help="Whether to disable JSON decoding or not.",
    )
    parser.add_argument(
        "--structured-output-ratio",
        type=float,
        default=1.0,
        help="Ratio of Structured Outputs requests",
    )
1036

1037
1038
1039
1040
1041
    return parser


if __name__ == "__main__":
    parser = create_argument_parser()
1042
1043
    args = parser.parse_args()
    main(args)