fuzzer.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. """Example of the Timer and Fuzzer APIs:
  2. $ python -m examples.fuzzer
  3. """
  4. import sys
  5. import torch.utils.benchmark as benchmark_utils
  6. def main():
  7. add_fuzzer = benchmark_utils.Fuzzer(
  8. parameters=[
  9. [
  10. benchmark_utils.FuzzedParameter(
  11. name=f"k{i}",
  12. minval=16,
  13. maxval=16 * 1024,
  14. distribution="loguniform",
  15. ) for i in range(3)
  16. ],
  17. benchmark_utils.FuzzedParameter(
  18. name="d",
  19. distribution={2: 0.6, 3: 0.4},
  20. ),
  21. ],
  22. tensors=[
  23. [
  24. benchmark_utils.FuzzedTensor(
  25. name=name,
  26. size=("k0", "k1", "k2"),
  27. dim_parameter="d",
  28. probability_contiguous=0.75,
  29. min_elements=64 * 1024,
  30. max_elements=128 * 1024,
  31. ) for name in ("x", "y")
  32. ],
  33. ],
  34. seed=0,
  35. )
  36. n = 250
  37. measurements = []
  38. for i, (tensors, tensor_properties, _) in enumerate(add_fuzzer.take(n=n)):
  39. x, x_order = tensors["x"], str(tensor_properties["x"]["order"])
  40. y, y_order = tensors["y"], str(tensor_properties["y"]["order"])
  41. shape = ", ".join(tuple(f'{i:>4}' for i in x.shape))
  42. description = "".join([
  43. f"{x.numel():>7} | {shape:<16} | ",
  44. f"{'contiguous' if x.is_contiguous() else x_order:<12} | ",
  45. f"{'contiguous' if y.is_contiguous() else y_order:<12} | ",
  46. ])
  47. timer = benchmark_utils.Timer(
  48. stmt="x + y",
  49. globals=tensors,
  50. description=description,
  51. )
  52. measurements.append(timer.blocked_autorange(min_run_time=0.1))
  53. measurements[-1].metadata = {"numel": x.numel()}
  54. print(f"\r{i + 1} / {n}", end="")
  55. sys.stdout.flush()
  56. print()
  57. # More string munging to make pretty output.
  58. print(f"Average attempts per valid config: {1. / (1. - add_fuzzer.rejection_rate):.1f}")
  59. def time_fn(m):
  60. return m.median / m.metadata["numel"]
  61. measurements.sort(key=time_fn)
  62. template = f"{{:>6}}{' ' * 19}Size Shape{' ' * 13}X order Y order\n{'-' * 80}"
  63. print(template.format("Best:"))
  64. for m in measurements[:15]:
  65. print(f"{time_fn(m) * 1e9:>4.1f} ns / element {m.description}")
  66. print("\n" + template.format("Worst:"))
  67. for m in measurements[-15:]:
  68. print(f"{time_fn(m) * 1e9:>4.1f} ns / element {m.description}")
  69. if __name__ == "__main__":
  70. main()