benchmark_gemm.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import time
  2. import torch
  3. import torch.utils.benchmark as benchmark
  4. from triton.testing import do_bench
  5. def benchmark_forward(fn, *inputs, repeats=10, desc='', verbose=True, **kwinputs):
  6. """Use Pytorch Benchmark on the forward pass of an arbitrary function."""
  7. if verbose:
  8. print(desc, '- Forward pass')
  9. t = benchmark.Timer(
  10. stmt='fn(*inputs, **kwinputs)',
  11. globals={'fn': fn, 'inputs': inputs, 'kwinputs': kwinputs},
  12. num_threads=torch.get_num_threads(),
  13. )
  14. m = t.timeit(repeats)
  15. if verbose:
  16. print(m)
  17. return t, m
  18. torch.manual_seed(0)
  19. repeats = 30
  20. dtype = torch.float16
  21. device = 'cuda'
  22. verbose = False
  23. m, n = 8192, 8192
  24. tflops_matmul = {}
  25. tflops_matmul1 = {}
  26. for k in [512, 1024, 1536, 2048, 2560, 3072, 3584, 4096, 4608, 5120, 5632, 6144, 6656, 7168, 7680, 8192]:
  27. a = torch.randn(m, k, device=device, dtype=dtype)
  28. b = torch.randn(n, k, device=device, dtype=dtype).transpose(-1, -2)
  29. nFLOPS_matmul = 2 * m * n * k
  30. time.sleep(2) # to reduce power throttling
  31. timing = benchmark_forward(torch.matmul, a, b, desc='cuBLAS', verbose=verbose, repeats=repeats)[1]
  32. tflops_matmul[k] = nFLOPS_matmul / timing.mean * 1e-12
  33. print(f'[torch.utils.benchmark] cuBLAS, {m = }, {n = }, {k = }: {timing.mean * 1e3:.3f}ms, {tflops_matmul[k]:.1f} TFLOPS')
  34. time.sleep(2) # to reduce power throttling
  35. ms = do_bench(lambda: torch.matmul(a, b), warmup=10, rep=repeats)
  36. tflops_matmul1[k] = nFLOPS_matmul / ms * 1e-9
  37. print(f'[triton.test.do_bench] cuBLAS, {m = }, {n = }, {k = }: {ms:.3f}ms, {tflops_matmul1[k]:.1f} TFLOPS')