profiler.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. import gzip
  2. import json
  3. import os
  4. import tempfile
  5. from enum import Enum
  6. from functools import partial
  7. from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple
  8. from warnings import warn
  9. import torch
  10. import torch.autograd.profiler as prof
  11. from torch._C._profiler import (
  12. _add_execution_graph_observer,
  13. _disable_execution_graph_observer,
  14. _enable_execution_graph_observer,
  15. _ExperimentalConfig,
  16. _remove_execution_graph_observer,
  17. )
  18. from torch.autograd import kineto_available, ProfilerActivity
  19. from torch.profiler import _memory_profiler
  20. __all__ = [
  21. "supported_activities",
  22. "ProfilerAction",
  23. "schedule",
  24. "tensorboard_trace_handler",
  25. "profile",
  26. "ExecutionGraphObserver",
  27. ]
  28. PROFILER_STEP_NAME = "ProfilerStep"
  29. def supported_activities():
  30. """
  31. Returns a set of supported profiler tracing activities.
  32. Note: profiler uses CUPTI library to trace on-device CUDA kernels.
  33. In case when CUDA is enabled but CUPTI is not available, passing
  34. ``ProfilerActivity.CUDA`` to profiler results in using the legacy CUDA
  35. profiling code (same as in the legacy ``torch.autograd.profiler``).
  36. This, in turn, results in including CUDA time in the profiler table output,
  37. but not in the JSON trace.
  38. """
  39. return torch.autograd._supported_activities()
  40. class _KinetoProfile:
  41. """Low-level profiler wrap the autograd profile
  42. Args:
  43. activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
  44. ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``.
  45. Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA.
  46. record_shapes (bool): save information about operator's input shapes.
  47. profile_memory (bool): track tensor memory allocation/deallocation.
  48. with_stack (bool): record source information (file and line number) for the ops.
  49. with_flops (bool): use formula to estimate the FLOPS of specific operators
  50. (matrix multiplication and 2D convolution).
  51. with_modules (bool): record module hierarchy (including function names)
  52. corresponding to the callstack of the op. e.g. If module A's forward call's
  53. module B's forward which contains an aten::add op,
  54. then aten::add's module hierarchy is A.B
  55. Note that this support exist, at the moment, only for TorchScript models
  56. and not eager mode models.
  57. experimental_config (_ExperimentalConfig) : A set of experimental options
  58. used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.
  59. .. note::
  60. This API is experimental and subject to change in the future.
  61. Enabling shape and stack tracing results in additional overhead.
  62. When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
  63. that may further prevent certain optimizations that depend on the reference count and introduce
  64. extra tensor copies.
  65. """
  66. def __init__(
  67. self,
  68. *,
  69. activities: Optional[Iterable[ProfilerActivity]] = None,
  70. record_shapes: bool = False,
  71. profile_memory: bool = False,
  72. with_stack: bool = False,
  73. with_flops: bool = False,
  74. with_modules: bool = False,
  75. experimental_config: Optional[_ExperimentalConfig] = None):
  76. self.activities = set(activities) if activities else supported_activities()
  77. self.record_shapes = record_shapes
  78. self.with_flops = with_flops
  79. self.profile_memory = profile_memory
  80. self.with_stack = with_stack
  81. self.with_modules = with_modules
  82. self.experimental_config = experimental_config
  83. self.profiler: Optional[prof.profile] = None
  84. def start(self):
  85. self.prepare_trace()
  86. self.start_trace()
  87. def stop(self):
  88. self.stop_trace()
  89. def prepare_trace(self):
  90. self.profiler = prof.profile(
  91. use_cuda=(ProfilerActivity.CUDA in self.activities),
  92. use_cpu=(ProfilerActivity.CPU in self.activities),
  93. record_shapes=self.record_shapes,
  94. with_flops=self.with_flops,
  95. profile_memory=self.profile_memory,
  96. with_stack=self.with_stack,
  97. with_modules=self.with_modules,
  98. use_kineto=True,
  99. experimental_config=self.experimental_config,
  100. )
  101. self.profiler._prepare_trace()
  102. def start_trace(self):
  103. assert self.profiler is not None
  104. self.profiler._start_trace()
  105. if self.profile_memory:
  106. self.add_metadata_json("profile_memory", "1")
  107. if self.with_stack:
  108. self.add_metadata_json("with_stack", "1")
  109. if self.record_shapes:
  110. self.add_metadata_json("record_shapes", "1")
  111. if self.with_modules:
  112. self.add_metadata_json("with_modules", "1")
  113. if self.with_flops:
  114. self.add_metadata_json("with_flops", "1")
  115. if kineto_available():
  116. dist_info = self._get_distributed_info()
  117. if dist_info:
  118. self.add_metadata_json("distributedInfo", json.dumps(dist_info))
  119. def stop_trace(self):
  120. assert self.profiler is not None
  121. self.profiler.__exit__(None, None, None)
  122. def export_chrome_trace(self, path: str):
  123. """
  124. Exports the collected trace in Chrome JSON format.
  125. """
  126. assert self.profiler
  127. if path.endswith('.gz'):
  128. fp = tempfile.NamedTemporaryFile('w+t', suffix='.json', delete=False)
  129. fp.close()
  130. retvalue = self.profiler.export_chrome_trace(fp.name)
  131. with open(fp.name) as fin:
  132. with gzip.open(path, 'wt') as fout:
  133. fout.writelines(fin)
  134. os.remove(fp.name)
  135. return retvalue
  136. else:
  137. return self.profiler.export_chrome_trace(path)
  138. def export_stacks(self, path: str, metric: str = "self_cpu_time_total"):
  139. """Save stack traces in a file in a format suitable for visualization.
  140. Args:
  141. path (str): save stacks file to this location;
  142. metric (str): metric to use: "self_cpu_time_total" or "self_cuda_time_total"
  143. .. note::
  144. Example of using FlameGraph tool:
  145. - git clone https://github.com/brendangregg/FlameGraph
  146. - cd FlameGraph
  147. - ./flamegraph.pl --title "CPU time" --countname "us." profiler.stacks > perf_viz.svg
  148. """
  149. assert self.profiler
  150. return self.profiler.export_stacks(path, metric)
  151. def key_averages(self, group_by_input_shape: bool = False, group_by_stack_n: int = 0):
  152. """Averages events, grouping them by operator name and (optionally) input shapes and
  153. stack.
  154. .. note::
  155. To use shape/stack functionality make sure to set record_shapes/with_stack
  156. when creating profiler context manager.
  157. """
  158. assert self.profiler
  159. return self.profiler.key_averages(group_by_input_shape, group_by_stack_n)
  160. def events(self):
  161. """
  162. Returns the list of unaggregated profiler events,
  163. to be used in the trace callback or after the profiling is finished
  164. """
  165. assert self.profiler
  166. return self.profiler.function_events
  167. def add_metadata(self, key: str, value: str):
  168. """
  169. Adds a user defined metadata with a string key and a string value
  170. into the trace file
  171. """
  172. wrapped_value = "\"" + value.replace('"', '\\"') + "\""
  173. torch.autograd._add_metadata_json(key, wrapped_value)
  174. def add_metadata_json(self, key: str, value: str):
  175. """
  176. Adds a user defined metadata with a string key and a valid json value
  177. into the trace file
  178. """
  179. torch.autograd._add_metadata_json(key, value)
  180. def _get_distributed_info(self):
  181. import torch.distributed as dist
  182. if not dist.is_available() or not dist.is_initialized():
  183. return None
  184. return {
  185. "backend": dist.get_backend(),
  186. "rank": dist.get_rank(),
  187. "world_size": dist.get_world_size()
  188. }
  189. def _memory_profile(self) -> _memory_profiler.MemoryProfile:
  190. required = ("record_shapes", "profile_memory", "with_stack")
  191. missing = [f"{i}=True" for i in required if not getattr(self, i)]
  192. if missing:
  193. raise ValueError(f"{', '.join(missing)} required for memory profiling.")
  194. assert self.profiler is not None and self.profiler.kineto_results is not None
  195. return _memory_profiler.MemoryProfile(self.profiler.kineto_results)
  196. class ProfilerAction(Enum):
  197. """
  198. Profiler actions that can be taken at the specified intervals
  199. """
  200. NONE = 0
  201. WARMUP = 1
  202. RECORD = 2
  203. RECORD_AND_SAVE = 3
  204. def schedule(*, wait: int, warmup: int, active: int, repeat: int = 0, skip_first: int = 0) -> Callable:
  205. """
  206. Returns a callable that can be used as profiler ``schedule`` argument. The profiler will skip
  207. the first ``skip_first`` steps, then wait for ``wait`` steps, then do the warmup for the next ``warmup`` steps,
  208. then do the active recording for the next ``active`` steps and then repeat the cycle starting with ``wait`` steps.
  209. The optional number of cycles is specified with the ``repeat`` parameter, the zero value means that
  210. the cycles will continue until the profiling is finished.
  211. """
  212. def schedule_fn(step: int) -> ProfilerAction:
  213. assert step >= 0
  214. if step < skip_first:
  215. return ProfilerAction.NONE
  216. else:
  217. step -= skip_first
  218. num_steps = wait + warmup + active
  219. if repeat > 0 and step / num_steps >= repeat:
  220. return ProfilerAction.NONE
  221. mod_step = step % num_steps
  222. if mod_step < wait:
  223. return ProfilerAction.NONE
  224. elif mod_step < wait + warmup:
  225. return ProfilerAction.WARMUP
  226. else:
  227. return ProfilerAction.RECORD if mod_step < num_steps - 1 \
  228. else ProfilerAction.RECORD_AND_SAVE
  229. assert wait >= 0 and warmup >= 0 and active > 0 and \
  230. repeat >= 0 and skip_first >= 0, "Invalid profiler schedule arguments"
  231. if warmup == 0:
  232. warn("Profiler won't be using warmup, this can skew profiler results")
  233. return schedule_fn
  234. def _default_schedule_fn(_: int) -> ProfilerAction:
  235. """
  236. Default profiler behavior - immediately starts recording the events,
  237. keeps doing it on every profiler step.
  238. """
  239. return ProfilerAction.RECORD
  240. def tensorboard_trace_handler(dir_name: str, worker_name: Optional[str] = None, use_gzip: bool = False):
  241. """
  242. Outputs tracing files to directory of ``dir_name``, then that directory can be
  243. directly delivered to tensorboard as logdir.
  244. ``worker_name`` should be unique for each worker in distributed scenario,
  245. it will be set to '[hostname]_[pid]' by default.
  246. """
  247. import os
  248. import socket
  249. import time
  250. def handler_fn(prof) -> None:
  251. nonlocal worker_name
  252. if not os.path.isdir(dir_name):
  253. try:
  254. os.makedirs(dir_name, exist_ok=True)
  255. except Exception as e:
  256. raise RuntimeError("Can't create directory: " + dir_name) from e
  257. if not worker_name:
  258. worker_name = "{}_{}".format(socket.gethostname(), str(os.getpid()))
  259. file_name = "{}.{}.pt.trace.json".format(worker_name, int(time.time() * 1000))
  260. if use_gzip:
  261. file_name = file_name + '.gz'
  262. prof.export_chrome_trace(os.path.join(dir_name, file_name))
  263. return handler_fn
  264. class profile(_KinetoProfile):
  265. """Profiler context manager.
  266. Args:
  267. activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
  268. ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``.
  269. Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA.
  270. schedule (Callable): callable that takes step (int) as a single parameter and returns
  271. ``ProfilerAction`` value that specifies the profiler action to perform at each step.
  272. on_trace_ready (Callable): callable that is called at each step when ``schedule``
  273. returns ``ProfilerAction.RECORD_AND_SAVE`` during the profiling.
  274. record_shapes (bool): save information about operator's input shapes.
  275. profile_memory (bool): track tensor memory allocation/deallocation.
  276. with_stack (bool): record source information (file and line number) for the ops.
  277. with_flops (bool): use formula to estimate the FLOPs (floating point operations) of specific operators
  278. (matrix multiplication and 2D convolution).
  279. with_modules (bool): record module hierarchy (including function names)
  280. corresponding to the callstack of the op. e.g. If module A's forward call's
  281. module B's forward which contains an aten::add op,
  282. then aten::add's module hierarchy is A.B
  283. Note that this support exist, at the moment, only for TorchScript models
  284. and not eager mode models.
  285. experimental_config (_ExperimentalConfig) : A set of experimental options
  286. used for Kineto library features. Note, backward compatibility is not guaranteed.
  287. use_cuda (bool):
  288. .. deprecated:: 1.8.1
  289. use ``activities`` instead.
  290. .. note::
  291. Use :func:`~torch.profiler.schedule` to generate the callable schedule.
  292. Non-default schedules are useful when profiling long training jobs
  293. and allow the user to obtain multiple traces at the different iterations
  294. of the training process.
  295. The default schedule simply records all the events continuously for the
  296. duration of the context manager.
  297. .. note::
  298. Use :func:`~torch.profiler.tensorboard_trace_handler` to generate result files for TensorBoard:
  299. ``on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)``
  300. After profiling, result files can be found in the specified directory. Use the command:
  301. ``tensorboard --logdir dir_name``
  302. to see the results in TensorBoard.
  303. For more information, see
  304. `PyTorch Profiler TensorBoard Plugin <https://github.com/pytorch/kineto/tree/master/tb_plugin>`__
  305. .. note::
  306. Enabling shape and stack tracing results in additional overhead.
  307. When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
  308. that may further prevent certain optimizations that depend on the reference count and introduce
  309. extra tensor copies.
  310. Examples:
  311. .. code-block:: python
  312. with torch.profiler.profile(
  313. activities=[
  314. torch.profiler.ProfilerActivity.CPU,
  315. torch.profiler.ProfilerActivity.CUDA,
  316. ]
  317. ) as p:
  318. code_to_profile()
  319. print(p.key_averages().table(
  320. sort_by="self_cuda_time_total", row_limit=-1))
  321. Using the profiler's ``schedule``, ``on_trace_ready`` and ``step`` functions:
  322. .. code-block:: python
  323. # Non-default profiler schedule allows user to turn profiler on and off
  324. # on different iterations of the training loop;
  325. # trace_handler is called every time a new trace becomes available
  326. def trace_handler(prof):
  327. print(prof.key_averages().table(
  328. sort_by="self_cuda_time_total", row_limit=-1))
  329. # prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json")
  330. with torch.profiler.profile(
  331. activities=[
  332. torch.profiler.ProfilerActivity.CPU,
  333. torch.profiler.ProfilerActivity.CUDA,
  334. ],
  335. # In this example with wait=1, warmup=1, active=2, repeat=1,
  336. # profiler will skip the first step/iteration,
  337. # start warming up on the second, record
  338. # the third and the forth iterations,
  339. # after which the trace will become available
  340. # and on_trace_ready (when set) is called;
  341. # the cycle repeats starting with the next step
  342. schedule=torch.profiler.schedule(
  343. wait=1,
  344. warmup=1,
  345. active=2,
  346. repeat=1),
  347. on_trace_ready=trace_handler
  348. # on_trace_ready=torch.profiler.tensorboard_trace_handler('./log')
  349. # used when outputting for tensorboard
  350. ) as p:
  351. for iter in range(N):
  352. code_iteration_to_profile(iter)
  353. # send a signal to the profiler that the next iteration has started
  354. p.step()
  355. """
  356. def __init__(
  357. self,
  358. *,
  359. activities: Optional[Iterable[ProfilerActivity]] = None,
  360. schedule: Optional[Callable[[int], ProfilerAction]] = None,
  361. on_trace_ready: Optional[Callable[..., Any]] = None,
  362. record_shapes: bool = False,
  363. profile_memory: bool = False,
  364. with_stack: bool = False,
  365. with_flops: bool = False,
  366. with_modules: bool = False,
  367. experimental_config: Optional[_ExperimentalConfig] = None,
  368. # deprecated:
  369. use_cuda: Optional[bool] = None):
  370. activities_set = set(activities) if activities else supported_activities()
  371. if use_cuda is not None:
  372. warn("use_cuda is deprecated, use activities argument instead")
  373. if use_cuda:
  374. activities_set.add(ProfilerActivity.CUDA)
  375. elif ProfilerActivity.CUDA in activities_set:
  376. activities_set.remove(ProfilerActivity.CUDA)
  377. assert len(activities_set) > 0, "No valid profiler activities found"
  378. super().__init__(
  379. activities=activities,
  380. record_shapes=record_shapes,
  381. profile_memory=profile_memory,
  382. with_stack=with_stack,
  383. with_flops=with_flops,
  384. with_modules=with_modules,
  385. experimental_config=experimental_config,
  386. )
  387. if schedule:
  388. self.schedule = schedule
  389. # add step markers into the trace and table view
  390. self.record_steps = True
  391. else:
  392. self.schedule = _default_schedule_fn
  393. self.record_steps = False
  394. self.on_trace_ready = on_trace_ready
  395. self.step_num = 0
  396. self.current_action = self.schedule(self.step_num)
  397. self.step_rec_fn: Optional[prof.record_function] = None
  398. self.action_map: Dict[Tuple[ProfilerAction, Optional[ProfilerAction]], List[Any]] = {
  399. # key is (prev_action, current_action), value is action list corresponding to the state pair.
  400. (ProfilerAction.NONE, ProfilerAction.NONE): [],
  401. (ProfilerAction.NONE, ProfilerAction.WARMUP): [self.prepare_trace],
  402. (ProfilerAction.NONE, ProfilerAction.RECORD): [self.prepare_trace, self.start_trace],
  403. (ProfilerAction.NONE, ProfilerAction.RECORD_AND_SAVE): [self.prepare_trace, self.start_trace],
  404. (ProfilerAction.WARMUP, ProfilerAction.NONE): [
  405. partial(warn, "Incorrect schedule: WARMUP followed by NONE"),
  406. self.start_trace,
  407. self.stop_trace],
  408. (ProfilerAction.WARMUP, ProfilerAction.WARMUP): [],
  409. (ProfilerAction.WARMUP, ProfilerAction.RECORD): [self.start_trace],
  410. (ProfilerAction.WARMUP, ProfilerAction.RECORD_AND_SAVE): [self.start_trace],
  411. (ProfilerAction.RECORD, ProfilerAction.NONE): [
  412. partial(warn, "Incorrect schedule: RECORD followed by NONE"),
  413. self.stop_trace],
  414. (ProfilerAction.RECORD, ProfilerAction.WARMUP): [
  415. partial(warn, "Incorrect schedule: RECORD followed by WARMUP"),
  416. self.stop_trace],
  417. (ProfilerAction.RECORD, ProfilerAction.RECORD): [],
  418. (ProfilerAction.RECORD, ProfilerAction.RECORD_AND_SAVE): [],
  419. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.NONE): [self.stop_trace, self._trace_ready],
  420. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.WARMUP): [self.stop_trace, self._trace_ready, self.prepare_trace],
  421. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.RECORD): [
  422. self.stop_trace,
  423. self._trace_ready,
  424. self.prepare_trace,
  425. self.start_trace],
  426. (ProfilerAction.RECORD_AND_SAVE, ProfilerAction.RECORD_AND_SAVE): [
  427. self.stop_trace,
  428. self._trace_ready,
  429. self.prepare_trace,
  430. self.start_trace],
  431. # used for exit action
  432. (ProfilerAction.WARMUP, None): [self.start_trace, self.stop_trace],
  433. (ProfilerAction.RECORD, None): [self.stop_trace, self._trace_ready],
  434. (ProfilerAction.RECORD_AND_SAVE, None): [self.stop_trace, self._trace_ready]
  435. }
  436. # Start tracking increments to profiler step, this will be used
  437. # by Kineto
  438. prof.KinetoStepTracker.init_step_count(PROFILER_STEP_NAME)
  439. def __enter__(self):
  440. self.start()
  441. return self
  442. def __exit__(self, exc_type, exc_val, exc_tb):
  443. self.stop()
  444. prof.KinetoStepTracker.erase_step_count(PROFILER_STEP_NAME)
  445. def start(self):
  446. self._transit_action(ProfilerAction.NONE, self.current_action)
  447. if self.record_steps:
  448. self.step_rec_fn = prof.record_function("ProfilerStep#" + str(self.step_num))
  449. self.step_rec_fn.__enter__()
  450. def stop(self):
  451. if self.record_steps and self.step_rec_fn:
  452. self.step_rec_fn.__exit__(None, None, None)
  453. self._transit_action(self.current_action, None)
  454. def step(self):
  455. """
  456. Signals the profiler that the next profiling step has started.
  457. """
  458. if self.record_steps and self.step_rec_fn:
  459. self.step_rec_fn.__exit__(None, None, None)
  460. prev_action = self.current_action
  461. cur_step = self.step_num
  462. self.step_num += 1
  463. self.current_action = self.schedule(self.step_num)
  464. self._transit_action(prev_action, self.current_action)
  465. prof.KinetoStepTracker.increment_step(PROFILER_STEP_NAME)
  466. if self.record_steps:
  467. self.step_rec_fn = prof.record_function("ProfilerStep#" + str(cur_step))
  468. self.step_rec_fn.__enter__()
  469. def _trace_ready(self):
  470. if self.on_trace_ready:
  471. self.on_trace_ready(self)
  472. def _transit_action(self, prev_action, current_action):
  473. action_list = self.action_map.get((prev_action, current_action))
  474. if action_list:
  475. for action in action_list:
  476. action()
  477. class ExecutionGraphObserver:
  478. """Execution Graph Observer
  479. Each process can have a single ExecutionGraphObserver instance. The observer
  480. can be added to record function callbacks via calling register_callback()
  481. explicitly. Without calling unregister_callback(), repeated calls to
  482. register_callback() will not add additional observers to record function
  483. callbacks. Once an ExecutionGraphObserver is created, the start() and stop()
  484. methods control when the event data is recorded.
  485. Deleting or calling unregister_callback() will remove the observer from the
  486. record function callbacks, finalize the output file, and will stop
  487. incurring any overheads.
  488. """
  489. def __init__(self):
  490. """
  491. Initializes the default states.
  492. """
  493. self._registered = False
  494. self._execution_graph_running = False
  495. def __del__(self):
  496. """
  497. Calls unregister_callback() to make sure to finalize outputs.
  498. """
  499. self.unregister_callback()
  500. def register_callback(self, output_file_path: str):
  501. """
  502. Adds EG observer to record function callbacks. The the data will be
  503. written to output_file_path.
  504. """
  505. if not self._registered:
  506. self._output_file_path = output_file_path
  507. self._registered = _add_execution_graph_observer(output_file_path)
  508. def unregister_callback(self):
  509. """
  510. Removes EG observer from record function callbacks.
  511. """
  512. if self._registered:
  513. self.stop()
  514. _remove_execution_graph_observer()
  515. self._registered = False
  516. @property
  517. def is_registered(self):
  518. """
  519. Return if the execution graph observer is registered.
  520. """
  521. return self._registered
  522. def start(self):
  523. """
  524. Starts to capture.
  525. """
  526. if self._registered and not self._execution_graph_running:
  527. _enable_execution_graph_observer()
  528. self._execution_graph_running = True
  529. def stop(self):
  530. """
  531. Stops to capture.
  532. """
  533. if self._execution_graph_running:
  534. _disable_execution_graph_observer()
  535. self._execution_graph_running = False
  536. def get_output_file_path(self) -> str:
  537. """
  538. Returns the output file name.
  539. """
  540. if self.is_registered:
  541. return self._output_file_path
  542. else:
  543. raise RuntimeError(
  544. "A callback to the EG profiler needs to be registered "
  545. "first before getting the output file path"
  546. )