profiler.py 49 KB

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