benchmark_serving_structured_output.py 36.2 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

On the server side, run one of the following commands:
    (vLLM OpenAI API server)
7
    vllm serve <your_model>
8
9

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

import datasets
import numpy as np
import pandas as pd
40
41
42
43
44
from backend_request_func import (
    ASYNC_REQUEST_FUNCS,
    RequestFuncInput,
    RequestFuncOutput,
)
45
46
from tqdm.asyncio import tqdm
from transformers import PreTrainedTokenizerBase
47

48
49
50
51
52
53
54
55
56
57
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

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

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
77
    percentiles_ttft_ms: list[tuple[float, float]]
78
79
80
    mean_tpot_ms: float
    median_tpot_ms: float
    std_tpot_ms: float
81
    percentiles_tpot_ms: list[tuple[float, float]]
82
83
84
    mean_itl_ms: float
    median_itl_ms: float
    std_itl_ms: float
85
    percentiles_itl_ms: list[tuple[float, float]]
86
87
88
89
90
91
    # 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
92
    percentiles_e2el_ms: list[tuple[float, float]]
93
94
95
96
97
98
99
100
101
102
103
104
105


@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.
    """
106

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


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

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

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

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

146
        requests = [
147
148
149
150
151
152
153
            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,
            )
154
            for i in range(args.num_prompts)
155
156
157
158
        ]

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

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

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

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

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

Reid's avatar
Reid committed
169
        number ::= "1 " | "2 "
170
171
172
173
174
175
176
        """
        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 = [
177
178
179
180
181
182
183
            SampleRequest(
                prompt=prompt,
                prompt_len=input_len,
                expected_output_len=args.output_len,
                schema=schema,
                structure_type=args.structure_type,
            )
184
185
186
187
188
189
190
191
192
193
194
195
196
            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 = [
197
198
199
200
201
202
203
            SampleRequest(
                prompt=prompt,
                prompt_len=input_len,
                expected_output_len=args.output_len,
                schema=regex,
                structure_type=args.structure_type,
            )
204
205
206
207
208
209
210
211
212
213
            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 = [
214
215
216
217
218
219
220
            SampleRequest(
                prompt=prompt,
                prompt_len=input_len,
                expected_output_len=args.output_len,
                schema=choice,
                structure_type=args.structure_type,
            )
221
222
223
224
            for _ in range(args.num_prompts)
        ]

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

        def _filter_func(item):
            import json
231

232
233
234
235
236
            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)
237
238
239
240
        print(
            f"dataset has {len(dataset)} entries after filtering "
            f"out {num_filtered_out} entries with unsupported features"
        )
241
242
243
244
245
246
        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]
247
248
249
            prompt = tokenizer.apply_chat_template(
                dataset["prompt"][idx], tokenize=False, add_generation_prompt=True
            )
250
251
252
253
            input_len = len(tokenizer(prompt).input_ids)
            completion = dataset["completion"][idx]

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

    return requests


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

276
    Args:
277
        input_requests:
278
            A list of input requests, each represented as a tuple.
279
        request_rate:
280
            The rate at which requests are generated (requests/s).
281
282
        burstiness (optional):
            The burstiness factor of the request generation.
283
284
285
            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.
286
287
            A lower burstiness value (0 < burstiness < 1) results
            in more bursty requests, while a higher burstiness value
