benchmark_e2e.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License. See License.txt in the project root for
  4. # license information.
  5. # --------------------------------------------------------------------------
  6. # This is an end-to-end benchmarking script for the Hugging Face LLaMA-2 model.
  7. #
  8. # Prerequisites:
  9. # 1) Install `huggingface-cli`:
  10. #
  11. # $ pip install huggingface_hub
  12. #
  13. # 2) Authenticate with Hugging Face's CLI:
  14. #
  15. # $ huggingface-cli login
  16. #
  17. # 3) Accept Meta's license in Hugging Face to access the models at https://huggingface.co/meta-llama/
  18. #
  19. # 4) Install the latest ONNX Runtime version
  20. #
  21. # $ pip install onnxruntime-gpu
  22. #
  23. # 5) Install flash attention v2
  24. #
  25. # $ pip install flash-attn --no-build-isolation
  26. #
  27. # 6) Install bitsandbytes
  28. #
  29. # $ pip install bitsandbytes
  30. from __future__ import annotations
  31. import argparse
  32. import datetime
  33. import gc
  34. import itertools
  35. import json
  36. import logging
  37. import os
  38. import textwrap
  39. import time
  40. import numpy as np
  41. import pandas as pd
  42. import torch
  43. from benchmark_helper import setup_logger
  44. from llama_inputs import add_io_bindings_as_tensors, get_initial_inputs_and_outputs
  45. from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
  46. import onnxruntime as ort
  47. logger = logging.getLogger(__name__)
  48. def get_model(args: argparse.Namespace):
  49. if args.benchmark_type in {"pt-eager", "pt-compile"}:
  50. model = None
  51. if args.onnx_precision == "int4" and args.device == "cuda":
  52. bnb_config = BitsAndBytesConfig(
  53. load_in_4bit=True,
  54. bnb_4bit_use_double_quant=True,
  55. bnb_4bit_quant_type="nf4",
  56. bnb_4bit_compute_dtype=torch.float16,
  57. )
  58. model = AutoModelForCausalLM.from_pretrained(
  59. args.hf_dir_path if args.hf_dir_path != "" else args.model_name,
  60. cache_dir=args.cache_dir,
  61. torch_dtype=args.torch_dtype,
  62. use_auth_token=args.auth,
  63. trust_remote_code=args.trust,
  64. use_cache=True,
  65. attn_implementation="flash_attention_2",
  66. quantization_config=bnb_config,
  67. max_memory={args.device_id: "80GB"},
  68. )
  69. else:
  70. try:
  71. model = AutoModelForCausalLM.from_pretrained(
  72. args.hf_dir_path if args.hf_dir_path != "" else args.model_name,
  73. cache_dir=args.cache_dir,
  74. torch_dtype=args.torch_dtype,
  75. use_auth_token=args.auth,
  76. trust_remote_code=args.trust,
  77. use_cache=True,
  78. attn_implementation=("flash_attention_2" if args.device == "cuda" else "sdpa"),
  79. ).to(args.target_device)
  80. except Exception as e:
  81. # When flash_attention or sdpa doesn't support a model, it throws an exception.
  82. # Rather than stopping a process, run as eager mode.
  83. print("Try to load a model using eager mode: ", e)
  84. model = AutoModelForCausalLM.from_pretrained(
  85. args.hf_dir_path if args.hf_dir_path != "" else args.model_name,
  86. cache_dir=args.cache_dir,
  87. torch_dtype=args.torch_dtype,
  88. use_auth_token=args.auth,
  89. trust_remote_code=args.trust,
  90. use_cache=True,
  91. attn_implementation="eager",
  92. ).to(args.target_device)
  93. model.eval()
  94. if args.benchmark_type == "pt-compile":
  95. model = torch.compile(model)
  96. else:
  97. sess_options = ort.SessionOptions()
  98. ep = (
  99. ("CUDAExecutionProvider", {"device_id": args.device_id})
  100. if args.device == "cuda"
  101. else "CPUExecutionProvider"
  102. )
  103. model = ort.InferenceSession(args.onnx_model_path, sess_options=sess_options, providers=[ep])
  104. return model
  105. def run_inference(args, model, runs, inputs, outputs):
  106. if args.benchmark_type == "pt-compile":
  107. with torch.no_grad():
  108. outputs = model(**inputs)
  109. # Synchronize inputs
  110. io_binding = None
  111. if args.benchmark_type in {"pt-eager", "pt-compile"}:
  112. if args.device != "cpu":
  113. torch.cuda.synchronize(args.target_device)
  114. else:
  115. io_binding = add_io_bindings_as_tensors(model, inputs, outputs, args.use_fp16, args.use_buffer_share)
  116. io_binding.synchronize_inputs()
  117. # Run inference
  118. start = time.perf_counter()
  119. for _ in range(runs):
  120. if args.benchmark_type in {"pt-eager", "pt-compile"}:
  121. with torch.no_grad():
  122. outputs = model(**inputs)
  123. if args.device != "cpu":
  124. torch.cuda.synchronize(args.target_device)
  125. else:
  126. model.run_with_iobinding(io_binding)
  127. io_binding.synchronize_outputs()
  128. end = time.perf_counter()
  129. avg = (end - start) / runs
  130. return avg, outputs
  131. def prepare_model_for_inference(args, model, config, tokenizer, prompt_length, prompt):
  132. clear_cache()
  133. inputs, outputs = get_initial_inputs_and_outputs(
  134. config, tokenizer, prompt_length, prompt, args.target_device, args.use_fp16, args.use_buffer_share, args.engine
  135. )
  136. _, outputs = run_inference(args, model, args.warmup_runs, inputs, outputs)
  137. return inputs, outputs
  138. def clear_cache():
  139. gc.collect()
  140. torch.cuda.empty_cache()
  141. def save_results(results, filename, gen_length):
  142. df = pd.DataFrame(
  143. results,
  144. columns=[
  145. "Batch Size",
  146. "Prompt Length",
  147. "Prompt Processing Latency (ms)",
  148. "Prompt Processing Throughput (tps)",
  149. "Sampling Latency (ms)",
  150. "Sampling Throughput (tps)",
  151. "First Token Generated Latency (ms)",
  152. "First Token Generated Throughput (tps)",
  153. f"Average Latency of First {gen_length // 2} Tokens Generated (ms)",
  154. f"Average Throughput of First {gen_length // 2} Tokens Generated (tps)",
  155. f"Average Latency of First {gen_length} Tokens Generated (ms)",
  156. f"Average Throughput of First {gen_length} Tokens Generated (tps)",
  157. "Wall-Clock Latency (s)",
  158. "Wall-Clock Throughput (tps)",
  159. ],
  160. )
  161. df.to_csv(filename, index=False)
  162. logger.info(f"Results saved in {filename}!")
  163. def get_args():
  164. parser = argparse.ArgumentParser()
  165. parser.add_argument(
  166. "-bt",
  167. "--benchmark-type",
  168. type=str,
  169. required=True,
  170. choices=["pt-eager", "pt-compile", "ort"],
  171. )
  172. parser.add_argument(
  173. "-m",
  174. "--model-name",
  175. type=str,
  176. required=False,
  177. help="Hugging Face name of model (e.g. 'meta-llama/Llama-2-7b-hf')",
  178. )
  179. parser.add_argument(
  180. "-a",
  181. "--auth",
  182. default=False,
  183. action="store_true",
  184. help="Use Hugging Face authentication token to access model",
  185. )
  186. parser.add_argument(
  187. "-t",
  188. "--trust",
  189. default=False,
  190. action="store_true",
  191. help="Whether or not to allow for custom models defined on the Hugging Face Hub in their own modeling files",
  192. )
  193. parser.add_argument(
  194. "-c",
  195. "--cache-dir",
  196. type=str,
  197. default=os.path.join(".", "model_cache"),
  198. help="Path to directory containing all Hugging Face files (e.g. config, tokenizer, PyTorch model). Use when loading model as `AutoModel.from_pretrained(model_name, cache_dir=cache_dir)`.",
  199. )
  200. parser.add_argument(
  201. "--hf-dir-path",
  202. type=str,
  203. default="",
  204. help="Path to directory containing all Hugging Face files (e.g. config, tokenizer, PyTorch model). Use when loading model as `AutoModel.from_pretrained(folder_path)`.",
  205. )
  206. parser.add_argument(
  207. "-o",
  208. "--onnx-model-path",
  209. required=False,
  210. help="Path to ONNX model",
  211. )
  212. parser.add_argument(
  213. "-f",
  214. "--prompts-file",
  215. required=True,
  216. default=os.path.join(".", "models", "llama", "prompts.json"),
  217. help="JSON file containing entries in the format 'prompt length: prompt' where prompt length = tokenized length of prompt",
  218. )
  219. parser.add_argument(
  220. "--use_buffer_share",
  221. default=False,
  222. action="store_true",
  223. help="Use when GroupQueryAttention (GQA) is in ONNX model",
  224. )
  225. (
  226. parser.add_argument(
  227. "--anomaly-filtering",
  228. default=False,
  229. action="store_true",
  230. help="Use this flag to filter anomaly accelerator times for tokens generated. \
  231. This may give more accurate latency and throughput metrics for tokens generated. \
  232. Wall-clock metrics are still reported with anomaly times though.",
  233. ),
  234. )
  235. parser.add_argument(
  236. "-b",
  237. "--batch-sizes",
  238. default="1 2",
  239. )
  240. parser.add_argument(
  241. "-s",
  242. "--prompt-lengths",
  243. default="16 64 256 1024",
  244. )
  245. parser.add_argument(
  246. "-p",
  247. "--precision",
  248. required=True,
  249. type=str,
  250. default="fp32",
  251. choices=["int4", "int8", "fp16", "fp32"],
  252. help="Precision for model. For ONNX models, the model's precision should be set before running this script.",
  253. )
  254. parser.add_argument(
  255. "-g",
  256. "--generation-length",
  257. type=int,
  258. default=256,
  259. help="Number of new tokens to generate",
  260. )
  261. parser.add_argument(
  262. "-d",
  263. "--device",
  264. type=str,
  265. default="cuda" if torch.cuda.is_available() else "cpu",
  266. choices=["cpu", "cuda"],
  267. )
  268. parser.add_argument("-id", "--device-id", type=int, default=0)
  269. parser.add_argument("-w", "--warmup-runs", type=int, default=5)
  270. parser.add_argument("-n", "--num-runs", type=int, default=100)
  271. parser.add_argument("--seed", type=int, default=2)
  272. args = parser.parse_args()
  273. # Set seed properties
  274. np.random.seed(args.seed)
  275. torch.manual_seed(args.seed)
  276. # Set runtime properties
  277. if "ort" in args.benchmark_type:
  278. setattr(args, "execution_provider", f"{args.device.upper()}ExecutionProvider") # noqa: B010
  279. if args.execution_provider == "CUDAExecutionProvider":
  280. args.execution_provider = (args.execution_provider, {"device_id": args.device_id})
  281. # Check that paths have been specified for any benchmarking with ORT
  282. if args.benchmark_type == "ort":
  283. assert args.onnx_model_path, "Please specify a path to `--onnx-model-path`"
  284. args.batch_sizes = args.batch_sizes.split(" ")
  285. args.prompt_lengths = args.prompt_lengths.split(" ")
  286. # Use FP32 precision for FP32, INT8, INT4 CPU models, use FP16 precision for FP16 and INT4 GPU models
  287. setattr(args, "onnx_precision", args.precision) # noqa: B010
  288. args.precision = (
  289. "fp32" if args.precision in {"int8", "fp32"} or (args.precision == "int4" and args.device == "cpu") else "fp16"
  290. )
  291. target_device = f"cuda:{args.device_id}" if args.device != "cpu" else args.device
  292. torch_dtype = torch.float16 if args.precision == "fp16" else torch.float32
  293. engine = "ort" if args.benchmark_type == "ort" else "pt"
  294. setattr(args, "target_device", target_device) # noqa: B010
  295. setattr(args, "torch_dtype", torch_dtype) # noqa: B010
  296. setattr(args, "engine", engine) # noqa: B010
  297. setattr(args, "use_fp16", args.precision == "fp16") # noqa: B010
  298. args.use_buffer_share = args.use_buffer_share and engine == "ort"
  299. return args
  300. def main():
  301. args = get_args()
  302. setup_logger(False)
  303. logger.info(args.__dict__)
  304. # Get prompts and prompt sizes
  305. size_to_prompt = None
  306. with open(args.prompts_file) as f:
  307. size_to_prompt = json.load(f, object_hook=lambda d: {int(k): v for k, v in d.items()})
  308. # Get config, tokenizer, and model
  309. config = AutoConfig.from_pretrained(
  310. args.hf_dir_path if args.hf_dir_path != "" else args.model_name,
  311. cache_dir=args.cache_dir,
  312. use_auth_token=args.auth,
  313. trust_remote_code=args.trust,
  314. )
  315. tokenizer = AutoTokenizer.from_pretrained(
  316. args.hf_dir_path if args.hf_dir_path != "" else args.model_name,
  317. cache_dir=args.cache_dir,
  318. use_auth_token=args.auth,
  319. trust_remote_code=args.trust,
  320. )
  321. model = get_model(args)
  322. all_csv_metrics = []
  323. for batch_size, prompt_length in itertools.product(args.batch_sizes, args.prompt_lengths):
  324. batch_size, prompt_length = int(batch_size), int(prompt_length) # noqa: PLW2901
  325. logger.info(f"Running batch size = {batch_size}, prompt length = {prompt_length}")
  326. clear_cache()
  327. max_length = prompt_length + args.generation_length
  328. if prompt_length not in size_to_prompt:
  329. raise NotImplementedError(
  330. textwrap.dedent(
  331. f"""
  332. A prompt of size {prompt_length} was not found in '{args.prompts_file}'. There are a couple of solutions to fix this.
  333. 1) You can change one of the keys in '{args.prompts_file}' to be {prompt_length}.
  334. If {prompt_length} < actual prompt's length, the benchmark E2E tool will repeat the first word in the prompt until {prompt_length} = actual prompt's length.
  335. If {prompt_length} > actual prompt's length, the benchmark E2E tool will automatically trim the actual prompt's length so that {prompt_length} = actual prompt's length.
  336. 2) You can add a new key-value entry in '{args.prompts_file}' of the form '{prompt_length}': 'your prompt goes here'.
  337. """
  338. )
  339. )
  340. prompt = [size_to_prompt[prompt_length]] * batch_size
  341. csv_metrics = [batch_size, prompt_length]
  342. try:
  343. # Measure prompt processing
  344. logger.info("Measuring prompt processing...")
  345. inputs, outputs = prepare_model_for_inference(args, model, config, tokenizer, prompt_length, prompt)
  346. accelerator_prompt_latency_s, outputs = run_inference(args, model, args.num_runs, inputs, outputs)
  347. # Calculate prompt metrics
  348. accelerator_prompt_latency_ms = accelerator_prompt_latency_s * 1000
  349. accelerator_prompt_thrpt = batch_size * (prompt_length / accelerator_prompt_latency_s)
  350. logger.info(f"Average Latency of Prompt Processing: {accelerator_prompt_latency_ms} ms")
  351. logger.info(
  352. f"Average Throughput of Prompt Processing: {batch_size * (prompt_length / accelerator_prompt_latency_s)} tps"
  353. )
  354. csv_metrics.extend([accelerator_prompt_latency_ms, accelerator_prompt_thrpt])
  355. # Measure token generation
  356. logger.info("Measuring token generation...")
  357. clear_cache()
  358. inputs, outputs = prepare_model_for_inference(args, model, config, tokenizer, prompt_length, prompt)
  359. all_token_ids = inputs["input_ids"].clone()
  360. current_length = all_token_ids.shape[-1]
  361. num_heads = config.num_key_value_heads
  362. head_size = (
  363. config.head_dim if hasattr(config, "head_dim") else config.hidden_size // config.num_attention_heads
  364. )
  365. has_eos = torch.zeros(batch_size, device=args.target_device, dtype=torch.bool)
  366. # 0th entry will have prompt accelerator time, 1st entry onwards will have token generation accelerator time
  367. accelerator_times = []
  368. sampling_times = [] # cost to sample after each model run
  369. wall_clock_start_time = time.perf_counter()
  370. while current_length <= max_length:
  371. # Run inference
  372. accelerator_time_latency_s, outputs = run_inference(args, model, 1, inputs, outputs)
  373. accelerator_times.append(accelerator_time_latency_s)
  374. # Sample with argmax (greedy search)
  375. sampling_start_time = time.perf_counter()
  376. if outputs["logits"].shape[1] > 1:
  377. prompt_end_indices = inputs["attention_mask"].sum(1) - 1
  378. idxs = (
  379. prompt_end_indices.unsqueeze(dim=1)
  380. .repeat(1, config.vocab_size)
  381. .view(batch_size, 1, config.vocab_size)
  382. )
  383. next_token_logits = torch.gather(outputs["logits"], 1, idxs).squeeze()
  384. else:
  385. next_token_logits = outputs["logits"][:, -1, :]
  386. next_tokens = torch.argmax(next_token_logits, dim=-1)
  387. # Check if we previously reached EOS token id or if generated token id is EOS token id
  388. has_eos = has_eos | next_tokens == tokenizer.eos_token_id
  389. # Determine which new tokens to add to list of all token ids
  390. # Add EOS token ids for batch entries that ended early (ragged batching scenario where some batch entries ended early and some haven't)
  391. tokens_to_add = next_tokens.masked_fill(has_eos, tokenizer.eos_token_id).reshape([batch_size, 1])
  392. sampling_end_time = time.perf_counter()
  393. sampling_times.append(sampling_end_time - sampling_start_time)
  394. all_token_ids = torch.cat([all_token_ids, tokens_to_add], dim=-1)
  395. current_length += 1
  396. # Update inputs for next inference run
  397. inputs["input_ids"] = tokens_to_add
  398. inputs["attention_mask"] = torch.cat(
  399. [inputs["attention_mask"], (~has_eos).to(torch.int64).reshape(batch_size, 1)], 1
  400. )
  401. if "position_ids" in inputs:
  402. inputs["position_ids"] = torch.max(inputs["position_ids"], dim=1)[0].reshape(batch_size, 1) + 1
  403. # Set logits to zeros for next inference run and re-use memory buffer
  404. if outputs["logits"].shape[1] != 1:
  405. outputs["logits"] = outputs["logits"][:, :1, :].contiguous()
  406. outputs["logits"].zero_()
  407. # Update KV caches for next inference run
  408. if args.engine == "pt":
  409. # Update KV caches for PyTorch
  410. inputs["past_key_values"] = outputs["past_key_values"]
  411. elif not args.use_buffer_share:
  412. # Update KV caches for ONNX Runtime if buffer sharing is not used
  413. for i in range(config.num_hidden_layers):
  414. inputs[f"past_key_values.{i}.key"] = outputs[f"present.{i}.key"]
  415. inputs[f"past_key_values.{i}.value"] = outputs[f"present.{i}.value"]
  416. new_sequence_length = inputs["attention_mask"].shape[1]
  417. for i in range(config.num_hidden_layers):
  418. present_key = torch.zeros(
  419. batch_size,
  420. num_heads,
  421. new_sequence_length,
  422. head_size,
  423. device=args.target_device,
  424. dtype=args.torch_dtype,
  425. )
  426. present_value = torch.zeros(
  427. batch_size,
  428. num_heads,
  429. new_sequence_length,
  430. head_size,
  431. device=args.target_device,
  432. dtype=args.torch_dtype,
  433. )
  434. outputs.update(
  435. {
  436. f"present.{i}.key": present_key.contiguous(),
  437. f"present.{i}.value": present_value.contiguous(),
  438. }
  439. )
  440. wall_clock_end_time = time.perf_counter()
  441. # Filter out any anomaly accelerator times (e.g. for `torch.compile`)
  442. accelerator_times.pop(0) # Remove prompt processing time
  443. if args.anomaly_filtering:
  444. anomaly_threshold_factor = 10
  445. min_time_s = min(accelerator_times)
  446. orig_size = len(accelerator_times)
  447. accelerator_times = list(
  448. filter(lambda acc_time: acc_time < anomaly_threshold_factor * min_time_s, accelerator_times)
  449. )
  450. new_size = len(accelerator_times)
  451. logger.info(
  452. f"Filtered out {orig_size - new_size} anomaly accelerator times that are {anomaly_threshold_factor}x greater than {min_time_s * 1000} ms..."
  453. )
  454. #######################################################
  455. # Calculate sampling and first token generated metrics
  456. #######################################################
  457. # Calculate sampling metrics
  458. avg_sampling_latency_s = sum(sampling_times) / len(sampling_times)
  459. avg_sampling_latency_ms = avg_sampling_latency_s * 1000
  460. avg_sampling_thrpt = batch_size * (1 / avg_sampling_latency_s)
  461. logger.info(f"Average Latency of Sampling: {avg_sampling_latency_ms} ms")
  462. logger.info(f"Average Throughput of Sampling: {avg_sampling_thrpt} tps")
  463. # Calculate first token generated metrics
  464. first_token_latency_s = accelerator_times[0]
  465. first_token_latency_ms = first_token_latency_s * 1000
  466. first_token_thrpt = batch_size * (1 / first_token_latency_s)
  467. logger.info(f"Latency of First Token Generated: {first_token_latency_ms} ms")
  468. logger.info(f"Throughput of First Token Generated: {first_token_thrpt} tps")
  469. ####################################################
  470. # Calculate first `halfway` token generated metrics
  471. ####################################################
  472. halfway = args.generation_length // 2
  473. halfway_token_latency_s = sum(accelerator_times[:halfway]) / len(accelerator_times[:halfway])
  474. halfway_token_latency_ms = halfway_token_latency_s * 1000
  475. halfway_token_thrpt = batch_size * (1 / halfway_token_latency_s)
  476. logger.info(f"Average Latency of First {halfway} Tokens Generated: {halfway_token_latency_ms} ms")
  477. logger.info(f"Average Throughput of First {halfway} Tokens Generated: {halfway_token_thrpt} tps")
  478. #########################################
  479. # Calculate all tokens generated metrics
  480. #########################################
  481. all_token_latency_s = sum(accelerator_times) / len(accelerator_times)
  482. all_token_latency_ms = all_token_latency_s * 1000
  483. all_token_thrpt = batch_size * (1 / all_token_latency_s)
  484. logger.info(
  485. f"Average Latency of First {args.generation_length} Tokens Generated: {all_token_latency_ms} ms"
  486. )
  487. logger.info(f"Average Throughput of First {args.generation_length} Tokens Generated: {all_token_thrpt} tps")
  488. ###############################
  489. # Calculate wall clock metrics
  490. ###############################
  491. wall_clock_latency_s = wall_clock_end_time - wall_clock_start_time
  492. wall_clock_thrpt = batch_size * ((prompt_length + args.generation_length) / wall_clock_latency_s)
  493. logger.info(f"Wall-Clock Latency: {wall_clock_latency_s} s")
  494. logger.info(
  495. f"Wall-Clock Throughput: {batch_size * ((prompt_length + args.generation_length) / wall_clock_latency_s)} tps"
  496. )
  497. # Add metrics to CSV
  498. logger.info("Adding results to CSV")
  499. csv_metrics.extend(
  500. [
  501. avg_sampling_latency_ms,
  502. avg_sampling_thrpt,
  503. first_token_latency_ms,
  504. first_token_thrpt,
  505. halfway_token_latency_ms,
  506. halfway_token_thrpt,
  507. all_token_latency_ms,
  508. all_token_thrpt,
  509. wall_clock_latency_s,
  510. wall_clock_thrpt,
  511. ]
  512. )
  513. all_csv_metrics.append(csv_metrics)
  514. except Exception as e:
  515. logger.info(f"Could not benchmark at batch size = {batch_size}, prompt length = {prompt_length} - {e}")
  516. filename = f"benchmark_{args.engine}_e2e_{datetime.datetime.now():%Y-%m-%d_%H:%M:%S}.csv"
  517. save_results(all_csv_metrics, filename, args.generation_length)
  518. if __name__ == "__main__":
  519. main()