gpt2_parity.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 script uses different configurations in mixed precision conversion for GPT-2 model, and
  7. # measures the inference latency, top 1 match rate (compared to PyTorch FP32 model) and ONNX model size.
  8. # It outputs a csv file with Mann-Whitney U test and T-Test on each pair of experiments, where
  9. # pvalue < 0.05 means two experiments have significant difference on top 1 match rate.
  10. # User could use this script to select the best mixed precision model according to these metrics.
  11. import argparse
  12. import csv
  13. import datetime
  14. import json
  15. import logging
  16. import os
  17. import onnx
  18. import scipy.stats
  19. from benchmark_helper import get_ort_environment_variables, setup_logger
  20. from convert_to_onnx import main
  21. from gpt2_helper import PRETRAINED_GPT2_MODELS, Gpt2Helper
  22. from onnx_model import OnnxModel
  23. logger = logging.getLogger("")
  24. def parse_arguments(argv=None):
  25. parser = argparse.ArgumentParser()
  26. parser.add_argument(
  27. "-m",
  28. "--model_name_or_path",
  29. required=True,
  30. type=str,
  31. help="Model path, or pretrained model name in the list: " + ", ".join(PRETRAINED_GPT2_MODELS),
  32. )
  33. parser.add_argument(
  34. "--csv",
  35. required=False,
  36. type=str,
  37. default="gpt2_parity_results.csv",
  38. help="path of csv file to save the result",
  39. )
  40. parser.add_argument(
  41. "--test_cases",
  42. required=False,
  43. type=int,
  44. default=500,
  45. help="number of test cases per run",
  46. )
  47. parser.add_argument("--runs", required=False, type=int, default=40, help="number of repeated runs")
  48. parser.add_argument("--use_gpu", required=False, action="store_true", help="use GPU for inference")
  49. parser.set_defaults(use_gpu=False)
  50. parser.add_argument(
  51. "--all",
  52. required=False,
  53. action="store_true",
  54. help="run all combinations of mixed precision",
  55. )
  56. parser.set_defaults(all=False)
  57. parser.add_argument("-e", "--use_external_data_format", required=False, action="store_true")
  58. parser.set_defaults(use_external_data_format=False)
  59. parser.add_argument("--verbose", required=False, action="store_true")
  60. parser.set_defaults(verbose=False)
  61. parser.add_argument(
  62. "--skip_test",
  63. required=False,
  64. action="store_true",
  65. help="do not run test, and only rank experiments based on existing csv file",
  66. )
  67. parser.set_defaults(skip_test=False)
  68. parser.add_argument(
  69. "--overwrite",
  70. required=False,
  71. action="store_true",
  72. help="Overwrite existing csv file",
  73. )
  74. parser.set_defaults(overwrite=False)
  75. args = parser.parse_args(argv)
  76. return args
  77. class ParityTask:
  78. def __init__(self, test_cases, total_runs, csv_path):
  79. self.total_runs = total_runs
  80. self.test_cases = test_cases
  81. self.csv_path = csv_path
  82. self.results = []
  83. self.run_id = 0
  84. def run(self, argv, experiment_name):
  85. start_time = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  86. run_id = f"{start_time}_{self.run_id}"
  87. self.run_id += 1
  88. try:
  89. result = main(
  90. [*argv, "-t", f"{self.test_cases}", "-r", f"{self.total_runs}"],
  91. experiment_name=experiment_name,
  92. run_id=run_id,
  93. csv_filename=self.csv_path,
  94. )
  95. if result:
  96. self.results.append(result)
  97. except Exception:
  98. logger.exception(f"Failed to run experiment {experiment_name}")
  99. result = None
  100. return result
  101. def load_results_from_csv(csv_path):
  102. rows = []
  103. import csv # noqa: PLC0415
  104. with open(csv_path, newline="") as csvfile:
  105. reader = csv.DictReader(csvfile)
  106. for row in reader:
  107. rows.append(row) # noqa: PERF402
  108. return rows
  109. def get_latency(row):
  110. for name in row:
  111. if name.startswith("average_latency(batch_size="):
  112. return float(row[name])
  113. raise RuntimeError("Failed to get average_latency from output")
  114. def score(row):
  115. """Scoring function based on 3 metrics. The larger score is better."""
  116. latency_in_ms = get_latency(row)
  117. top1_match_rate = float(row["top1_match_rate"])
  118. onnx_size_in_MB = float(row["onnx_size_in_MB"]) # noqa: N806
  119. # A simple scoring function: cost of 0.1ms latency ~ 0.1% match rate ~ 100MB size
  120. return top1_match_rate * 1000 - latency_in_ms * 10 - onnx_size_in_MB / 100
  121. def print_wins(wins, rows, test_name):
  122. print()
  123. print("*" * 10)
  124. row_map = {}
  125. for row in rows:
  126. row_map[row["run_id"]] = row
  127. sorted_wins = dict(
  128. sorted(
  129. wins.items(),
  130. key=lambda item: (item[1], score(row_map[item[0]])),
  131. reverse=True,
  132. )
  133. )
  134. logger.debug(f"{test_name} Wins:{sorted_wins}")
  135. logger.info(f"Based on {test_name} wins and a scoring function, the ranking:")
  136. rank = 0
  137. previous_value = -1
  138. for count, (key, value) in enumerate(sorted_wins.items()):
  139. if value != previous_value:
  140. rank = count
  141. previous_value = value
  142. for row in rows:
  143. if row["run_id"] == key:
  144. logger.info(
  145. "{:02d}: WINs={:02d}, run_id={}, latency={:5.2f}, top1_match={:.4f}, size={}_MB, experiment={}, {}".format( # noqa: G001
  146. rank,
  147. value,
  148. key,
  149. get_latency(row),
  150. float(row["top1_match_rate"]),
  151. row["onnx_size_in_MB"],
  152. row["experiment"],
  153. get_ort_environment_variables(),
  154. )
  155. )
  156. break
  157. def run_significance_test(rows, output_csv_path):
  158. """Run U test and T test."""
  159. utest_wins = {}
  160. ttest_wins = {}
  161. for row in rows:
  162. run_id = row["run_id"]
  163. utest_wins[run_id] = 0
  164. ttest_wins[run_id] = 0
  165. with open(output_csv_path, "w", newline="") as csvfile:
  166. column_names = [
  167. "model_name",
  168. "run_id_1",
  169. "experiment_1",
  170. "top1_match_rate_1",
  171. "run_id_2",
  172. "experiment_2",
  173. "top1_match_rate_2",
  174. "U_statistic",
  175. "U_pvalue",
  176. "T_statistic",
  177. "T_pvalue",
  178. ]
  179. writer = csv.DictWriter(csvfile, fieldnames=column_names)
  180. writer.writeheader()
  181. required_match_columns = ["model_name", "test_cases", "runs"]
  182. num_results = len(rows)
  183. for i in range(num_results - 1):
  184. result1 = rows[i]
  185. if isinstance(result1["top1_match_rate_per_run"], str):
  186. a = json.loads(result1["top1_match_rate_per_run"])
  187. else:
  188. a = result1["top1_match_rate_per_run"]
  189. for j in range(i + 1, num_results, 1):
  190. result2 = rows[j]
  191. all_matched = True
  192. for column in required_match_columns:
  193. if result1[column] != result2[column]:
  194. all_matched = False
  195. break
  196. if not all_matched:
  197. continue
  198. if isinstance(result2["top1_match_rate_per_run"], str):
  199. b = json.loads(result2["top1_match_rate_per_run"])
  200. else:
  201. b = result2["top1_match_rate_per_run"]
  202. try:
  203. utest_statistic, utest_pvalue = scipy.stats.mannwhitneyu(
  204. a, b, use_continuity=True, alternative="two-sided"
  205. ) # TODO: shall we use one-sided: less or greater according to "top1_match_rate"
  206. except ValueError: # ValueError: All numbers are identical in mannwhitneyu
  207. utest_statistic = None
  208. utest_pvalue = None
  209. ttest_statistic, ttest_pvalue = scipy.stats.ttest_ind(a, b, axis=None, equal_var=True)
  210. if utest_pvalue is not None and utest_pvalue < 0.05:
  211. if float(result1["top1_match_rate"]) > float(result2["top1_match_rate"]):
  212. utest_wins[result1["run_id"]] += 1
  213. else:
  214. utest_wins[result2["run_id"]] += 1
  215. if ttest_pvalue < 0.05:
  216. if float(result1["top1_match_rate"]) > float(result2["top1_match_rate"]):
  217. ttest_wins[result1["run_id"]] += 1
  218. else:
  219. ttest_wins[result2["run_id"]] += 1
  220. row = {
  221. "model_name": result1["model_name"],
  222. "run_id_1": result1["run_id"],
  223. "experiment_1": result1["experiment"],
  224. "top1_match_rate_1": float(result1["top1_match_rate"]),
  225. "run_id_2": result2["run_id"],
  226. "experiment_2": result2["experiment"],
  227. "top1_match_rate_2": float(result2["top1_match_rate"]),
  228. "U_statistic": utest_statistic,
  229. "U_pvalue": utest_pvalue,
  230. "T_statistic": ttest_statistic,
  231. "T_pvalue": ttest_pvalue,
  232. }
  233. writer.writerow(row)
  234. logger.info(f"U-Test and T-Test results are output to {output_csv_path}")
  235. print_wins(utest_wins, rows, "U-Test")
  236. print_wins(ttest_wins, rows, "T-Test")
  237. def get_last_matmul_node_name(raw_onnx_model: str):
  238. model = onnx.load(raw_onnx_model)
  239. onnx_model = OnnxModel(model)
  240. output_name_to_node = onnx_model.output_name_to_node()
  241. assert model.graph.output[0].name in output_name_to_node
  242. node = output_name_to_node[model.graph.output[0].name]
  243. if node.op_type == "MatMul":
  244. logger.info(f"Found last MatMul node for logits: {node.name}")
  245. return node.name
  246. logger.warning(f"Failed to find MatMul node for logits. Found {node.op_type} of node {node.name}")
  247. return None
  248. def get_mixed_precision_parameters(args, last_matmul_node_name, op_block_list):
  249. model = args.model_name_or_path
  250. parameters = f"-m {model} -o --use_gpu -p fp16".split()
  251. if args.use_external_data_format:
  252. parameters.append("--use_external_data_format")
  253. parameters += [
  254. "--io_block_list",
  255. "logits",
  256. "--node_block_list",
  257. last_matmul_node_name,
  258. ]
  259. if op_block_list:
  260. parameters.extend(["--op_block_list", *op_block_list])
  261. return parameters
  262. def run_candidate(
  263. task: ParityTask,
  264. args,
  265. last_matmul_node_name,
  266. op_block_list=["FastGelu", "LayerNormalization"], # noqa: B006
  267. ):
  268. parameters = get_mixed_precision_parameters(args, last_matmul_node_name, op_block_list)
  269. op_block_list_str = ",".join(sorted(op_block_list))
  270. if op_block_list:
  271. name = f"Mixed precision baseline + {op_block_list_str} in FP32"
  272. else:
  273. name = f"Mixed precision baseline (logits output and last MatMul node {last_matmul_node_name} in FP32)"
  274. env_vars = get_ort_environment_variables()
  275. if env_vars:
  276. name = name + f" ({env_vars})"
  277. task.run(parameters, name)
  278. def get_baselines(args):
  279. model = args.model_name_or_path
  280. fp32_baseline = f"-m {model} -o -p fp32".split()
  281. if args.use_gpu:
  282. fp32_baseline.append("--use_gpu")
  283. if args.use_external_data_format:
  284. fp32_baseline.append("--use_external_data_format")
  285. fp16_baseline = f"-m {model} -o --use_gpu -p fp16".split()
  286. if args.use_external_data_format:
  287. fp16_baseline.append("--use_external_data_format")
  288. return fp32_baseline, fp16_baseline
  289. def run_tuning_step0(task, fp16_baseline, all_ops, optimized_ops):
  290. """Step 0 is to check which operator in FP16 causes most loss"""
  291. fp32_logits = ["--io_block_list", "logits"]
  292. task.run(fp16_baseline + fp32_logits, "FP16 except logits")
  293. fp32_io = ["--keep_io_types"]
  294. task.run(fp16_baseline + fp32_io, "Graph I/O FP32, Other FP16")
  295. # Only weights in FP16
  296. task.run(
  297. fp16_baseline + fp32_io + ["--op_block_list"] + list(all_ops) + ["--force_fp16_initializers"],
  298. "FP32 except weights in FP16",
  299. )
  300. optimized_ops_results = []
  301. op_list = optimized_ops
  302. for op in op_list:
  303. op_block_list = ["--op_block_list"] + [o for o in op_list if o != op]
  304. result = task.run(fp16_baseline + fp32_io + op_block_list, f"FP32 except {op} in FP16")
  305. if result:
  306. optimized_ops_results.append(result)
  307. # Check which optimized operator causes the most loss in precision
  308. min_result = min(optimized_ops_results, key=lambda y: y["top1_match_rate"])
  309. print("step 0: optimized operator causes the most loss in precision", min_result)
  310. def run_tuning_step1(task, mixed_precision_baseline, optimized_ops):
  311. """Step 1 is to figure out which optimized operator in FP32 could benefit most"""
  312. for op in optimized_ops:
  313. op_block_list = ["--op_block_list", op]
  314. task.run(
  315. mixed_precision_baseline + op_block_list,
  316. f"Mixed precision baseline + {op} in FP32",
  317. )
  318. def run_tuning_step2(task, mixed_precision_baseline, optimized_ops):
  319. """Assumed that you have run step 0 and 1 to figure out that Logits FP32 and some operators shall be in FP32,
  320. This step will try add one more operator.
  321. """
  322. candidate_fp32_ops = ["FastGelu", "LayerNormalization", "SkipLayerNormalization"]
  323. fp32_ops = [x for x in candidate_fp32_ops if x in optimized_ops]
  324. for op in optimized_ops:
  325. if op not in fp32_ops:
  326. op_block_list = [*fp32_ops, op]
  327. task.run(
  328. [*mixed_precision_baseline, "--op_block_list", *op_block_list],
  329. "Mixed precision baseline + {},{} in FP32".format(",".join(fp32_ops), op),
  330. )
  331. def run_parity(task: ParityTask, args):
  332. onnx_model_paths = Gpt2Helper.get_onnx_paths(
  333. "onnx_models",
  334. args.model_name_or_path,
  335. new_folder=args.use_external_data_format,
  336. remove_existing=[],
  337. )
  338. fp32_baseline, fp16_baseline = get_baselines(args)
  339. result = task.run(fp32_baseline, "FP32 baseline")
  340. optimized_ops = []
  341. if result and ("optimized_operators" in result) and result["optimized_operators"]:
  342. optimized_ops = result["optimized_operators"].split(",")
  343. else:
  344. raise RuntimeError("Failed to get optimized operators")
  345. all_ops = []
  346. if result and ("operators" in result) and result["operators"]:
  347. all_ops = result["operators"].split(",")
  348. else:
  349. raise RuntimeError("Failed to get operators")
  350. # The following tests for fp16 requires GPU
  351. if not args.use_gpu:
  352. logger.info("skip mixed precision since --use_gpu is not specified")
  353. return
  354. task.run(fp16_baseline, "FP16 baseline")
  355. last_matmul_node_name = get_last_matmul_node_name(onnx_model_paths["raw"])
  356. # Mixed precision baseline
  357. run_candidate(task, args, last_matmul_node_name, op_block_list=[])
  358. def get_fp32_ops(x):
  359. return [op for op in x if op in all_ops]
  360. if args.all:
  361. run_tuning_step0(task, fp16_baseline, all_ops, optimized_ops)
  362. mixed_precision_baseline = get_mixed_precision_parameters(args, last_matmul_node_name, op_block_list=[])
  363. run_tuning_step1(task, mixed_precision_baseline, optimized_ops)
  364. run_tuning_step2(task, mixed_precision_baseline, optimized_ops)
  365. else:
  366. run_candidate(
  367. task,
  368. args,
  369. last_matmul_node_name,
  370. op_block_list=get_fp32_ops(["SkipLayerNormalization", "LayerNormalization", "Add"]),
  371. )
  372. run_candidate(task, args, last_matmul_node_name, op_block_list=["FastGelu"])
  373. # Run a few good candidates
  374. run_candidate(
  375. task,
  376. args,
  377. last_matmul_node_name,
  378. op_block_list=get_fp32_ops(["FastGelu", "SkipLayerNormalization", "LayerNormalization", "Add"]),
  379. )
  380. run_candidate(
  381. task,
  382. args,
  383. last_matmul_node_name,
  384. op_block_list=get_fp32_ops(
  385. ["FastGelu", "EmbedLayerNormalization", "SkipLayerNormalization", "LayerNormalization", "Add"]
  386. ),
  387. )
  388. if __name__ == "__main__":
  389. args = parse_arguments()
  390. setup_logger(args.verbose)
  391. if args.test_cases < 100 or args.runs < 20 or args.test_cases * args.runs < 10000:
  392. logger.warning(
  393. "Not enough test cases or runs to get stable results or test significance. "
  394. "Recommend test_cases >= 100, runs >= 20, test_cases * runs >= 10000."
  395. )
  396. if os.path.exists(args.csv) and not args.skip_test:
  397. if not args.overwrite:
  398. raise RuntimeError(
  399. f"Output file {args.csv} existed. Please remove the file, or use either --skip_test or --overwrite."
  400. )
  401. else:
  402. logger.info("Remove existing file %s since --overwrite is specified", args.csv)
  403. os.remove(args.csv)
  404. task = ParityTask(args.test_cases, args.runs, args.csv)
  405. if not args.skip_test:
  406. run_parity(task, args)
  407. try:
  408. rows = load_results_from_csv(task.csv_path)
  409. except Exception:
  410. logger.exception(f"Failed to load csv {task.csv_path}")
  411. rows = task.results
  412. logger.info("Start running significance tests...")
  413. summary_csv = task.csv_path.replace(".csv", ".stats.csv")
  414. run_significance_test(rows, summary_csv)