profiler.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. # mypy: allow-untyped-defs
  2. import gzip
  3. import json
  4. import os
  5. import shutil
  6. import tempfile
  7. from abc import ABC, abstractmethod
  8. from collections.abc import Callable, Iterable
  9. from enum import Enum
  10. from functools import partial
  11. from typing import Any, Optional
  12. from typing_extensions import deprecated, Self
  13. from warnings import warn
  14. import torch
  15. import torch.autograd.profiler as prof
  16. from torch._C import _get_privateuse1_backend_name
  17. from torch._C._profiler import (
  18. _add_execution_trace_observer,
  19. _disable_execution_trace_observer,
  20. _enable_execution_trace_observer,
  21. _ExperimentalConfig,
  22. _remove_execution_trace_observer,
  23. )
  24. from torch._environment import is_fbcode
  25. from torch._utils_internal import profiler_allow_cudagraph_cupti_lazy_reinit_cuda12
  26. from torch.autograd import kineto_available, ProfilerActivity
  27. from torch.profiler._memory_profiler import MemoryProfile, MemoryProfileTimeline
  28. __all__ = [
  29. "supported_activities",
  30. "ProfilerAction",
  31. "schedule",
  32. "tensorboard_trace_handler",
  33. "profile",
  34. "ExecutionTraceObserver",
  35. ]
  36. PROFILER_STEP_NAME = "ProfilerStep"
  37. _WARNINGS_SHOWN = set()
  38. def _warn_once(msg, category=UserWarning, stacklevel=2):
  39. if msg not in _WARNINGS_SHOWN:
  40. _WARNINGS_SHOWN.add(msg)
  41. warn(msg, category=category, stacklevel=stacklevel)
  42. class _NumpyEncoder(json.JSONEncoder):
  43. """
  44. Json encoder for numpy types (np.int, np.float, np.array etc.)
  45. Returns default encoder if numpy is not available
  46. """
  47. def default(self, obj):
  48. """Encode NumPy types to JSON"""
  49. try:
  50. import numpy as np
  51. except ImportError:
  52. return json.JSONEncoder.default(self, obj)
  53. if isinstance(obj, np.integer):
  54. return int(obj)
  55. elif isinstance(obj, np.floating):
  56. return float(obj)
  57. elif isinstance(obj, np.ndarray):
  58. return obj.tolist()
  59. else:
  60. return json.JSONEncoder.default(self, obj)
  61. def supported_activities():
  62. """
  63. Returns a set of supported profiler tracing activities.
  64. Note: profiler uses CUPTI library to trace on-device CUDA kernels.
  65. In case when CUDA is enabled but CUPTI is not available, passing
  66. ``ProfilerActivity.CUDA`` to profiler results in using the legacy CUDA
  67. profiling code (same as in the legacy ``torch.autograd.profiler``).
  68. This, in turn, results in including CUDA time in the profiler table output,
  69. but not in the JSON trace.
  70. """
  71. return torch.autograd._supported_activities()
  72. class _ITraceObserver(ABC):
  73. """Abstract interface for a Trace observer.
  74. This satisfies 3 methods: start, stop and cleanup"""
  75. @abstractmethod
  76. def start(self):
  77. pass
  78. @abstractmethod
  79. def stop(self):
  80. pass
  81. @abstractmethod
  82. def cleanup(self):
  83. pass
  84. class _KinetoProfile:
  85. """Low-level profiler wrap the autograd profile
  86. Args:
  87. activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
  88. ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``,
  89. ``torch.profiler.ProfilerActivity.XPU``.
  90. Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA
  91. or (when available) ProfilerActivity.XPU.
  92. record_shapes (bool): save information about operator's input shapes.
  93. profile_memory (bool): track tensor memory allocation/deallocation (see ``export_memory_timeline``
  94. for more details).
  95. with_stack (bool): record source information (file and line number) for the ops.
  96. with_flops (bool): use formula to estimate the FLOPS of specific operators
  97. (matrix multiplication and 2D convolution).
  98. with_modules (bool): record module hierarchy (including function names)
  99. corresponding to the callstack of the op. e.g. If module A's forward call's
  100. module B's forward which contains an aten::add op,
  101. then aten::add's module hierarchy is A.B
  102. Note that this support exist, at the moment, only for TorchScript models
  103. and not eager mode models.
  104. experimental_config (_ExperimentalConfig) : A set of experimental options
  105. used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.
  106. execution_trace_observer (ExecutionTraceObserver) : A PyTorch Execution Trace Observer object.
  107. `PyTorch Execution Traces <https://arxiv.org/pdf/2305.14516.pdf>`__ offer a graph based
  108. representation of AI/ML workloads and enable replay benchmarks, simulators, and emulators.
  109. When this argument is included the observer start() and stop() will be called for the
  110. same time window as PyTorch profiler.
  111. acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles
  112. .. note::
  113. This API is experimental and subject to change in the future.
  114. Enabling shape and stack tracing results in additional overhead.
  115. When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
  116. that may further prevent certain optimizations that depend on the reference count and introduce
  117. extra tensor copies.
  118. """
  119. def __init__(
  120. self,
  121. *,
  122. activities: Iterable[ProfilerActivity] | None = None,
  123. record_shapes: bool = False,
  124. profile_memory: bool = False,
  125. with_stack: bool = False,
  126. with_flops: bool = False,
  127. with_modules: bool = False,
  128. experimental_config: _ExperimentalConfig | None = None,
  129. execution_trace_observer: _ITraceObserver | None = None,
  130. acc_events: bool = False,
  131. custom_trace_id_callback: Callable[[], str] | None = None,
  132. ) -> None:
  133. self.activities = set(activities) if activities else supported_activities()
  134. self.record_shapes = record_shapes
  135. self.with_flops = with_flops
  136. self.profile_memory = profile_memory
  137. self.with_stack = with_stack
  138. self.with_modules = with_modules
  139. self.experimental_config = experimental_config
  140. self.execution_trace_observer = execution_trace_observer
  141. self.acc_events = acc_events
  142. self.custom_trace_id_callback = custom_trace_id_callback
  143. self.profiler: prof.profile | None = None
  144. self.has_cudagraphs = False
  145. self.mem_tl: MemoryProfileTimeline | None = None
  146. self.use_device = None
  147. if ProfilerActivity.CUDA in self.activities:
  148. # pyrefly: ignore [bad-assignment]
  149. self.use_device = "cuda"
  150. elif ProfilerActivity.XPU in self.activities:
  151. # pyrefly: ignore [bad-assignment]
  152. self.use_device = "xpu"
  153. elif ProfilerActivity.MTIA in self.activities:
  154. # pyrefly: ignore [bad-assignment]
  155. self.use_device = "mtia"
  156. elif ProfilerActivity.HPU in self.activities:
  157. # pyrefly: ignore [bad-assignment]
  158. self.use_device = "hpu"
  159. elif ProfilerActivity.PrivateUse1 in self.activities:
  160. # pyrefly: ignore [bad-assignment]
  161. self.use_device = _get_privateuse1_backend_name()
  162. # user-defined metadata to be amended to the trace
  163. self.preset_metadata: dict[str, str] = {}
  164. def start(self) -> None:
  165. self.prepare_trace()
  166. self.start_trace()
  167. def stop(self) -> None:
  168. self.stop_trace()
  169. def prepare_trace(self) -> None:
  170. if hasattr(torch, "_inductor"):
  171. import torch._inductor.config as inductor_config
  172. self.has_cudagraphs = inductor_config.triton.cudagraphs
  173. if (self.profiler is None) or (not self.acc_events):
  174. self.profiler = prof.profile(
  175. use_cpu=(ProfilerActivity.CPU in self.activities),
  176. use_device=self.use_device,
  177. record_shapes=self.record_shapes,
  178. with_flops=self.with_flops,
  179. profile_memory=self.profile_memory,
  180. with_stack=self.with_stack,
  181. with_modules=self.with_modules,
  182. use_kineto=True,
  183. experimental_config=self.experimental_config,
  184. acc_events=self.acc_events,
  185. custom_trace_id_callback=self.custom_trace_id_callback,
  186. )
  187. if (self.profiler is not None) and (not self.acc_events):
  188. _warn_once(
  189. "Warning: Profiler clears events at the end of each cycle."
  190. "Only events from the current cycle will be reported."
  191. "To keep events across cycles, set acc_events=True."
  192. )
  193. self.profiler._prepare_trace()
  194. def start_trace(self) -> None:
  195. if self.execution_trace_observer:
  196. self.execution_trace_observer.start()
  197. if self.profiler is None:
  198. raise AssertionError("Profiler must be initialized before starting trace")
  199. self.profiler._start_trace()
  200. if self.profile_memory:
  201. self.add_metadata_json("profile_memory", "1")
  202. if self.with_stack:
  203. self.add_metadata_json("with_stack", "1")
  204. if self.record_shapes:
  205. self.add_metadata_json("record_shapes", "1")
  206. if self.with_modules:
  207. self.add_metadata_json("with_modules", "1")
  208. if self.with_flops:
  209. self.add_metadata_json("with_flops", "1")
  210. if kineto_available():
  211. dist_info = self._get_distributed_info()
  212. if dist_info:
  213. self.add_metadata_json(
  214. "distributedInfo", json.dumps(dist_info, cls=_NumpyEncoder)
  215. )
  216. cuda_version = None
  217. if hasattr(torch, "version"):
  218. from torch.torch_version import TorchVersion
  219. cuda_version = TorchVersion(getattr(torch.version, "cuda", "0.0"))
  220. if self.has_cudagraphs and (
  221. (cuda_version and cuda_version < "12.6")
  222. or not profiler_allow_cudagraph_cupti_lazy_reinit_cuda12()
  223. ):
  224. os.environ["DISABLE_CUPTI_LAZY_REINIT"] = "1"
  225. self.add_metadata_json("DISABLE_CUPTI_LAZY_REINIT", "1")
  226. # FIXME: CUDA Graph does not work well with CUPTI teardown.
  227. # 1) crashes on 1st lazy CUPTI re-init after teardown (CUDA 11)
  228. # 2) crashes on 2nd non-lazy CUPTI re-init after teardown (CUDA 12)
  229. # Workaround: turn off CUPTI teardown when using CUDA Graphs.
  230. os.environ["TEARDOWN_CUPTI"] = "0"
  231. # Insert the preset user metadata to the trace
  232. for k, v in self.preset_metadata.items():
  233. self.add_metadata_json(k, v)
  234. def stop_trace(self) -> None:
  235. if self.execution_trace_observer:
  236. self.execution_trace_observer.stop()
  237. if self.profiler is None:
  238. raise AssertionError("Profiler must be initialized before stopping trace")
  239. self.profiler.__exit__(None, None, None)
  240. def export_chrome_trace(self, path: str):
  241. """
  242. Exports the collected trace in Chrome JSON format. If kineto is enabled, only
  243. last cycle in schedule is exported.
  244. """
  245. if self.profiler is None:
  246. raise AssertionError(
  247. "Profiler must be initialized before exporting chrome trace"
  248. )
  249. if path.endswith(".gz"):
  250. with tempfile.NamedTemporaryFile("w+b", suffix=".json") as fp:
  251. retvalue = self.profiler.export_chrome_trace(fp.name)
  252. with open(fp.name, "rb") as fin, gzip.open(path, "wb") as fout:
  253. fout.writelines(fin)
  254. return retvalue
  255. else:
  256. return self.profiler.export_chrome_trace(path)
  257. def export_stacks(self, path: str, metric: str = "self_cpu_time_total"):
  258. """Save stack traces to a file
  259. Args:
  260. path (str): save stacks file to this location;
  261. metric (str): metric to use: "self_cpu_time_total" or "self_cuda_time_total"
  262. """
  263. if self.profiler is None:
  264. raise AssertionError("Profiler must be initialized before exporting stacks")
  265. return self.profiler.export_stacks(path, metric)
  266. def toggle_collection_dynamic(
  267. self, enable: bool, activities: Iterable[ProfilerActivity]
  268. ) -> None:
  269. """Toggle collection of activities on/off at any point of collection. Currently supports toggling Torch Ops
  270. (CPU) and CUDA activity supported in Kineto
  271. Args:
  272. activities (iterable): list of activity groups to use in profiling, supported values:
  273. ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``
  274. Examples:
  275. .. code-block:: python
  276. with torch.profiler.profile(
  277. activities=[
  278. torch.profiler.ProfilerActivity.CPU,
  279. torch.profiler.ProfilerActivity.CUDA,
  280. ]
  281. ) as p:
  282. code_to_profile_0()
  283. // turn off collection of all CUDA activity
  284. p.toggle_collection_dynamic(False, [torch.profiler.ProfilerActivity.CUDA])
  285. code_to_profile_1()
  286. // turn on collection of all CUDA activity
  287. p.toggle_collection_dynamic(True, [torch.profiler.ProfilerActivity.CUDA])
  288. code_to_profile_2()
  289. print(p.key_averages().table(
  290. sort_by="self_cuda_time_total", row_limit=-1))
  291. """
  292. if self.profiler is None:
  293. return
  294. self.profiler.toggle_collection_dynamic(enable, activities)
  295. def key_averages(
  296. self,
  297. group_by_input_shape: bool = False,
  298. group_by_stack_n: int = 0,
  299. group_by_overload_name: bool = False,
  300. ):
  301. """Averages events, grouping them by operator name and (optionally) input shapes, stack
  302. and overload name.
  303. .. note::
  304. To use shape/stack functionality make sure to set record_shapes/with_stack
  305. when creating profiler context manager.
  306. """
  307. if self.profiler is None:
  308. raise AssertionError(
  309. "Profiler must be initialized before getting key averages"
  310. )
  311. return self.profiler.key_averages(
  312. group_by_input_shape, group_by_stack_n, group_by_overload_name
  313. )
  314. def events(self):
  315. """
  316. Returns the list of unaggregated profiler events,
  317. to be used in the trace callback or after the profiling is finished
  318. """
  319. if self.profiler is None:
  320. raise AssertionError("Profiler must be initialized before accessing events")
  321. return self.profiler.function_events
  322. def add_metadata(self, key: str, value: str) -> None:
  323. """
  324. Adds a user defined metadata with a string key and a string value
  325. into the trace file
  326. """
  327. wrapped_value = '"' + value.replace('"', '\\"') + '"'
  328. torch.autograd._add_metadata_json(key, wrapped_value)
  329. def add_metadata_json(self, key: str, value: str) -> None:
  330. """
  331. Adds a user defined metadata with a string key and a valid json value
  332. into the trace file
  333. """
  334. torch.autograd._add_metadata_json(key, value)
  335. def preset_metadata_json(self, key: str, value: str) -> None:
  336. """
  337. Preset a user defined metadata when the profiler is not started
  338. and added into the trace file later.
  339. Metadata is in the format of a string key and a valid json value
  340. """
  341. self.preset_metadata[key] = value
  342. def _get_distributed_info(self):
  343. import torch.distributed as dist
  344. if not dist.is_available() or not dist.is_initialized():
  345. return None
  346. backend = dist.get_backend()
  347. dist_info = {
  348. "backend": backend,
  349. "rank": dist.get_rank(),
  350. "world_size": dist.get_world_size(),
  351. "pg_count": dist.get_pg_count(),
  352. "pg_config": dist.distributed_c10d._get_all_pg_configs(),
  353. }
  354. if backend == "nccl":
  355. nccl_version = torch.cuda.nccl.version()
  356. # pyrefly: ignore [unsupported-operation]
  357. dist_info["nccl_version"] = ".".join(str(v) for v in nccl_version)
  358. return dist_info
  359. def _memory_profile(self) -> MemoryProfile:
  360. required = ("record_shapes", "profile_memory", "with_stack")
  361. missing = [f"{i}=True" for i in required if not getattr(self, i)]
  362. if missing:
  363. raise ValueError(f"{', '.join(missing)} required for memory profiling.")
  364. if self.profiler is None or self.profiler.kineto_results is None:
  365. raise AssertionError(
  366. "Profiler and kineto_results must be initialized for memory profiling"
  367. )
  368. return MemoryProfile(self.profiler.kineto_results)
  369. @deprecated(
  370. "`export_memory_timeline` is deprecated and will be removed in a future version. "
  371. "Please use `torch.cuda.memory._record_memory_history` and `torch.cuda.memory._export_memory_snapshot` instead.",
  372. category=FutureWarning,
  373. )
  374. def export_memory_timeline(self, path: str, device: str | None = None) -> None:
  375. """Export memory event information from the profiler collected
  376. tree for a given device, and export a timeline plot. There are 3
  377. exportable files using ``export_memory_timeline``, each controlled by the
  378. ``path``'s suffix.
  379. - For an HTML compatible plot, use the suffix ``.html``, and a memory timeline
  380. plot will be embedded as a PNG file in the HTML file.
  381. - For plot points consisting of ``[times, [sizes by category]]``, where
  382. ``times`` are timestamps and ``sizes`` are memory usage for each category.
  383. The memory timeline plot will be saved a JSON (``.json``) or gzipped JSON
  384. (``.json.gz``) depending on the suffix.
  385. - For raw memory points, use the suffix ``.raw.json.gz``. Each raw memory
  386. event will consist of ``(timestamp, action, numbytes, category)``, where
  387. ``action`` is one of ``[PREEXISTING, CREATE, INCREMENT_VERSION, DESTROY]``,
  388. and ``category`` is one of the enums from
  389. ``torch.profiler._memory_profiler.Category``.
  390. Output: Memory timeline written as gzipped JSON, JSON, or HTML.
  391. .. deprecated::
  392. ``export_memory_timeline`` is deprecated and will be removed in a future version.
  393. Please use ``torch.cuda.memory._record_memory_history`` and
  394. ``torch.cuda.memory._export_memory_snapshot`` instead.
  395. """
  396. # Default to device 0, if unset. Fallback on cpu.
  397. if device is None:
  398. if self.use_device and self.use_device != "cuda":
  399. device = self.use_device + ":0"
  400. else:
  401. device = "cuda:0" if torch.cuda.is_available() else "cpu"
  402. # Construct the memory timeline plot data
  403. self.mem_tl = MemoryProfileTimeline(self._memory_profile())
  404. # Depending on the file suffix, save the data as json.gz or json.
  405. # For html, we can embed the image into an HTML file.
  406. if path.endswith(".html"):
  407. self.mem_tl.export_memory_timeline_html(path, device)
  408. elif path.endswith(".gz"):
  409. with tempfile.NamedTemporaryFile("w+t", suffix=".json") as fp:
  410. if path.endswith("raw.json.gz"):
  411. self.mem_tl.export_memory_timeline_raw(fp.name, device)
  412. else:
  413. self.mem_tl.export_memory_timeline(fp.name, device)
  414. with open(fp.name) as fin, gzip.open(path, "wt") as fout:
  415. fout.writelines(fin)
  416. else:
  417. self.mem_tl.export_memory_timeline(path, device)
  418. class ProfilerAction(Enum):
  419. """
  420. Profiler actions that can be taken at the specified intervals
  421. """
  422. NONE = 0
  423. WARMUP = 1
  424. RECORD = 2
  425. RECORD_AND_SAVE = 3
  426. def schedule(
  427. *,
  428. wait: int,
  429. warmup: int,
  430. active: int,
  431. repeat: int = 0,
  432. skip_first: int = 0,
  433. skip_first_wait: int = 0,
  434. ) -> Callable:
  435. """
  436. Returns a callable that can be used as profiler ``schedule`` argument. The profiler will skip
  437. the first ``skip_first`` steps, then wait for ``wait`` steps, then do the warmup for the next ``warmup`` steps,
  438. then do the active recording for the next ``active`` steps and then repeat the cycle starting with ``wait`` steps.
  439. The optional number of cycles is specified with the ``repeat`` parameter, the zero value means that
  440. the cycles will continue until the profiling is finished.
  441. The ``skip_first_wait`` parameter controls whether the first ``wait`` stage should be skipped.
  442. This can be useful if a user wants to wait longer than ``skip_first`` between cycles, but not
  443. for the first profile. For example, if ``skip_first`` is 10 and ``wait`` is 20, the first cycle will
  444. wait 10 + 20 = 30 steps before warmup if ``skip_first_wait`` is zero, but will wait only 10
  445. steps if ``skip_first_wait`` is non-zero. All subsequent cycles will then wait 20 steps between the
  446. last active and warmup.
  447. """
  448. def schedule_fn(step: int) -> ProfilerAction:
  449. if step < 0:
  450. raise AssertionError(f"Step must be non-negative. Got {step}.")
  451. if step < skip_first:
  452. return ProfilerAction.NONE
  453. else:
  454. step -= skip_first
  455. # If wait >> skip_first and we want to grab profiling early, shift left by wait if skip_first_wait is True
  456. if skip_first_wait != 0:
  457. step += wait
  458. num_steps = wait + warmup + active
  459. if repeat > 0 and step / num_steps >= repeat:
  460. return ProfilerAction.NONE
  461. mod_step = step % num_steps
  462. if mod_step < wait:
  463. return ProfilerAction.NONE
  464. elif mod_step < wait + warmup:
  465. return ProfilerAction.WARMUP
  466. else:
  467. return (
  468. ProfilerAction.RECORD
  469. if mod_step < num_steps - 1
  470. else ProfilerAction.RECORD_AND_SAVE
  471. )
  472. if wait < 0 or warmup < 0 or active <= 0 or repeat < 0 or skip_first < 0:
  473. raise AssertionError(
  474. f"Invalid profiler schedule arguments. Got wait={wait} (need >= 0), warmup={warmup} (need >= 0), "
  475. f"active={active} (need > 0), repeat={repeat} (need >= 0), skip_first={skip_first} (need >= 0)."
  476. )
  477. if warmup == 0:
  478. warn(
  479. "Profiler won't be using warmup, this can skew profiler results",
  480. stacklevel=2,
  481. )
  482. return schedule_fn
  483. def _default_schedule_fn(_: int) -> ProfilerAction:
  484. """
  485. Default profiler behavior - immediately starts recording the events,
  486. keeps doing it on every profiler step.
  487. """
  488. return ProfilerAction.RECORD
  489. def tensorboard_trace_handler(
  490. dir_name: str, worker_name: str | None = None, use_gzip: bool = False
  491. ):
  492. """
  493. Outputs tracing files to directory of ``dir_name``, then that directory can be
  494. directly delivered to tensorboard as logdir.
  495. ``worker_name`` should be unique for each worker in distributed scenario,
  496. it will be set to '[hostname]_[pid]' by default.
  497. """
  498. import socket
  499. import time
  500. def handler_fn(prof) -> None:
  501. nonlocal worker_name
  502. if not os.path.isdir(dir_name):
  503. try:
  504. os.makedirs(dir_name, exist_ok=True)
  505. except Exception as e:
  506. raise RuntimeError("Can't create directory: " + dir_name) from e
  507. if not worker_name:
  508. worker_name = f"{socket.gethostname()}_{os.getpid()}"
  509. # Use nanosecond here to avoid naming clash when exporting the trace
  510. file_name = f"{worker_name}.{time.time_ns()}.pt.trace.json"
  511. if use_gzip:
  512. file_name = file_name + ".gz"
  513. prof.export_chrome_trace(os.path.join(dir_name, file_name))
  514. return handler_fn
  515. class profile(_KinetoProfile):
  516. """Profiler context manager.
  517. Args:
  518. activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
  519. ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``,
  520. ``torch.profiler.ProfilerActivity.XPU``.
  521. Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA
  522. or (when available) ProfilerActivity.XPU.
  523. schedule (Callable): callable that takes step (int) as a single parameter and returns
  524. ``ProfilerAction`` value that specifies the profiler action to perform at each step.
  525. on_trace_ready (Callable): callable that is called at each step when ``schedule``
  526. returns ``ProfilerAction.RECORD_AND_SAVE`` during the profiling.
  527. record_shapes (bool): save information about operator's input shapes.
  528. profile_memory (bool): track tensor memory allocation/deallocation.
  529. with_stack (bool): record source information (file and line number) for the ops.
  530. with_flops (bool): use formula to estimate the FLOPs (floating point operations) of specific operators
  531. (matrix multiplication and 2D convolution).
  532. with_modules (bool): record module hierarchy (including function names)
  533. corresponding to the callstack of the op. e.g. If module A's forward call's
  534. module B's forward which contains an aten::add op,
  535. then aten::add's module hierarchy is A.B
  536. Note that this support exist, at the moment, only for TorchScript models
  537. and not eager mode models.
  538. experimental_config (_ExperimentalConfig) : A set of experimental options
  539. used for Kineto library features. Note, backward compatibility is not guaranteed.
  540. execution_trace_observer (ExecutionTraceObserver) : A PyTorch Execution Trace Observer object.
  541. `PyTorch Execution Traces <https://arxiv.org/pdf/2305.14516.pdf>`__ offer a graph based
  542. representation of AI/ML workloads and enable replay benchmarks, simulators, and emulators.
  543. When this argument is included the observer start() and stop() will be called for the
  544. same time window as PyTorch profiler. See the examples section below for a code sample.
  545. acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles
  546. use_cuda (bool):
  547. .. deprecated:: 1.8.1
  548. use ``activities`` instead.
  549. .. note::
  550. Use :func:`~torch.profiler.schedule` to generate the callable schedule.
  551. Non-default schedules are useful when profiling long training jobs
  552. and allow the user to obtain multiple traces at the different iterations
  553. of the training process.
  554. The default schedule simply records all the events continuously for the
  555. duration of the context manager.
  556. .. note::
  557. Use :func:`~torch.profiler.tensorboard_trace_handler` to generate result files for TensorBoard:
  558. ``on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)``
  559. After profiling, result files can be found in the specified directory. Use the command:
  560. ``tensorboard --logdir dir_name``
  561. to see the results in TensorBoard.
  562. For more information, see
  563. `PyTorch Profiler TensorBoard Plugin <https://github.com/pytorch/kineto/tree/master/tb_plugin>`__
  564. .. note::
  565. Enabling shape and stack tracing results in additional overhead.
  566. When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
  567. that may further prevent certain optimizations that depend on the reference count and introduce
  568. extra tensor copies.
  569. Examples:
  570. .. code-block:: python
  571. with torch.profiler.profile(
  572. activities=[
  573. torch.profiler.ProfilerActivity.CPU,
  574. torch.profiler.ProfilerActivity.CUDA,
  575. ]
  576. ) as p:
  577. code_to_profile()
  578. print(p.key_averages().table(sort_by="self_cuda_time_total", row_limit=-1))
  579. Using the profiler's ``schedule``, ``on_trace_ready`` and ``step`` functions:
  580. .. code-block:: python
  581. # Non-default profiler schedule allows user to turn profiler on and off
  582. # on different iterations of the training loop;
  583. # trace_handler is called every time a new trace becomes available
  584. def trace_handler(prof):
  585. print(
  586. prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=-1)
  587. )
  588. # prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json")
  589. with torch.profiler.profile(
  590. activities=[
  591. torch.profiler.ProfilerActivity.CPU,
  592. torch.profiler.ProfilerActivity.CUDA,
  593. ],
  594. # In this example with wait=1, warmup=1, active=2, repeat=1,
  595. # profiler will skip the first step/iteration,
  596. # start warming up on the second, record
  597. # the third and the forth iterations,
  598. # after which the trace will become available
  599. # and on_trace_ready (when set) is called;
  600. # the cycle repeats starting with the next step
  601. schedule=torch.profiler.schedule(wait=1, warmup=1, active=2, repeat=1),
  602. on_trace_ready=trace_handler,
  603. # on_trace_ready=torch.profiler.tensorboard_trace_handler('./log')
  604. # used when outputting for tensorboard
  605. ) as p:
  606. for iter in range(N):
  607. code_iteration_to_profile(iter)
  608. # send a signal to the profiler that the next iteration has started
  609. p.step()
  610. The following sample shows how to setup up an Execution Trace Observer (`execution_trace_observer`)
  611. .. code-block:: python
  612. with torch.profiler.profile(
  613. ...
  614. execution_trace_observer=(
  615. ExecutionTraceObserver().register_callback("./execution_trace.json")
  616. ),
  617. ) as p:
  618. for iter in range(N):
  619. code_iteration_to_profile(iter)
  620. p.step()
  621. You can also refer to test_execution_trace_with_kineto() in tests/profiler/test_profiler.py.
  622. Note: One can also pass any object satisfying the _ITraceObserver interface.
  623. """
  624. def __init__(
  625. self,
  626. *,
  627. activities: Iterable[ProfilerActivity] | None = None,
  628. schedule: Callable[[int], ProfilerAction] | None = None,
  629. on_trace_ready: Callable[..., Any] | None = None,
  630. record_shapes: bool = False,
  631. profile_memory: bool = False,
  632. with_stack: bool = False,
  633. with_flops: bool = False,
  634. with_modules: bool = False,
  635. experimental_config: _ExperimentalConfig | None = None,
  636. execution_trace_observer: _ITraceObserver | None = None,
  637. acc_events: bool = False,
  638. # deprecated:
  639. use_cuda: bool | None = None,
  640. custom_trace_id_callback: Callable[[], str] | None = None,
  641. ) -> None:
  642. activities_set = set(activities) if activities else supported_activities()
  643. if use_cuda is not None:
  644. warn(
  645. "`use_cuda` is deprecated, use `activities` argument instead",
  646. FutureWarning,
  647. stacklevel=2,
  648. )
  649. if use_cuda:
  650. activities_set.add(ProfilerActivity.CUDA)
  651. elif ProfilerActivity.CUDA in activities_set:
  652. activities_set.remove(ProfilerActivity.CUDA)
  653. if len(activities_set) == 0:
  654. raise AssertionError("No valid profiler activities found")
  655. super().__init__(
  656. activities=activities,
  657. record_shapes=record_shapes,
  658. profile_memory=profile_memory,
  659. with_stack=with_stack,
  660. with_flops=with_flops,
  661. with_modules=with_modules,
  662. experimental_config=experimental_config,
  663. execution_trace_observer=execution_trace_observer
  664. if execution_trace_observer
  665. else ExecutionTraceObserver.build_execution_trace_obs_from_env(),
  666. acc_events=acc_events,
  667. custom_trace_id_callback=custom_trace_id_callback,
  668. )
  669. if schedule:
  670. self.schedule = schedule
  671. # add step markers into the trace and table view
  672. self.record_steps = True
  673. else:
  674. self.schedule = _default_schedule_fn
  675. self.record_steps = False
  676. self.on_trace_ready = on_trace_ready
  677. self.step_num = 0
  678. self.current_action = self.schedule(self.step_num)
  679. self.step_rec_fn: prof.record_function | None = None
  680. self.action_map: dict[
  681. tuple[ProfilerAction, ProfilerAction | None], list[Any]
  682. ] = {
  683. # key is (prev_action, current_action), value is action list corresponding to the state pair.
  684. (ProfilerAction.NONE, ProfilerAction.NONE): [],
  685. (ProfilerAction.NONE, ProfilerAction.WARMUP): [self.prepare_trace],
  686. (ProfilerAction.NONE, ProfilerAction.RECORD): [
  687. self.prepare_trace,
  688. self.start_trace,
  689. ],
  690. (ProfilerAction.NONE, ProfilerAction.RECORD_AND_SAVE): [
  691. self.prepare_trace,
  692. self.start_trace,
  693. ],
  694. (ProfilerAction.WARMUP, ProfilerAction.NONE): [
  695. partial(warn, "Incorrect schedule: WARMUP followed by NONE"),
  696. self.start_trace,
  697. self.stop_trace,
  698. ],
  699. (ProfilerAction.WARMUP, ProfilerAction.WARMUP): [],
  700. (ProfilerAction.WARMUP, ProfilerAction.RECORD): [self.start_trace],
  701. (ProfilerAction.WARMUP, ProfilerAction.RECORD_AND_SAVE): [self.start_trace],
  702. (ProfilerAction.RECORD, ProfilerAction.NONE): [
  703. partial(warn, "Incorrect schedule: RECORD followed by NONE"),
  704. self.stop_trace,
  705. ],
  706. (ProfilerAction.RECORD, ProfilerAction.WARMUP): [
  707. partial(warn, "Incorrect schedule: RECORD followed by WARMUP"),
  708. self.stop_trace,
  709. ],
  710. (ProfilerAction.RECORD, ProfilerAction.RECORD): [],
  711. (ProfilerAction.RECORD, ProfilerAction.RECORD_AND_SAVE): [],
  712. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.NONE): [
  713. self.stop_trace,
  714. self._trace_ready,
  715. ],
  716. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.WARMUP): [
  717. self.stop_trace,
  718. self._trace_ready,
  719. self.prepare_trace,
  720. ],
  721. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.RECORD): [
  722. self.stop_trace,
  723. self._trace_ready,
  724. self.prepare_trace,
  725. self.start_trace,
  726. ],
  727. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.RECORD_AND_SAVE): [
  728. self.stop_trace,
  729. self._trace_ready,
  730. self.prepare_trace,
  731. self.start_trace,
  732. ],
  733. # used for exit action
  734. (ProfilerAction.WARMUP, None): [self.start_trace, self.stop_trace],
  735. (ProfilerAction.RECORD, None): [self.stop_trace, self._trace_ready],
  736. (ProfilerAction.RECORD_AND_SAVE, None): [
  737. self.stop_trace,
  738. self._trace_ready,
  739. ],
  740. }
  741. # Start tracking increments to profiler step, this will be used
  742. # by Kineto
  743. prof.KinetoStepTracker.init_step_count(PROFILER_STEP_NAME)
  744. def __enter__(self):
  745. self.start()
  746. return self
  747. def __exit__(self, exc_type, exc_val, exc_tb):
  748. self.stop()
  749. prof.KinetoStepTracker.erase_step_count(PROFILER_STEP_NAME)
  750. if self.execution_trace_observer:
  751. self.execution_trace_observer.cleanup()
  752. def start(self) -> None:
  753. self._transit_action(ProfilerAction.NONE, self.current_action)
  754. if self.record_steps:
  755. self.step_rec_fn = prof.record_function(
  756. "ProfilerStep#" + str(self.step_num)
  757. )
  758. self.step_rec_fn.__enter__()
  759. def stop(self) -> None:
  760. if self.record_steps and self.step_rec_fn:
  761. self.step_rec_fn.__exit__(None, None, None)
  762. self._transit_action(self.current_action, None)
  763. def step(self) -> None:
  764. """
  765. Signals the profiler that the next profiling step has started.
  766. """
  767. if self.record_steps and self.step_rec_fn:
  768. self.step_rec_fn.__exit__(None, None, None)
  769. prev_action = self.current_action
  770. self.step_num += 1
  771. self.current_action = self.schedule(self.step_num)
  772. self._transit_action(prev_action, self.current_action)
  773. if os.environ.get("KINETO_USE_DAEMON", "") or (
  774. is_fbcode() and os.environ.get("KINETO_FORCE_STEP_HOOK", "")
  775. ):
  776. prof.KinetoStepTracker.increment_step(PROFILER_STEP_NAME)
  777. if self.record_steps:
  778. self.step_rec_fn = prof.record_function(
  779. "ProfilerStep#" + str(self.step_num)
  780. )
  781. self.step_rec_fn.__enter__()
  782. def set_custom_trace_id_callback(self, callback) -> None:
  783. """
  784. Sets a callback to be called when a new trace ID is generated.
  785. """
  786. self.custom_trace_id_callback = callback
  787. def get_trace_id(self):
  788. """
  789. Returns the current trace ID.
  790. """
  791. if self.profiler is None:
  792. return None
  793. return self.profiler.trace_id
  794. def _trace_ready(self) -> None:
  795. if self.on_trace_ready:
  796. self.on_trace_ready(self)
  797. def _transit_action(self, prev_action, current_action) -> None:
  798. action_list = self.action_map.get((prev_action, current_action))
  799. if action_list:
  800. for action in action_list:
  801. action()
  802. def _stats(self) -> prof._ProfilerStats | None:
  803. if self.profiler is None:
  804. return None
  805. return self.profiler._stats
  806. class ExecutionTraceObserver(_ITraceObserver):
  807. """Execution Trace Observer
  808. Each process can have a single ExecutionTraceObserver instance. The observer
  809. can be added to record function callbacks via calling register_callback()
  810. explicitly. Without calling unregister_callback(), repeated calls to
  811. register_callback() will not add additional observers to record function
  812. callbacks. Once an ExecutionTraceObserver is created, the start() and stop()
  813. methods control when the event data is recorded.
  814. Deleting or calling unregister_callback() will remove the observer from the
  815. record function callbacks, finalize the output file, and will stop
  816. incurring any overheads.
  817. """
  818. def __init__(self) -> None:
  819. """
  820. Initializes the default states.
  821. """
  822. self._registered = False
  823. self._execution_trace_running = False
  824. self.extra_resources_collection = False
  825. self.resources_dir: str = ""
  826. self.output_file_path: str = ""
  827. self.output_file_path_observer: str = ""
  828. def __del__(self) -> None:
  829. """
  830. Calls unregister_callback() to make sure to finalize outputs.
  831. """
  832. self.unregister_callback()
  833. @staticmethod
  834. def build_execution_trace_obs_from_env() -> Optional["ExecutionTraceObserver"]:
  835. """
  836. Returns an ExecutionTraceObserver instance if the environment variable
  837. ENABLE_PYTORCH_EXECUTION_TRACE is set to 1, otherwise returns None.
  838. Configures the observer to also collect extra resources if the environment variable
  839. ``ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAS=1``. These are resources such as generated kernels,
  840. index tensor data etc. that are required to make the Execution Trace replayable.
  841. """
  842. if os.environ.get("ENABLE_PYTORCH_EXECUTION_TRACE", "0") == "1":
  843. try:
  844. with tempfile.NamedTemporaryFile(
  845. "w+t", suffix=".et.json", delete=False
  846. ) as fp:
  847. filename = fp.name
  848. except Exception as e:
  849. warn(
  850. f"Execution trace will not be recorded. Exception on creating default temporary file: {e}",
  851. stacklevel=2,
  852. )
  853. return None
  854. et = ExecutionTraceObserver()
  855. et.register_callback(filename)
  856. # additionally, check if the env requires us to collect extra resources
  857. if os.environ.get("ENABLE_PYTORCH_EXECUTION_TRACE_EXTRAS", "0") == "1":
  858. et.set_extra_resource_collection(True)
  859. else:
  860. et.set_extra_resource_collection(False)
  861. return et
  862. return None
  863. def set_extra_resource_collection(self, val) -> None:
  864. """
  865. Collects extra resources such as generated kernels, index tensor data, and any other
  866. metadata that is required to complete the Execution Trace content.
  867. The caller should call this method with val=True after calling register_callback() if they want
  868. to collect the extra resources.
  869. """
  870. self.extra_resources_collection = val
  871. if self.extra_resources_collection:
  872. self.get_resources_dir(can_create=True)
  873. return
  874. def register_callback(self, output_file_path: str) -> Self:
  875. """
  876. Adds ET observer to record function callbacks. The data will be
  877. written to output_file_path.
  878. """
  879. def get_temp_uncompressed_file() -> str:
  880. with tempfile.NamedTemporaryFile("w+b", suffix=".json", delete=False) as fp:
  881. return fp.name
  882. if not self._registered:
  883. self.output_file_path = output_file_path
  884. if output_file_path.endswith(".gz"):
  885. output_file_path = get_temp_uncompressed_file()
  886. self.output_file_path_observer = output_file_path
  887. self._registered = _add_execution_trace_observer(output_file_path)
  888. return self
  889. def get_resources_dir(self, can_create=False) -> str | None:
  890. """
  891. Generates the resources directory for the generated kernels,
  892. or index tensor data or any other metadata that is required
  893. to complete the Execution Trace content.
  894. The directory is created right where the ET file is being output.
  895. Only works if the observer has called set_extra_resource_collection(val=True).
  896. Returns None if the observer is not configured with extra resource collection.
  897. """
  898. if not self.extra_resources_collection:
  899. return None
  900. if self.resources_dir:
  901. # already created
  902. return self.resources_dir
  903. generated_path = ExecutionTraceObserver.get_resources_dir_for_et_path(
  904. self.output_file_path, create_dir=can_create
  905. )
  906. if not generated_path:
  907. # could not find of create the resources dir
  908. return None
  909. self.resources_dir = generated_path
  910. return self.resources_dir
  911. @staticmethod
  912. def get_resources_dir_for_et_path(
  913. trace_path, create_dir: bool = False
  914. ) -> str | None:
  915. work_dir, file_name = os.path.split(trace_path)
  916. resource_dir = os.path.join(
  917. work_dir, os.path.splitext(file_name)[0] + "_resources"
  918. )
  919. if not os.path.exists(resource_dir):
  920. if create_dir:
  921. try:
  922. os.mkdir(resource_dir)
  923. except Exception:
  924. warn(
  925. f"Execution trace exception when creating {resource_dir}",
  926. stacklevel=2,
  927. )
  928. return None
  929. else:
  930. return None
  931. return resource_dir
  932. def unregister_callback(self) -> None:
  933. """
  934. Removes ET observer from record function callbacks.
  935. """
  936. def _save_triton_kernels() -> None:
  937. try:
  938. resource_dir = self.get_resources_dir()
  939. except Exception as e:
  940. warn(
  941. f"Execution trace exception when generating resource directory: {e}",
  942. stacklevel=2,
  943. )
  944. return
  945. if not resource_dir:
  946. return
  947. # Save the kernel paths for the generated kernels
  948. from torch._inductor.codecache import PyCodeCache
  949. kernel_files = [
  950. v.__file__
  951. for v in PyCodeCache.modules
  952. if getattr(v, "__file__", None) is not None
  953. ]
  954. for kernel_file in kernel_files:
  955. if kernel_file is None:
  956. continue
  957. name = os.path.basename(kernel_file)
  958. dst = os.path.join(resource_dir, name)
  959. shutil.copyfile(kernel_file, dst)
  960. def _save_gz_file(uncompressed_file: str, output_file: str) -> None:
  961. print(f"Execution Trace: compressing {uncompressed_file} to {output_file}")
  962. with open(uncompressed_file, "rb") as fin:
  963. with gzip.open(output_file, "wb") as fout:
  964. fout.writelines(fin)
  965. os.remove(uncompressed_file)
  966. if self._registered:
  967. self.stop()
  968. try:
  969. _save_triton_kernels()
  970. except Exception as e:
  971. warn(f"Execution trace failed to save kernels: {e}", stacklevel=2)
  972. _remove_execution_trace_observer()
  973. if self.output_file_path.endswith("gz"):
  974. _save_gz_file(self.output_file_path_observer, self.output_file_path)
  975. self._registered = False
  976. @property
  977. def is_registered(self):
  978. """
  979. Returns True if the execution trace observer is registered, otherwise False.
  980. """
  981. return self._registered
  982. def is_running(self):
  983. """
  984. Returns True if the observer is running, otherwise False.
  985. """
  986. return self._execution_trace_running
  987. def start(self) -> None:
  988. """
  989. Starts to capture.
  990. """
  991. if self._registered and not self._execution_trace_running:
  992. _enable_execution_trace_observer()
  993. self._execution_trace_running = True
  994. self._record_pg_config()
  995. def stop(self) -> None:
  996. """
  997. Stops to capture.
  998. """
  999. if self._execution_trace_running:
  1000. _disable_execution_trace_observer()
  1001. self._execution_trace_running = False
  1002. def cleanup(self) -> None:
  1003. """
  1004. Calls unregister_callback() to make sure to finalize outputs.
  1005. """
  1006. self.unregister_callback()
  1007. def get_output_file_path(self) -> str | None:
  1008. """
  1009. Returns the output file name or None.
  1010. """
  1011. if self.output_file_path:
  1012. return self.output_file_path
  1013. else:
  1014. return None
  1015. def _record_pg_config(self) -> None:
  1016. # Records the PG config info to the trace as node:
  1017. # ## process_group:init ##
  1018. if (
  1019. self.is_registered
  1020. and torch.distributed.is_available()
  1021. and torch.distributed.is_initialized()
  1022. ):
  1023. pg_config_info = torch.distributed.distributed_c10d._world.pg_config_info
  1024. torch.autograd._record_function_with_args_enter(
  1025. "## process_group:init ##",
  1026. json.dumps(pg_config_info, cls=_NumpyEncoder),
  1027. )