"tests/entrypoints/pooling/openai/test_vision_embedding.py" did not exist on "8f10d5e3930f05c2057a831cd80ba24c52b8ceef"
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
35
36
37
38
from dataclasses import dataclass

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

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

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

        def _filter_func(item):
            import json
230

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

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

    return requests


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

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

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

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

        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

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

    return metrics, actual_output_lens


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

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

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

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

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

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

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

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

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

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

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

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

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

    print("=" * 50)

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

672
673
674
675
676
677
    return result, ret


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

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

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

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

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

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

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


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


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

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

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

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

806
807
    goodput_config_dict = check_goodput_args(args)

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

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


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

1040
1041
1042
1043
1044
    return parser


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