profiler.py 51 KB

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