profiler.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. # mypy: allow-untyped-defs
  2. import uuid
  3. from collections import defaultdict
  4. from collections.abc import Iterable
  5. from dataclasses import dataclass
  6. from time import perf_counter_ns
  7. from typing import Any, Optional
  8. from warnings import warn
  9. import torch
  10. import torch.cuda
  11. from torch._C import _get_privateuse1_backend_name
  12. from torch._C._profiler import _ExperimentalConfig
  13. from torch.autograd import (
  14. _disable_profiler,
  15. _enable_profiler,
  16. _kineto_step,
  17. _prepare_profiler,
  18. _ProfilerResult,
  19. _supported_activities,
  20. _toggle_collection_dynamic,
  21. DeviceType,
  22. kineto_available,
  23. ProfilerActivity,
  24. ProfilerConfig,
  25. ProfilerState,
  26. )
  27. from torch.autograd.profiler_util import (
  28. _filter_name,
  29. _filter_stack_entry,
  30. _rewrite_name,
  31. EventList,
  32. FunctionEvent,
  33. MEMORY_EVENT_NAME,
  34. MemRecordsAcc,
  35. OUT_OF_MEMORY_EVENT_NAME,
  36. )
  37. from torch.futures import Future
  38. __all__ = [
  39. "profile",
  40. "record_function",
  41. "emit_itt",
  42. "emit_nvtx",
  43. "load_nvprof",
  44. "EnforceUnique",
  45. "parse_nvprof_trace",
  46. "KinetoStepTracker",
  47. "EventList",
  48. "FunctionEvent",
  49. "MemRecordsAcc",
  50. ]
  51. try:
  52. # Available in Python >= 3.2
  53. from contextlib import ContextDecorator as _ContextDecorator
  54. except ImportError:
  55. import functools
  56. class _ContextDecorator: # type: ignore[no-redef]
  57. def __enter__(self):
  58. raise NotImplementedError
  59. def __exit__(self, exc_type, exc_val, exc_tb):
  60. raise NotImplementedError
  61. def __call__(self, func):
  62. @functools.wraps(func)
  63. def wrapped(*args, **kwargs):
  64. with self:
  65. return func(*args, **kwargs)
  66. return wrapped
  67. # global python state - whether profiler is currently enabled
  68. # useful for fast python checks to reduce latency
  69. _is_profiler_enabled: bool = False
  70. def _set_is_profiler_enabled(enable: bool):
  71. global _is_profiler_enabled
  72. _is_profiler_enabled = enable
  73. def _run_on_profiler_start():
  74. _set_is_profiler_enabled(True)
  75. def _run_on_profiler_stop():
  76. _set_is_profiler_enabled(False)
  77. @dataclass
  78. class _ProfilerStats:
  79. "Profiler timing and stats used by developers to catch issues/regressions"
  80. profiling_window_duration_sec: float = 0
  81. number_of_events: int = 0
  82. profiler_prepare_call_duration_us: int = 0
  83. profiler_enable_call_duration_us: int = 0
  84. profiler_disable_call_duration_us: int = 0
  85. parse_kineto_call_duration_us: int = 0
  86. function_events_build_tree_call_duration_us: int = 0
  87. class profile:
  88. """Context manager that manages autograd profiler state and holds a summary of results.
  89. .. note::
  90. This is the backend, most people should use :mod:`torch.profiler` instead.
  91. Under the hood it just records events of functions being executed in C++ and
  92. exposes those events to Python. You can wrap any code into it and it will
  93. only report runtime of PyTorch functions.
  94. Note: profiler is thread local and is automatically propagated into the async tasks
  95. Args:
  96. enabled (bool, optional): Setting this to False makes this context manager a no-op.
  97. use_cuda (bool, optional): Enables timing of CUDA events as well
  98. using the cudaEvent API. (will be deprecated)
  99. use_device (str, optional): Enables timing of device events.
  100. Adds approximately 4us of overhead to each tensor operation when use cuda.
  101. The valid devices options are 'cuda', 'xpu', 'mtia' and 'privateuseone'.
  102. record_shapes (bool, optional): If shapes recording is set, information
  103. about input dimensions will be collected. This allows one to see which
  104. dimensions have been used under the hood and further group by them
  105. using prof.key_averages(group_by_input_shape=True). Please note that
  106. shape recording might skew your profiling data. It is recommended to
  107. use separate runs with and without shape recording to validate the timing.
  108. Most likely the skew will be negligible for bottom most events (in a case
  109. of nested function calls). But for higher level functions the total
  110. self cpu time might be artificially increased because of the shape
  111. collection.
  112. with_flops (bool, optional): If with_flops is set, the profiler will estimate
  113. the FLOPs (floating point operations) value using the operator's input shape.
  114. This allows one to estimate the hardware performance. Currently,
  115. this option only works for the matrix multiplication and 2D convolution operators.
  116. profile_memory (bool, optional): track tensor memory allocation/deallocation.
  117. with_stack (bool, optional): record source information (file and line number) for the ops.
  118. with_modules (bool): record module hierarchy (including function names)
  119. corresponding to the callstack of the op. e.g. If module A's forward call's
  120. module B's forward which contains an aten::add op,
  121. then aten::add's module hierarchy is A.B
  122. Note that this support exist, at the moment, only for TorchScript models
  123. and not eager mode models.
  124. use_kineto (bool, optional): experimental, enable profiling with Kineto profiler.
  125. use_cpu (bool, optional): profile CPU events; setting to ``False`` requires
  126. ``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling.
  127. experimental_config (_ExperimentalConfig) : A set of experimental options
  128. used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.
  129. acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles
  130. .. warning::
  131. Enabling memory profiling or source attribution incurs additional profiler
  132. overhead
  133. .. warning::
  134. This context managers should not be called recursively, i.e. no nested
  135. instances are allowed
  136. .. warning::
  137. Due to some CUDA multiprocessing limitations (see :ref:`multiprocessing-cuda-note`),
  138. one cannot use the profiler with ``use_device = 'cuda'`` to benchmark
  139. DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading,
  140. please use ``use_device = None`` or ``num_workers = 0``.
  141. Example:
  142. >>> # xdoctest: +SKIP
  143. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
  144. >>> x = torch.randn((1, 1), requires_grad=True)
  145. >>> with torch.autograd.profiler.profile() as prof:
  146. >>> for _ in range(100): # any normal python code, really!
  147. >>> y = x ** 2
  148. >>> y.backward()
  149. >>> # NOTE: some columns were removed for brevity
  150. >>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
  151. ----------------------------------- --------------- --------------- ---------------
  152. Name Self CPU total CPU time avg Number of Calls
  153. ----------------------------------- --------------- --------------- ---------------
  154. mul 32.048ms 32.048ms 200
  155. pow 27.041ms 27.041ms 200
  156. PowBackward0 9.727ms 55.483ms 100
  157. torch::autograd::AccumulateGrad 9.148ms 9.148ms 100
  158. torch::autograd::GraphRoot 691.816us 691.816us 100
  159. ----------------------------------- --------------- --------------- ---------------
  160. """
  161. def __init__(
  162. self,
  163. enabled=True,
  164. *,
  165. use_cuda=False, # Deprecated
  166. use_device=None,
  167. record_shapes=False,
  168. with_flops=False,
  169. profile_memory=False,
  170. with_stack=False,
  171. with_modules=False,
  172. use_kineto=False,
  173. use_cpu=True,
  174. experimental_config=None,
  175. acc_events=False,
  176. custom_trace_id_callback=None,
  177. ):
  178. self.enabled: bool = enabled
  179. if not self.enabled:
  180. return
  181. self.use_cuda = use_cuda
  182. if self.use_cuda:
  183. warn(
  184. "The attribute `use_cuda` will be deprecated soon, "
  185. "please use ``use_device = 'cuda'`` instead.",
  186. FutureWarning,
  187. stacklevel=2,
  188. )
  189. self.use_device: Optional[str] = "cuda"
  190. else:
  191. self.use_device = use_device
  192. # TODO Consider changing _function_events into data structure with size cap
  193. self._function_events: Optional[EventList] = None
  194. self._old_function_events: Optional[EventList] = None
  195. # Function event processing is done lazily
  196. self._needs_processing = False
  197. self.entered = False
  198. self.record_shapes = record_shapes
  199. self.with_flops = with_flops
  200. self.record_shapes |= self.with_flops
  201. self.profile_memory = profile_memory
  202. self.with_stack = with_stack
  203. self.with_modules = with_modules
  204. self.use_cpu = use_cpu
  205. self.acc_events = acc_events
  206. if experimental_config is None:
  207. experimental_config = _ExperimentalConfig()
  208. self.experimental_config = experimental_config
  209. self.kineto_results: Optional[_ProfilerResult] = None
  210. self.profiling_start_time_ns = 0
  211. self.profiling_end_time_ns = 0
  212. self._stats = _ProfilerStats()
  213. self.custom_trace_id_callback = custom_trace_id_callback
  214. self.trace_id = ""
  215. if not self.use_cpu:
  216. assert use_kineto, (
  217. "Device-only events supported only with Kineto (use_kineto=True)"
  218. )
  219. if self.use_device is not None:
  220. VALID_DEVICE_OPTIONS = ["cuda", "xpu", "mtia", "hpu"]
  221. if _get_privateuse1_backend_name() != "privateuseone":
  222. VALID_DEVICE_OPTIONS.append(_get_privateuse1_backend_name())
  223. if self.use_device not in VALID_DEVICE_OPTIONS:
  224. warn(f"The {self.use_device} is not a valid device option.")
  225. self.use_device = None
  226. if self.use_device == "cuda" and not torch.cuda.is_available():
  227. warn("CUDA is not available, disabling CUDA profiling")
  228. self.use_cuda = False
  229. self.use_device = None
  230. if self.use_device == "xpu" and not torch.xpu.is_available():
  231. warn("XPU is not available, disabling XPU profiling")
  232. self.use_device = None
  233. if self.use_device == "hpu" and not (
  234. hasattr(torch, "hpu") and torch.hpu.is_available()
  235. ):
  236. warn("HPU is not available, disabling HPU profiling")
  237. self.use_device = None
  238. self.kineto_activities = set()
  239. if self.use_cpu:
  240. self.kineto_activities.add(ProfilerActivity.CPU)
  241. self.profiler_kind = ProfilerState.KINETO
  242. if self.use_device == "cuda":
  243. if not use_kineto or ProfilerActivity.CUDA not in _supported_activities():
  244. assert self.use_cpu, "Legacy CUDA profiling requires use_cpu=True"
  245. self.profiler_kind = ProfilerState.KINETO_GPU_FALLBACK
  246. else:
  247. self.kineto_activities.add(ProfilerActivity.CUDA)
  248. elif self.use_device == "xpu":
  249. assert use_kineto and ProfilerActivity.XPU in _supported_activities(), (
  250. "Legacy XPU profiling is not supported. Requires use_kineto=True on XPU devices."
  251. )
  252. self.kineto_activities.add(ProfilerActivity.XPU)
  253. elif self.use_device == "mtia":
  254. assert use_kineto and ProfilerActivity.MTIA in _supported_activities(), (
  255. "Legacy MTIA profiling is not supported. Requires use_kineto=True on MTIA devices."
  256. )
  257. self.kineto_activities.add(ProfilerActivity.MTIA)
  258. elif self.use_device == "hpu":
  259. assert use_kineto and ProfilerActivity.HPU in _supported_activities(), (
  260. "Legacy HPU profiling is not supported. Requires use_kineto=True on HPU devices."
  261. )
  262. self.kineto_activities.add(ProfilerActivity.HPU)
  263. elif self.use_device is not None and self.use_device != "privateuseone":
  264. if (
  265. not use_kineto
  266. or ProfilerActivity.PrivateUse1 not in _supported_activities()
  267. ):
  268. assert self.use_cpu, (
  269. "Legacy custombackend profiling requires use_cpu=True"
  270. )
  271. self.profiler_kind = ProfilerState.KINETO_PRIVATEUSE1_FALLBACK
  272. else:
  273. self.kineto_activities.add(ProfilerActivity.PrivateUse1)
  274. assert len(self.kineto_activities) > 0, (
  275. "No activities specified for the profiler"
  276. )
  277. def default_trace_id(self):
  278. # Generate a UUID
  279. uuid_raw = uuid.uuid4()
  280. return f"{uuid_raw.int:032X}"
  281. def create_trace_id(self):
  282. if self.custom_trace_id_callback:
  283. return self.custom_trace_id_callback()
  284. return self.default_trace_id()
  285. def config(self, create_trace_id=False):
  286. # only need to generate new trace id upon prepare trace not start trace
  287. if create_trace_id:
  288. trace_id = self.create_trace_id()
  289. self.trace_id = trace_id
  290. return ProfilerConfig(
  291. self.profiler_kind,
  292. self.record_shapes,
  293. self.profile_memory,
  294. self.with_stack,
  295. self.with_flops,
  296. self.with_modules,
  297. self.experimental_config,
  298. self.trace_id,
  299. )
  300. def __enter__(self):
  301. if not self.enabled:
  302. return
  303. if self.entered:
  304. raise RuntimeError("Profiler context manager is not reentrant")
  305. self._prepare_trace()
  306. self._start_trace()
  307. return self
  308. def _prepare_trace(self):
  309. self.entered = True
  310. t0 = perf_counter_ns()
  311. _prepare_profiler(self.config(create_trace_id=True), self.kineto_activities)
  312. t1 = perf_counter_ns()
  313. self._stats.profiler_prepare_call_duration_us = int((t1 - t0) / 1000)
  314. def _start_trace(self):
  315. self.entered = True
  316. _run_on_profiler_start()
  317. t0 = perf_counter_ns()
  318. _enable_profiler(self.config(create_trace_id=False), self.kineto_activities)
  319. t1 = perf_counter_ns()
  320. self._stats.profiler_enable_call_duration_us = int((t1 - t0) / 1000)
  321. self.profiling_start_time_ns = t1
  322. def __exit__(self, exc_type, exc_val, exc_tb):
  323. if not self.enabled:
  324. return
  325. if self.use_device and hasattr(torch, self.use_device):
  326. device_module = getattr(torch, self.use_device)
  327. if hasattr(device_module, "synchronize"):
  328. device_module.synchronize()
  329. if self._function_events and self.acc_events:
  330. self._old_function_events = self._function_events
  331. self._function_events = None
  332. self._needs_processing = True
  333. t0 = perf_counter_ns()
  334. self.kineto_results = _disable_profiler()
  335. t1 = perf_counter_ns()
  336. self._stats.profiler_disable_call_duration_us = int((t1 - t0) / 1000)
  337. self.profiling_end_time_ns = t0
  338. _run_on_profiler_stop()
  339. self._stats.profiling_window_duration_sec = (
  340. (self.profiling_end_time_ns - self.profiling_start_time_ns) * 1.0 / 1e9
  341. )
  342. # If we plan to accumulate events we should post process the function events
  343. # right away to retain the state across multiple start/stop calls
  344. if self.acc_events:
  345. self._ensure_function_events()
  346. return False
  347. def __repr__(self):
  348. if self._needs_processing:
  349. self._ensure_function_events()
  350. if self._function_events is None:
  351. return "<unfinished torch.autograd.profile>"
  352. return repr(self._function_events)
  353. def __str__(self):
  354. if self._needs_processing:
  355. self._ensure_function_events()
  356. if self._function_events is None:
  357. return "<unfinished torch.autograd.profile>"
  358. return str(self._function_events)
  359. def _ensure_function_events(self):
  360. """Process function events lazily if required"""
  361. if self._function_events is not None:
  362. return
  363. self._needs_processing = False
  364. t0 = perf_counter_ns()
  365. parsed_results = []
  366. if self.kineto_results:
  367. parsed_results = self._parse_kineto_results(self.kineto_results)
  368. t1 = perf_counter_ns()
  369. self._stats.parse_kineto_call_duration_us = int((t1 - t0) / 1000)
  370. self._function_events = EventList(
  371. parsed_results,
  372. use_device=self.use_device,
  373. profile_memory=self.profile_memory,
  374. with_flops=self.with_flops,
  375. )
  376. t0 = perf_counter_ns()
  377. self._function_events._build_tree()
  378. t1 = perf_counter_ns()
  379. self._stats.function_events_build_tree_call_duration_us = int((t1 - t0) / 1000)
  380. self._stats.number_of_events = len(self._function_events)
  381. if self._old_function_events and self.acc_events:
  382. for evt in self._old_function_events:
  383. self._function_events.append(evt)
  384. self._old_function_events = None
  385. if self._function_events is None:
  386. raise RuntimeError("Profiler didn't finish running")
  387. @property
  388. def function_events(self):
  389. if self._function_events is None or self._needs_processing:
  390. self._ensure_function_events()
  391. return self._function_events
  392. def table(
  393. self,
  394. sort_by=None,
  395. row_limit=100,
  396. max_src_column_width=75,
  397. max_name_column_width=55,
  398. max_shapes_column_width=80,
  399. header=None,
  400. top_level_events_only=False,
  401. ):
  402. self._ensure_function_events()
  403. assert self._function_events is not None
  404. return self._function_events.table(
  405. sort_by=sort_by,
  406. row_limit=row_limit,
  407. max_src_column_width=max_src_column_width,
  408. max_name_column_width=max_name_column_width,
  409. max_shapes_column_width=max_shapes_column_width,
  410. header=header,
  411. top_level_events_only=top_level_events_only,
  412. )
  413. table.__doc__ = EventList.table.__doc__
  414. def export_chrome_trace(self, path):
  415. """
  416. Exports the collected trace in Chrome JSON format. If kineto is enabled, only
  417. last cycle in schedule is exported.
  418. """
  419. if kineto_available():
  420. self.kineto_results.save(path) # type: ignore[union-attr]
  421. else:
  422. self._ensure_function_events()
  423. return self._function_events.export_chrome_trace(path) # type: ignore[union-attr]
  424. export_chrome_trace.__doc__ = EventList.export_chrome_trace.__doc__
  425. def export_stacks(self, path: str, metric: str = "self_cpu_time_total"):
  426. self._ensure_function_events()
  427. assert self._function_events is not None, "Expected profiling results"
  428. assert self.with_stack, "export_stacks() requires with_stack=True"
  429. return self._function_events.export_stacks(path, metric)
  430. def toggle_collection_dynamic(
  431. self, enabled: bool, activities: Iterable[ProfilerActivity]
  432. ):
  433. """
  434. Toggles the collection of activities for the current profiler instance.
  435. """
  436. return _toggle_collection_dynamic(enabled, set(activities))
  437. def key_averages(
  438. self,
  439. group_by_input_shape=False,
  440. group_by_stack_n=0,
  441. group_by_overload_name=False,
  442. ):
  443. self._ensure_function_events()
  444. assert self._function_events is not None, "Expected profiling results"
  445. return self._function_events.key_averages(
  446. group_by_input_shape, group_by_stack_n, group_by_overload_name
  447. )
  448. key_averages.__doc__ = EventList.key_averages.__doc__
  449. def total_average(self):
  450. self._ensure_function_events()
  451. assert self._function_events is not None, "Expected profiling results"
  452. return self._function_events.total_average()
  453. total_average.__doc__ = EventList.total_average.__doc__
  454. @property
  455. def self_cpu_time_total(self):
  456. """Returns total time spent on CPU.
  457. The total time is a sum of all self times across all the events.
  458. """
  459. self._ensure_function_events()
  460. assert self._function_events is not None
  461. return self._function_events.self_cpu_time_total
  462. def _parse_kineto_results(self, result: _ProfilerResult):
  463. # result.events() has most of the events - PyTorch op-level and device-level events
  464. trace_start_ns = result.trace_start_ns()
  465. mem_records = [
  466. [evt, False] for evt in result.events() if evt.name() == MEMORY_EVENT_NAME
  467. ]
  468. oom_records = [
  469. evt for evt in result.events() if evt.name() == OUT_OF_MEMORY_EVENT_NAME
  470. ]
  471. mem_records_acc = MemRecordsAcc(mem_records)
  472. def _cpu_memory_usage(mem_record):
  473. return (
  474. mem_record.nbytes()
  475. if mem_record.device_type()
  476. in [DeviceType.CPU, DeviceType.MKLDNN, DeviceType.IDEEP]
  477. else 0
  478. )
  479. def _device_memory_usage(mem_record):
  480. return (
  481. mem_record.nbytes()
  482. if mem_record.device_type()
  483. in [
  484. DeviceType.CUDA,
  485. DeviceType.PrivateUse1,
  486. DeviceType.HIP,
  487. DeviceType.XPU,
  488. ]
  489. else 0
  490. )
  491. # Create and return FunctionEvent list, which contains all function events
  492. # Here 2 function events are created:
  493. # all_function_events contains all events associated with each kineto event from result
  494. all_function_events = []
  495. # frontend_function_events contains the events in aten or torch frontend level,
  496. # whose correlation id is 0
  497. frontend_function_events = []
  498. device_corr_map: dict[int, list[FunctionEvent]] = {}
  499. max_evt_id = 0
  500. for kineto_event in result.events():
  501. if (
  502. _filter_name(kineto_event.name())
  503. or getattr(kineto_event, "is_hidden_event", lambda: False)()
  504. ):
  505. continue
  506. rel_start_ns = kineto_event.start_ns() - trace_start_ns
  507. rel_end_ns = kineto_event.end_ns() - trace_start_ns
  508. abs_end_ns = kineto_event.end_ns()
  509. cpu_memory_usage = 0
  510. device_memory_usage = 0
  511. if kineto_event.device_type() == DeviceType.CPU:
  512. # find the corresponding memory allocation events
  513. for mem_record in mem_records_acc.in_interval(
  514. kineto_event.start_ns() / 1000, abs_end_ns / 1000
  515. ):
  516. cpu_memory_usage += _cpu_memory_usage(mem_record[0])
  517. device_memory_usage += _device_memory_usage(mem_record[0])
  518. mem_record[1] = True
  519. is_async = kineto_event.is_async() or (
  520. kineto_event.start_thread_id() != kineto_event.end_thread_id()
  521. )
  522. fe = FunctionEvent(
  523. id=kineto_event.correlation_id(),
  524. name=_rewrite_name(name=kineto_event.name(), with_wildcard=True),
  525. overload_name=kineto_event.overload_name(),
  526. trace_name=_rewrite_name(name=kineto_event.name(), with_wildcard=False),
  527. thread=kineto_event.start_thread_id(),
  528. start_us=rel_start_ns / 1000,
  529. end_us=rel_end_ns / 1000,
  530. fwd_thread=kineto_event.fwd_thread_id(),
  531. input_shapes=kineto_event.shapes(),
  532. concrete_inputs=kineto_event.concrete_inputs(),
  533. kwinputs=kineto_event.kwinputs(),
  534. stack=[
  535. entry
  536. for entry in kineto_event.stack()
  537. if _filter_stack_entry(entry)
  538. ],
  539. scope=kineto_event.scope(),
  540. use_device=self.use_device,
  541. cpu_memory_usage=cpu_memory_usage,
  542. device_memory_usage=device_memory_usage,
  543. is_async=is_async,
  544. sequence_nr=kineto_event.sequence_nr(),
  545. device_type=kineto_event.device_type(),
  546. device_index=kineto_event.device_index(),
  547. device_resource_id=kineto_event.device_resource_id(),
  548. flops=kineto_event.flops(),
  549. is_user_annotation=kineto_event.is_user_annotation(),
  550. )
  551. max_evt_id = max(max_evt_id, fe.id)
  552. if fe.device_type == DeviceType.CPU and not fe.is_async:
  553. if self.use_device == _get_privateuse1_backend_name():
  554. privateuse1_time = kineto_event.privateuse1_elapsed_us()
  555. if privateuse1_time > 0:
  556. fe.append_kernel(fe.name, fe.device_index, privateuse1_time)
  557. fe.is_legacy = True
  558. elif self.use_device == "cuda":
  559. # Check if we have CUDA time as a fallback
  560. cuda_time = kineto_event.cuda_elapsed_us()
  561. if cuda_time > 0:
  562. fe.append_kernel(fe.name, fe.device_index, cuda_time)
  563. fe.is_legacy = True
  564. all_function_events.append(fe)
  565. corr_id = kineto_event.linked_correlation_id()
  566. if corr_id > 0:
  567. if corr_id not in device_corr_map:
  568. device_corr_map[corr_id] = []
  569. device_corr_map[corr_id].append(fe)
  570. elif corr_id == 0:
  571. frontend_function_events.append(fe)
  572. else:
  573. raise RuntimeError(
  574. f"Got negative correlation id {corr_id} in profiler post processing"
  575. )
  576. # associate device kernels and device runtime (CPU) with CPU events
  577. for fe in frontend_function_events:
  578. if (
  579. fe.device_type == DeviceType.CPU
  580. and not fe.is_async
  581. and fe.id in device_corr_map
  582. ):
  583. for f_evt in device_corr_map[fe.id]:
  584. if (
  585. f_evt.device_type == DeviceType.CUDA
  586. or f_evt.device_type == DeviceType.PrivateUse1
  587. ):
  588. fe.append_kernel(
  589. f_evt.name,
  590. f_evt.device_index,
  591. f_evt.time_range.end - f_evt.time_range.start,
  592. )
  593. elif f_evt.device_type == DeviceType.CPU:
  594. # make sure that 'thread' of a CPU Kineto (e.g. Device Runtime) event is associated
  595. # with the 'thread' of the corresponding linked PyTorch event to properly track
  596. # parents and children
  597. f_evt.thread = fe.thread
  598. def createFunctionEventForMemoryEvents(evt):
  599. rel_start_ns = evt.start_ns() - trace_start_ns
  600. fe = FunctionEvent(
  601. id=max_evt_id,
  602. name=evt.name(),
  603. overload_name="",
  604. trace_name=None, # not outputting in the trace
  605. thread=evt.start_thread_id(),
  606. start_us=rel_start_ns / 1000,
  607. end_us=rel_start_ns / 1000, # no duration
  608. fwd_thread=evt.start_thread_id(),
  609. input_shapes=[],
  610. stack=[],
  611. scope=0, # RecordScope::FUNCTION
  612. use_device=self.use_device,
  613. cpu_memory_usage=_cpu_memory_usage(evt),
  614. device_memory_usage=_device_memory_usage(evt),
  615. is_async=False,
  616. sequence_nr=-1,
  617. device_type=DeviceType.CPU,
  618. device_index=0,
  619. )
  620. return fe
  621. # output top-level memory events
  622. for mem_record in mem_records:
  623. if not mem_record[1]:
  624. max_evt_id += 1
  625. fe = createFunctionEventForMemoryEvents(mem_record[0])
  626. all_function_events.append(fe)
  627. for oom_record in oom_records:
  628. max_evt_id += 1
  629. fe = createFunctionEventForMemoryEvents(oom_record)
  630. all_function_events.append(fe)
  631. all_function_events.sort(
  632. key=lambda evt: [evt.time_range.start, -evt.time_range.end]
  633. )
  634. return all_function_events
  635. class record_function(_ContextDecorator):
  636. """Context manager/function decorator that adds a label to a code block/function when running autograd profiler.
  637. Label will only appear if CPU activity tracing is enabled.
  638. It is useful when tracing the code profile.
  639. Args:
  640. name (str): Label assigned to the block of code.
  641. node_id (int): ID of node, for distributed profiling. Unset in
  642. non-distributed cases.
  643. Example:
  644. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
  645. >>> x = torch.randn((1, 1), requires_grad=True)
  646. >>> with torch.autograd.profiler.profile() as prof:
  647. ... y = x**2
  648. ... with torch.autograd.profiler.record_function(
  649. ... "label-z"
  650. ... ): # label the block
  651. ... z = y**3
  652. ... y.backward()
  653. >>> # xdoctest: +IGNORE_WANT
  654. >>> # NOTE: some columns were removed for brevity
  655. >>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
  656. ----------------------------------- --------------- --------------- ---------------
  657. Name Self CPU total % CPU time avg Number of Calls
  658. ----------------------------------- --------------- --------------- ---------------
  659. pow 60.77% 47.470us 3
  660. mul 21.73% 25.465us 2
  661. PowBackward0 12.03% 121.891us 1
  662. torch::autograd::AccumulateGrad 2.70% 6.324us 1
  663. label-z 2.13% 12.421us 1
  664. torch::autograd::GraphRoot 0.64% 1.503us 1
  665. ----------------------------------- --------------- --------------- ---------------
  666. Self CPU time total: 234.344us
  667. CUDA time total: 0.000us
  668. """
  669. def __init__(self, name: str, args: Optional[str] = None):
  670. self.name: str = name
  671. self.args: Optional[str] = args
  672. # Whether or not we should run record function's end callbacks when exiting.
  673. self.run_callbacks_on_exit: bool = True
  674. # TODO: TorchScript ignores standard type annotation here
  675. # self.record: Optional["torch.classes.profiler._RecordFunction"] = None
  676. self.record = torch.jit.annotate(
  677. Optional["torch.classes.profiler._RecordFunction"], None
  678. )
  679. def __enter__(self):
  680. self.record = torch.ops.profiler._record_function_enter_new(
  681. self.name, self.args
  682. )
  683. return self
  684. def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any):
  685. if not self.run_callbacks_on_exit:
  686. return
  687. # Local variable is needed by TorchScript to refine Optional[T] to T
  688. record = self.record
  689. assert record is not None
  690. # TODO: Too slow with __torch_function__ handling enabled
  691. # See https://github.com/pytorch/pytorch/issues/76410
  692. if not torch.jit.is_scripting():
  693. with torch._C.DisableTorchFunctionSubclass():
  694. torch.ops.profiler._record_function_exit._RecordFunction(record)
  695. else:
  696. torch.ops.profiler._record_function_exit(record)
  697. def _call_end_callbacks_on_future(self, fut: Future[Any]) -> Future[Any]:
  698. """Use for profiling async calls that return a future.
  699. Calling this function will extend recording beyond this scope, until the future is
  700. satisfied. It is useful for profiling the end to end time of asynchronous calls.
  701. This function should only be called once to attach the callback onto the future, and
  702. will throw if called multiple times.
  703. Args:
  704. fut: (torch._C.Future): future for which to schedule
  705. callback for.
  706. Returns:
  707. A future that completes with the value of the passed in future when
  708. the profiling callbacks have ran.
  709. """
  710. # Throw if we have already attached a callback onto the future.
  711. if not self.run_callbacks_on_exit:
  712. raise RuntimeError("_call_end_callbacks_on_future can only be called once.")
  713. # We are scheduling to run this RecordFunction's end callbacks when the
  714. # passed in future completes, so don't run end callbacks on exit.
  715. self.run_callbacks_on_exit = False
  716. # Local variable is needed by TorchScript to refine Optional[T] to T
  717. record = self.record
  718. assert record is not None
  719. # TODO: Too slow with __torch_function__ handling enabled
  720. # See https://github.com/pytorch/pytorch/issues/76410
  721. if not torch.jit.is_scripting():
  722. with torch._C.DisableTorchFunctionSubclass():
  723. profiled_future = (
  724. torch.ops.profiler._call_end_callbacks_on_jit_fut._RecordFunction(
  725. record, fut
  726. )
  727. )
  728. else:
  729. profiled_future = torch.ops.profiler._call_end_callbacks_on_jit_fut(
  730. record, fut
  731. )
  732. return profiled_future
  733. class emit_itt:
  734. """Context manager that makes every autograd operation emit an ITT range.
  735. It is useful when running the program under Intel(R) VTune Profiler::
  736. vtune <--vtune-flags> <regular command here>
  737. The Instrumentation and Tracing Technology (ITT) API enables your application to generate and
  738. control the collection of trace data during its execution across different Intel tools.
  739. This context manager is to annotate Intel(R) VTune Profiling trace. With help of this context manager,
  740. you will be able to see labeled ranges in Intel(R) VTune Profiler GUI.
  741. .. warning:
  742. This context manager should not be called recursively, i.e. at most one
  743. instance should be enabled at any given time.
  744. Args:
  745. enabled (bool, optional): Setting ``enabled=False`` makes this context manager a no-op.
  746. Default: ``True``.
  747. record_shapes (bool, optional): If ``record_shapes=True``, the itt range wrapping
  748. each autograd op will append information about the sizes of Tensor arguments received
  749. by that op, in the following format:
  750. ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]``
  751. Non-tensor arguments will be represented by ``[]``.
  752. Arguments will be listed in the order they are received by the backend op.
  753. Please note that this order may not match the order in which those arguments were passed
  754. on the Python side. Also note that shape recording may increase the overhead of itt range creation.
  755. Default: ``False``
  756. Example:
  757. >>> # xdoctest: +SKIP("Undefined variables")
  758. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
  759. >>> with torch.autograd.profiler.emit_itt():
  760. ... model(x)
  761. """
  762. def __init__(self, enabled=True, record_shapes=False):
  763. self.enabled = enabled
  764. self.entered = False
  765. self.record_shapes = record_shapes
  766. def __enter__(self):
  767. if not self.enabled:
  768. return
  769. if self.entered:
  770. raise RuntimeError("ITT annotation context manager is not reentrant")
  771. self.entered = True
  772. _run_on_profiler_start()
  773. _enable_profiler(
  774. ProfilerConfig(
  775. ProfilerState.ITT,
  776. self.record_shapes,
  777. False,
  778. False,
  779. False,
  780. False,
  781. _ExperimentalConfig(),
  782. ),
  783. set(),
  784. )
  785. return self
  786. def __exit__(self, exc_type, exc_val, exc_tb):
  787. if not self.enabled:
  788. return
  789. _disable_profiler()
  790. _run_on_profiler_stop()
  791. return False
  792. class emit_nvtx:
  793. """Context manager that makes every autograd operation emit an NVTX range.
  794. It is useful when running the program under nvprof::
  795. nvprof --profile-from-start off -o trace_name.prof -- <regular command here>
  796. Unfortunately, there's no way to force nvprof to flush the data it collected
  797. to disk, so for CUDA profiling one has to use this context manager to annotate
  798. nvprof traces and wait for the process to exit before inspecting them.
  799. Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or
  800. :func:`torch.autograd.profiler.load_nvprof` can load the results for inspection
  801. e.g. in Python REPL.
  802. .. warning:
  803. This context manager should not be called recursively, i.e. at most one
  804. instance should be enabled at any given time.
  805. Args:
  806. enabled (bool, optional): Setting ``enabled=False`` makes this context manager a no-op.
  807. Default: ``True``.
  808. record_shapes (bool, optional): If ``record_shapes=True``, the nvtx range wrapping
  809. each autograd op will append information about the sizes of Tensor arguments received
  810. by that op, in the following format:
  811. ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]``
  812. Non-tensor arguments will be represented by ``[]``.
  813. Arguments will be listed in the order they are received by the backend op.
  814. Please note that this order may not match the order in which those arguments were passed
  815. on the Python side. Also note that shape recording may increase the overhead of nvtx range creation.
  816. Default: ``False``
  817. Example:
  818. >>> # xdoctest: +SKIP("undefined variables")
  819. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
  820. >>> with torch.cuda.profiler.profile():
  821. ... model(x) # Warmup CUDA memory allocator and profiler
  822. ... with torch.autograd.profiler.emit_nvtx():
  823. ... model(x)
  824. **Forward-backward correlation**
  825. When viewing a profile created using :class:`emit_nvtx` in the Nvidia Visual Profiler,
  826. correlating each backward-pass op with the corresponding forward-pass op can be difficult.
  827. To ease this task, :class:`emit_nvtx` appends sequence number information to the ranges it
  828. generates.
  829. During the forward pass, each function range is decorated with ``seq=<N>``. ``seq`` is a running
  830. counter, incremented each time a new backward Function object is created and stashed for backward.
  831. Thus, the ``seq=<N>`` annotation associated with each forward function range tells you that
  832. if a backward Function object is created by this forward function,
  833. the backward object will receive sequence number N.
  834. During the backward pass, the top-level range wrapping each C++ backward Function's
  835. ``apply()`` call is decorated with ``stashed seq=<M>``. ``M`` is the sequence number that
  836. the backward object was created with. By comparing ``stashed seq`` numbers in backward with ``seq``
  837. numbers in forward, you can track down which forward op created each backward Function.
  838. Any functions executed during the backward pass are also decorated with ``seq=<N>``. During
  839. default backward (with ``create_graph=False``) this information is irrelevant, and in fact,
  840. ``N`` may simply be 0 for all such functions. Only the top-level ranges associated with
  841. backward Function objects' ``apply()`` methods are useful, as a way to correlate these Function
  842. objects with the earlier forward pass.
  843. **Double-backward**
  844. If, on the other hand, a backward pass with ``create_graph=True`` is underway (in other words,
  845. if you are setting up for a double-backward), each function's execution during backward
  846. is given a nonzero, useful ``seq=<N>``. Those functions may themselves create Function objects
  847. to be executed later during double-backward, just as the original functions in the forward pass did.
  848. The relationship between backward and double-backward is conceptually the same as the relationship
  849. between forward and backward: The functions still emit current-sequence-number-tagged ranges,
  850. the Function objects they create still stash those sequence numbers, and during the eventual
  851. double-backward, the Function objects' ``apply()`` ranges are still tagged with ``stashed seq``
  852. numbers, which can be compared to `seq` numbers from the backward pass.
  853. .. warning:
  854. The sequence number is thread-local, and some forward functions don't create an associated
  855. backward Function object (instead delegating that to sub-functions further down the call chain).
  856. For these reasons, the correspondence of stashed sequence numbers in
  857. backward Function ``apply()`` ranges with `seq` numbers in forward-pass ranges is
  858. not guaranteed to be 1 to 1. The sequence numbers alone may not be enough to fully
  859. disambiguate which forward function created which
  860. backward Function object. You may need to make a judgment based on analytic knowledge of what
  861. the expected correspondence should be.
  862. """
  863. def __init__(self, enabled=True, record_shapes=False):
  864. self.enabled = enabled
  865. self.entered = False
  866. self.record_shapes = record_shapes
  867. def __enter__(self):
  868. if not self.enabled:
  869. return
  870. if self.entered:
  871. raise RuntimeError("NVTX annotation context manager is not reentrant")
  872. self.entered = True
  873. torch.cuda.synchronize()
  874. _run_on_profiler_start()
  875. _enable_profiler(
  876. ProfilerConfig(
  877. ProfilerState.NVTX,
  878. self.record_shapes,
  879. False,
  880. False,
  881. False,
  882. False,
  883. _ExperimentalConfig(),
  884. ),
  885. set(),
  886. )
  887. return self
  888. def __exit__(self, exc_type, exc_val, exc_tb):
  889. if not self.enabled:
  890. return
  891. torch.cuda.synchronize()
  892. _disable_profiler()
  893. _run_on_profiler_stop()
  894. return False
  895. def load_nvprof(path):
  896. """Open an nvprof trace file and parses autograd annotations.
  897. Args:
  898. path (str): path to nvprof trace
  899. """
  900. return EventList(parse_nvprof_trace(path))
  901. class EnforceUnique:
  902. """Raises an error if a key is seen more than once."""
  903. def __init__(self):
  904. self.seen = set()
  905. def see(self, *key):
  906. r"""
  907. Observe a key and raise an error if it is seen multiple times.
  908. """
  909. if key in self.seen:
  910. raise RuntimeError("duplicate key: " + str(key))
  911. self.seen.add(key)
  912. def parse_nvprof_trace(path):
  913. import sqlite3
  914. conn = sqlite3.connect(path)
  915. conn.row_factory = sqlite3.Row
  916. # Parse strings table
  917. strings = {}
  918. for r in conn.execute("SELECT _id_ as id, value FROM StringTable"):
  919. strings[r["id"]] = torch._C._demangle(r["value"])
  920. # First, find all functions and create FunctionEvents for them
  921. marker_query = """
  922. SELECT
  923. start.id AS marker_id, start.name, start.timestamp AS start_time, end.timestamp AS end_time
  924. FROM
  925. CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end
  926. ON start.id = end.id
  927. WHERE
  928. start.name != 0 AND end.name = 0
  929. """
  930. functions = []
  931. functions_map = {}
  932. unique = EnforceUnique()
  933. for row in conn.execute(marker_query):
  934. unique.see(row["marker_id"])
  935. evt = FunctionEvent(
  936. id=row["marker_id"],
  937. node_id=0, # missing a node_id when calling FunctionEvent. This is just to ensure
  938. # that pytorch doesn't crash when creating a FunctionEvent() object
  939. name=strings[row["name"]],
  940. start_us=row["start_time"],
  941. end_us=row["end_time"],
  942. thread=0,
  943. ) # TODO: find in sqlite database
  944. functions.append(evt)
  945. functions_map[evt.id] = evt
  946. # Now, correlate all kernels with FunctionEvents
  947. kernel_query = """
  948. SELECT
  949. start.id AS marker_id, start.name, start.timestamp, end.timestamp,
  950. runtime._id_ AS runtime_id, runtime.cbid, runtime.start AS runtime_start, runtime.end AS runtime_end,
  951. kernel.start AS kernel_start, kernel.end AS kernel_end, kernel.name AS kernel_name
  952. FROM
  953. CUPTI_ACTIVITY_KIND_MARKER AS start
  954. INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end
  955. ON start.id = end.id
  956. INNER JOIN CUPTI_ACTIVITY_KIND_RUNTIME as runtime
  957. ON (start.timestamp < runtime.start AND runtime.end < end.timestamp)
  958. INNER JOIN CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL AS kernel
  959. ON kernel.correlationId = runtime.correlationId
  960. """
  961. unique = EnforceUnique()
  962. for row in conn.execute(kernel_query):
  963. unique.see(row["marker_id"], row["runtime_id"])
  964. # 211 is cudaKernelLaunch for cuda >= 9.2
  965. assert row["cbid"] == 211
  966. evt = functions_map[row["marker_id"]]
  967. evt.append_kernel(
  968. row["kernel_name"], 0, row["kernel_end"] - row["kernel_start"]
  969. )
  970. functions.sort(key=lambda evt: evt.time_range.start)
  971. return functions
  972. class KinetoStepTracker:
  973. """Provides an abstraction for incrementing the step count globally.
  974. Previously, we only had one place to mark that a step() has occurred
  975. in the program via pytorch profiler step(). We will now add step hooks
  976. in the Optimizer class https://github.com/pytorch/pytorch/issues/88446
  977. - This could mean programs that already call profiler.step() every
  978. iteration can end up double incrementing step count.
  979. - If a model uses multiple optimizers we can also have double or more
  980. counting of the step.
  981. We fix this by adding a layer of abstraction before calling step()
  982. to the kineto library. The idea is to maintain steps per requester in a dict:
  983. .. code-block::
  984. {
  985. "ProfilerStep": 100, # triggered by profiler step() call
  986. "Optimizer1Step": 100, # Optimizer 1 or 2 are just examples, could be SGD, Adam etc
  987. "Optimizer2Step": 100,
  988. }
  989. To figure out the global step count just take the max of dict values (100).
  990. If one of the count increments the max will go up.
  991. .. code-block::
  992. {
  993. "ProfilerStep": 100,
  994. "Optimizer1Step": 101, # Optimizer1 got incremented first say
  995. "Optimizer2Step": 100,
  996. }
  997. Then global step count is 101
  998. We only call the kineto step() function when global count increments.
  999. NOTE: Please do not use the KinetoStepTracker in modules beside the Optimizer
  1000. for now. The result could be incorrect increments of the step count.
  1001. """
  1002. _current_step = 0
  1003. _step_dict: dict[str, int] = defaultdict(int)
  1004. @classmethod
  1005. def init_step_count(cls, requester: str):
  1006. r"""
  1007. Initialize for a given requester.
  1008. """
  1009. cls._step_dict[requester] = cls._current_step
  1010. @classmethod
  1011. def erase_step_count(cls, requester: str) -> bool:
  1012. r"""
  1013. Remove a given requester.
  1014. """
  1015. return cls._step_dict.pop(requester, None) is not None
  1016. @classmethod
  1017. def increment_step(cls, requester: str) -> int:
  1018. """Increments the step count for the requester.
  1019. Additionally if the max over all step counts has incremented then
  1020. trigger the _kineto_step() returns global step count
  1021. """
  1022. if requester not in cls._step_dict:
  1023. cls.init_step_count(requester)
  1024. cls._step_dict[requester] += 1
  1025. new_step = max(cls._step_dict.values())
  1026. if new_step > cls._current_step:
  1027. delta = new_step - cls._current_step
  1028. if delta > 1:
  1029. warn(
  1030. "Profiler step count has increased more than 1 - "
  1031. f"current_step = {cls._current_step} step dict = {cls._step_dict}"
  1032. )
  1033. for _ in range(0, delta):
  1034. _kineto_step()
  1035. cls._current_step = new_step
  1036. return cls._current_step
  1037. @classmethod
  1038. def current_step(cls) -> int:
  1039. r"""
  1040. Get the latest step for any requester
  1041. """
  1042. return cls._current_step