timer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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 timeit
  15. from collections import OrderedDict
  16. class Stack:
  17. """
  18. The stack in a Last-In/First-Out (LIFO) manner. New element is added at
  19. the end and an element is removed from that end.
  20. """
  21. def __init__(self):
  22. self.items = []
  23. def push(self, item):
  24. self.items.append(item)
  25. def pop(self):
  26. return self.items.pop()
  27. def is_empty(self):
  28. return len(self.items) == 0
  29. def peek(self):
  30. if not self.is_empty():
  31. return self.items[len(self.items) - 1]
  32. else:
  33. return None
  34. class Event:
  35. """
  36. A Event is used to record the cost of every step and the cost of
  37. the total steps except skipped steps.
  38. """
  39. def __init__(self):
  40. self.reader_cost_averager = TimeAverager()
  41. self.batch_cost_averager = TimeAverager()
  42. self.total_samples = 0
  43. self.total_iters = 0
  44. self.skip_iter = 10
  45. self.reader_records = {'max': 0, 'min': float('inf'), 'total': 0}
  46. self.batch_records = {'max': 0, 'min': float('inf'), 'total': 0}
  47. self.speed_records = {'max': 0, 'min': float('inf')}
  48. self.reader = None
  49. self.need_record = True
  50. # The speed mode depends on the setting of num_samples, there
  51. # are 2 modes: steps/s(num_samples=None) or samples/s.
  52. self.speed_mode = 'samples/s'
  53. # The speed unit depends on the unit of samples that is
  54. # specified in step_info and only works in this speed_mode="samples/s".
  55. self.speed_unit = 'samples/s'
  56. def reset(self):
  57. self.reader_cost_averager.reset()
  58. self.batch_cost_averager.reset()
  59. def record_reader(self, usetime):
  60. self.reader_cost_averager.record(usetime)
  61. if self.total_iters >= self.skip_iter:
  62. self._update_records(usetime, self.reader_records)
  63. def record_batch(self, usetime, num_samples=None):
  64. if num_samples is None:
  65. self.speed_mode = "steps/s"
  66. self.speed_unit = "steps/s"
  67. self.batch_cost_averager.record(usetime, num_samples)
  68. self.total_iters += 1
  69. if self.total_iters >= self.skip_iter:
  70. self._update_records(usetime, self.batch_records)
  71. if self.speed_mode == "samples/s":
  72. current_speed = float(num_samples) / usetime
  73. self.total_samples += num_samples
  74. else:
  75. current_speed = 1.0 / usetime # steps/s
  76. self._update_records(current_speed, self.speed_records)
  77. def _update_records(self, current_record, records):
  78. if current_record > records['max']:
  79. records['max'] = current_record
  80. elif current_record < records['min']:
  81. records['min'] = current_record
  82. if 'total' in records.keys():
  83. records['total'] += current_record
  84. def reader_average(self):
  85. return self.reader_cost_averager.get_average()
  86. def batch_average(self):
  87. return self.batch_cost_averager.get_average()
  88. def speed_average(self):
  89. if self.speed_mode == "samples/s":
  90. return self.batch_cost_averager.get_ips_average()
  91. else:
  92. return self.batch_cost_averager.get_step_average()
  93. def get_summary(self):
  94. if self.total_iters <= self.skip_iter:
  95. return {}
  96. reader_avg = 0
  97. batch_avg = 0
  98. speed_avg = 0
  99. self.total_iters -= self.skip_iter
  100. reader_avg = self.reader_records['total'] / float(self.total_iters)
  101. batch_avg = self.batch_records['total'] / float(self.total_iters)
  102. if self.speed_mode == "samples/s":
  103. speed_avg = float(self.total_samples) / self.batch_records['total']
  104. else:
  105. speed_avg = float(self.total_iters) / self.batch_records['total']
  106. reader_summary = {
  107. 'max': self.reader_records['max'],
  108. 'min': self.reader_records['min'],
  109. 'avg': reader_avg,
  110. }
  111. batch_summary = {
  112. 'max': self.batch_records['max'],
  113. 'min': self.batch_records['min'],
  114. 'avg': batch_avg,
  115. }
  116. ips_summary = {
  117. 'max': self.speed_records['max'],
  118. 'min': self.speed_records['min'],
  119. 'avg': speed_avg,
  120. }
  121. reader_ratio = (reader_avg / batch_avg) * 100
  122. summary = {
  123. 'reader_summary': reader_summary,
  124. 'batch_summary': batch_summary,
  125. 'ips_summary': ips_summary,
  126. 'reader_ratio': reader_ratio,
  127. }
  128. return summary
  129. class Hook:
  130. """
  131. As the base class. All types of hooks should inherit from it.
  132. """
  133. def begin(self, benchmark):
  134. pass
  135. def end(self, benchmark):
  136. pass
  137. def before_reader(self, benchmark):
  138. pass
  139. def after_reader(self, benchmark):
  140. pass
  141. def after_step(self, benchmark):
  142. pass
  143. class TimerHook(Hook):
  144. """
  145. A hook for recording real-time performance and the summary
  146. performance of total steps.
  147. """
  148. def __init__(self):
  149. self.start_time = timeit.default_timer()
  150. self.start_reader = timeit.default_timer()
  151. def begin(self, benchmark):
  152. """
  153. Create the event for timing and initialize the start time of a step.
  154. This function will be called in `Profiler.start()`.
  155. """
  156. benchmark.events.push(Event())
  157. benchmark.current_event = benchmark.events.peek()
  158. self.start_time = timeit.default_timer()
  159. def before_reader(self, benchmark):
  160. """
  161. Initialize the start time of the dataloader. This function will be
  162. called at the beginning of `next` method in `_DataLoaderIterMultiProcess` or
  163. `_DataLoaderIterSingleProcess`.
  164. """
  165. self.start_reader = timeit.default_timer()
  166. def after_reader(self, benchmark):
  167. """
  168. Record the cost of dataloader for the current step. Since the skipped steps
  169. are 10, it will update the maximum, minimum and the total time from the step
  170. 11 to the current step. This function will be called at the end of `next`
  171. method in `_DataLoaderIterMultiProcess` or `_DataLoaderIterSingleProcess`.
  172. """
  173. reader_cost = timeit.default_timer() - self.start_reader
  174. if (
  175. (benchmark.current_event is None)
  176. or (not benchmark.current_event.need_record)
  177. or (reader_cost == 0)
  178. ):
  179. return
  180. benchmark.current_event.record_reader(reader_cost)
  181. def after_step(self, benchmark):
  182. """
  183. Record the cost for the current step. It will contain the cost of the loading
  184. data if there is a dataloader. Similar to `after_reader`, it will also update
  185. the maximum, minimum and the total time from the step 11 to the current step
  186. as well as the maximum and minimum speed of the model. This function will
  187. be called in `Profiler.step()`.
  188. """
  189. if (benchmark.current_event is None) or (
  190. not benchmark.current_event.need_record
  191. ):
  192. return
  193. batch_cost = timeit.default_timer() - self.start_time
  194. benchmark.current_event.record_batch(batch_cost, benchmark.num_samples)
  195. self.start_time = timeit.default_timer()
  196. def end(self, benchmark):
  197. """
  198. Print the performance summary of the model and pop the current event
  199. from the events stack. Since there may be nested timing events, such
  200. as evaluation in the training process, the current event needs to be
  201. update to the event at the top of the stack.
  202. """
  203. if benchmark.events.is_empty():
  204. return
  205. self._print_summary(benchmark)
  206. benchmark.events.pop()
  207. benchmark.current_event = benchmark.events.peek()
  208. self.start_time = timeit.default_timer()
  209. def _print_summary(self, benchmark):
  210. summary = benchmark.current_event.get_summary()
  211. if not summary:
  212. return
  213. print('Perf Summary'.center(100, '='))
  214. if summary['reader_ratio'] != 0:
  215. print('Reader Ratio: ' + '%.3f' % (summary['reader_ratio']) + '%')
  216. print(
  217. 'Time Unit: s, IPS Unit: %s' % (benchmark.current_event.speed_unit)
  218. )
  219. print(
  220. '|',
  221. ''.center(15),
  222. '|',
  223. 'avg'.center(15),
  224. '|',
  225. 'max'.center(15),
  226. '|',
  227. 'min'.center(15),
  228. '|',
  229. )
  230. # if DataLoader is not called, reader_summary is unnecessary.
  231. if summary['reader_summary']['avg'] != 0:
  232. self._print_stats('reader_cost', summary['reader_summary'])
  233. self._print_stats('batch_cost', summary['batch_summary'])
  234. self._print_stats('ips', summary['ips_summary'])
  235. def _print_stats(self, item, message_dict):
  236. avg_str = '%.5f' % (message_dict['avg'])
  237. max_str = '%.5f' % (message_dict['max'])
  238. min_str = '%.5f' % (message_dict['min'])
  239. print(
  240. '|',
  241. item.center(15),
  242. '|',
  243. avg_str.center(15),
  244. '|',
  245. max_str.center(15),
  246. '|',
  247. min_str.center(15),
  248. '|',
  249. )
  250. class TimeAverager:
  251. """
  252. Record the cost of every step and count the average.
  253. """
  254. def __init__(self):
  255. self.reset()
  256. def reset(self):
  257. self._total_iters = 0
  258. self._total_time = 0
  259. self._total_samples = 0
  260. def record(self, usetime, num_samples=None):
  261. self._total_iters += 1
  262. self._total_time += usetime
  263. if num_samples:
  264. self._total_samples += num_samples
  265. def get_average(self):
  266. """
  267. Get the average cost of loading data or a step.
  268. """
  269. if self._total_iters == 0:
  270. return 0
  271. return self._total_time / float(self._total_iters)
  272. def get_ips_average(self):
  273. """
  274. Get the average throughput when speed mode is "samples/s".
  275. """
  276. if not self._total_samples or self._total_iters == 0:
  277. return 0
  278. return float(self._total_samples) / self._total_time
  279. def get_step_average(self):
  280. """
  281. Get the average speed when speed mode is "step/s".
  282. """
  283. if self._total_iters == 0:
  284. return 0
  285. return float(self._total_iters) / self._total_time
  286. class Benchmark:
  287. """
  288. A tool for the statistics of model performance. The `before_reader`
  289. and `after_reader` are called in the DataLoader to count the cost
  290. of loading the data. The `begin`, `step` and `end` are called to
  291. count the cost of a step or total steps.
  292. """
  293. def __init__(self):
  294. self.num_samples = None
  295. self.hooks = OrderedDict(timer_hook=TimerHook())
  296. self.current_event = None
  297. self.events = Stack()
  298. def step(self, num_samples=None):
  299. """
  300. Record the statistic for the current step. It will be called in
  301. `Profiler.step()`.
  302. """
  303. self.num_samples = num_samples
  304. self.after_step()
  305. def step_info(self, unit):
  306. """
  307. It returns the statistic of the current step as a string. It contains
  308. "reader_cost", "batch_cost" and "ips".
  309. """
  310. message = ''
  311. reader_average = self.current_event.reader_average()
  312. batch_average = self.current_event.batch_average()
  313. if reader_average:
  314. message += ' reader_cost: %.5f s' % (reader_average)
  315. if batch_average:
  316. if self.current_event.speed_mode == 'steps/s':
  317. self.current_event.speed_unit = 'steps/s'
  318. else:
  319. self.current_event.speed_unit = unit + '/s'
  320. message += ' {}: {:.5f} s'.format('batch_cost', batch_average)
  321. speed_average = self.current_event.speed_average()
  322. if speed_average:
  323. message += (
  324. f' ips: {speed_average:.3f} {self.current_event.speed_unit}'
  325. )
  326. self.current_event.reset()
  327. return message
  328. def begin(self):
  329. for hook in self.hooks.values():
  330. hook.begin(self)
  331. def before_reader(self):
  332. for hook in self.hooks.values():
  333. hook.before_reader(self)
  334. def after_reader(self):
  335. for hook in self.hooks.values():
  336. hook.after_reader(self)
  337. def after_step(self):
  338. for hook in self.hooks.values():
  339. hook.after_step(self)
  340. def end(self):
  341. for hook in self.hooks.values():
  342. hook.end(self)
  343. def check_if_need_record(self, reader):
  344. if self.current_event is None:
  345. return
  346. if self.current_event.need_record:
  347. # set reader for the current event at the first iter
  348. if self.current_event.reader is None:
  349. self.current_event.reader = reader
  350. elif (
  351. self.current_event.reader.__dict__['_dataset']
  352. != reader.__dict__['_dataset']
  353. ):
  354. # enter a new task but not calling begin() to record it.
  355. # we pause the timer until the end of new task, so that
  356. # the cost of new task is not added to the current event.
  357. # eg. start evaluation in the training task
  358. self.current_event.need_record = False
  359. else:
  360. # when the new task exits, continue timing for the current event.
  361. if (
  362. self.current_event.reader.__dict__['_dataset']
  363. == reader.__dict__['_dataset']
  364. ):
  365. self.current_event.need_record = True
  366. self.hooks['timer_hook'].start_time = timeit.default_timer()
  367. _benchmark_ = Benchmark()
  368. def benchmark():
  369. return _benchmark_