prefix_ratio_benchmark.py 9.22 KB
Newer Older
Yan Ru Pei's avatar
Yan Ru Pei committed
1
2
#!/usr/bin/env python3

3
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Yan Ru Pei's avatar
Yan Ru Pei committed
4
5
6
7
8
9
# SPDX-License-Identifier: Apache-2.0

import argparse
import json
import os
import subprocess
10
from typing import Dict, Optional
Yan Ru Pei's avatar
Yan Ru Pei committed
11
12
13
14
15

import matplotlib

matplotlib.use("Agg")  # Use non-interactive backend
import matplotlib.pyplot as plt
16
17
18
19
20
from common import (
    add_common_args,
    get_common_aiperf_flags,
    resolve_tokenizer,
    setup_logger,
Yan Ru Pei's avatar
Yan Ru Pei committed
21
)
22
23

logger = setup_logger(__name__)
Yan Ru Pei's avatar
Yan Ru Pei committed
24
25


26
def get_aiperf_cmd(
Yan Ru Pei's avatar
Yan Ru Pei committed
27
    model,
28
    tokenizer,
Yan Ru Pei's avatar
Yan Ru Pei committed
29
30
31
32
33
34
35
36
37
    prefix_ratio,
    isl,
    osl,
    requests,
    concurrency,
    seed,
    num_prefix_prompts,
    artifact_dir,
    url="http://localhost:8888",
38
    use_expected_osl=False,
Yan Ru Pei's avatar
Yan Ru Pei committed
39
):
40
    """Build aiperf command based on prefix ratio"""
Yan Ru Pei's avatar
Yan Ru Pei committed
41
42
43
    prefix_length = int(isl * prefix_ratio)
    synthetic_input_length = int(isl * (1 - prefix_ratio))

44
45
46
47
48
49
    # Build nvext JSON with optional expected_output_tokens
    nvext_dict = {"ignore_eos": True}
    if use_expected_osl:
        nvext_dict["expected_output_tokens"] = osl
    nvext_json = json.dumps({"nvext": nvext_dict})

50
    cmd = [
51
        "aiperf",
Yan Ru Pei's avatar
Yan Ru Pei committed
52
53
54
55
        "profile",
        "--model",
        model,
        "--tokenizer",
56
        tokenizer,
Yan Ru Pei's avatar
Yan Ru Pei committed
57
58
59
60
61
62
63
64
65
66
67
        "--url",
        url,
        "--synthetic-input-tokens-mean",
        str(synthetic_input_length),
        "--synthetic-input-tokens-stddev",
        str(round(synthetic_input_length / 4)),
        "--output-tokens-mean",
        str(osl),
        "--output-tokens-stddev",
        str(round(osl / 4)),
        "--extra-inputs",
68
        nvext_json,
Yan Ru Pei's avatar
Yan Ru Pei committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
        "--concurrency",
        str(concurrency),
        "--request-count",
        str(requests),
        "--num-dataset-entries",
        str(requests),
        "--random-seed",
        str(seed),
        "--prefix-prompt-length",
        str(prefix_length),
        "--num-prefix-prompts",
        str(num_prefix_prompts),
        "--artifact-dir",
        artifact_dir,
83
84
        "--dataset-sampling-strategy",
        "shuffle",
Yan Ru Pei's avatar
Yan Ru Pei committed
85
    ]
86
87
    cmd.extend(get_common_aiperf_flags())
    return cmd
Yan Ru Pei's avatar
Yan Ru Pei committed
88
89


90
91
def get_aiperf_result(artifact_dir: str) -> dict:
    """Parse aiperf results from JSON file"""
Yan Ru Pei's avatar
Yan Ru Pei committed
92
93
    json_file_path = None
    for root, _, files in os.walk(artifact_dir):
94
95
        if "profile_export_aiperf.json" in files:
            json_file_path = os.path.join(root, "profile_export_aiperf.json")
Yan Ru Pei's avatar
Yan Ru Pei committed
96
97
98
99
            break

    if json_file_path is None:
        raise FileNotFoundError(
100
            f"profile_export_aiperf.json not found in {artifact_dir}"
Yan Ru Pei's avatar
Yan Ru Pei committed
101
102
103
104
105
106
        )

    with open(json_file_path, "r") as f:
        return json.load(f)


