profiler.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import datetime
  15. import importlib
  16. import json
  17. import os
  18. import socket
  19. from enum import Enum
  20. from typing import Any, Callable, Iterable, Optional, Union
  21. from warnings import warn
  22. import paddle
  23. from paddle.base.core import (
  24. ProfilerOptions,
  25. TracerEventType,
  26. _Profiler,
  27. disable_memory_recorder,
  28. disable_op_info_recorder,
  29. enable_memory_recorder,
  30. enable_op_info_recorder,
  31. )
  32. from paddle.profiler import utils
  33. from .profiler_statistic import (
  34. SortedKeys,
  35. StatisticData,
  36. _build_table,
  37. gen_layer_flops,
  38. )
  39. from .timer import benchmark
  40. from .utils import RecordEvent, wrap_optimizers
  41. class SummaryView(Enum):
  42. r"""
  43. SummaryView define the summary view of different contents.
  44. - **SummaryView.DeviceView** : The device summary view.
  45. - **SummaryView.OverView** : The overview summary view.
  46. - **SummaryView.ModelView** : The model summary view.
  47. - **SummaryView.DistributedView** : The distributed summary view.
  48. - **SummaryView.KernelView** : The kernel summary view.
  49. - **SummaryView.OperatorView** : The operator summary view.
  50. - **SummaryView.MemoryView** : The memory summary view.
  51. - **SummaryView.MemoryManipulationView** : The memory manipulation summary view.
  52. - **SummaryView.UDFView** : The user defined summary view.
  53. """
  54. DeviceView = 0
  55. OverView = 1
  56. ModelView = 2
  57. DistributedView = 3
  58. KernelView = 4
  59. OperatorView = 5
  60. MemoryView = 6
  61. MemoryManipulationView = 7
  62. UDFView = 8
  63. class ProfilerState(Enum):
  64. r"""
  65. ProfilerState is used to present the state of :ref:`Profiler <api_paddle_profiler_Profiler>` .
  66. The meaning of each ProfilerState is as following
  67. - **ProfilerState.CLOSED** : The profiler is closed, and no profiling data will be recorded.
  68. - **ProfilerState.READY** : The profiler is open, but the data will not be recorded. This state is used for reducing overhead influence when profiler starts.
  69. - **ProfilerState.RECORD** : The profiler is open, and the data will be recorded.
  70. - **ProfilerState.RECORD_AND_RETURN** : The profiler is open, and this state stands for the last batch of "RECORD" state in current profiling period. The collected data will be returned in this state.
  71. """
  72. CLOSED = 0
  73. READY = 1
  74. RECORD = 2
  75. RECORD_AND_RETURN = 3 # the last step of RECORD
  76. class ProfilerTarget(Enum):
  77. r"""
  78. ProfilerTarget is used to specify target device for :ref:`Profiler <api_paddle_profiler_Profiler>` . Only CPU, GPU and XPU are supported currently.
  79. The meaning of each ProfilerState is as following
  80. - **ProfilerTarget.CPU** : Profile events on CPU.
  81. - **ProfilerTarget.GPU** : Profile events on GPU.
  82. - **ProfilerTarget.XPU** : Profile events on XPU.
  83. """
  84. CPU = 0
  85. GPU = 1
  86. XPU = 2
  87. CUSTOM_DEVICE = 3
  88. def make_scheduler(
  89. *,
  90. closed: int,
  91. ready: int,
  92. record: int,
  93. repeat: int = 0,
  94. skip_first: int = 0,
  95. ) -> Callable:
  96. r"""
  97. Return a scheduler function, which scheduler the :ref:`ProfilerState <api_paddle_profiler_ProfilerState>` according to the setting.
  98. The state transform confirms to:
  99. .. code-block:: text
  100. (CLOSED) (CLOSED) (CLOSED) (READY) (RECORD,last RETURN) (CLOSED)
  101. START -> skip_first -> closed -> ready -> record -> END
  102. | |
  103. | | (if has_repeated < repeat)
  104. - - - - - - - - - - - -
  105. Note that repeat <= 0 means the cycle will continue until the profiler exits.
  106. Args:
  107. closed(int): The number of steps in state ProfilerState.CLOSED.
  108. ready(int): The number of steps in state ProfilerState.READY.
  109. record(int): The number of steps in state ProfilerState.RECORD, and the state in last step will be set as ProfilerState.RECORD_AND_RETURN.
  110. repeat(int, optional): The number of cycles to repeat above state transform. Default value is 0, which means it will repeat this cycle until profiler exits.
  111. skip_first(int, optional): The number of first steps to drop, not participate in the state transform, and at ProfilerState.CLOSED state. Default value is 0.
  112. Returns:
  113. A scheduler function, conforms to above state transform setting. The function will takes one parameter `step_num`, and returns corresponding ProfilerState.
  114. Examples:
  115. 1. profiling range [2, 5].
  116. Assume batch 0: closed, batch 1: ready, batch [2, 5] record.
  117. .. code-block:: python
  118. :name: code-example1
  119. >>> import paddle.profiler as profiler
  120. >>> profiler.make_scheduler(closed=1, ready=1, record=4, repeat=1)
  121. 2. profiling range [3,6], [9,12], [15,18].
  122. Assume batch 0: skipped, batch 1: closed, batch 2: ready, batch [3,6]: record, repeat.
  123. .. code-block:: python
  124. :name: code-example2
  125. >>> import paddle.profiler as profiler
  126. >>> profiler.make_scheduler(closed=1, ready=1, record=4, skip_first=1)
  127. """
  128. def getScheduleState(step: int) -> ProfilerState:
  129. assert step >= 0
  130. if step < skip_first: # within skip_first, just skip
  131. return ProfilerState.CLOSED
  132. step = step - skip_first
  133. period_steps = closed + ready + record
  134. has_repeated = step // period_steps
  135. if (
  136. repeat > 0 and has_repeated >= repeat
  137. ): # the period has repeated repeat times, return CLOSED state
  138. return ProfilerState.CLOSED
  139. mod_step = step % period_steps
  140. if mod_step < closed:
  141. return ProfilerState.CLOSED
  142. elif mod_step >= closed and mod_step < closed + ready:
  143. return ProfilerState.READY
  144. else:
  145. if mod_step < period_steps - 1:
  146. return ProfilerState.RECORD
  147. else:
  148. return ProfilerState.RECORD_AND_RETURN
  149. assert (
  150. closed >= 0
  151. and ready >= 0
  152. and record > 0
  153. and repeat >= 0
  154. and skip_first >= 0
  155. ), "Invalid profiler scheduler arguments"
  156. if ready == 0:
  157. warn(
  158. "Profiler will record data after enabling profiler immediately, \
  159. some data collected at the beginning of profiling may be 'noisy' because of overhead."
  160. )
  161. return getScheduleState
  162. def _default_state_scheduler(step: int):
  163. r"""
  164. A default state scheduler, keep recording from the beginning of the profiler until ending.
  165. """
  166. return ProfilerState.RECORD
  167. def export_chrome_tracing(
  168. dir_name: str, worker_name: Optional[str] = None
  169. ) -> Callable:
  170. r"""
  171. Return a callable, used for outputing tracing data to chrome tracing format file.
  172. The output file will be saved in directory ``dir_name``, and file name will be set as `worker_name`.
  173. if `worker_name` is not set, the default name is `[hostname]_[pid]`.
  174. Args:
  175. dir_name(str): Directory to save profiling data.
  176. worker_name(str, optional): Prefix of the file name saved, default is `[hostname]_[pid]`.
  177. Returns:
  178. A callable, which takes a Profiler object as parameter and calls its export method to save data to chrome tracing format file.
  179. Examples:
  180. The return value can be used as parameter ``on_trace_ready`` in :ref:`Profiler <api_paddle_profiler_Profiler>` .
  181. .. code-block:: python
  182. >>> # doctest: +REQUIRES(env:GPU)
  183. >>> import paddle.profiler as profiler
  184. >>> import paddle
  185. >>> paddle.device.set_device('gpu')
  186. >>> with profiler.Profiler(
  187. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  188. ... scheduler = (3, 10),
  189. ... on_trace_ready=profiler.export_chrome_tracing('./log')) as p:
  190. ... for iter in range(10):
  191. ... #train()
  192. ... p.step()
  193. """
  194. if not os.path.exists(dir_name):
  195. try:
  196. os.makedirs(dir_name, exist_ok=True)
  197. except Exception:
  198. raise RuntimeError(
  199. f"Can not create directory '{dir_name}' for saving profiling results."
  200. )
  201. def handle_fn(prof):
  202. nonlocal worker_name
  203. if not worker_name:
  204. worker_name = f"host_{socket.gethostname()}pid_{str(os.getpid())}"
  205. now = datetime.datetime.now()
  206. filename = '{}_time_{}.paddle_trace.json'.format(
  207. worker_name, now.strftime('%Y_%m_%d_%H_%M_%S_%f')
  208. )
  209. prof.export(os.path.join(dir_name, filename), "json")
  210. return handle_fn
  211. def export_protobuf(
  212. dir_name: str, worker_name: Optional[str] = None
  213. ) -> Callable:
  214. r"""
  215. Return a callable, used for outputing tracing data to protobuf file.
  216. The output file will be saved in directory ``dir_name``, and file name will be set as ``worker_name``.
  217. if ``worker_name`` is not set, the default name is `[hostname]_[pid]`.
  218. Args:
  219. dir_name(str): Directory to save profiling data.
  220. worker_name(str, optional): Prefix of the file name saved, default is `[hostname]_[pid]`.
  221. Returns:
  222. A callable, which takes a Profiler object as parameter and calls its export method to save data to protobuf file.
  223. Examples:
  224. The return value can be used as parameter ``on_trace_ready`` in :ref:`Profiler <api_paddle_profiler_Profiler>` .
  225. .. code-block:: python
  226. >>> # doctest: +REQUIRES(env:GPU)
  227. >>> import paddle.profiler as profiler
  228. >>> import paddle
  229. >>> paddle.device.set_device('gpu')
  230. >>> with profiler.Profiler(
  231. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  232. ... scheduler = (3, 10),
  233. ... on_trace_ready = profiler.export_protobuf('./log')
  234. ... ) as p:
  235. ... for iter in range(10):
  236. ... # train()
  237. ... p.step()
  238. """
  239. if not os.path.exists(dir_name):
  240. try:
  241. os.makedirs(dir_name, exist_ok=True)
  242. except Exception:
  243. raise RuntimeError(
  244. f"Can not create directory '{dir_name}' for saving profiling results."
  245. )
  246. def handle_fn(prof):
  247. nonlocal worker_name
  248. if not worker_name:
  249. worker_name = f"host_{socket.gethostname()}pid_{str(os.getpid())}"
  250. now = datetime.datetime.now()
  251. filename = '{}_time_{}.paddle_trace.pb'.format(
  252. worker_name, now.strftime('%Y_%m_%d_%H_%M_%S_%f')
  253. )
  254. prof.export(os.path.join(dir_name, filename), "pb")
  255. return handle_fn
  256. def _get_supported_targets() -> Iterable[ProfilerTarget]:
  257. r"""
  258. Get the current supported profiler target in the system.
  259. """
  260. if _Profiler.is_cupti_supported():
  261. return [
  262. ProfilerTarget.CPU,
  263. ProfilerTarget.GPU,
  264. ProfilerTarget.CUSTOM_DEVICE,
  265. ]
  266. if _Profiler.is_cnpapi_supported():
  267. return [
  268. ProfilerTarget.CPU,
  269. ProfilerTarget.CUSTOM_DEVICE,
  270. ]
  271. if _Profiler.is_xpti_supported():
  272. return [
  273. ProfilerTarget.CPU,
  274. ProfilerTarget.XPU,
  275. ProfilerTarget.CUSTOM_DEVICE,
  276. ]
  277. return [ProfilerTarget.CPU, ProfilerTarget.CUSTOM_DEVICE]
  278. class Profiler:
  279. r"""
  280. Profiler context manager, user interface to manage profiling process to start, stop, export profiling data and print summary table.
  281. Args:
  282. targets (list, optional): specify target devices to profile, and all existing and supported devices will be chosen by default. Currently supported values, :ref:`ProfilerTarget.CPU <api_paddle_profiler_ProfilerTarget>` , :ref:`ProfilerTarget.GPU <api_paddle_profiler_ProfilerTarget>` and :ref:`ProfilerTarget.XPU <api_paddle_profiler_ProfilerTarget>` .
  283. scheduler (Callable|tuple, optional): If it is a callable object, it takes a step number as parameter and return the corresponding :ref:`ProfilerState <api_paddle_profiler_ProfilerState>`. This callable object can be generated by :ref:`make_scheduler <api_paddle_profiler_make_scheduler>` function.
  284. If not provided (None), the default scheduler will keep tracing until the profiler exits. If it is a tuple, it has two values start_batch and end_batch,
  285. which means profiling range [start_batch, end_batch).
  286. on_trace_ready (Callable, optional): Callable object, serves as callback function, and takes the Profiler object as parameter, which provides a way for users to do post-processing.
  287. This callable object will be called when ``scheduler`` returns ``ProfilerState.RECORD_AND_RETURN``. The default value is :ref:`export_chrome_tracing <api_paddle_profiler_export_chrome_tracing>`.
  288. timer_only (bool, optional): If it is True, the cost of Dataloader and every step of the model will be count without profiling. Otherwise, the model will
  289. be timed and profiled. Default: False.
  290. record_shapes (bool, optional): If it is True, collect op's input shape information. Default: False.
  291. profile_memory (bool, optional): If it is True, collect tensor memory allocation and release information. Default: False.
  292. custom_device_types (list, optional): If targets contain profiler.ProfilerTarget.CUSTOM_DEVICE, custom_device_types select the custom device type for profiling. The default value represents all custom devices will be selected.
  293. with_flops (bool, optional): If it is True, the flops of the op will be calculated. Default: False.
  294. Examples:
  295. 1. profiling range [2, 5).
  296. .. code-block:: python
  297. :name: code-example1
  298. >>> # doctest: +REQUIRES(env:GPU)
  299. >>> import paddle.profiler as profiler
  300. >>> import paddle
  301. >>> paddle.device.set_device('gpu')
  302. >>> with profiler.Profiler(
  303. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  304. ... scheduler = (2, 5),
  305. ... on_trace_ready = profiler.export_chrome_tracing('./log')
  306. ... ) as p:
  307. ... for iter in range(10):
  308. ... # train()
  309. ... p.step()
  310. 2. profiling range [2,4], [7, 9], [11,13].
  311. .. code-block:: python
  312. :name: code-example2
  313. >>> # doctest: +REQUIRES(env:GPU)
  314. >>> import paddle.profiler as profiler
  315. >>> import paddle
  316. >>> paddle.device.set_device('gpu')
  317. >>> with profiler.Profiler(
  318. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  319. ... scheduler = profiler.make_scheduler(closed=1, ready=1, record=3, repeat=3),
  320. ... on_trace_ready = profiler.export_chrome_tracing('./log')
  321. ... ) as p:
  322. ... for iter in range(10):
  323. ... # train()
  324. ... p.step()
  325. 3. Use profiler without context manager, and use default parameters.
  326. .. code-block:: python
  327. :name: code-example3
  328. >>> # doctest: +REQUIRES(env:GPU)
  329. >>> import paddle.profiler as profiler
  330. >>> import paddle
  331. >>> paddle.device.set_device('gpu')
  332. >>> p = profiler.Profiler()
  333. >>> p.start()
  334. >>> for iter in range(10):
  335. ... #train()
  336. ... p.step()
  337. >>> p.stop()
  338. >>> p.summary()
  339. 4. Use profiler to get throughput and cost of the model.
  340. .. code-block:: python
  341. :name: code-example-timer1
  342. >>> import paddle
  343. >>> import paddle.profiler as profiler
  344. >>> class RandomDataset(paddle.io.Dataset):
  345. ... def __init__(self, num_samples):
  346. ... self.num_samples = num_samples
  347. ... def __getitem__(self, idx):
  348. ... image = paddle.rand(shape=[100], dtype='float32')
  349. ... label = paddle.randint(0, 10, shape=[1], dtype='int64')
  350. ... return image, label
  351. ... def __len__(self):
  352. ... return self.num_samples
  353. >>> class SimpleNet(paddle.nn.Layer):
  354. ... def __init__(self):
  355. ... super().__init__()
  356. ... self.fc = paddle.nn.Linear(100, 10)
  357. ... def forward(self, image, label=None):
  358. ... return self.fc(image)
  359. >>> dataset = RandomDataset(20 * 4)
  360. >>> simple_net = SimpleNet()
  361. >>> opt = paddle.optimizer.SGD(learning_rate=1e-3, parameters=simple_net.parameters())
  362. >>> BATCH_SIZE = 4
  363. >>> loader = paddle.io.DataLoader(
  364. ... dataset,
  365. ... batch_size=BATCH_SIZE)
  366. >>> p = profiler.Profiler(timer_only=True)
  367. >>> p.start()
  368. >>> for i, (image, label) in enumerate(loader()):
  369. ... out = simple_net(image)
  370. ... loss = paddle.nn.functional.cross_entropy(out, label)
  371. ... avg_loss = paddle.mean(loss)
  372. ... avg_loss.backward()
  373. ... opt.minimize(avg_loss)
  374. ... simple_net.clear_gradients()
  375. ... p.step(num_samples=BATCH_SIZE)
  376. ... if i % 10 == 0:
  377. ... step_info = p.step_info(unit='images')
  378. ... print("Iter {}: {}".format(i, step_info))
  379. ... # The average statistics for 10 steps between the last and this call will be
  380. ... # printed when the "step_info" is called at 10 iteration intervals.
  381. ... # The values you get may be different from the following.
  382. ... # Iter 0: reader_cost: 0.51946 s batch_cost: 0.66077 s ips: 6.054 images/s
  383. ... # Iter 10: reader_cost: 0.00014 s batch_cost: 0.00441 s ips: 907.009 images/s
  384. >>> p.stop()
  385. >>> # The performance summary will be automatically printed when the "stop" is called.
  386. >>> # Reader Ratio: 2.658%
  387. >>> # Time Unit: s, IPS Unit: images/s
  388. >>> # | | avg | max | min |
  389. >>> # | reader_cost | 0.00011 | 0.00013 | 0.00007 |
  390. >>> # | batch_cost | 0.00405 | 0.00434 | 0.00326 |
  391. >>> # | ips | 1086.42904 | 1227.30604 | 959.92796 |
  392. """
  393. def __init__(
  394. self,
  395. *,
  396. targets: Optional[Iterable[ProfilerTarget]] = None,
  397. scheduler: Union[Callable[[int], ProfilerState], tuple, None] = None,
  398. on_trace_ready: Optional[Callable[..., Any]] = None,
  399. record_shapes: Optional[bool] = False,
  400. profile_memory: Optional[bool] = False,
  401. timer_only: Optional[bool] = False,
  402. emit_nvtx: Optional[bool] = False,
  403. custom_device_types: Optional[list] = [],
  404. with_flops: Optional[bool] = False,
  405. ):
  406. supported_targets = _get_supported_targets()
  407. if targets:
  408. self.targets = set(targets)
  409. for target in targets:
  410. if target not in supported_targets:
  411. self.targets.remove(target)
  412. warn(
  413. f"Profiling {target} is not supported in current context."
  414. )
  415. else:
  416. self.targets = supported_targets
  417. profileoption = ProfilerOptions()
  418. if ProfilerTarget.CPU in self.targets:
  419. profileoption.trace_switch |= 1
  420. if ProfilerTarget.GPU in self.targets:
  421. profileoption.trace_switch |= 1 << 1
  422. if ProfilerTarget.XPU in self.targets:
  423. profileoption.trace_switch |= 1 << 2
  424. if ProfilerTarget.CUSTOM_DEVICE in self.targets:
  425. profileoption.trace_switch |= 1 << 3
  426. if not custom_device_types:
  427. custom_device_types = paddle.device.get_all_custom_device_type()
  428. wrap_optimizers()
  429. self.profiler = _Profiler.create(profileoption, custom_device_types)
  430. if callable(scheduler):
  431. self.scheduler = scheduler
  432. elif isinstance(scheduler, (tuple, list)):
  433. assert len(scheduler) == 2 and scheduler[1] > scheduler[0]
  434. start_batch, end_batch = scheduler
  435. start_batch = max(start_batch, 0)
  436. if start_batch >= 1:
  437. self.scheduler = make_scheduler(
  438. closed=max(start_batch - 1, 0),
  439. ready=1,
  440. record=(end_batch - start_batch),
  441. repeat=1,
  442. )
  443. else:
  444. self.scheduler = make_scheduler(
  445. closed=0,
  446. ready=0,
  447. record=(end_batch - start_batch),
  448. repeat=1,
  449. )
  450. else:
  451. self.scheduler = _default_state_scheduler
  452. if on_trace_ready is None:
  453. self.on_trace_ready = export_chrome_tracing('./profiler_log/')
  454. else:
  455. self.on_trace_ready = on_trace_ready
  456. self.step_num = 0
  457. self.previous_state = ProfilerState.CLOSED
  458. self.current_state = self.scheduler(self.step_num)
  459. self.record_event = None
  460. self.profiler_result = None
  461. self.timer_only = timer_only
  462. self.record_shapes = record_shapes
  463. self.profile_memory = profile_memory
  464. self.with_flops = with_flops
  465. self.emit_nvtx = emit_nvtx
  466. def __enter__(self):
  467. self.start()
  468. return self
  469. def __exit__(self, exc_type, exc_val, exc_tb):
  470. self.stop()
  471. def start(self):
  472. r'''
  473. Start profiler and enter the first profiler step(0).
  474. State transformed from CLOSED to self.current_state and trigger corresponding action.
  475. Examples:
  476. .. code-block:: python
  477. :name: code-example4
  478. >>> # doctest: +REQUIRES(env:GPU)
  479. >>> import paddle.profiler as profiler
  480. >>> import paddle
  481. >>> paddle.device.set_device('gpu')
  482. >>> prof = profiler.Profiler(
  483. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  484. ... scheduler = (1, 9),
  485. ... on_trace_ready = profiler.export_chrome_tracing('./log'))
  486. >>> prof.start()
  487. >>> for iter in range(10):
  488. ... # train()
  489. ... prof.step()
  490. >>> prof.stop()
  491. '''
  492. # Timing only without profiling.
  493. benchmark().begin()
  494. if not self.timer_only or self.emit_nvtx:
  495. utils._is_profiler_used = True
  496. if self.timer_only:
  497. return
  498. if self.record_shapes or self.with_flops:
  499. enable_op_info_recorder()
  500. if self.profile_memory:
  501. enable_memory_recorder()
  502. # CLOSED -> self.current_state
  503. if self.current_state == ProfilerState.READY:
  504. self.profiler.prepare()
  505. elif self.current_state == ProfilerState.RECORD:
  506. self.profiler.prepare()
  507. self.profiler.start()
  508. elif self.current_state == ProfilerState.RECORD_AND_RETURN:
  509. self.profiler.prepare()
  510. self.profiler.start()
  511. self.record_event = RecordEvent(
  512. name=f"ProfileStep#{self.step_num}",
  513. event_type=TracerEventType.ProfileStep,
  514. )
  515. self.record_event.begin()
  516. def stop(self):
  517. r'''
  518. Stop profiler and State transformed from self.current_state to CLOSED.
  519. Trigger corresponding action and post-process profiler result using self.on_trace_ready if result exists.
  520. Examples:
  521. .. code-block:: python
  522. :name: code-example5
  523. >>> # doctest: +REQUIRES(env:GPU)
  524. >>> import paddle.profiler as profiler
  525. >>> import paddle
  526. >>> paddle.device.set_device('gpu')
  527. >>> prof = profiler.Profiler(
  528. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  529. ... scheduler = (1, 7),
  530. ... on_trace_ready = profiler.export_chrome_tracing('./log'))
  531. >>> prof.start()
  532. >>> for iter in range(10):
  533. ... # train()
  534. ... prof.step()
  535. ... prof.stop()
  536. '''
  537. benchmark().end()
  538. if self.timer_only:
  539. return
  540. if self.record_shapes or self.with_flops:
  541. disable_op_info_recorder()
  542. if self.profile_memory:
  543. disable_memory_recorder()
  544. # self.current_state -> CLOSED
  545. # In this situation, RECORD state is regarded as RECORD_AND_RETURN.
  546. if self.record_event:
  547. self.record_event.end()
  548. self.record_event = None
  549. if self.current_state == ProfilerState.READY:
  550. warn(
  551. "Inproper Profiler state transform: READY->CLOSED, profiler will start and stop without saving data"
  552. )
  553. self.profiler.start()
  554. self.profiler.stop()
  555. if (
  556. self.current_state == ProfilerState.RECORD
  557. or self.current_state == ProfilerState.RECORD_AND_RETURN
  558. ):
  559. self.profiler_result = self.profiler.stop()
  560. if self.on_trace_ready:
  561. self.on_trace_ready(self)
  562. utils._is_profiler_used = False
  563. def step(self, num_samples: Optional[int] = None):
  564. r"""
  565. Signals the profiler that the next profiling step has started.
  566. Get the new ProfilerState and trigger corresponding action.
  567. Args:
  568. num_samples (int|None, optional): Specifies the batch size of every step of the model
  569. that is used to compute throughput when `timer_only` is True. Default: None.
  570. Examples:
  571. .. code-block:: python
  572. :name: code-example6
  573. >>> # doctest: +REQUIRES(env:GPU)
  574. >>> import paddle.profiler as profiler
  575. >>> import paddle
  576. >>> paddle.device.set_device('gpu')
  577. >>> prof = profiler.Profiler(
  578. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  579. ... scheduler = (3, 7),
  580. ... on_trace_ready = profiler.export_chrome_tracing('./log'))
  581. >>> prof.start()
  582. >>> for iter in range(10):
  583. ... #train()
  584. ... prof.step()
  585. >>> prof.stop()
  586. """
  587. benchmark().step(num_samples)
  588. if self.timer_only:
  589. return
  590. if self.record_event:
  591. self.record_event.end()
  592. self.record_event = None
  593. self.previous_state = self.current_state
  594. self.step_num += 1
  595. self.current_state = self.scheduler(self.step_num)
  596. self._trigger_action()
  597. self.record_event = RecordEvent(
  598. name=f"ProfileStep#{self.step_num}",
  599. event_type=TracerEventType.ProfileStep,
  600. )
  601. self.record_event.begin()
  602. def step_info(self, unit=None):
  603. r"""
  604. Get statistics for current step. If the function is called at certain iteration
  605. intervals, the result is the average of all steps between the previous call and
  606. this call. Statistics are as follows:
  607. 1. reader_cost: the cost of loading data measured in seconds.
  608. 2. batch_cost: the cost of step measured in seconds.
  609. 3. ips(Instance Per Second): the throughput of the model measured in `samples/s`
  610. or others depends on the `unit`. When `num_samples` of `step()` is None, it is
  611. measured in `steps/s`.
  612. Args:
  613. unit (string, optional): The unit of input data is only used When `num_samples`
  614. of `step()` is specified as a number. For example, when it is `images`, the unit
  615. of throughput is `images/s`. Default: None, the unit of throughput is `samples/s`.
  616. Returns:
  617. string: A string representing the statistic.
  618. Examples:
  619. .. code-block:: python
  620. :name: code-example-timer2
  621. >>> import paddle.profiler as profiler
  622. >>> prof = profiler.Profiler(timer_only=True)
  623. >>> prof.start()
  624. >>> for iter in range(20):
  625. ... #train()
  626. ... prof.step()
  627. ... if iter % 10 == 0:
  628. ... print("Iter {}: {}".format(iter, prof.step_info()))
  629. ... # The example does not call the DataLoader, so there is no "reader_cost".
  630. ... # Iter 0: batch_cost: 0.00001 s ips: 86216.623 steps/s
  631. ... # Iter 10: batch_cost: 0.00001 s ips: 103645.034 steps/s
  632. >>> prof.stop()
  633. >>> # Time Unit: s, IPS Unit: steps/s
  634. >>> # | | avg | max | min |
  635. >>> # | batch_cost | 0.00000 | 0.00002 | 0.00000 |
  636. >>> # | ips | 267846.19437 | 712030.38727 | 45134.16662 |
  637. """
  638. if unit is None:
  639. unit = 'samples'
  640. return benchmark().step_info(unit)
  641. def _trigger_action(self):
  642. if self.previous_state == ProfilerState.CLOSED:
  643. if self.current_state == ProfilerState.READY: # CLOSED -> READY
  644. self.profiler.prepare()
  645. if self.current_state == ProfilerState.RECORD: # CLOSED -> RECORD
  646. self.profiler.prepare()
  647. self.profiler.start()
  648. if (
  649. self.current_state == ProfilerState.RECORD_AND_RETURN
  650. ): # CLOSED -> RECORD_AND_RETURN
  651. self.profiler.prepare()
  652. self.profiler.start()
  653. elif self.previous_state == ProfilerState.READY:
  654. if self.current_state == ProfilerState.CLOSED: # READY -> CLOSED
  655. warn(
  656. "Improper schedule: READY->CLOSED, profiler will start and stop without saving data"
  657. )
  658. self.profiler.start()
  659. self.profiler.stop()
  660. if self.current_state == ProfilerState.RECORD: # READY -> RECORD
  661. self.profiler.start()
  662. if (
  663. self.current_state == ProfilerState.RECORD_AND_RETURN
  664. ): # READY -> RECORD_AND_RETURN
  665. self.profiler.start()
  666. elif self.previous_state == ProfilerState.RECORD:
  667. if self.current_state == ProfilerState.CLOSED: # RECORD -> CLOSED
  668. warn(
  669. "Improper schedule: RECORD->CLOSED, profiler will not saving data"
  670. )
  671. self.profiler.stop()
  672. if self.current_state == ProfilerState.READY: # RECORD -> READY
  673. warn(
  674. "Improper schedule: RECORD->READY, profiler will stop and re-prepare"
  675. )
  676. self.profiler.stop()
  677. self.profiler.prepare()
  678. if (
  679. self.current_state == ProfilerState.RECORD_AND_RETURN
  680. ): # RECORD -> RECORD_AND_RETURN
  681. pass
  682. else:
  683. assert self.previous_state == ProfilerState.RECORD_AND_RETURN
  684. if (
  685. self.current_state == ProfilerState.CLOSED
  686. ): # RECORD_AND_RETURN -> CLOSED
  687. self.profiler_result = self.profiler.stop()
  688. if (
  689. self.current_state == ProfilerState.READY
  690. ): # RECORD_AND_RETURN -> READY
  691. self.profiler_result = self.profiler.stop()
  692. self.profiler.prepare()
  693. if (
  694. self.current_state == ProfilerState.RECORD
  695. ): # RECORD_AND_RETURN -> RECORD
  696. self.profiler_result = self.profiler.stop()
  697. self.profiler.prepare()
  698. self.profiler.start()
  699. if (
  700. self.current_state == ProfilerState.RECORD_AND_RETURN
  701. ): # RECORD_AND_RETURN -> RECORD_AND_RETURN
  702. self.profiler_result = self.profiler.stop()
  703. self.profiler.prepare()
  704. self.profiler.start()
  705. if self.on_trace_ready:
  706. self.on_trace_ready(self)
  707. def export(self, path="", format="json"):
  708. r"""
  709. Exports the tracing data to file.
  710. Args:
  711. path(str): file path of the output.
  712. format(str, optional): output format, can be chosen from ['json', 'pb'], 'json' for chrome tracing and 'pb' for protobuf, default value is 'json'.
  713. Examples:
  714. .. code-block:: python
  715. :name: code-example7
  716. >>> # doctest: +REQUIRES(env:GPU)
  717. >>> import paddle
  718. >>> paddle.device.set_device('gpu')
  719. >>> import paddle.profiler as profiler
  720. >>> prof = profiler.Profiler(
  721. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  722. ... scheduler = (3, 7))
  723. >>> prof.start()
  724. >>> for iter in range(10):
  725. ... # train()
  726. ... prof.step()
  727. >>> prof.stop()
  728. >>> prof.export(path="./profiler_data.json", format="json")
  729. """
  730. if self.profiler_result:
  731. self.profiler_result.save(path, format)
  732. def summary(
  733. self,
  734. sorted_by=SortedKeys.CPUTotal,
  735. op_detail=True,
  736. thread_sep=False,
  737. time_unit='ms',
  738. views=None,
  739. ):
  740. r"""
  741. Print the Summary table. Currently support overview, model, distributed, operator, memory manipulation and user-defined summary.
  742. Args:
  743. sorted_by( :ref:`SortedKeys <api_paddle_profiler_SortedKeys>` , optional): how to rank the op table items, default value is SortedKeys.CPUTotal.
  744. op_detail(bool, optional): expand each operator detail information, default value is True.
  745. thread_sep(bool, optional): print op table each thread, default value is False.
  746. time_unit(str, optional): time unit for display, can be chosen form ['s', 'ms', 'us', 'ns'], default value is 'ms'.
  747. views(SummaryView|list[SummaryView], optional): summary tables to print, default to None means all views to be printed.
  748. Examples:
  749. .. code-block:: python
  750. >>> # doctest: +REQUIRES(env:GPU)
  751. >>> import paddle
  752. >>> paddle.device.set_device('gpu')
  753. >>> import paddle.profiler as profiler
  754. >>> prof = profiler.Profiler(
  755. ... targets=[profiler.ProfilerTarget.CPU, profiler.ProfilerTarget.GPU],
  756. ... scheduler = (3, 7),
  757. ... on_trace_ready = profiler.export_chrome_tracing('./log'))
  758. >>> prof.start()
  759. >>> for iter in range(10):
  760. ... # train()
  761. ... prof.step()
  762. >>> prof.stop()
  763. >>> prof.summary(sorted_by=profiler.SortedKeys.CPUTotal, op_detail=True, thread_sep=False, time_unit='ms')
  764. """
  765. if isinstance(views, SummaryView):
  766. views = [views]
  767. if self.profiler_result:
  768. statistic_data = StatisticData(
  769. self.profiler_result.get_data(),
  770. self.profiler_result.get_extra_info(),
  771. )
  772. print(
  773. _build_table(
  774. statistic_data,
  775. sorted_by=sorted_by,
  776. op_detail=op_detail,
  777. thread_sep=thread_sep,
  778. time_unit=time_unit,
  779. views=views,
  780. )
  781. )
  782. if self.with_flops:
  783. self._print_flops()
  784. def _print_flops(self, repeat=1):
  785. if not self.with_flops:
  786. print('ERROR: with_flops disabled.')
  787. return
  788. print(" Flops Profiler Begin ".center(100, "-"))
  789. print(gen_layer_flops(self.profiler_result.get_data(), repeat))
  790. print("- Flops Profiler End -".center(100, "-"))
  791. def get_profiler(config_path):
  792. try:
  793. with open(config_path, 'r') as filehandle:
  794. config_dict = json.load(filehandle)
  795. except Exception as e:
  796. print(f'Load config file for profiler error: {e}')
  797. print('Use default parameters instead.')
  798. return Profiler()
  799. translated_config_dict = {}
  800. if "targets" in config_dict:
  801. try:
  802. translated_config_dict['targets'] = []
  803. for target in config_dict['targets']:
  804. if target.lower() == "cpu":
  805. translated_config_dict['targets'].append(ProfilerTarget.CPU)
  806. elif target.lower() == 'gpu':
  807. translated_config_dict['targets'].append(ProfilerTarget.GPU)
  808. except:
  809. print('Set targets parameter error, use default parameter instead.')
  810. translated_config_dict['targets'] = None
  811. if "scheduler" in config_dict:
  812. try:
  813. if isinstance(config_dict['scheduler'], dict):
  814. for key, value in config_dict['scheduler'].items():
  815. module_path = value['module']
  816. use_direct = value['use_direct']
  817. module = importlib.import_module(module_path)
  818. method = getattr(module, key)
  819. if not use_direct:
  820. translated_config_dict['scheduler'] = method(
  821. *value['args'], **value['kwargs']
  822. )
  823. else:
  824. translated_config_dict['scheduler'] = method
  825. else:
  826. translated_config_dict['scheduler'] = [
  827. config_dict['scheduler'][0],
  828. config_dict['scheduler'][1],
  829. ]
  830. except:
  831. print(
  832. 'Set scheduler parameter error, use default parameter instead.'
  833. )
  834. translated_config_dict['scheduler'] = None
  835. if "on_trace_ready" in config_dict:
  836. try:
  837. if isinstance(config_dict['on_trace_ready'], dict):
  838. for key, value in config_dict['on_trace_ready'].items():
  839. module_path = value['module']
  840. use_direct = value['use_direct']
  841. module = importlib.import_module(module_path)
  842. method = getattr(module, key)
  843. if not use_direct:
  844. translated_config_dict['on_trace_ready'] = method(
  845. *value['args'], **value['kwargs']
  846. )
  847. else:
  848. translated_config_dict['on_trace_ready'] = method
  849. except:
  850. print(
  851. 'Set on_trace_ready parameter error, use default parameter instead.'
  852. )
  853. translated_config_dict['on_trace_ready'] = None
  854. if "timer_only" in config_dict:
  855. if isinstance(config_dict['timer_only'], bool):
  856. translated_config_dict['timer_only'] = config_dict['timer_only']
  857. else:
  858. print(
  859. 'Set timer_only parameter error, use default parameter instead.'
  860. )
  861. return Profiler(**translated_config_dict)