benchmark_serving_structured_output.py 35.9 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
        --structured-output-backend auto \
16
17
18
19
20
21
22
        --request-rate 10 \
        --num-prompts 1000

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

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

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

        def _filter_func(item):
            import json
233

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

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

    return requests


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

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

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

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

        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

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

    return metrics, actual_output_lens


async def benchmark(
    backend: str,
    api_url: str,
    base_url: str,
    model_id: str,
    tokenizer: PreTrainedTokenizerBase,
433
    input_requests: list[SampleRequest],
434
435
436
437
    request_rate: float,
    burstiness: float,
    disable_tqdm: bool,
    profile: bool,
438
439
    selected_percentile_metrics: list[str],
    selected_percentiles: list[str],
440
441
    ignore_eos: bool,
    max_concurrency: Optional[int],
442
    structured_output_ratio: float,
443
    goodput_config_dict: Optional[dict[str, float]] = None,
444
445
446
447
448
449
450
451
452
453
454
455
456
):
    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...")
457
    structured_output_req_idx = random.sample(
458
459
        range(len(input_requests)), int(len(input_requests) * structured_output_ratio)
    )
460
461

    test_request = input_requests[0]
462
463
464
    test_req_extra_body = (
        prepare_extra_body(test_request) if 0 in structured_output_req_idx else None
    )
465
466
467
468
469
470
471
    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,
472
        extra_body=test_req_extra_body,
473
474
475
476
477
    )
    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 "
478
479
            f"are correctly specified. Error: {test_output.error}"
        )
480
481
482
483
484
485
486
487
488
489
490
491
    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,
492
            extra_body=test_req_extra_body,
493
494
495
496
497
        )
        profile_output = await request_func(request_func_input=profile_input)
        if profile_output.success:
            print("Profiler started")

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

    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())
510
    semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else None
511
512
513

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

    benchmark_start_time = time.perf_counter()
519
520
    tasks: list[asyncio.Task] = []
    expected: list[str] = []
521
522
523
524
    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
        )
525
526
527
528
529
530
531
532
533
534
535
536
        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(
537
538
539
                limited_request_func(request_func_input=request_func_input, pbar=pbar)
            )
        )
540
    outputs: list[RequestFuncOutput] = await asyncio.gather(*tasks)
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
567

    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,
568
        goodput_config_dict=goodput_config_dict,
569
570
    )

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

    result = {
599
600
601
602
603
604
605
606
607
608
609
610
611
        "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(),
612
        "input_lens": [output.prompt_len for output in outputs],
613
        "output_lens": actual_output_lens,
614
615
616
617
618
        "ttfts": [output.ttft for output in outputs],
        "itls": [output.itl for output in outputs],
        "errors": [output.error for output in outputs],
    }

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

    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
636
637
638
639
640
641
642
643
644
645
646
647
648
        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"),
            )
        )
649
        result[f"mean_{metric_attribute_name}_ms"] = getattr(
650
651
            metrics, f"mean_{metric_attribute_name}_ms"
        )
652
        result[f"median_{metric_attribute_name}_ms"] = getattr(
653
654
            metrics, f"median_{metric_attribute_name}_ms"
        )
655
        result[f"std_{metric_attribute_name}_ms"] = getattr(
656
657
658
            metrics, f"std_{metric_attribute_name}_ms"
        )
        for p, value in getattr(metrics, f"percentiles_{metric_attribute_name}_ms"):
659
            p_word = str(int(p)) if int(p) == p else str(p)
660
            print("{:<40} {:<10.2f}".format(f"P{p_word} {metric_name} (ms):", value))
661
662
663
            result[f"p{p_word}_{metric_attribute_name}_ms"] = value

    process_one_metric("ttft", "TTFT", "Time to First Token")
664
    process_one_metric("tpot", "TPOT", "Time per Output Token (excl. 1st token)")
665
666
667
668
669
670
671
672
673
674
675
    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
676
        import regex as re
677
678

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

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

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

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

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

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


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


757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
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}"

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

779
780
781
782
783
784
    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"
785
    else:
786
        args.structure_type = "guided_json"
787

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

804
805
    goodput_config_dict = check_goodput_args(args)

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

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


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

    args = parser.parse_args()
    main(args)