107
def run_benchmark(
Yan Ru Pei's avatar
Yan Ru Pei committed
108
    model,
109
    tokenizer,
Yan Ru Pei's avatar
Yan Ru Pei committed
110
111
112
113
114
115
116
    prefix_ratio,
    isl,
    osl,
    requests,
    concurrency,
    seed,
    num_prefix_prompts,
117
    output_dir,
Yan Ru Pei's avatar
Yan Ru Pei committed
118
    url,
119
    use_expected_osl=False,
Yan Ru Pei's avatar
Yan Ru Pei committed
120
) -> Optional[Dict]:
121
122
123
124
125
126
127
128
    """Run aiperf benchmark for a specific prefix ratio"""
    logger.info(
        f"Running benchmark with prefix_ratio={prefix_ratio}, seed={seed}, url={url}"
    )

    artifact_dir = f"{output_dir}/prefix_ratio_{prefix_ratio}_seed_{seed}"
    os.makedirs(artifact_dir, exist_ok=True)

129
    aiperf_cmd = get_aiperf_cmd(
Yan Ru Pei's avatar
Yan Ru Pei committed
130
        model,
131
        tokenizer,
Yan Ru Pei's avatar
Yan Ru Pei committed
132
133
134
135
136
137
138
139
140
        prefix_ratio,
        isl,
        osl,
        requests,
        concurrency,
        seed,
        num_prefix_prompts,
        artifact_dir,
        url,
141
        use_expected_osl,
Yan Ru Pei's avatar
Yan Ru Pei committed
142
143
    )

144
    logger.info(f"Command: {' '.join(aiperf_cmd)}")
Yan Ru Pei's avatar
Yan Ru Pei committed
145
146

    try:
147
        subprocess.run(aiperf_cmd, check=True)
148
149
        logger.info("AIPerf profiling completed successfully")
        return get_aiperf_result(artifact_dir)
Yan Ru Pei's avatar
Yan Ru Pei committed
150
    except subprocess.CalledProcessError as e:
151
        logger.error(f"AIPerf failed with error code: {e.returncode}")
Yan Ru Pei's avatar
Yan Ru Pei committed
152
153
154
155
156
157
158
        return None


def main():
    parser = argparse.ArgumentParser(
        description="Benchmark prefix ratios and plot results"
    )
159
160
161

    add_common_args(parser)

Yan Ru Pei's avatar
Yan Ru Pei committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    parser.add_argument(
        "--output-dir",
        type=str,
        default="kv_router",
        help="Output directory for results",
    )
    parser.add_argument("--num-prefix-prompts", type=int, default=20)
    parser.add_argument("--isl", type=int, default=14000, help="Input sequence length")
    parser.add_argument("--osl", type=int, default=200, help="Output sequence length")
    parser.add_argument("--requests", type=int, default=200, help="Number of requests")
    parser.add_argument("--concurrency", type=int, default=20, help="Concurrency level")
    parser.add_argument(
        "--prefix-ratios",
        type=float,
        nargs="+",
        default=[0.1, 0.3, 0.5, 0.7, 0.9],
        help="List of prefix ratios to test",
    )

    args = parser.parse_args()
182
    resolve_tokenizer(args)
Yan Ru Pei's avatar
Yan Ru Pei committed
183
184
185
186
187
188

    # Create output directory
    os.makedirs(args.output_dir, exist_ok=True)

    # Store results
    prefix_ratios = []
189
190
191
192
193
194
    ttft_p25_values = []
    ttft_p50_values = []
    ttft_p75_values = []
    itl_p25_values = []
    itl_p50_values = []
    itl_p75_values = []
Yan Ru Pei's avatar
Yan Ru Pei committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210

    current_seed = args.seed

    # Run benchmarks for each prefix ratio
    for prefix_ratio in args.prefix_ratios:
        result = run_benchmark(
            args.model,
            args.tokenizer,
            prefix_ratio,
            args.isl,
            args.osl,
            args.requests,
            args.concurrency,
            current_seed,
            args.num_prefix_prompts,
            args.output_dir,
211
            args.url,
212
            args.use_expected_osl,
Yan Ru Pei's avatar
Yan Ru Pei committed
213
214
215
        )

        if result is not None:
216
217
            ttft = result["time_to_first_token"]
            itl = result["inter_token_latency"]
Yan Ru Pei's avatar
Yan Ru Pei committed
218
219

            prefix_ratios.append(prefix_ratio)
220
221
222
223
224
225
            ttft_p25_values.append(ttft["p25"])
            ttft_p50_values.append(ttft["p50"])
            ttft_p75_values.append(ttft["p75"])
            itl_p25_values.append(itl["p25"])
            itl_p50_values.append(itl["p50"])
            itl_p75_values.append(itl["p75"])
