__main__.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import argparse
  2. import cProfile
  3. import pstats
  4. import sys
  5. import os
  6. from typing import Dict
  7. import torch
  8. from torch.autograd import profiler
  9. from torch.utils.collect_env import get_env_info
  10. def redirect_argv(new_argv):
  11. sys.argv[:] = new_argv[:]
  12. def compiled_with_cuda(sysinfo):
  13. if sysinfo.cuda_compiled_version:
  14. return 'compiled w/ CUDA {}'.format(sysinfo.cuda_compiled_version)
  15. return 'not compiled w/ CUDA'
  16. env_summary = """
  17. --------------------------------------------------------------------------------
  18. Environment Summary
  19. --------------------------------------------------------------------------------
  20. PyTorch {pytorch_version}{debug_str} {cuda_compiled}
  21. Running with Python {py_version} and {cuda_runtime}
  22. `{pip_version} list` truncated output:
  23. {pip_list_output}
  24. """.strip()
  25. def run_env_analysis():
  26. print('Running environment analysis...')
  27. info = get_env_info()
  28. result: Dict[str, str] = {}
  29. debug_str = ''
  30. if info.is_debug_build:
  31. debug_str = ' DEBUG'
  32. cuda_avail = ''
  33. if info.is_cuda_available:
  34. cuda = info.cuda_runtime_version
  35. if cuda is not None:
  36. cuda_avail = 'CUDA ' + cuda
  37. else:
  38. cuda = 'CUDA unavailable'
  39. pip_version = info.pip_version
  40. pip_list_output = info.pip_packages
  41. if pip_list_output is None:
  42. pip_list_output = 'Unable to fetch'
  43. result = {
  44. 'debug_str': debug_str,
  45. 'pytorch_version': info.torch_version,
  46. 'cuda_compiled': compiled_with_cuda(info),
  47. 'py_version': '{}.{}'.format(sys.version_info[0], sys.version_info[1]),
  48. 'cuda_runtime': cuda_avail,
  49. 'pip_version': pip_version,
  50. 'pip_list_output': pip_list_output,
  51. }
  52. return env_summary.format(**result)
  53. def run_cprofile(code, globs, launch_blocking=False):
  54. print('Running your script with cProfile')
  55. prof = cProfile.Profile()
  56. prof.enable()
  57. exec(code, globs, None)
  58. prof.disable()
  59. return prof
  60. cprof_summary = """
  61. --------------------------------------------------------------------------------
  62. cProfile output
  63. --------------------------------------------------------------------------------
  64. """.strip()
  65. def print_cprofile_summary(prof, sortby='tottime', topk=15):
  66. print(cprof_summary)
  67. cprofile_stats = pstats.Stats(prof).sort_stats(sortby)
  68. cprofile_stats.print_stats(topk)
  69. def run_autograd_prof(code, globs):
  70. def run_prof(use_cuda=False):
  71. with profiler.profile(use_cuda=use_cuda) as prof:
  72. exec(code, globs, None)
  73. return prof
  74. print('Running your script with the autograd profiler...')
  75. result = [run_prof(use_cuda=False)]
  76. if torch.cuda.is_available():
  77. result.append(run_prof(use_cuda=True))
  78. else:
  79. result.append(None)
  80. return result
  81. autograd_prof_summary = """
  82. --------------------------------------------------------------------------------
  83. autograd profiler output ({mode} mode)
  84. --------------------------------------------------------------------------------
  85. {description}
  86. {cuda_warning}
  87. {output}
  88. """.strip()
  89. def print_autograd_prof_summary(prof, mode, sortby='cpu_time', topk=15):
  90. valid_sortby = ['cpu_time', 'cuda_time', 'cpu_time_total', 'cuda_time_total', 'count']
  91. if sortby not in valid_sortby:
  92. warn = ('WARNING: invalid sorting option for autograd profiler results: {}\n'
  93. 'Expected `cpu_time`, `cpu_time_total`, or `count`. '
  94. 'Defaulting to `cpu_time`.')
  95. print(warn.format(sortby))
  96. sortby = 'cpu_time'
  97. if mode == 'CUDA':
  98. cuda_warning = ('\n\tBecause the autograd profiler uses the CUDA event API,\n'
  99. '\tthe CUDA time column reports approximately max(cuda_time, cpu_time).\n'
  100. '\tPlease ignore this output if your code does not use CUDA.\n')
  101. else:
  102. cuda_warning = ''
  103. sorted_events = sorted(prof.function_events,
  104. key=lambda x: getattr(x, sortby), reverse=True)
  105. topk_events = sorted_events[:topk]
  106. result = {
  107. 'mode': mode,
  108. 'description': 'top {} events sorted by {}'.format(topk, sortby),
  109. 'output': torch.autograd.profiler_util._build_table(topk_events),
  110. 'cuda_warning': cuda_warning
  111. }
  112. print(autograd_prof_summary.format(**result))
  113. descript = """
  114. `bottleneck` is a tool that can be used as an initial step for debugging
  115. bottlenecks in your program.
  116. It summarizes runs of your script with the Python profiler and PyTorch\'s
  117. autograd profiler. Because your script will be profiled, please ensure that it
  118. exits in a finite amount of time.
  119. For more complicated uses of the profilers, please see
  120. https://docs.python.org/3/library/profile.html and
  121. https://pytorch.org/docs/master/autograd.html#profiler for more information.
  122. """.strip()
  123. def parse_args():
  124. parser = argparse.ArgumentParser(description=descript)
  125. parser.add_argument('scriptfile', type=str,
  126. help='Path to the script to be run. '
  127. 'Usually run with `python path/to/script`.')
  128. parser.add_argument('args', type=str, nargs=argparse.REMAINDER,
  129. help='Command-line arguments to be passed to the script.')
  130. return parser.parse_args()
  131. def cpu_time_total(autograd_prof):
  132. return sum([event.cpu_time_total for event in autograd_prof.function_events])
  133. def main():
  134. args = parse_args()
  135. # Customizable constants.
  136. scriptfile = args.scriptfile
  137. scriptargs = [] if args.args is None else args.args
  138. scriptargs.insert(0, scriptfile)
  139. cprofile_sortby = 'tottime'
  140. cprofile_topk = 15
  141. autograd_prof_sortby = 'cpu_time_total'
  142. autograd_prof_topk = 15
  143. redirect_argv(scriptargs)
  144. sys.path.insert(0, os.path.dirname(scriptfile))
  145. with open(scriptfile, 'rb') as stream:
  146. code = compile(stream.read(), scriptfile, 'exec')
  147. globs = {
  148. '__file__': scriptfile,
  149. '__name__': '__main__',
  150. '__package__': None,
  151. '__cached__': None,
  152. }
  153. print(descript)
  154. env_summary = run_env_analysis()
  155. if torch.cuda.is_available():
  156. torch.cuda.init()
  157. cprofile_prof = run_cprofile(code, globs)
  158. autograd_prof_cpu, autograd_prof_cuda = run_autograd_prof(code, globs)
  159. print(env_summary)
  160. print_cprofile_summary(cprofile_prof, cprofile_sortby, cprofile_topk)
  161. if not torch.cuda.is_available():
  162. print_autograd_prof_summary(autograd_prof_cpu, 'CPU', autograd_prof_sortby, autograd_prof_topk)
  163. return
  164. # Print both the result of the CPU-mode and CUDA-mode autograd profilers
  165. # if their execution times are very different.
  166. cuda_prof_exec_time = cpu_time_total(autograd_prof_cuda)
  167. if len(autograd_prof_cpu.function_events) > 0:
  168. cpu_prof_exec_time = cpu_time_total(autograd_prof_cpu)
  169. pct_diff = (cuda_prof_exec_time - cpu_prof_exec_time) / cuda_prof_exec_time
  170. if abs(pct_diff) > 0.05:
  171. print_autograd_prof_summary(autograd_prof_cpu, 'CPU', autograd_prof_sortby, autograd_prof_topk)
  172. print_autograd_prof_summary(autograd_prof_cuda, 'CUDA', autograd_prof_sortby, autograd_prof_topk)
  173. if __name__ == '__main__':
  174. main()