__main__.py 7.0 KB

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