288
289
290
291
292
293
            (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, (
294
295
        f"A positive burstiness factor is expected, but given {burstiness}."
    )
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
    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(
313
314
    input_requests: list[tuple[str, int, int]],
    outputs: list[RequestFuncOutput],
315
316
    dur_s: float,
    tokenizer: PreTrainedTokenizerBase,
317
318
319
320
321
    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] = []
322
323
324
    total_input = 0
    completed = 0
    good_completed = 0
325
326
327
328
329
    itls: list[float] = []
    tpots: list[float] = []
    all_tpots: list[float] = []
    ttfts: list[float] = []
    e2els: list[float] = []
330
331
332
333
334
335
336
    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(
337
338
                tokenizer(outputs[i].generated_text, add_special_tokens=False).input_ids
            )
339
340
341
342
            actual_output_lens.append(output_len)
            total_input += input_requests[i].prompt_len
            tpot = 0
            if output_len > 1:
343
344
                latency_minus_ttft = outputs[i].latency - outputs[i].ttft
                tpot = latency_minus_ttft / (output_len - 1)
345
                tpots.append(tpot)
346
            outputs[i].tpot = tpot
347
348
349
350
351
352
353
354
355
            # 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)

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

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

        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

381
382
383
384
    if completed == 0:
        warnings.warn(
            "All requests failed. This is likely due to a misconfiguration "
            "on the benchmark arguments.",
385
386
            stacklevel=2,
        )
387
388
389
390
391
392
393
394
    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,
395
396
        mean_ttft_ms=np.mean(ttfts or 0)
        * 1000,  # ttfts is empty if streaming is not supported by backend
397
398
        std_ttft_ms=np.std(ttfts or 0) * 1000,
        median_ttft_ms=np.median(ttfts or 0) * 1000,
399
400
401
        percentiles_ttft_ms=[
            (p, np.percentile(ttfts or 0, p) * 1000) for p in selected_percentiles
        ],
402
403
404
        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,
405
406
407
        percentiles_tpot_ms=[
            (p, np.percentile(tpots or 0, p) * 1000) for p in selected_percentiles
        ],
408
409
410
        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,
411
412
413
        percentiles_itl_ms=[
            (p, np.percentile(itls or 0, p) * 1000) for p in selected_percentiles
        ],
414
415
416
        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,
417
418
419
        percentiles_e2el_ms=[
            (p, np.percentile(e2els or 0, p) * 1000) for p in selected_percentiles
        ],
420
421
422
423
424
425
426
427
428
429
430
    )

    return metrics, actual_output_lens


async def benchmark(
    backend: str,
    api_url: str,
    base_url: str,
    model_id: str,
    tokenizer: PreTrainedTokenizerBase,
431
    input_requests: list[SampleRequest],
432
433
434
435
    request_rate: float,
    burstiness: float,
    disable_tqdm: bool,
    profile: bool,
436
437
    selected_percentile_metrics: list[str],
    selected_percentiles: list[str],
438
439
    ignore_eos: bool,
    max_concurrency: Optional[int],
440
    structured_output_ratio: float,
441
    goodput_config_dict: Optional[dict[str, float]] = None,
442
443
444
445
446
447
448
449
450
):
    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
451
452
        extra_body["structured_outputs"] = {}
        extra_body["structured_outputs"][request.structure_type] = request.schema
453
454
455
        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

    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,
553
        goodput_config_dict=goodput_config_dict,
554
555
    )

556
    print("{s:{c}^{n}}".format(s=" Serving Benchmark Result ", n=50, c="="))
557
    print("{:<40} {:<10}".format("Successful requests:", metrics.completed))
558
559
560
561
    if max_concurrency is not None:
        print("{:<40} {:<10}".format("Maximum request concurrency:", max_concurrency))
    if request_rate != float("inf"):
        print("{:<40} {:<10.2f}".format("Request rate configured (RPS):", request_rate))
562
    print("{:<40} {:<10.2f}".format("Benchmark duration (s):", benchmark_duration))
563
    print("{:<40} {:<10}".format("Total input tokens:", metrics.total_input))
564
565
566
567
568
569
    print("{:<40} {:<10}".format("Total generated tokens:", metrics.total_output))
    print(
        "{:<40} {:<10.2f}".format(
            "Request throughput (req/s):", metrics.request_throughput
        )
    )
570
    if goodput_config_dict:
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
        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
        )
    )
586
587

    result = {
588
589
590
591
592
593
594
595
596
597
598
599
600
        "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(),
601
        "input_lens": [output.prompt_len for output in outputs],
602
        "output_lens": actual_output_lens,
603
604
605
606
607
        "ttfts": [output.ttft for output in outputs],
        "itls": [output.itl for output in outputs],
        "errors": [output.error for output in outputs],
    }

