notebook.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. # coding=utf-8
  2. # Copyright 2020 Hugging Face
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import re
  16. import time
  17. from typing import Optional
  18. import IPython.display as disp
  19. from ..trainer_callback import TrainerCallback
  20. from ..trainer_utils import IntervalStrategy, has_length
  21. def format_time(t):
  22. "Format `t` (in seconds) to (h):mm:ss"
  23. t = int(t)
  24. h, m, s = t // 3600, (t // 60) % 60, t % 60
  25. return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}"
  26. def html_progress_bar(value, total, prefix, label, width=300):
  27. # docstyle-ignore
  28. return f"""
  29. <div>
  30. {prefix}
  31. <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress>
  32. {label}
  33. </div>
  34. """
  35. def text_to_html_table(items):
  36. "Put the texts in `items` in an HTML table."
  37. html_code = """<table border="1" class="dataframe">\n"""
  38. html_code += """ <thead>\n <tr style="text-align: left;">\n"""
  39. for i in items[0]:
  40. html_code += f" <th>{i}</th>\n"
  41. html_code += " </tr>\n </thead>\n <tbody>\n"
  42. for line in items[1:]:
  43. html_code += " <tr>\n"
  44. for elt in line:
  45. elt = f"{elt:.6f}" if isinstance(elt, float) else str(elt)
  46. html_code += f" <td>{elt}</td>\n"
  47. html_code += " </tr>\n"
  48. html_code += " </tbody>\n</table><p>"
  49. return html_code
  50. class NotebookProgressBar:
  51. """
  52. A progress par for display in a notebook.
  53. Class attributes (overridden by derived classes)
  54. - **warmup** (`int`) -- The number of iterations to do at the beginning while ignoring `update_every`.
  55. - **update_every** (`float`) -- Since calling the time takes some time, we only do it every presumed
  56. `update_every` seconds. The progress bar uses the average time passed up until now to guess the next value
  57. for which it will call the update.
  58. Args:
  59. total (`int`):
  60. The total number of iterations to reach.
  61. prefix (`str`, *optional*):
  62. A prefix to add before the progress bar.
  63. leave (`bool`, *optional*, defaults to `True`):
  64. Whether or not to leave the progress bar once it's completed. You can always call the
  65. [`~utils.notebook.NotebookProgressBar.close`] method to make the bar disappear.
  66. parent ([`~notebook.NotebookTrainingTracker`], *optional*):
  67. A parent object (like [`~utils.notebook.NotebookTrainingTracker`]) that spawns progress bars and handle
  68. their display. If set, the object passed must have a `display()` method.
  69. width (`int`, *optional*, defaults to 300):
  70. The width (in pixels) that the bar will take.
  71. Example:
  72. ```python
  73. import time
  74. pbar = NotebookProgressBar(100)
  75. for val in range(100):
  76. pbar.update(val)
  77. time.sleep(0.07)
  78. pbar.update(100)
  79. ```"""
  80. warmup = 5
  81. update_every = 0.2
  82. def __init__(
  83. self,
  84. total: int,
  85. prefix: Optional[str] = None,
  86. leave: bool = True,
  87. parent: Optional["NotebookTrainingTracker"] = None,
  88. width: int = 300,
  89. ):
  90. self.total = total
  91. self.prefix = "" if prefix is None else prefix
  92. self.leave = leave
  93. self.parent = parent
  94. self.width = width
  95. self.last_value = None
  96. self.comment = None
  97. self.output = None
  98. self.value = None
  99. self.label = None
  100. def update(self, value: int, force_update: bool = False, comment: str = None):
  101. """
  102. The main method to update the progress bar to `value`.
  103. Args:
  104. value (`int`):
  105. The value to use. Must be between 0 and `total`.
  106. force_update (`bool`, *optional*, defaults to `False`):
  107. Whether or not to force and update of the internal state and display (by default, the bar will wait for
  108. `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute
  109. since the last update to avoid adding boilerplate).
  110. comment (`str`, *optional*):
  111. A comment to add on the left of the progress bar.
  112. """
  113. self.value = value
  114. if comment is not None:
  115. self.comment = comment
  116. if self.last_value is None:
  117. self.start_time = self.last_time = time.time()
  118. self.start_value = self.last_value = value
  119. self.elapsed_time = self.predicted_remaining = None
  120. self.first_calls = self.warmup
  121. self.wait_for = 1
  122. self.update_bar(value)
  123. elif value <= self.last_value and not force_update:
  124. return
  125. elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
  126. if self.first_calls > 0:
  127. self.first_calls -= 1
  128. current_time = time.time()
  129. self.elapsed_time = current_time - self.start_time
  130. # We could have value = self.start_value if the update is called twixe with the same start value.
  131. if value > self.start_value:
  132. self.average_time_per_item = self.elapsed_time / (value - self.start_value)
  133. else:
  134. self.average_time_per_item = None
  135. if value >= self.total:
  136. value = self.total
  137. self.predicted_remaining = None
  138. if not self.leave:
  139. self.close()
  140. elif self.average_time_per_item is not None:
  141. self.predicted_remaining = self.average_time_per_item * (self.total - value)
  142. self.update_bar(value)
  143. self.last_value = value
  144. self.last_time = current_time
  145. if (self.average_time_per_item is None) or (self.average_time_per_item == 0):
  146. self.wait_for = 1
  147. else:
  148. self.wait_for = max(int(self.update_every / self.average_time_per_item), 1)
  149. def update_bar(self, value, comment=None):
  150. spaced_value = " " * (len(str(self.total)) - len(str(value))) + str(value)
  151. if self.elapsed_time is None:
  152. self.label = f"[{spaced_value}/{self.total} : < :"
  153. elif self.predicted_remaining is None:
  154. self.label = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)}"
  155. else:
  156. self.label = (
  157. f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <"
  158. f" {format_time(self.predicted_remaining)}"
  159. )
  160. if self.average_time_per_item == 0:
  161. self.label += ", +inf it/s"
  162. else:
  163. self.label += f", {1/self.average_time_per_item:.2f} it/s"
  164. self.label += "]" if self.comment is None or len(self.comment) == 0 else f", {self.comment}]"
  165. self.display()
  166. def display(self):
  167. self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
  168. if self.parent is not None:
  169. # If this is a child bar, the parent will take care of the display.
  170. self.parent.display()
  171. return
  172. if self.output is None:
  173. self.output = disp.display(disp.HTML(self.html_code), display_id=True)
  174. else:
  175. self.output.update(disp.HTML(self.html_code))
  176. def close(self):
  177. "Closes the progress bar."
  178. if self.parent is None and self.output is not None:
  179. self.output.update(disp.HTML(""))
  180. class NotebookTrainingTracker(NotebookProgressBar):
  181. """
  182. An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics.
  183. Args:
  184. num_steps (`int`): The number of steps during training. column_names (`List[str]`, *optional*):
  185. The list of column names for the metrics table (will be inferred from the first call to
  186. [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set).
  187. """
  188. def __init__(self, num_steps, column_names=None):
  189. super().__init__(num_steps)
  190. self.inner_table = None if column_names is None else [column_names]
  191. self.child_bar = None
  192. def display(self):
  193. self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
  194. if self.inner_table is not None:
  195. self.html_code += text_to_html_table(self.inner_table)
  196. if self.child_bar is not None:
  197. self.html_code += self.child_bar.html_code
  198. if self.output is None:
  199. self.output = disp.display(disp.HTML(self.html_code), display_id=True)
  200. else:
  201. self.output.update(disp.HTML(self.html_code))
  202. def write_line(self, values):
  203. """
  204. Write the values in the inner table.
  205. Args:
  206. values (`Dict[str, float]`): The values to display.
  207. """
  208. if self.inner_table is None:
  209. self.inner_table = [list(values.keys()), list(values.values())]
  210. else:
  211. columns = self.inner_table[0]
  212. for key in values.keys():
  213. if key not in columns:
  214. columns.append(key)
  215. self.inner_table[0] = columns
  216. if len(self.inner_table) > 1:
  217. last_values = self.inner_table[-1]
  218. first_column = self.inner_table[0][0]
  219. if last_values[0] != values[first_column]:
  220. # write new line
  221. self.inner_table.append([values[c] if c in values else "No Log" for c in columns])
  222. else:
  223. # update last line
  224. new_values = values
  225. for c in columns:
  226. if c not in new_values.keys():
  227. new_values[c] = last_values[columns.index(c)]
  228. self.inner_table[-1] = [new_values[c] for c in columns]
  229. else:
  230. self.inner_table.append([values[c] for c in columns])
  231. def add_child(self, total, prefix=None, width=300):
  232. """
  233. Add a child progress bar displayed under the table of metrics. The child progress bar is returned (so it can be
  234. easily updated).
  235. Args:
  236. total (`int`): The number of iterations for the child progress bar.
  237. prefix (`str`, *optional*): A prefix to write on the left of the progress bar.
  238. width (`int`, *optional*, defaults to 300): The width (in pixels) of the progress bar.
  239. """
  240. self.child_bar = NotebookProgressBar(total, prefix=prefix, parent=self, width=width)
  241. return self.child_bar
  242. def remove_child(self):
  243. """
  244. Closes the child progress bar.
  245. """
  246. self.child_bar = None
  247. self.display()
  248. class NotebookProgressCallback(TrainerCallback):
  249. """
  250. A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or
  251. Google colab.
  252. """
  253. def __init__(self):
  254. self.training_tracker = None
  255. self.prediction_bar = None
  256. self._force_next_update = False
  257. def on_train_begin(self, args, state, control, **kwargs):
  258. self.first_column = "Epoch" if args.eval_strategy == IntervalStrategy.EPOCH else "Step"
  259. self.training_loss = 0
  260. self.last_log = 0
  261. column_names = [self.first_column] + ["Training Loss"]
  262. if args.eval_strategy != IntervalStrategy.NO:
  263. column_names.append("Validation Loss")
  264. self.training_tracker = NotebookTrainingTracker(state.max_steps, column_names)
  265. def on_step_end(self, args, state, control, **kwargs):
  266. epoch = int(state.epoch) if int(state.epoch) == state.epoch else f"{state.epoch:.2f}"
  267. self.training_tracker.update(
  268. state.global_step + 1,
  269. comment=f"Epoch {epoch}/{state.num_train_epochs}",
  270. force_update=self._force_next_update,
  271. )
  272. self._force_next_update = False
  273. def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs):
  274. if not has_length(eval_dataloader):
  275. return
  276. if self.prediction_bar is None:
  277. if self.training_tracker is not None:
  278. self.prediction_bar = self.training_tracker.add_child(len(eval_dataloader))
  279. else:
  280. self.prediction_bar = NotebookProgressBar(len(eval_dataloader))
  281. self.prediction_bar.update(1)
  282. else:
  283. self.prediction_bar.update(self.prediction_bar.value + 1)
  284. def on_predict(self, args, state, control, **kwargs):
  285. if self.prediction_bar is not None:
  286. self.prediction_bar.close()
  287. self.prediction_bar = None
  288. def on_log(self, args, state, control, logs=None, **kwargs):
  289. # Only for when there is no evaluation
  290. if args.eval_strategy == IntervalStrategy.NO and "loss" in logs:
  291. values = {"Training Loss": logs["loss"]}
  292. # First column is necessarily Step sine we're not in epoch eval strategy
  293. values["Step"] = state.global_step
  294. self.training_tracker.write_line(values)
  295. def on_evaluate(self, args, state, control, metrics=None, **kwargs):
  296. if self.training_tracker is not None:
  297. values = {"Training Loss": "No log", "Validation Loss": "No log"}
  298. for log in reversed(state.log_history):
  299. if "loss" in log:
  300. values["Training Loss"] = log["loss"]
  301. break
  302. if self.first_column == "Epoch":
  303. values["Epoch"] = int(state.epoch)
  304. else:
  305. values["Step"] = state.global_step
  306. metric_key_prefix = "eval"
  307. for k in metrics:
  308. if k.endswith("_loss"):
  309. metric_key_prefix = re.sub(r"\_loss$", "", k)
  310. _ = metrics.pop("total_flos", None)
  311. _ = metrics.pop("epoch", None)
  312. _ = metrics.pop(f"{metric_key_prefix}_runtime", None)
  313. _ = metrics.pop(f"{metric_key_prefix}_samples_per_second", None)
  314. _ = metrics.pop(f"{metric_key_prefix}_steps_per_second", None)
  315. _ = metrics.pop(f"{metric_key_prefix}_jit_compilation_time", None)
  316. for k, v in metrics.items():
  317. splits = k.split("_")
  318. name = " ".join([part.capitalize() for part in splits[1:]])
  319. if name == "Loss":
  320. # Single dataset
  321. name = "Validation Loss"
  322. values[name] = v
  323. self.training_tracker.write_line(values)
  324. self.training_tracker.remove_child()
  325. self.prediction_bar = None
  326. # Evaluation takes a long time so we should force the next update.
  327. self._force_next_update = True
  328. def on_train_end(self, args, state, control, **kwargs):
  329. self.training_tracker.update(
  330. state.global_step,
  331. comment=f"Epoch {int(state.epoch)}/{state.num_train_epochs}",
  332. force_update=True,
  333. )
  334. self.training_tracker = None