forked from NVIDIA/TensorRT-LLM
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_e2e.py
More file actions
3511 lines (3146 loc) · 133 KB
/
test_e2e.py
File metadata and controls
3511 lines (3146 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
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
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright (c) 2022-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any, Optional, Tuple, Union
import pytest
import yaml
from defs.common import convert_weights
from defs.trt_test_alternative import (check_call, check_call_negative_test,
check_output)
from .common import (PluginOptions, convert_weights, get_mmlu_accuracy,
prune_checkpoint, quantize_data, refit_model,
venv_check_call)
from .conftest import (get_device_count, get_sm_version, llm_models_root,
skip_no_sm120, skip_nvlink_inactive, skip_post_blackwell,
skip_pre_ada, skip_pre_blackwell, skip_pre_hopper,
tests_path, unittest_path)
sys.path.append(os.path.join(str(tests_path()), '/../examples/apps'))
TEST_MEM_USAGE = os.environ.get('TEST_MEM_USAGE', True)
if TEST_MEM_USAGE:
os.environ['TLLM_LOG_LEVEL'] = 'INFO'
_MEM_FRACTION_50 = 0.5
_MEM_FRACTION_80 = 0.8
_MEM_FRACTION_95 = 0.95
def _get_mem_info_from_log(file, ranks_num):
import re
# Peak memory size, model memory size and extra memory size are printed
# only when TLLM_LOG_LEVEL=INFO
pattern = re.compile(r"\[MemUsageChange] Allocated ([\d]+\.[\d]+) GiB ")
fraction_pattern = re.compile(r"fraction is set ([\d]+\.[\d]+), ")
total_mem_pattern = re.compile(r"device total memory ([\d]+\.[\d]+) GiB")
peak_mem_pattern = re.compile(
r"Peak memory during memory usage profiling \(torch \+ non-torch\): ([\d]+\.[\d]+) GiB"
)
extra_mem_pattern = re.compile(
r"Memory used outside torch \(e\.g\., NCCL and CUDA graphs\) in memory usage profiling: ([\d]+\.[\d]+) GiB"
)
activation_pattern = re.compile(
r"Memory dynamically allocated during inference \(inside torch\) in memory usage profiling: ([\d]+\.[\d]+) GiB"
)
model_pattern = re.compile(
r"Memory used after loading model weights \(inside torch\) in memory usage profiling: ([\d]+\.[\d]+) GiB"
)
tmp_kv_patterm = re.compile(r"tmp kv_mem ([\d]+\.[\d]+) GiB")
start_time_mem_pattern = re.compile(
r"Memory used after loading model weights \(outside torch\) in memory usage profiling: ([\d]+\.[\d]+) GiB"
)
fraction = 0.90
kv_mem_size = []
total_memory = []
peak_memory = []
extra_memory = []
activation_memory = []
model_memory = []
tmp_kv = []
start_time_mem = []
file.seek(0)
lines = file.readlines()
for line in lines:
match = pattern.findall(line)
if len(match) > 0:
kv_mem_size.append(float(match[0]))
match = fraction_pattern.findall(line)
if len(match) > 0:
fraction = float(match[0])
match = total_mem_pattern.findall(line)
if len(match) > 0:
total_memory.append(float(match[0]))
match = peak_mem_pattern.findall(line)
if len(match) > 0:
peak_memory.append(float(match[0]))
match = extra_mem_pattern.findall(line)
if len(match) > 0:
extra_memory.append(float(match[0]))
match = activation_pattern.findall(line)
if len(match) > 0:
activation_memory.append(float(match[0]))
match = model_pattern.findall(line)
if len(match) > 0:
model_memory.append(float(match[0]))
match = tmp_kv_patterm.findall(line)
if len(match) > 0:
tmp_kv.append(float(match[0]))
match = start_time_mem_pattern.findall(line)
if len(match) > 0:
start_time_mem.append(float(match[0]))
assert len(
kv_mem_size) % 2 == 0, "no enough memory usage information in log"
kv_mem_size = kv_mem_size[len(kv_mem_size) // 2:]
return peak_memory, model_memory, sum(
kv_mem_size
) / ranks_num, extra_memory, fraction, total_memory, activation_memory, sum(
tmp_kv) / ranks_num, sum(start_time_mem) - ranks_num
def _get_kv_mem_size_candidate(total_Gib, used_Gib, fraction):
return (total_Gib - used_Gib) * fraction
def _check_mem_usage(file, mem_info, ranks_num=1):
if file is None or not TEST_MEM_USAGE:
return
delta = 0.3 # 0.3 GB as buffer
peak, model_size, kv_mem_size, extra, fraction, total_memory, activation_memory, tmp_kv, start_time_mem = _get_mem_info_from_log(
file, ranks_num)
peak = max(peak)
min_total = min(total_memory)
e_peak, e_model_size, e_kv_mem_size, e_extra = mem_info
import torch
_, total = torch.cuda.mem_get_info()
e_kv_mem_size = _get_kv_mem_size_candidate(min_total,
(e_peak + start_time_mem),
fraction)
print(
f"Expected memory usage: peak mem {e_peak + start_time_mem}, model mem {e_model_size}, kv mem {e_kv_mem_size:.2f}, extra {e_extra}, total {total / (1 << 30):.2f}"
)
print(
f"Running memory information: peak mem {peak}, model mem {model_size}, kv mem {kv_mem_size}, extra {extra}, total {min_total}, activation {activation_memory}, tmp_kv {tmp_kv}, fraction {fraction}, none-torch memory at starttime {start_time_mem}"
)
assert peak - tmp_kv <= e_peak + start_time_mem + delta, f"peak memory {peak} is larger than expected {e_peak}"
assert kv_mem_size >= e_kv_mem_size - delta, f"kv memory size {kv_mem_size} is smaller than expected {e_kv_mem_size}"
# assert model_size <= e_model_size + delta, f"model memory {model_size} is larger than expected {e_model_size}"
# assert max(extra) <= e_extra + delta, f"extra memory size {extra} is larger than expected {e_extra}"
def test_gpt3_175b_1layers_build_only(llm_root, llm_venv, engine_dir):
"Build GPT-3 175B: 96 layer w/ plugins"
example_root = os.path.join(llm_root, "examples", "models", "core", "gpt")
engine_dir = os.path.join(engine_dir, "gpt-175-96layers-build-only")
dtype = 'float16'
convert_cmd = [
f"{example_root}/../../../generate_checkpoint_config.py",
f"--output_path={engine_dir}/ckpt_config.json",
"--architecture=GPTForCausalLM", f"--dtype={dtype}",
"--num_hidden_layers=1", "--num_attention_heads=96",
"--hidden_size=12288", "--vocab_size=51200", "--tp_size=8"
]
venv_check_call(llm_venv, convert_cmd)
print("Building engines...")
build_cmd = [
"trtllm-build",
f"--model_config={engine_dir}/ckpt_config.json",
f"--output_dir={engine_dir}",
"--max_batch_size=256",
"--max_input_len=200",
"--max_seq_len=400",
"--max_beam_width=1",
f"--gpt_attention_plugin={dtype}",
]
check_call(" ".join(build_cmd), shell=True, env=llm_venv._new_env)
@pytest.mark.parametrize("additional_build_option", ["", "--multi_query_mode"],
ids=lambda x: x.strip("-"))
@pytest.mark.parametrize("use_py_session", [False, True],
ids=["use_cpp_session", "use_py_session"])
def test_gpt_fp32(llm_root, llm_venv, additional_build_option, use_py_session,
engine_dir):
example_root = os.path.join(llm_root, "examples", "models", "core", "gpt")
engine_dir = os.path.join(engine_dir, "gpt2")
dtype = 'float32'
convert_cmd = [
f"{example_root}/../../../generate_checkpoint_config.py",
f"--output_path={engine_dir}/ckpt_config.json",
"--architecture=GPTForCausalLM", f"--dtype={dtype}",
"--num_hidden_layers=2", "--num_attention_heads=16",
"--hidden_size=1024", "--vocab_size=51200"
]
if 'multi_query_mode' in additional_build_option:
convert_cmd.append("--num_key_value_heads=1")
venv_check_call(llm_venv, convert_cmd)
print("Building engines...")
build_cmd = [
"trtllm-build",
f"--model_config={engine_dir}/ckpt_config.json",
f"--output_dir={engine_dir}",
"--max_batch_size=256",
"--max_input_len=200",
"--max_seq_len=400",
"--max_beam_width=1",
f"--gpt_attention_plugin={dtype}",
]
check_call(" ".join(build_cmd), shell=True, env=llm_venv._new_env)
print("Running inference...")
run_cmd = [
f"{example_root}/../../../run.py", "--max_output_len=1",
f"--engine_dir={engine_dir}"
]
if use_py_session:
run_cmd.extend(["--use_py_session"])
venv_check_call(llm_venv, run_cmd)
@pytest.mark.parametrize("prune", [False, True], ids=["", "prune"])
@pytest.mark.parametrize(
"additional_build_option",
["", "remove_input_padding", "quantization int8_sq_per_tensor"],
ids=lambda x: x.replace(" ", "_"))
@pytest.mark.parametrize("use_py_session", [False, True],
ids=["use_cpp_session", "use_py_session"])
def test_llama_e2e(llama_example_root, llama_tokenizer_model_root, llm_venv,
cmodel_dir, engine_dir, additional_build_option,
use_py_session, prune):
model_name = 'llama-e2e'
model_dir = convert_weights(
llm_venv=llm_venv,
example_root=llama_example_root,
cmodel_dir=cmodel_dir,
model=model_name,
model_path=llama_tokenizer_model_root,
)
unpruned_model_dir = model_dir
if prune:
print("Pruning checkpoint...")
model_dir = prune_checkpoint(llm_venv, model_dir)
build_cmd = [
"trtllm-build", f"--checkpoint_dir={model_dir}",
f"--output_dir={engine_dir}", f"--max_beam_width=4",
f"--max_batch_size={1}", f"--max_input_len={1024}",
f"--gpt_attention_plugin=float16", f"--gemm_plugin=float16"
]
print("Build engines...")
if additional_build_option == "":
build_cmd += [f"--remove_input_padding=disable"]
elif additional_build_option == "remove_input_padding":
build_cmd += [f"--remove_input_padding=enable"]
else:
build_cmd += [f"--{additional_build_option}"]
if prune:
build_cmd.append("--strip_plan")
build_cmd.extend(PluginOptions("float16", None, "float16", None).to_args())
check_call(" ".join(build_cmd), shell=True, env=llm_venv._new_env)
if prune:
print("Refitting engine...")
engine_dir = refit_model(llm_venv, engine_dir, unpruned_model_dir)
print("Run inference...")
run_cmd = [
f"{llama_example_root}/../../../run.py",
"--max_output_len=1",
f"--tokenizer_dir={llama_tokenizer_model_root}",
"--log_level=verbose",
f"--engine_dir={engine_dir}",
]
if use_py_session:
run_cmd.extend(["--use_py_session"])
venv_check_call(llm_venv, run_cmd)
@pytest.mark.parametrize("prune", [False, True], ids=["", "prune"])
@pytest.mark.parametrize("enable_fp8", [False, True], ids=["", "enable_fp8"])
@pytest.mark.parametrize("additional_build_option",
["", "remove_input_padding"],
ids=lambda x: x)
@pytest.mark.parametrize("use_py_session", [False, True],
ids=["use_cpp_session", "use_py_session"])
def test_mistral_e2e(llama_example_root, llama_tokenizer_model_root, llm_venv,
cmodel_dir, engine_dir, enable_fp8,
additional_build_option, use_py_session, prune):
model_name = 'mistral-e2e'
if enable_fp8:
model_dir = quantize_data(llm_venv=llm_venv,
example_root=llama_example_root,
model_dir=llama_tokenizer_model_root,
dtype='float16',
qformat='fp8',
quantize_dir=cmodel_dir,
kv_cache_dtype='fp8',
calib_size=32)
else:
model_dir = convert_weights(llm_venv=llm_venv,
example_root=llama_example_root,
cmodel_dir=cmodel_dir,
model=model_name,
model_path=llama_tokenizer_model_root,
enable_fp8=enable_fp8)
unpruned_model_dir = model_dir
if prune:
print("Pruning checkpoint...")
model_dir = prune_checkpoint(llm_venv, model_dir)
build_cmd = [
"trtllm-build",
f"--checkpoint_dir={model_dir}",
f"--output_dir={engine_dir}",
f"--max_batch_size=1",
f"--max_input_len=1024",
f"--max_num_tokens=1024",
f"--max_beam_width=4",
f"--gemm_plugin=float16",
]
print("Build engines...")
if additional_build_option == "":
if not enable_fp8:
build_cmd += [f"--remove_input_padding=disable"]
elif additional_build_option == "remove_input_padding":
build_cmd += [f"--remove_input_padding=enable"]
else:
build_cmd += [f"--{additional_build_option}"]
if enable_fp8:
build_cmd.append("--use_fp8_context_fmha=enable")
else:
build_cmd.append("--context_fmha=disable")
build_cmd.append("--gpt_attention_plugin=float16")
build_cmd.extend(
PluginOptions("float16", None, "float16", None).to_args())
if prune:
build_cmd.append("--strip_plan")
os.path.join(cmodel_dir, ".internal_trt.cfg")
check_call(" ".join(build_cmd), shell=True, env=llm_venv._new_env)
if prune:
print("Refitting engine...")
engine_dir = refit_model(llm_venv, engine_dir, unpruned_model_dir)
print("Run inference...")
run_cmd = [
f"{llama_example_root}/../../../run.py",
"--max_output_len=1",
f"--tokenizer_dir={llama_tokenizer_model_root}",
"--log_level=verbose",
"--max_attention_window_size=5",
f"--engine_dir={engine_dir}",
]
if use_py_session:
run_cmd.extend(["--use_py_session"])
venv_check_call(llm_venv, run_cmd)
@pytest.mark.parametrize("model_name,model_path", [
("DeepSeek-R1-Distill-Qwen-1.5B", "DeepSeek-R1-Distill-Qwen-1.5B"),
])
def test_qwen_e2e_cpprunner_large_new_tokens(model_name, model_path, llm_venv,
qwen_example_root, cmodel_dir,
engine_dir):
"RCCA: https://nvbugs/5238105"
model_dir = convert_weights(
llm_venv=llm_venv,
example_root=qwen_example_root,
cmodel_dir=cmodel_dir,
model=model_name,
model_path=f"{llm_models_root()}/{model_path}",
)
build_cmd = [
"trtllm-build", f"--checkpoint_dir={model_dir}",
f"--output_dir={engine_dir}", f"--gemm_plugin=float16",
"--max_num_tokens=32768"
]
check_call(" ".join(build_cmd), shell=True, env=llm_venv._new_env)
from transformers import AutoTokenizer
from tensorrt_llm.runtime import PYTHON_BINDINGS
if PYTHON_BINDINGS:
from tensorrt_llm.runtime import ModelRunnerCpp
tokenizer = AutoTokenizer.from_pretrained(
f"{llm_models_root()}/{model_path}",
trust_remote_code=True,
use_fast=False)
message = r"<|begin▁of▁sentence|><|User|>The operation $\otimes$ is defined for all nonzero numbers by $a \otimes b = \frac{a^{2}}{b}$. Determine $[(1 \otimes 2) \otimes 3] - [1 \otimes (2 \otimes 3)]$. Let's think step by step and output the final answer within \boxed{}.<|Assistant|>"
inputs = tokenizer(message, return_tensors='pt',
add_special_tokens=False)['input_ids']
runner = ModelRunnerCpp.from_dir(engine_dir=f"{engine_dir}",
max_input_len=128,
max_output_len=4096,
max_batch_size=8)
outputs = runner.generate(inputs,
end_id=tokenizer.eos_token_id,
pad_id=tokenizer.pad_token_id,
temperature=0.6,
top_p=1.0,
top_k=1024,
max_new_tokens=1024,
return_dict=True,
min_length=1,
num_return_sequences=4,
output_sequence_lengths=True)
seq_lengths = outputs['sequence_lengths']
assert not (seq_lengths == 0).any(
), f"Found zero length in sequence_lengths tensor: {seq_lengths}"
# TODO replace the trtllm_bench_prolog
class BenchRunner:
def __init__(self,
llm_root: str,
llm_venv: Any,
model_subdir: str,
model_name: str,
streaming: bool,
tp_size: int,
use_pytorch_backend: bool = False,
skip_engine_build: bool = False,
quant: Optional[str] = None,
extra_llm_api_options: Optional[str] = None,
use_mpirun: bool = False,
concurrency: Optional[int] = None,
num_requests: int = 10):
llm_models = llm_models_root()
assert llm_models is not None
self.llm_root = llm_root
self.llm_venv = llm_venv
self.model_path = Path(llm_models, model_subdir).absolute()
self.model_name = model_name
self.quant = quant
self.streaming = streaming
self.skip_engine_build = skip_engine_build
self.use_pytorch_backend = use_pytorch_backend
self.use_mpirun = use_mpirun
self.tp_size = tp_size
self.quant_name = self.quant if self.quant is not None else "FP16"
self.extra_llm_api_options = extra_llm_api_options
self.work_dir = Path(tempfile.TemporaryDirectory().name)
self.dataset_path = os.path.join(self.work_dir, f"data.txt")
if self.use_mpirun:
self.mpirun_cmd = f"mpirun --allow-run-as-root -n {self.tp_size} trtllm-llmapi-launch"
else:
self.mpirun_cmd = ""
self.engine_path = None
self.concurrency = concurrency
self.num_requests = num_requests
def __call__(self):
self.prepare_dataset()
if not (self.skip_engine_build or self.use_pytorch_backend):
self.build_engine()
return self.run_bench()
def prepare_dataset(self):
dataset_tool = Path(self.llm_root, "benchmarks", "cpp",
"prepare_dataset.py")
# Generate a small dataset to run a test.
self.work_dir.mkdir(parents=True)
command = [
f"{dataset_tool.resolve()}",
"--stdout",
"--tokenizer",
f"{self.model_path}",
"token-norm-dist",
"--input-mean",
"128",
"--output-mean",
"128",
"--input-stdev",
"0",
"--output-stdev",
"0",
"--num-requests",
str(self.num_requests),
]
print(f"Running command: {' '.join(command)}")
dataset_output = self.llm_venv.run_cmd(
command,
caller=check_output,
)
# Grab the stdout and write it to a dataset file for passing to suite.
with open(self.dataset_path, "w") as dataset:
dataset.write(dataset_output)
def build_engine(self):
if self.skip_engine_build:
return
build_cmd = \
f"{self.mpirun_cmd} " \
f"trtllm-bench " \
f"--model {self.model_name} " \
f"--model_path {self.model_path} " \
f"--workspace {self.work_dir} " \
f"build --tp_size {self.tp_size}"
if self.quant is not None:
build_cmd = f"{build_cmd} --quantization {self.quant}"
build_cmd = f"{build_cmd} --dataset {self.dataset_path}"
build_output = check_output(build_cmd,
shell=True,
env=self.llm_venv._new_env)
for line in build_output.split("\n")[::-1]:
if line.startswith("ENGINE SAVED:"):
self.engine_path = Path(line.split(":")[1])
break
def run_bench(self):
streaming = "--streaming" if self.streaming else ""
benchmark_cmd = \
f"{self.mpirun_cmd} " \
f"trtllm-bench --model {self.model_name} --model_path {self.model_path} " \
f"throughput " \
f"--tp {self.tp_size} "
if self.engine_path:
benchmark_cmd += f"--engine_dir {self.engine_path} "
benchmark_cmd += f" --dataset {self.dataset_path} {streaming}"
if self.use_pytorch_backend:
benchmark_cmd += " --backend pytorch"
else:
benchmark_cmd += " --backend tensorrt"
if self.extra_llm_api_options:
benchmark_cmd += f" --extra_llm_api_options {self.extra_llm_api_options}"
if self.concurrency:
benchmark_cmd += f" --concurrency {self.concurrency}"
if self.num_requests:
benchmark_cmd += f" --num_requests {self.num_requests}"
benchmark_output = check_output(benchmark_cmd,
shell=True,
env=self.llm_venv._new_env)
return self.parse_benchmark_output(benchmark_output)
def parse_benchmark_output(self, output):
"""Parse the benchmark output to extract key metrics."""
result = {
'concurrency': self.concurrency,
'num_requests': self.num_requests,
'throughput': 0,
'latency': 0
}
lines = output.split('\n')
for line in lines:
line = line.strip()
if 'total token throughput' in line.lower(
) and 'tokens/sec' in line.lower():
try:
throughput = line.split(":")[1].strip()
result['throughput'] = throughput
except (IndexError, ValueError) as e:
print(
f"Failed to parse throughput from line: {line}. Error: {e}"
)
elif 'total latency' in line.lower() and 'ms' in line.lower():
try:
latency = line.split(":")[1].strip()
result['latency'] = latency
except (IndexError, ValueError) as e:
print(
f"Failed to parse latency from line: {line}. Error: {e}"
)
return result
@pytest.mark.parametrize("model_name", ["meta-llama/Meta-Llama-3-8B-Instruct"],
ids=["llama3-8b"])
@pytest.mark.parametrize("model_subdir",
["llama-models-v3/llama-v3-8b-instruct-hf"],
ids=["llama-v3"])
@pytest.mark.parametrize("use_pytorch_backend", [True, False],
ids=["pytorch_backend", "trt_backend"])
def test_trtllm_bench_llmapi_launch(llm_root, llm_venv, model_name,
model_subdir, use_pytorch_backend):
runner = BenchRunner(llm_root=llm_root,
llm_venv=llm_venv,
model_name=model_name,
model_subdir=model_subdir,
streaming=False,
use_pytorch_backend=use_pytorch_backend,
use_mpirun=True,
tp_size=2)
runner()
@skip_pre_hopper
@pytest.mark.skip_less_device_memory(80000)
@pytest.mark.parametrize("model_name", ["meta/Meta-Llama-3.1-8B"],
ids=["llama3_1-8b"])
@pytest.mark.parametrize("model_subdir", ["llama-3.1-model/Meta-Llama-3.1-8B"],
ids=["llama_v3_1"])
@pytest.mark.parametrize("use_pytorch_backend", [False], ids=["trt_backend"])
def test_trtllm_bench_mig_launch(llm_root, llm_venv, model_name, model_subdir,
use_pytorch_backend):
"run bench mark in MIG mode, check if the throughput is increasing by concurrency"
skip_engine_build = False
results = {}
concurrency_list = [1, 32, 64, 128]
for concurrency in concurrency_list:
num_requests = concurrency * 10
runner = BenchRunner(llm_root=llm_root,
llm_venv=llm_venv,
model_name=model_name,
model_subdir=model_subdir,
streaming=False,
use_pytorch_backend=use_pytorch_backend,
use_mpirun=False,
tp_size=1,
concurrency=concurrency,
num_requests=num_requests,
skip_engine_build=skip_engine_build)
output = runner()
results[concurrency] = output
print(f"\n=== Benchmark Results Comparison ===")
print(f"Model: {model_name}")
print(f"Backend: {'PyTorch' if use_pytorch_backend else 'TensorRT'}")
print(
f"{'Concurrency':<15} {'Throughput':<15} {'Latency':<15} {'Num Requests':<15}"
)
print("-" * 60)
for idx, val in enumerate(concurrency_list):
metrics = results.get(val)
if not isinstance(metrics, dict):
pytest.fail(
f"Unexpected benchmark result type for concurrency {val}: {type(metrics)}"
)
try:
throughput = float(metrics.get('throughput', 0))
latency = float(metrics.get('latency', 0))
num_requests = int(metrics.get('num_requests', 0))
except (ValueError, TypeError) as e:
pytest.fail(
f"Failed to parse benchmark results for concurrency {val}: {e}")
assert throughput > 0, f"Throughput is 0 for concurrency {val}"
assert latency > 0, f"Latency is 0 for concurrency {val}"
print(f"{val:<15} {throughput:<15} {latency:<15} {num_requests:<15}")
if idx > 0:
prev_throughput = float(results[concurrency_list[idx - 1]].get(
'throughput', 0))
assert throughput > prev_throughput * 1.3, f"Throughput is not increasing for concurrency {concurrency_list[idx]}"
@pytest.mark.parametrize(
"model_name, llama_model_root",
[pytest.param("TinyLlama-1.1B-Chat-v1.0", "TinyLlama-1.1B-Chat-v1.0")],
indirect=["llama_model_root"])
def test_trtllm_bench_invalid_token_pytorch(llm_root, llm_venv, model_name,
llama_model_root):
# Prepare dataset with invalid tokens
_, _, dataset_path = trtllm_bench_prolog(llm_root,
llm_venv,
engine_dir=None,
model_subdir=llama_model_root,
model_name=model_name,
quant=None,
streaming=False,
skip_engine_build=True)
with open(dataset_path) as f:
dataset = [json.loads(line) for line in f.readlines()]
dataset[0]["input_ids"][-1] = -1
with open(dataset_path, "w") as f:
f.writelines(f"{json.dumps(data)}\n" for data in dataset)
# Run benchmark
extra_options = {
"cuda_graph_config": {
"enable_padding": True,
"batch_sizes": [1, 2, 4, 8, 16, 32, 64, 128, 256, 384],
},
}
with tempfile.TemporaryDirectory() as tmpdir:
extra_options_path = Path(tmpdir) / "extra-llm-api-options.yml"
with open(extra_options_path, "w") as f:
yaml.dump(extra_options, f)
output_path = Path(tmpdir) / "stdout.log"
benchmark_cmd = \
f"trtllm-bench --model {model_name} " \
f"--model_path {llama_model_root} " \
f"throughput " \
f"--dataset {str(dataset_path)} --backend pytorch " \
f"--extra_llm_api_options {extra_options_path} " \
f"> {output_path} 2>&1"
# Check clean shutdown (no hang)
with pytest.raises(subprocess.CalledProcessError) as exc_info:
check_call(benchmark_cmd, shell=True, env=llm_venv._new_env)
# Check non-zero exit code
assert exc_info.value.returncode != 0
with open(output_path) as f:
stdout = f.read()
# Check that error is reported correctly
assert "Requests failed: Token ID out of range (1 requests)" in stdout
def trtllm_bench_prolog(
llm_root,
llm_venv,
engine_dir: Optional[str],
model_subdir,
model_name: str,
quant: str,
streaming: bool,
skip_engine_build: bool = False
) -> Union[Tuple[Path, Path, Path], Path]:
''' Optionally build engine and generate dataset for benchmark.
Returns:
Union[Tuple[Path, Path, Path], Path]:
- Tuple containing model_path, engine_path, and dataset_path.
- A single dataset_path object if skip_engine_build is True.
'''
llm_models = llm_models_root()
# skip when llm_models_root is None
if llm_models is None:
return
model_path = Path(llm_models, model_subdir).absolute()
engine_path = None
quant_name = quant if quant is not None else "FP16"
stream_mode = "streaming" if streaming else "non-streaming"
benchmark_name = f"trtllm-bench-sanity-{quant_name}-{stream_mode}"
benchmark_name += "-pytorch-backend" if skip_engine_build else benchmark_name
dataset_tool = Path(llm_root, "benchmarks", "cpp", "prepare_dataset.py")
work_dir = Path(tempfile.TemporaryDirectory().name
) if skip_engine_build else Path(engine_dir)
dataset_path = Path(work_dir, f"{benchmark_name}.txt")
# Clean up an existing directory if it exists
shutil.rmtree(work_dir, ignore_errors=True)
# Generate a small dataset to run a test.
work_dir.mkdir(parents=True)
dataset_output = llm_venv.run_cmd(
[
f"{dataset_tool.resolve()}",
"--stdout",
"--tokenizer",
f"{model_path}",
"token-norm-dist",
"--input-mean",
"128",
"--output-mean",
"128",
"--input-stdev",
"0",
"--output-stdev",
"0",
"--num-requests",
"10",
],
caller=check_output,
)
# Grab the stdout and write it to a dataset file for passing to suite.
with open(dataset_path, "w") as dataset:
dataset.write(dataset_output)
if not skip_engine_build:
build_cmd = \
f"trtllm-bench " \
f"--model {model_name} " \
f"--model_path {model_path} " \
f"--workspace {work_dir} " \
f"build --tp_size 1"
if quant is not None:
build_cmd = f"{build_cmd} --quantization {quant}"
build_cmd = f"{build_cmd} --dataset {dataset_path}"
build_output = check_output(build_cmd, shell=True)
for line in build_output.split("\n")[::-1]:
if line.startswith("ENGINE SAVED:"):
engine_path = Path(line.split(":")[1])
break
return model_path, engine_path, dataset_path
@pytest.fixture
def get_tmp_file():
return tempfile.mkstemp()
@pytest.fixture
def temp_extra_llm_api_options_file(request):
if request.node.callspec.params['use_extra_config']:
temp_dir = tempfile.gettempdir()
temp_file_path = os.path.join(temp_dir, "extra_llm_api_options.yaml")
try:
extra_llm_api_options_dict = {
"enable_chunked_prefill": False,
"kv_cache_config": {
"enable_block_reuse": False,
"max_tokens": 40000
},
"num_postprocess_workers": 2,
}
pytorch_backend_config = {}
if request.node.callspec.params['pytorch_backend_config']:
pytorch_backend_config = {
"cuda_graph_config": {},
# trtllm-bench will set cuda_max_batch_size to
# max_batch_size, so the cuda_graph_batch_sizes is not
# needed.
# "cuda_graph_batch_sizes": [1, 2, 3],
}
# Flatten the pytorch_backend_config
extra_llm_api_options_dict.update(pytorch_backend_config)
with open(temp_file_path, 'w') as f:
yaml.dump(extra_llm_api_options_dict, f)
yield temp_file_path
finally:
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
else:
assert not request.node.callspec.params['pytorch_backend_config']
yield None
@pytest.mark.parametrize("model_subdir", [
"llama-3.1-model/Meta-Llama-3.1-8B",
],
ids=lambda x: x.strip("-"))
@pytest.mark.parametrize(
"model_name",
[
"meta-llama/Llama-3.1-8B",
],
)
@pytest.mark.parametrize("quant", [None, "FP8"], ids=["FP16", "FP8"])
@pytest.mark.parametrize("streaming", ["", "--streaming"],
ids=["non-streaming", "streaming"])
@pytest.mark.parametrize("use_extra_config", [True, False],
ids=["extra_config", ""])
@pytest.mark.parametrize("pytorch_backend_config", [False], ids=[""])
def test_trtllm_bench_sanity(llm_root, llm_venv, engine_dir, model_subdir,
model_name, quant, streaming, use_extra_config,
pytorch_backend_config,
temp_extra_llm_api_options_file):
'''
sanity check on the new benchmark script to make sure it works
- meta-llama/Llama-3.1-8B for baseline
- fp16 and fp8 to test quantization
'''
model_path, engine_path, dataset_path = trtllm_bench_prolog(
llm_root, llm_venv, engine_dir, model_subdir, model_name, quant,
"streaming" in streaming)
benchmark_cmd = \
f"trtllm-bench --model {model_name} --model_path {model_path} " \
f"throughput --engine_dir {engine_path} " \
f"--backend tensorrt " \
f"--dataset {dataset_path} {streaming}"
assert not pytorch_backend_config
if use_extra_config:
benchmark_cmd += f" --extra_llm_api_options {temp_extra_llm_api_options_file}"
check_call(benchmark_cmd, shell=True)
@pytest.mark.parametrize(
"model_name, llama_model_root, use_extra_config, pytorch_backend_config",
[('meta-llama/Llama-3.1-8B', 'llama-3.1-8b', False, False),
pytest.param('meta-llama/Llama-3.1-8B',
'llama-3.1-8b-instruct-hf-fp8',
True,
False,
marks=skip_pre_hopper),
pytest.param('meta-llama/Llama-3.1-8B',
'llama-3.1-8b-instruct-hf-fp8',
True,
True,
marks=skip_pre_hopper),
pytest.param('meta-llama/Llama-3.1-8B',
'llama-3.1-8b-hf-nvfp4',
False,
False,
marks=skip_pre_blackwell)],
indirect=['llama_model_root'])
def test_trtllm_bench_pytorch_backend_sanity(llm_root, llm_venv,
llama_model_root, model_name,
use_extra_config,
pytorch_backend_config,
temp_extra_llm_api_options_file):
'''
sanity check on latency benchmark for LLM API with PyTorch backend
'''
model_path, _, dataset_path = trtllm_bench_prolog(llm_root,
llm_venv,
None,
llama_model_root,
model_name,
False,
False,
skip_engine_build=True)
benchmark_cmd = \
f"trtllm-bench --model {model_name} --model_path {model_path} " \
f"throughput " \
f"--dataset {dataset_path} --backend pytorch"
mapping = {
"Meta-Llama-3.1-8B": 19.4,
"Llama-3.1-8B-Instruct-FP8": 12.0,
"Meta-Llama-3.1-8B-NVFP4": 10.2
}
if use_extra_config:
benchmark_cmd += f" --extra_llm_api_options {temp_extra_llm_api_options_file}"
model_id = llama_model_root.split(r"/")[-1]
if "nvfp4-quantized" in llama_model_root:
model_id += "-NVFP4"
with tempfile.NamedTemporaryFile(mode='w+t',
suffix=f".{model_id}.log",
dir="./",
delete=True,
delete_on_close=True) as running_log:
check_call(benchmark_cmd, shell=True, stdout=running_log)
if model_id in mapping and not use_extra_config:
# extra config defines max kv cache tokens number to be 40000 which makes the checking
# the checking process not unified.
_check_mem_usage(running_log, [mapping[model_id], 0, 0, 0])
def test_trtllm_bench_mgmn(llm_root, llm_venv):
model_name = "meta-llama/Llama-3.1-8B"
llama_model_dir = Path(
llm_models_root()) / "llama-3.1-model/Llama-3.1-8B-Instruct"
_, _, dataset_path = trtllm_bench_prolog(llm_root,
llm_venv,
engine_dir=None,
model_subdir=llama_model_dir,
model_name=model_name,
quant=None,
streaming=False,
skip_engine_build=True)
benchmark_cmd = \
f"mpirun --allow-run-as-root -n 2 trtllm-llmapi-launch trtllm-bench --model {model_name} " \
f"--model_path {llama_model_dir} " \
f"throughput " \
f"--dataset {str(dataset_path)} --backend pytorch --tp 2"
model_name = model_name.split(r"/")[-1]
with tempfile.NamedTemporaryFile(mode='w+t',
suffix=f".{model_name}.log",
dir="./",
delete=True,