608
609
610
611
    ret = [
        {"generated": output.generated_text, "expected": gt}
        for output, gt in zip(outputs, expected)
    ]
612
613
614
615
616
617
618
619
620
621
622
623
624

    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
625
626
627
628
629
630
631
632
633
634
635
636
637
        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"),
            )
        )
638
        result[f"mean_{metric_attribute_name}_ms"] = getattr(
639
640
            metrics, f"mean_{metric_attribute_name}_ms"
        )
641
        result[f"median_{metric_attribute_name}_ms"] = getattr(
642
643
            metrics, f"median_{metric_attribute_name}_ms"
        )
644
        result[f"std_{metric_attribute_name}_ms"] = getattr(
645
646
647
            metrics, f"std_{metric_attribute_name}_ms"
        )
        for p, value in getattr(metrics, f"percentiles_{metric_attribute_name}_ms"):
648
            p_word = str(int(p)) if int(p) == p else str(p)
649
            print("{:<40} {:<10.2f}".format(f"P{p_word} {metric_name} (ms):", value))
650
651
652
            result[f"p{p_word}_{metric_attribute_name}_ms"] = value

    process_one_metric("ttft", "TTFT", "Time to First Token")
653
    process_one_metric("tpot", "TPOT", "Time per Output Token (excl. 1st token)")
654
655
656
657
658
    process_one_metric("itl", "ITL", "Inter-token Latency")
    process_one_metric("e2el", "E2EL", "End-to-end Latency")

    print("=" * 50)

659
660
661
662
663
664
665
666
667
668
669
670
671
672
    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")

673
674
675
676
677
678
    return result, ret


def evaluate(ret, args):
    def _eval_correctness_json(expected, actual):
        # extract json string from string using regex
679
        import regex as re
680
681

        actual = actual.replace("\n", "").replace(" ", "").strip()
682
        try:
683
            actual = re.search(r"\{.*\}", actual).group()
684
685
686
687
688
689
690
691
692
693
            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):
694
        import regex as re
695

696
697
698
        return re.match(args.regex, actual) is not None

    def _eval_correctness(expected, actual):
699
        if args.structure_type == "json":
700
            return _eval_correctness_json(expected, actual)
701
        elif args.structure_type == "regex":
702
            return _eval_correctness_regex(expected, actual)
703
        elif args.structure_type == "choice":
704
705
706
707
708
709
            return _eval_correctness_choice(expected, actual)
        else:
            return None

    scores = []
    for res in ret:
710
711
        score = _eval_correctness(res["expected"], res["generated"])
        res["correctness"] = score
712
713
714
715
        scores.append(score)

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

716
717
718
719
720
    return (
        (sum(not_none_scores) / len(not_none_scores) * 100)
        if len(not_none_scores) > 0
        else None
    )
721
722


723
724
725
726
727
728
729
730
731
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. "
732
            'Specify service level objectives for goodput as "KEY:VALUE" '
733
            "pairs, where the key is a metric name, and the value is a "
734
735
            "number in milliseconds."
        ) from err
736
737
738
739
740
741
742
743
744
745
746
747
748
    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 "
749
750
                    f"{str(VALID_NAMES)}. "
                )
751
752
753
754
            if slo_val < 0:
                raise ValueError(
                    f"Invalid value found, {slo_name}: {slo_val}. "
                    "The service level objective value should be "
755
756
                    "non-negative."
                )
757
758
759
    return goodput_config_dict


760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
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}"

776
777
778
779
780
    tokenizer = get_tokenizer(
        tokenizer_id,
        trust_remote_code=args.trust_remote_code,
        tokenizer_mode=args.tokenizer_mode,
    )
781

782
    if args.dataset == "grammar":
783
        args.structure_type = "grammar"
784
    elif args.dataset == "regex":
785
        args.structure_type = "regex"
786
    elif args.dataset == "choice":
787
        args.structure_type = "choice"
788
    else:
789
        args.structure_type = "json"
790

