throughput_benchmark.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # mypy: allow-untyped-defs
  2. import torch._C
  3. def format_time(time_us=None, time_ms=None, time_s=None):
  4. """Define time formatting."""
  5. assert sum([time_us is not None, time_ms is not None, time_s is not None]) == 1
  6. US_IN_SECOND = 1e6
  7. US_IN_MS = 1e3
  8. if time_us is None:
  9. if time_ms is not None:
  10. time_us = time_ms * US_IN_MS
  11. elif time_s is not None:
  12. time_us = time_s * US_IN_SECOND
  13. else:
  14. raise AssertionError("Shouldn't reach here :)")
  15. if time_us >= US_IN_SECOND:
  16. return f'{time_us / US_IN_SECOND:.3f}s'
  17. if time_us >= US_IN_MS:
  18. return f'{time_us / US_IN_MS:.3f}ms'
  19. return f'{time_us:.3f}us'
  20. class ExecutionStats:
  21. def __init__(self, c_stats, benchmark_config):
  22. self._c_stats = c_stats
  23. self.benchmark_config = benchmark_config
  24. @property
  25. def latency_avg_ms(self):
  26. return self._c_stats.latency_avg_ms
  27. @property
  28. def num_iters(self):
  29. return self._c_stats.num_iters
  30. @property
  31. def iters_per_second(self):
  32. """Return total number of iterations per second across all calling threads."""
  33. return self.num_iters / self.total_time_seconds
  34. @property
  35. def total_time_seconds(self):
  36. return self.num_iters * (
  37. self.latency_avg_ms / 1000.0) / self.benchmark_config.num_calling_threads
  38. def __str__(self):
  39. return '\n'.join([
  40. "Average latency per example: " + format_time(time_ms=self.latency_avg_ms),
  41. f"Total number of iterations: {self.num_iters}",
  42. f"Total number of iterations per second (across all threads): {self.iters_per_second:.2f}",
  43. "Total time: " + format_time(time_s=self.total_time_seconds)
  44. ])
  45. class ThroughputBenchmark:
  46. """
  47. This class is a wrapper around a c++ component throughput_benchmark::ThroughputBenchmark.
  48. This wrapper on the throughput_benchmark::ThroughputBenchmark component is responsible
  49. for executing a PyTorch module (nn.Module or ScriptModule) under an inference
  50. server like load. It can emulate multiple calling threads to a single module
  51. provided. In the future we plan to enhance this component to support inter and
  52. intra-op parallelism as well as multiple models running in a single process.
  53. Please note that even though nn.Module is supported, it might incur an overhead
  54. from the need to hold GIL every time we execute Python code or pass around
  55. inputs as Python objects. As soon as you have a ScriptModule version of your
  56. model for inference deployment it is better to switch to using it in this
  57. benchmark.
  58. Example::
  59. >>> # xdoctest: +SKIP("undefined vars")
  60. >>> from torch.utils import ThroughputBenchmark
  61. >>> bench = ThroughputBenchmark(my_module)
  62. >>> # Pre-populate benchmark's data set with the inputs
  63. >>> for input in inputs:
  64. ... # Both args and kwargs work, same as any PyTorch Module / ScriptModule
  65. ... bench.add_input(input[0], x2=input[1])
  66. >>> # Inputs supplied above are randomly used during the execution
  67. >>> stats = bench.benchmark(
  68. ... num_calling_threads=4,
  69. ... num_warmup_iters = 100,
  70. ... num_iters = 1000,
  71. ... )
  72. >>> print("Avg latency (ms): {}".format(stats.latency_avg_ms))
  73. >>> print("Number of iterations: {}".format(stats.num_iters))
  74. """
  75. def __init__(self, module):
  76. if isinstance(module, torch.jit.ScriptModule):
  77. self._benchmark = torch._C.ThroughputBenchmark(module._c)
  78. else:
  79. self._benchmark = torch._C.ThroughputBenchmark(module)
  80. def run_once(self, *args, **kwargs):
  81. """
  82. Given input id (input_idx) run benchmark once and return prediction.
  83. This is useful for testing that benchmark actually runs the module you
  84. want it to run. input_idx here is an index into inputs array populated
  85. by calling add_input() method.
  86. """
  87. return self._benchmark.run_once(*args, **kwargs)
  88. def add_input(self, *args, **kwargs):
  89. """
  90. Store a single input to a module into the benchmark memory and keep it there.
  91. During the benchmark execution every thread is going to pick up a
  92. random input from the all the inputs ever supplied to the benchmark via
  93. this function.
  94. """
  95. self._benchmark.add_input(*args, **kwargs)
  96. def benchmark(
  97. self,
  98. num_calling_threads=1,
  99. num_warmup_iters=10,
  100. num_iters=100,
  101. profiler_output_path=""):
  102. """
  103. Run a benchmark on the module.
  104. Args:
  105. num_warmup_iters (int): Warmup iters are used to make sure we run a module
  106. a few times before actually measuring things. This way we avoid cold
  107. caches and any other similar problems. This is the number of warmup
  108. iterations for each of the thread in separate
  109. num_iters (int): Number of iterations the benchmark should run with.
  110. This number is separate from the warmup iterations. Also the number is
  111. shared across all the threads. Once the num_iters iterations across all
  112. the threads is reached, we will stop execution. Though total number of
  113. iterations might be slightly larger. Which is reported as
  114. stats.num_iters where stats is the result of this function
  115. profiler_output_path (str): Location to save Autograd Profiler trace.
  116. If not empty, Autograd Profiler will be enabled for the main benchmark
  117. execution (but not the warmup phase). The full trace will be saved
  118. into the file path provided by this argument
  119. This function returns BenchmarkExecutionStats object which is defined via pybind11.
  120. It currently has two fields:
  121. - num_iters - number of actual iterations the benchmark have made
  122. - avg_latency_ms - average time it took to infer on one input example in milliseconds
  123. """
  124. config = torch._C.BenchmarkConfig()
  125. config.num_calling_threads = num_calling_threads
  126. config.num_warmup_iters = num_warmup_iters
  127. config.num_iters = num_iters
  128. config.profiler_output_path = profiler_output_path
  129. c_stats = self._benchmark.benchmark(config)
  130. return ExecutionStats(c_stats, config)