import torch
import torch_mlu
import torch_mlu_ops as tmo
from common import benchmark_forward, save_to_csv
import argparse
from tabulate import tabulate
import os

e2e_time_param_dict_list = [{"input_shape": [100, 100, 100], "input_dtype": [torch.float16, torch.bfloat16]},
                            {"input_shape": [100, 100], "input_dtype": [torch.float16, torch.bfloat16]},
                            {"input_shape": [50, 50, 50], "input_dtype": [torch.float16, torch.bfloat16]},
                            {"input_shape": [1, 100, 1000], "input_dtype": [torch.float16, torch.bfloat16]}
                           ]
def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--repeat_times', type=int, default=10, help='repeat times for testing')
  parser.add_argument('--csv', action='store_true', help='write the report data to csv')
  parser.add_argument('-o', type=str, help='specify the output folder name under --csv mode')

  args = parser.parse_args()
  device = 'mlu'
  titles = ["input_shape", "input_dtype", "hardware_time(us)", "e2e_latency(us)"]
  contents = []
  for params_dict in e2e_time_param_dict_list:
    input_shape = params_dict["input_shape"]
    input_dtype_list = params_dict["input_dtype"]
    for dtype in input_dtype_list:
      if dtype == torch.bfloat16 and not torch_mlu.mlu.is_bf16_supported():
        continue
      input = torch.randn(input_shape).to(device).to(dtype)
      hardware_time, e2e_time = benchmark_forward(tmo.preload,
                                                  input,
                                                  input.element_size() * input.numel(),
                                                  repeats=args.repeat_times)
      content = [f"{input_shape}", f"{dtype}", f"{hardware_time}", f"{e2e_time}"]
      contents.append(content)
  table = [titles] + contents
  print(tabulate(table, headers="firstrow", tablefmt="grid"))

  if args.csv:
    current_file_path = __file__
    _, file_name = os.path.split(current_file_path)
    save_to_csv(table, args.o, file_name)

if __name__=="__main__":
  main()