791
792
    if args.no_structured_output:
        args.structured_output_ratio = 0
793
    if args.save_results:
794
        result_file_name = f"{args.structured_output_ratio}so"
795
796
797
798
799
800
801
802
803
804
805
806
        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)

807
808
    goodput_config_dict = check_goodput_args(args)

809
810
811
812
813
814
815
816
817
818
819
820
821
    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(","),
822
            selected_percentiles=[float(p) for p in args.metric_percentiles.split(",")],
823
824
            ignore_eos=args.ignore_eos,
            max_concurrency=args.max_concurrency,
825
            structured_output_ratio=args.structured_output_ratio,
826
            goodput_config_dict=goodput_config_dict,
827
828
        )
    )
829
830
831

    # Save config and results to json
    score = evaluate(ret, args)
832
    print("correct_rate(%)", score, "\n")
833
834
    if args.save_results:
        results = {
835
836
837
838
839
840
841
842
843
844
            "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,
845
846
847
848
849
850
851
852
        }
        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)
853
        with open(result_file_name, "w", encoding="utf-8") as outfile:
854
855
856
            json.dump(results, outfile, indent=4)


857
def create_argument_parser():
858
    parser = FlexibleArgumentParser(
859
860
        description="Benchmark the online serving throughput."
    )
861
862
863
864
865
866
867
868
869
870
871
872
    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.",
    )
873
874
    # 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")
875
876
877
878
879
880
881
    parser.add_argument("--port", type=int, default=8000)
    parser.add_argument(
        "--endpoint",
        type=str,
        default="/v1/completions",
        help="API endpoint.",
    )
882
883
884
885
886
887
888
889
    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."
    )
890
891
892
893
894
895
896
897
898
899
900
    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, "
901
902
        "if the server is not processing requests fast enough to keep up.",
    )
903
904
905
906
907
908
909
910
911
    parser.add_argument(
        "--model",
        type=str,
        required=True,
        help="Name of the model.",
    )
    parser.add_argument(
        "--tokenizer",
        type=str,
912
        help="Name or path of the tokenizer, if not using the default tokenizer.",  # noqa: E501
913
    )
914
915
916
917
    parser.add_argument(
        "--tokenizer-mode",
        type=str,
        default="auto",
918
        help="Name or path of the tokenizer, if not using the default tokenizer.",  # noqa: E501
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
991
992
993
994
    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."
995
996
        "Warning: ignore_eos is not supported in deepspeed_mii and tgi.",
    )
997
998
999
1000
    parser.add_argument(
        "--percentile-metrics",
        type=str,
        default="ttft,tpot,itl",
1001
        help="Comma-separated list of selected metrics to report percentiles. "
1002
        "This argument specifies the metrics to report percentiles. "
1003
1004
1005
        'Allowed metric names are "ttft", "tpot", "itl", "e2el". '
        'Default value is "ttft,tpot,itl".',
    )
1006
1007
1008
1009
    parser.add_argument(
        "--metric-percentiles",
        type=str,
        default="99",
1010
        help="Comma-separated list of percentiles for selected metrics. "
1011
1012
1013
        'To report 25-th, 50-th, and 75-th percentiles, use "25,50,75". '
        'Default value is "99". '
        'Use "--percentile-metrics" to select metrics.',
1014
    )
1015
1016
1017
1018
    parser.add_argument(
        "--goodput",
        nargs="+",
        required=False,
1019
        help='Specify service level objectives for goodput as "KEY:VALUE" '
1020
        "pairs, where the key is a metric name, and the value is in "
1021
        'milliseconds. Multiple "KEY:VALUE" pairs can be provided, '
1022
        "separated by spaces. Allowed request level metric names are "
1023
        '"ttft", "tpot", "e2el". For more context on the definition of '
1024
        "goodput, refer to DistServe paper: https://arxiv.org/pdf/2401.09670 "
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
        "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",
    )
1040

1041
1042
1043
1044
1045
    return parser


if __name__ == "__main__":
    parser = create_argument_parser()
1046
1047
    args = parser.parse_args()
    main(args)