compare_results.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import numpy as np
  2. import os
  3. import subprocess
  4. import json
  5. import argparse
  6. import glob
  7. def init_args():
  8. parser = argparse.ArgumentParser()
  9. # params for testing assert allclose
  10. parser.add_argument("--atol", type=float, default=1e-3)
  11. parser.add_argument("--rtol", type=float, default=1e-3)
  12. parser.add_argument("--gt_file", type=str, default="")
  13. parser.add_argument("--log_file", type=str, default="")
  14. parser.add_argument("--precision", type=str, default="fp32")
  15. return parser
  16. def parse_args():
  17. parser = init_args()
  18. return parser.parse_args()
  19. def run_shell_command(cmd):
  20. p = subprocess.Popen(
  21. cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
  22. out, err = p.communicate()
  23. if p.returncode == 0:
  24. return out.decode('utf-8')
  25. else:
  26. return None
  27. def parser_results_from_log_by_name(log_path, names_list):
  28. if not os.path.exists(log_path):
  29. raise ValueError("The log file {} does not exists!".format(log_path))
  30. if names_list is None or len(names_list) < 1:
  31. return []
  32. parser_results = {}
  33. for name in names_list:
  34. cmd = "grep {} {}".format(name, log_path)
  35. outs = run_shell_command(cmd)
  36. outs = outs.split("\n")[0]
  37. result = outs.split("{}".format(name))[-1]
  38. try:
  39. result = json.loads(result)
  40. except:
  41. result = np.array([int(r) for r in result.split()]).reshape(-1, 4)
  42. parser_results[name] = result
  43. return parser_results
  44. def load_gt_from_file(gt_file):
  45. if not os.path.exists(gt_file):
  46. raise ValueError("The log file {} does not exists!".format(gt_file))
  47. with open(gt_file, 'r') as f:
  48. data = f.readlines()
  49. f.close()
  50. parser_gt = {}
  51. for line in data:
  52. image_name, result = line.strip("\n").split("\t")
  53. image_name = image_name.split('/')[-1]
  54. try:
  55. result = json.loads(result)
  56. except:
  57. result = np.array([int(r) for r in result.split()]).reshape(-1, 4)
  58. parser_gt[image_name] = result
  59. return parser_gt
  60. def load_gt_from_txts(gt_file):
  61. gt_list = glob.glob(gt_file)
  62. gt_collection = {}
  63. for gt_f in gt_list:
  64. gt_dict = load_gt_from_file(gt_f)
  65. basename = os.path.basename(gt_f)
  66. if "fp32" in basename:
  67. gt_collection["fp32"] = [gt_dict, gt_f]
  68. elif "fp16" in basename:
  69. gt_collection["fp16"] = [gt_dict, gt_f]
  70. elif "int8" in basename:
  71. gt_collection["int8"] = [gt_dict, gt_f]
  72. else:
  73. continue
  74. return gt_collection
  75. def collect_predict_from_logs(log_path, key_list):
  76. log_list = glob.glob(log_path)
  77. pred_collection = {}
  78. for log_f in log_list:
  79. pred_dict = parser_results_from_log_by_name(log_f, key_list)
  80. key = os.path.basename(log_f)
  81. pred_collection[key] = pred_dict
  82. return pred_collection
  83. def testing_assert_allclose(dict_x, dict_y, atol=1e-7, rtol=1e-7):
  84. for k in dict_x:
  85. np.testing.assert_allclose(
  86. np.array(dict_x[k]), np.array(dict_y[k]), atol=atol, rtol=rtol)
  87. if __name__ == "__main__":
  88. # Usage:
  89. # python3.7 tests/compare_results.py --gt_file=./tests/results/*.txt --log_file=./tests/output/infer_*.log
  90. args = parse_args()
  91. gt_collection = load_gt_from_txts(args.gt_file)
  92. key_list = gt_collection["fp32"][0].keys()
  93. pred_collection = collect_predict_from_logs(args.log_file, key_list)
  94. for filename in pred_collection.keys():
  95. if "fp32" in filename:
  96. gt_dict, gt_filename = gt_collection["fp32"]
  97. elif "fp16" in filename:
  98. gt_dict, gt_filename = gt_collection["fp16"]
  99. elif "int8" in filename:
  100. gt_dict, gt_filename = gt_collection["int8"]
  101. else:
  102. continue
  103. pred_dict = pred_collection[filename]
  104. try:
  105. testing_assert_allclose(
  106. gt_dict, pred_dict, atol=args.atol, rtol=args.rtol)
  107. print(
  108. "Assert allclose passed! The results of {} and {} are consistent!".
  109. format(filename, gt_filename))
  110. except Exception as E:
  111. print(E)
  112. raise ValueError(
  113. "The results of {} and the results of {} are inconsistent!".
  114. format(filename, gt_filename))