Yan Ru Pei's avatar
Yan Ru Pei committed
226
227

            logger.info(
228
229
                f"Prefix ratio {prefix_ratio}: TTFT p50={ttft['p50']:.2f}ms (p25={ttft['p25']:.2f}, p75={ttft['p75']:.2f}), "
                f"ITL p50={itl['p50']:.2f}ms (p25={itl['p25']:.2f}, p75={itl['p75']:.2f})"
Yan Ru Pei's avatar
Yan Ru Pei committed
230
231
232
233
234
            )

        current_seed += 1

    # Create plots
235
    if prefix_ratios and ttft_p50_values and itl_p50_values:
Yan Ru Pei's avatar
Yan Ru Pei committed
236
237
        plt.figure(figsize=(12, 5))

238
        # Plot TTFT vs Prefix Ratio with shaded p25-p75 region
Yan Ru Pei's avatar
Yan Ru Pei committed
239
        plt.subplot(1, 2, 1)
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
        plt.fill_between(
            prefix_ratios,
            ttft_p25_values,
            ttft_p75_values,
            alpha=0.3,
            color="blue",
            label="p25-p75",
        )
        plt.plot(
            prefix_ratios,
            ttft_p50_values,
            "bo-",
            linewidth=2,
            markersize=8,
            label="p50",
        )
Yan Ru Pei's avatar
Yan Ru Pei committed
256
257
258
259
        plt.xlabel("Prefix Ratio")
        plt.ylabel("Time to First Token (ms)")
        plt.title("TTFT vs Prefix Ratio")
        plt.grid(True, alpha=0.3)
260
261
        plt.legend()
        for i, (pr, p50) in enumerate(zip(prefix_ratios, ttft_p50_values)):
Yan Ru Pei's avatar
Yan Ru Pei committed
262
            plt.annotate(
263
264
                f"{p50:.1f}ms",
                (pr, p50),
Yan Ru Pei's avatar
Yan Ru Pei committed
265
266
267
268
269
                textcoords="offset points",
                xytext=(0, 10),
                ha="center",
            )

270
        # Plot ITL vs Prefix Ratio with shaded p25-p75 region
Yan Ru Pei's avatar
Yan Ru Pei committed
271
        plt.subplot(1, 2, 2)
272
273
274
275
276
277
278
279
280
281
282
        plt.fill_between(
            prefix_ratios,
            itl_p25_values,
            itl_p75_values,
            alpha=0.3,
            color="red",
            label="p25-p75",
        )
        plt.plot(
            prefix_ratios, itl_p50_values, "ro-", linewidth=2, markersize=8, label="p50"
        )
Yan Ru Pei's avatar
Yan Ru Pei committed
283
        plt.xlabel("Prefix Ratio")
284
285
        plt.ylabel("Inter-Token Latency (ms)")
        plt.title("ITL vs Prefix Ratio")
Yan Ru Pei's avatar
Yan Ru Pei committed
286
        plt.grid(True, alpha=0.3)
287
288
        plt.legend()
        for i, (pr, p50) in enumerate(zip(prefix_ratios, itl_p50_values)):
Yan Ru Pei's avatar
Yan Ru Pei committed
289
            plt.annotate(
290
291
                f"{p50:.1f}ms",
                (pr, p50),
Yan Ru Pei's avatar
Yan Ru Pei committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
                textcoords="offset points",
                xytext=(0, 10),
                ha="center",
            )

        plt.tight_layout()

        # Save plot
        plot_path = f"{args.output_dir}/prefix_ratio_performance.png"
        plt.savefig(plot_path, dpi=300, bbox_inches="tight")
        logger.info(f"Performance plot saved to {plot_path}")

        # Save results to JSON
        results_data = {
            "prefix_ratios": prefix_ratios,
307
308
309
310
311
312
            "ttft_p25_values": ttft_p25_values,
            "ttft_p50_values": ttft_p50_values,
            "ttft_p75_values": ttft_p75_values,
            "itl_p25_values": itl_p25_values,
            "itl_p50_values": itl_p50_values,
            "itl_p75_values": itl_p75_values,
Yan Ru Pei's avatar
Yan Ru Pei committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
            "config": {
                "model": args.model,
                "tokenizer": args.tokenizer,
                "isl": args.isl,
                "osl": args.osl,
                "requests": args.requests,
                "concurrency": args.concurrency,
                "initial_seed": args.seed,
            },
        }

        results_path = f"{args.output_dir}/results_summary.json"
        with open(results_path, "w") as f:
            json.dump(results_data, f, indent=2)
        logger.info(f"Results summary saved to {results_path}")

    else:
        logger.error("No successful benchmark results to plot")


if __name__ == "__main__":
    main()