benchmark_serving_structured_output.py 35.8 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 contextlib import nullcontext
35
36
37
38
39
from dataclasses import dataclass

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
try:
49
    from vllm.tokenizers import get_tokenizer
50
51
52
53
except ImportError:
    from backend_request_func import get_tokenizer

try:
54
    from vllm.utils.argparse_utils import FlexibleArgumentParser
55
56
57
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
    selected_percentile_metrics: list[str],
    selected_percentiles: list[float],
319
    goodput_config_dict: dict[str, float] | None = None,
320
321
) -> 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
    ignore_eos: bool,
439
    max_concurrency: int | None,
440
    structured_output_ratio: float,
441
    goodput_config_dict: dict[str, float] | None = 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

    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))

505
    semaphore = asyncio.Semaphore(max_concurrency) if max_concurrency else nullcontext()
506
507
508

    async def limited_request_func(request_func_input, pbar):
        async with semaphore:
509
            return await request_func(request_func_input=request_func_input, pbar=pbar)
510
511

    benchmark_start_time = time.perf_counter()
512
513
    tasks: list[asyncio.Task] = []
    expected: list[str] = []
514
515
516
517
    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
        )
518
519
520
521
522
523
524
525
526
527
528
529
        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(
530
531
532
                limited_request_func(request_func_input=request_func_input, pbar=pbar)
            )
        )
533
    outputs: list[RequestFuncOutput] = await asyncio.gather(*tasks)
534
535
536
537
538
539
540
541
542
543
544
545
546

    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,
547
        goodput_config_dict=goodput_config_dict,
548
549
    )

550
    print("{s:{c}^{n}}".format(s=" Serving Benchmark Result ", n=50, c="="))
551
    print("{:<40} {:<10}".format("Successful requests:", metrics.completed))
552
553
554
555
    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))
556
    print("{:<40} {:<10.2f}".format("Benchmark duration (s):", benchmark_duration))
557
    print("{:<40} {:<10}".format("Total input tokens:", metrics.total_input))
558
559
560
561
562
563
    print("{:<40} {:<10}".format("Total generated tokens:", metrics.total_output))
    print(
        "{:<40} {:<10.2f}".format(
            "Request throughput (req/s):", metrics.request_throughput
        )
    )
564
    if goodput_config_dict:
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
        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
        )
    )
580
581

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

602
603
604
605
    ret = [
        {"generated": output.generated_text, "expected": gt}
        for output, gt in zip(outputs, expected)
    ]
606
607
608
609
610
611
612
613
614
615
616
617
618

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

    process_one_metric("ttft", "TTFT", "Time to First Token")
647
    process_one_metric("tpot", "TPOT", "Time per Output Token (excl. 1st token)")
648
649
650
651
652
    process_one_metric("itl", "ITL", "Inter-token Latency")
    process_one_metric("e2el", "E2EL", "End-to-end Latency")

    print("=" * 50)

653
654
655
656
657
658
659
660
661
662
663
664
665
666
    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")

667
668
669
670
671
672
    return result, ret


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

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

690
691
692
        return re.match(args.regex, actual) is not None

    def _eval_correctness(expected, actual):
693
        if args.structure_type == "json":
694
            return _eval_correctness_json(expected, actual)
695
        elif args.structure_type == "regex":
696
            return _eval_correctness_regex(expected, actual)
697
        elif args.structure_type == "choice":
698
699
700
701
702
703
            return _eval_correctness_choice(expected, actual)
        else:
            return None

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

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

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


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


754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
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}"

770
771
772
773
774
    tokenizer = get_tokenizer(
        tokenizer_id,
        trust_remote_code=args.trust_remote_code,
        tokenizer_mode=args.tokenizer_mode,
    )
775

776
    if args.dataset == "grammar":
777
        args.structure_type = "grammar"
778
    elif args.dataset == "regex":
779
        args.structure_type = "regex"
780
    elif args.dataset == "choice":
781
        args.structure_type = "choice"
782
    else:
783
        args.structure_type = "json"
784

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

801
802
    goodput_config_dict = check_goodput_args(args)

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

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


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

1034
1035
1036
1037
1038
    return parser


if __name__ == "__main__":
    parser = create_argument_parser()
1039
1040
    args = parser.parse_args()
    main(args)