notebook.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. # Copyright 2020 Hugging Face
  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 os
  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. if "VSCODE_PID" in os.environ:
  101. self.update_every = 0.5 # Adjusted for smooth updated as html rending is slow on VS Code
  102. # This is the only adjustment required to optimize training html rending
  103. def update(self, value: int, force_update: bool = False, comment: Optional[str] = None):
  104. """
  105. The main method to update the progress bar to `value`.
  106. Args:
  107. value (`int`):
  108. The value to use. Must be between 0 and `total`.
  109. force_update (`bool`, *optional*, defaults to `False`):
  110. Whether or not to force and update of the internal state and display (by default, the bar will wait for
  111. `value` to reach the value it predicted corresponds to a time of more than the `update_every` attribute
  112. since the last update to avoid adding boilerplate).
  113. comment (`str`, *optional*):
  114. A comment to add on the left of the progress bar.
  115. """
  116. self.value = value
  117. if comment is not None:
  118. self.comment = comment
  119. if self.last_value is None:
  120. self.start_time = self.last_time = time.time()
  121. self.start_value = self.last_value = value
  122. self.elapsed_time = self.predicted_remaining = None
  123. self.first_calls = self.warmup
  124. self.wait_for = 1
  125. self.update_bar(value)
  126. elif value <= self.last_value and not force_update:
  127. return
  128. elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
  129. if self.first_calls > 0:
  130. self.first_calls -= 1
  131. current_time = time.time()
  132. self.elapsed_time = current_time - self.start_time
  133. # We could have value = self.start_value if the update is called twixe with the same start value.
  134. if value > self.start_value:
  135. self.average_time_per_item = self.elapsed_time / (value - self.start_value)
  136. else:
  137. self.average_time_per_item = None
  138. if value >= self.total:
  139. value = self.total
  140. self.predicted_remaining = None
  141. if not self.leave:
  142. self.close()
  143. elif self.average_time_per_item is not None:
  144. self.predicted_remaining = self.average_time_per_item * (self.total - value)
  145. self.update_bar(value)
  146. self.last_value = value
  147. self.last_time = current_time
  148. if (self.average_time_per_item is None) or (self.average_time_per_item == 0):
  149. self.wait_for = 1
  150. else:
  151. self.wait_for = max(int(self.update_every / self.average_time_per_item), 1)
  152. def update_bar(self, value, comment=None):
  153. spaced_value = " " * (len(str(self.total)) - len(str(value))) + str(value)
  154. if self.elapsed_time is None:
  155. self.label = f"[{spaced_value}/{self.total} : < :"
  156. elif self.predicted_remaining is None:
  157. self.label = f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)}"
  158. else:
  159. self.label = (
  160. f"[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <"
  161. f" {format_time(self.predicted_remaining)}"
  162. )
  163. if self.average_time_per_item == 0:
  164. self.label += ", +inf it/s"
  165. else:
  166. self.label += f", {1 / self.average_time_per_item:.2f} it/s"
  167. self.label += "]" if self.comment is None or len(self.comment) == 0 else f", {self.comment}]"
  168. self.display()
  169. def display(self):
  170. self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
  171. if self.parent is not None:
  172. # If this is a child bar, the parent will take care of the display.
  173. self.parent.display()
  174. return
  175. if self.output is None:
  176. self.output = disp.display(disp.HTML(self.html_code), display_id=True)
  177. else:
  178. self.output.update(disp.HTML(self.html_code))
  179. def close(self):
  180. "Closes the progress bar."
  181. if self.parent is None and self.output is not None:
  182. self.output.update(disp.HTML(""))
  183. class NotebookTrainingTracker(NotebookProgressBar):
  184. """
  185. An object tracking the updates of an ongoing training with progress bars and a nice table reporting metrics.
  186. Args:
  187. num_steps (`int`): The number of steps during training. column_names (`list[str]`, *optional*):
  188. The list of column names for the metrics table (will be inferred from the first call to
  189. [`~utils.notebook.NotebookTrainingTracker.write_line`] if not set).
  190. """
  191. def __init__(self, num_steps, column_names=None):
  192. super().__init__(num_steps)
  193. self.inner_table = None if column_names is None else [column_names]
  194. self.child_bar = None
  195. def display(self):
  196. self.html_code = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
  197. if self.inner_table is not None:
  198. self.html_code += text_to_html_table(self.inner_table)
  199. if self.child_bar is not None:
  200. self.html_code += self.child_bar.html_code
  201. if self.output is None:
  202. self.output = disp.display(disp.HTML(self.html_code), display_id=True)
  203. else:
  204. self.output.update(disp.HTML(self.html_code))
  205. def write_line(self, values):
  206. """
  207. Write the values in the inner table.
  208. Args:
  209. values (`dict[str, float]`): The values to display.
  210. """
  211. if self.inner_table is None:
  212. self.inner_table = [list(values.keys()), list(values.values())]
  213. else:
  214. columns = self.inner_table[0]
  215. for key in values:
  216. if key not in columns:
  217. columns.append(key)
  218. self.inner_table[0] = columns
  219. if len(self.inner_table) > 1:
  220. last_values = self.inner_table[-1]
  221. first_column = self.inner_table[0][0]
  222. if last_values[0] != values[first_column]:
  223. # write new line
  224. self.inner_table.append([values.get(c, "No Log") for c in columns])
  225. else:
  226. # update last line
  227. new_values = values
  228. for c in columns:
  229. if c not in new_values:
  230. new_values[c] = last_values[columns.index(c)]
  231. self.inner_table[-1] = [new_values[c] for c in columns]
  232. else:
  233. self.inner_table.append([values[c] for c in columns])
  234. def add_child(self, total, prefix=None, width=300):
  235. """
  236. Add a child progress bar displayed under the table of metrics. The child progress bar is returned (so it can be
  237. easily updated).
  238. Args:
  239. total (`int`): The number of iterations for the child progress bar.
  240. prefix (`str`, *optional*): A prefix to write on the left of the progress bar.
  241. width (`int`, *optional*, defaults to 300): The width (in pixels) of the progress bar.
  242. """
  243. self.child_bar = NotebookProgressBar(total, prefix=prefix, parent=self, width=width)
  244. return self.child_bar
  245. def remove_child(self):
  246. """
  247. Closes the child progress bar.
  248. """
  249. self.child_bar = None
  250. self.display()
  251. class NotebookProgressCallback(TrainerCallback):
  252. """
  253. A [`TrainerCallback`] that displays the progress of training or evaluation, optimized for Jupyter Notebooks or
  254. Google colab.
  255. """
  256. def __init__(self):
  257. self.training_tracker = None
  258. self.prediction_bar = None
  259. self._force_next_update = False
  260. def on_train_begin(self, args, state, control, **kwargs):
  261. self.first_column = "Epoch" if args.eval_strategy == IntervalStrategy.EPOCH else "Step"
  262. self.training_loss = 0
  263. self.last_log = 0
  264. column_names = [self.first_column] + ["Training Loss"]
  265. if args.eval_strategy != IntervalStrategy.NO:
  266. column_names.append("Validation Loss")
  267. self.training_tracker = NotebookTrainingTracker(state.max_steps, column_names)
  268. def on_step_end(self, args, state, control, **kwargs):
  269. epoch = int(state.epoch) if int(state.epoch) == state.epoch else f"{state.epoch:.2f}"
  270. self.training_tracker.update(
  271. state.global_step + 1,
  272. comment=f"Epoch {epoch}/{state.num_train_epochs}",
  273. force_update=self._force_next_update,
  274. )
  275. self._force_next_update = False
  276. def on_prediction_step(self, args, state, control, eval_dataloader=None, **kwargs):
  277. if not has_length(eval_dataloader):
  278. return
  279. if self.prediction_bar is None:
  280. if self.training_tracker is not None:
  281. self.prediction_bar = self.training_tracker.add_child(len(eval_dataloader))
  282. else:
  283. self.prediction_bar = NotebookProgressBar(len(eval_dataloader))
  284. self.prediction_bar.update(1)
  285. else:
  286. self.prediction_bar.update(self.prediction_bar.value + 1)
  287. def on_predict(self, args, state, control, **kwargs):
  288. if self.prediction_bar is not None:
  289. self.prediction_bar.close()
  290. self.prediction_bar = None
  291. def on_log(self, args, state, control, logs=None, **kwargs):
  292. # Only for when there is no evaluation
  293. if args.eval_strategy == IntervalStrategy.NO and "loss" in logs:
  294. values = {"Training Loss": logs["loss"]}
  295. # First column is necessarily Step sine we're not in epoch eval strategy
  296. values["Step"] = state.global_step
  297. self.training_tracker.write_line(values)
  298. def on_evaluate(self, args, state, control, metrics=None, **kwargs):
  299. if self.training_tracker is not None:
  300. values = {"Training Loss": "No log", "Validation Loss": "No log"}
  301. for log in reversed(state.log_history):
  302. if "loss" in log:
  303. values["Training Loss"] = log["loss"]
  304. break
  305. if self.first_column == "Epoch":
  306. values["Epoch"] = int(state.epoch)
  307. else:
  308. values["Step"] = state.global_step
  309. metric_key_prefix = "eval"
  310. for k in metrics:
  311. if k.endswith("_loss"):
  312. metric_key_prefix = re.sub(r"\_loss$", "", k)
  313. _ = metrics.pop("total_flos", None)
  314. _ = metrics.pop("epoch", None)
  315. _ = metrics.pop(f"{metric_key_prefix}_runtime", None)
  316. _ = metrics.pop(f"{metric_key_prefix}_samples_per_second", None)
  317. _ = metrics.pop(f"{metric_key_prefix}_steps_per_second", None)
  318. _ = metrics.pop(f"{metric_key_prefix}_jit_compilation_time", None)
  319. for k, v in metrics.items():
  320. splits = k.split("_")
  321. name = " ".join([part.capitalize() for part in splits[1:]])
  322. if name == "Loss":
  323. # Single dataset
  324. name = "Validation Loss"
  325. values[name] = v
  326. self.training_tracker.write_line(values)
  327. self.training_tracker.remove_child()
  328. self.prediction_bar = None
  329. # Evaluation takes a long time so we should force the next update.
  330. self._force_next_update = True
  331. def on_train_end(self, args, state, control, **kwargs):
  332. self.training_tracker.update(
  333. state.global_step,
  334. comment=f"Epoch {int(state.epoch)}/{state.num_train_epochs}",
  335. force_update=True,
  336. )
  337. self.training_tracker = None