tracking.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. # Copyright 2022 The HuggingFace Team. 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. # Expectation:
  15. # Provide a project dir name, then each type of logger gets stored in project/{`logging_dir`}
  16. import json
  17. import os
  18. import time
  19. from functools import wraps
  20. from typing import Any, Optional, Union
  21. import yaml
  22. from packaging import version
  23. from .logging import get_logger
  24. from .state import PartialState
  25. from .utils import (
  26. LoggerType,
  27. compare_versions,
  28. is_aim_available,
  29. is_clearml_available,
  30. is_comet_ml_available,
  31. is_dvclive_available,
  32. is_mlflow_available,
  33. is_swanlab_available,
  34. is_tensorboard_available,
  35. is_trackio_available,
  36. is_wandb_available,
  37. listify,
  38. )
  39. _available_trackers = []
  40. if is_tensorboard_available():
  41. _available_trackers.append(LoggerType.TENSORBOARD)
  42. if is_wandb_available():
  43. _available_trackers.append(LoggerType.WANDB)
  44. if is_comet_ml_available():
  45. _available_trackers.append(LoggerType.COMETML)
  46. if is_aim_available():
  47. _available_trackers.append(LoggerType.AIM)
  48. if is_mlflow_available():
  49. _available_trackers.append(LoggerType.MLFLOW)
  50. if is_clearml_available():
  51. _available_trackers.append(LoggerType.CLEARML)
  52. if is_dvclive_available():
  53. _available_trackers.append(LoggerType.DVCLIVE)
  54. if is_swanlab_available():
  55. _available_trackers.append(LoggerType.SWANLAB)
  56. if is_trackio_available():
  57. _available_trackers.append(LoggerType.TRACKIO)
  58. logger = get_logger(__name__)
  59. def on_main_process(function):
  60. """
  61. Decorator to selectively run the decorated function on the main process only based on the `main_process_only`
  62. attribute in a class.
  63. Checks at function execution rather than initialization time, not triggering the initialization of the
  64. `PartialState`.
  65. """
  66. @wraps(function)
  67. def execute_on_main_process(self, *args, **kwargs):
  68. if getattr(self, "main_process_only", False):
  69. return PartialState().on_main_process(function)(self, *args, **kwargs)
  70. else:
  71. return function(self, *args, **kwargs)
  72. return execute_on_main_process
  73. def get_available_trackers():
  74. "Returns a list of all supported available trackers in the system"
  75. return _available_trackers
  76. class GeneralTracker:
  77. """
  78. A base Tracker class to be used for all logging integration implementations.
  79. Each function should take in `**kwargs` that will automatically be passed in from a base dictionary provided to
  80. [`Accelerator`].
  81. Should implement `name`, `requires_logging_directory`, and `tracker` properties such that:
  82. `name` (`str`): String representation of the tracker class name, such as "TensorBoard" `requires_logging_directory`
  83. (`bool`): Whether the logger requires a directory to store their logs. `tracker` (`object`): Should return internal
  84. tracking mechanism used by a tracker class (such as the `run` for wandb)
  85. Implementations can also include a `main_process_only` (`bool`) attribute to toggle if relevant logging, init, and
  86. other functions should occur on the main process or across all processes (by default will use `True`)
  87. """
  88. main_process_only = True
  89. def __init__(self, _blank=False):
  90. if not _blank:
  91. err = ""
  92. if not hasattr(self, "name"):
  93. err += "`name`"
  94. if not hasattr(self, "requires_logging_directory"):
  95. if len(err) > 0:
  96. err += ", "
  97. err += "`requires_logging_directory`"
  98. # as tracker is a @property that relies on post-init
  99. if "tracker" not in dir(self):
  100. if len(err) > 0:
  101. err += ", "
  102. err += "`tracker`"
  103. if len(err) > 0:
  104. raise NotImplementedError(
  105. f"The implementation for this tracker class is missing the following "
  106. f"required attributes. Please define them in the class definition: "
  107. f"{err}"
  108. )
  109. def start(self):
  110. """
  111. Lazy initialization of the tracker inside Accelerator to avoid initializing PartialState before
  112. InitProcessGroupKwargs.
  113. """
  114. pass
  115. def store_init_configuration(self, values: dict):
  116. """
  117. Logs `values` as hyperparameters for the run. Implementations should use the experiment configuration
  118. functionality of a tracking API.
  119. Args:
  120. values (Dictionary `str` to `bool`, `str`, `float` or `int`):
  121. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  122. `str`, `float`, `int`, or `None`.
  123. """
  124. pass
  125. def log(self, values: dict, step: Optional[int], **kwargs):
  126. """
  127. Logs `values` to the current run. Base `log` implementations of a tracking API should go in here, along with
  128. special behavior for the `step parameter.
  129. Args:
  130. values (Dictionary `str` to `str`, `float`, or `int`):
  131. Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
  132. step (`int`, *optional*):
  133. The run step. If included, the log will be affiliated with this step.
  134. """
  135. pass
  136. def finish(self):
  137. """
  138. Should run any finalizing functions within the tracking API. If the API should not have one, just don't
  139. overwrite that method.
  140. """
  141. pass
  142. class TensorBoardTracker(GeneralTracker):
  143. """
  144. A `Tracker` class that supports `tensorboard`. Should be initialized at the start of your script.
  145. Args:
  146. run_name (`str`):
  147. The name of the experiment run
  148. logging_dir (`str`, `os.PathLike`):
  149. Location for TensorBoard logs to be stored.
  150. **kwargs (additional keyword arguments, *optional*):
  151. Additional key word arguments passed along to the `tensorboard.SummaryWriter.__init__` method.
  152. """
  153. name = "tensorboard"
  154. requires_logging_directory = True
  155. def __init__(self, run_name: str, logging_dir: Union[str, os.PathLike], **kwargs):
  156. super().__init__()
  157. self.run_name = run_name
  158. self.logging_dir_param = logging_dir
  159. self.init_kwargs = kwargs
  160. @on_main_process
  161. def start(self):
  162. try:
  163. from torch.utils import tensorboard
  164. except ModuleNotFoundError:
  165. import tensorboardX as tensorboard
  166. self.logging_dir = os.path.join(self.logging_dir_param, self.run_name)
  167. self.writer = tensorboard.SummaryWriter(self.logging_dir, **self.init_kwargs)
  168. logger.debug(f"Initialized TensorBoard project {self.run_name} logging to {self.logging_dir}")
  169. logger.debug(
  170. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  171. )
  172. @property
  173. def tracker(self):
  174. return self.writer
  175. @on_main_process
  176. def store_init_configuration(self, values: dict):
  177. """
  178. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
  179. hyperparameters in a yaml file for future use.
  180. Args:
  181. values (Dictionary `str` to `bool`, `str`, `float` or `int`):
  182. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  183. `str`, `float`, `int`, or `None`.
  184. """
  185. self.writer.add_hparams(values, metric_dict={})
  186. self.writer.flush()
  187. project_run_name = time.time()
  188. dir_name = os.path.join(self.logging_dir, str(project_run_name))
  189. os.makedirs(dir_name, exist_ok=True)
  190. with open(os.path.join(dir_name, "hparams.yml"), "w") as outfile:
  191. try:
  192. yaml.dump(values, outfile)
  193. except yaml.representer.RepresenterError:
  194. logger.error("Serialization to store hyperparameters failed")
  195. raise
  196. logger.debug("Stored initial configuration hyperparameters to TensorBoard and hparams yaml file")
  197. @on_main_process
  198. def log(self, values: dict, step: Optional[int] = None, **kwargs):
  199. """
  200. Logs `values` to the current run.
  201. Args:
  202. values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
  203. Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
  204. `str` to `float`/`int`.
  205. step (`int`, *optional*):
  206. The run step. If included, the log will be affiliated with this step.
  207. kwargs:
  208. Additional key word arguments passed along to either `SummaryWriter.add_scaler`,
  209. `SummaryWriter.add_text`, or `SummaryWriter.add_scalers` method based on the contents of `values`.
  210. """
  211. values = listify(values)
  212. for k, v in values.items():
  213. if isinstance(v, (int, float)):
  214. self.writer.add_scalar(k, v, global_step=step, **kwargs)
  215. elif isinstance(v, str):
  216. self.writer.add_text(k, v, global_step=step, **kwargs)
  217. elif isinstance(v, dict):
  218. self.writer.add_scalars(k, v, global_step=step, **kwargs)
  219. self.writer.flush()
  220. logger.debug("Successfully logged to TensorBoard")
  221. @on_main_process
  222. def log_images(self, values: dict, step: Optional[int], **kwargs):
  223. """
  224. Logs `images` to the current run.
  225. Args:
  226. values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
  227. Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
  228. step (`int`, *optional*):
  229. The run step. If included, the log will be affiliated with this step.
  230. kwargs:
  231. Additional key word arguments passed along to the `SummaryWriter.add_image` method.
  232. """
  233. for k, v in values.items():
  234. self.writer.add_images(k, v, global_step=step, **kwargs)
  235. logger.debug("Successfully logged images to TensorBoard")
  236. @on_main_process
  237. def finish(self):
  238. """
  239. Closes `TensorBoard` writer
  240. """
  241. self.writer.close()
  242. logger.debug("TensorBoard writer closed")
  243. class WandBTracker(GeneralTracker):
  244. """
  245. A `Tracker` class that supports `wandb`. Should be initialized at the start of your script.
  246. Args:
  247. run_name (`str`):
  248. The name of the experiment run.
  249. **kwargs (additional keyword arguments, *optional*):
  250. Additional key word arguments passed along to the `wandb.init` method.
  251. """
  252. name = "wandb"
  253. requires_logging_directory = False
  254. main_process_only = False
  255. def __init__(self, run_name: str, **kwargs):
  256. super().__init__()
  257. self.run_name = run_name
  258. self.init_kwargs = kwargs
  259. @on_main_process
  260. def start(self):
  261. import wandb
  262. self.run = wandb.init(project=self.run_name, **self.init_kwargs)
  263. logger.debug(f"Initialized WandB project {self.run_name}")
  264. logger.debug(
  265. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  266. )
  267. @property
  268. def tracker(self):
  269. return self.run
  270. @on_main_process
  271. def store_init_configuration(self, values: dict):
  272. """
  273. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
  274. Args:
  275. values (Dictionary `str` to `bool`, `str`, `float` or `int`):
  276. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  277. `str`, `float`, `int`, or `None`.
  278. """
  279. import wandb
  280. if os.environ.get("WANDB_MODE") == "offline":
  281. # In offline mode, restart wandb with config included
  282. if hasattr(self, "run") and self.run:
  283. self.run.finish()
  284. init_kwargs = self.init_kwargs.copy()
  285. init_kwargs["config"] = values
  286. self.run = wandb.init(project=self.run_name, **init_kwargs)
  287. else:
  288. wandb.config.update(values, allow_val_change=True)
  289. logger.debug("Stored initial configuration hyperparameters to WandB")
  290. @on_main_process
  291. def log(self, values: dict, step: Optional[int] = None, **kwargs):
  292. """
  293. Logs `values` to the current run.
  294. Args:
  295. values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
  296. Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
  297. `str` to `float`/`int`.
  298. step (`int`, *optional*):
  299. The run step. If included, the log will be affiliated with this step.
  300. kwargs:
  301. Additional key word arguments passed along to the `wandb.log` method.
  302. """
  303. self.run.log(values, step=step, **kwargs)
  304. logger.debug("Successfully logged to WandB")
  305. @on_main_process
  306. def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
  307. """
  308. Logs `images` to the current run.
  309. Args:
  310. values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
  311. Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
  312. step (`int`, *optional*):
  313. The run step. If included, the log will be affiliated with this step.
  314. kwargs:
  315. Additional key word arguments passed along to the `wandb.log` method.
  316. """
  317. import wandb
  318. for k, v in values.items():
  319. self.log({k: [wandb.Image(image) for image in v]}, step=step, **kwargs)
  320. logger.debug("Successfully logged images to WandB")
  321. @on_main_process
  322. def log_table(
  323. self,
  324. table_name: str,
  325. columns: Optional[list[str]] = None,
  326. data: Optional[list[list[Any]]] = None,
  327. dataframe: Any = None,
  328. step: Optional[int] = None,
  329. **kwargs,
  330. ):
  331. """
  332. Log a Table containing any object type (text, image, audio, video, molecule, html, etc). Can be defined either
  333. with `columns` and `data` or with `dataframe`.
  334. Args:
  335. table_name (`str`):
  336. The name to give to the logged table on the wandb workspace
  337. columns (list of `str`, *optional*):
  338. The name of the columns on the table
  339. data (List of List of Any data type, *optional*):
  340. The data to be logged in the table
  341. dataframe (Any data type, *optional*):
  342. The data to be logged in the table
  343. step (`int`, *optional*):
  344. The run step. If included, the log will be affiliated with this step.
  345. """
  346. import wandb
  347. values = {table_name: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
  348. self.log(values, step=step, **kwargs)
  349. @on_main_process
  350. def finish(self):
  351. """
  352. Closes `wandb` writer
  353. """
  354. self.run.finish()
  355. logger.debug("WandB run closed")
  356. class TrackioTracker(GeneralTracker):
  357. """
  358. A `Tracker` class that supports `trackio`. Should be initialized at the start of your script.
  359. Args:
  360. run_name (`str`):
  361. The name of the experiment run. Will be used as the `project` name when instantiating trackio.
  362. **kwargs (additional keyword arguments, *optional*):
  363. Additional key word arguments passed along to the `trackio.init` method. Refer to this
  364. [init](https://github.com/gradio-app/trackio/blob/814809552310468b13f84f33764f1369b4e5136c/trackio/__init__.py#L22)
  365. to see all supported key word arguments.
  366. """
  367. name = "trackio"
  368. requires_logging_directory = False
  369. main_process_only = False
  370. def __init__(self, run_name: str, **kwargs):
  371. super().__init__()
  372. self.run_name = run_name
  373. self.init_kwargs = kwargs
  374. @on_main_process
  375. def start(self):
  376. import trackio
  377. self.run = trackio.init(project=self.run_name, **self.init_kwargs)
  378. logger.debug(f"Initialized trackio project {self.run_name}")
  379. logger.debug(
  380. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  381. )
  382. @property
  383. def tracker(self):
  384. return self.run
  385. @on_main_process
  386. def store_init_configuration(self, values: dict):
  387. """
  388. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
  389. Args:
  390. values (Dictionary `str` to `bool`, `str`, `float` or `int`):
  391. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  392. `str`, `float`, `int`, or `None`.
  393. """
  394. import trackio
  395. trackio.config.update(values, allow_val_change=True)
  396. logger.debug("Stored initial configuration hyperparameters to trackio")
  397. @on_main_process
  398. def log(self, values: dict, step: Optional[int] = None, **kwargs):
  399. """
  400. Logs `values` to the current run.
  401. Args:
  402. values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
  403. Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
  404. `str` to `float`/`int`.
  405. step (`int`, *optional*):
  406. The run step. If included, the log will be affiliated with this step.
  407. kwargs:
  408. Additional key word arguments passed along to the `trackio.log` method.
  409. """
  410. self.run.log(values, **kwargs)
  411. logger.debug("Successfully logged to trackio")
  412. @on_main_process
  413. def finish(self):
  414. """
  415. Closes `trackio` run
  416. """
  417. self.run.finish()
  418. logger.debug("trackio run closed")
  419. class CometMLTracker(GeneralTracker):
  420. """
  421. A `Tracker` class that supports `comet_ml`. Should be initialized at the start of your script.
  422. API keys must be stored in a Comet config file.
  423. Note:
  424. For `comet_ml` versions < 3.41.0, additional keyword arguments are passed to `comet_ml.Experiment` instead:
  425. https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/Experiment/#comet_ml.Experiment.__init__
  426. Args:
  427. run_name (`str`):
  428. The name of the experiment run.
  429. **kwargs (additional keyword arguments, *optional*):
  430. Additional key word arguments passed along to the `comet_ml.start` method:
  431. https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/start/
  432. """
  433. name = "comet_ml"
  434. requires_logging_directory = False
  435. def __init__(self, run_name: str, **kwargs):
  436. super().__init__()
  437. self.run_name = run_name
  438. self.init_kwargs = kwargs
  439. @on_main_process
  440. def start(self):
  441. import comet_ml
  442. comet_version = version.parse(comet_ml.__version__)
  443. if compare_versions(comet_version, ">=", "3.41.0"):
  444. self.writer = comet_ml.start(project_name=self.run_name, **self.init_kwargs)
  445. else:
  446. logger.info("Update `comet_ml` (>=3.41.0) for experiment reuse and offline support.")
  447. self.writer = comet_ml.Experiment(project_name=self.run_name, **self.init_kwargs)
  448. logger.debug(f"Initialized CometML project {self.run_name}")
  449. logger.debug(
  450. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  451. )
  452. @property
  453. def tracker(self):
  454. return self.writer
  455. @on_main_process
  456. def store_init_configuration(self, values: dict):
  457. """
  458. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
  459. Args:
  460. values (Dictionary `str` to `bool`, `str`, `float` or `int`):
  461. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  462. `str`, `float`, `int`, or `None`.
  463. """
  464. self.writer.log_parameters(values)
  465. logger.debug("Stored initial configuration hyperparameters to Comet")
  466. @on_main_process
  467. def log(self, values: dict, step: Optional[int] = None, **kwargs):
  468. """
  469. Logs `values` to the current run.
  470. Args:
  471. values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`):
  472. Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of
  473. `str` to `float`/`int`.
  474. step (`int`, *optional*):
  475. The run step. If included, the log will be affiliated with this step.
  476. kwargs:
  477. Additional key word arguments passed along to either `Experiment.log_metric`, `Experiment.log_other`,
  478. or `Experiment.log_metrics` method based on the contents of `values`.
  479. """
  480. if step is not None:
  481. self.writer.set_step(step)
  482. for k, v in values.items():
  483. if isinstance(v, (int, float)):
  484. self.writer.log_metric(k, v, step=step, **kwargs)
  485. elif isinstance(v, str):
  486. self.writer.log_other(k, v, **kwargs)
  487. elif isinstance(v, dict):
  488. self.writer.log_metrics(v, step=step, **kwargs)
  489. logger.debug("Successfully logged to Comet")
  490. @on_main_process
  491. def finish(self):
  492. """
  493. Flush `comet-ml` writer
  494. """
  495. self.writer.end()
  496. logger.debug("Comet run flushed")
  497. class AimTracker(GeneralTracker):
  498. """
  499. A `Tracker` class that supports `aim`. Should be initialized at the start of your script.
  500. Args:
  501. run_name (`str`):
  502. The name of the experiment run.
  503. **kwargs (additional keyword arguments, *optional*):
  504. Additional key word arguments passed along to the `Run.__init__` method.
  505. """
  506. name = "aim"
  507. requires_logging_directory = True
  508. def __init__(self, run_name: str, logging_dir: Optional[Union[str, os.PathLike]] = ".", **kwargs):
  509. super().__init__()
  510. self.run_name = run_name
  511. self.aim_repo_path = logging_dir
  512. self.init_kwargs = kwargs
  513. @on_main_process
  514. def start(self):
  515. from aim import Run
  516. self.writer = Run(repo=self.aim_repo_path, **self.init_kwargs)
  517. self.writer.name = self.run_name
  518. logger.debug(f"Initialized Aim project {self.run_name}")
  519. logger.debug(
  520. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  521. )
  522. @property
  523. def tracker(self):
  524. return self.writer
  525. @on_main_process
  526. def store_init_configuration(self, values: dict):
  527. """
  528. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
  529. Args:
  530. values (`dict`):
  531. Values to be stored as initial hyperparameters as key-value pairs.
  532. """
  533. self.writer["hparams"] = values
  534. @on_main_process
  535. def log(self, values: dict, step: Optional[int], **kwargs):
  536. """
  537. Logs `values` to the current run.
  538. Args:
  539. values (`dict`):
  540. Values to be logged as key-value pairs.
  541. step (`int`, *optional*):
  542. The run step. If included, the log will be affiliated with this step.
  543. kwargs:
  544. Additional key word arguments passed along to the `Run.track` method.
  545. """
  546. # Note: replace this with the dictionary support when merged
  547. for key, value in values.items():
  548. self.writer.track(value, name=key, step=step, **kwargs)
  549. @on_main_process
  550. def log_images(self, values: dict, step: Optional[int] = None, kwargs: Optional[dict[str, dict]] = None):
  551. """
  552. Logs `images` to the current run.
  553. Args:
  554. values (`Dict[str, Union[np.ndarray, PIL.Image, Tuple[np.ndarray, str], Tuple[PIL.Image, str]]]`):
  555. Values to be logged as key-value pairs. The values need to have type `np.ndarray` or PIL.Image. If a
  556. tuple is provided, the first element should be the image and the second element should be the caption.
  557. step (`int`, *optional*):
  558. The run step. If included, the log will be affiliated with this step.
  559. kwargs (`Dict[str, dict]`):
  560. Additional key word arguments passed along to the `Run.Image` and `Run.track` method specified by the
  561. keys `aim_image` and `track`, respectively.
  562. """
  563. import aim
  564. aim_image_kw = {}
  565. track_kw = {}
  566. if kwargs is not None:
  567. aim_image_kw = kwargs.get("aim_image", {})
  568. track_kw = kwargs.get("track", {})
  569. for key, value in values.items():
  570. if isinstance(value, tuple):
  571. img, caption = value
  572. else:
  573. img, caption = value, ""
  574. aim_image = aim.Image(img, caption=caption, **aim_image_kw)
  575. self.writer.track(aim_image, name=key, step=step, **track_kw)
  576. @on_main_process
  577. def finish(self):
  578. """
  579. Closes `aim` writer
  580. """
  581. self.writer.close()
  582. class MLflowTracker(GeneralTracker):
  583. """
  584. A `Tracker` class that supports `mlflow`. Should be initialized at the start of your script.
  585. Args:
  586. experiment_name (`str`, *optional*):
  587. Name of the experiment. Environment variable MLFLOW_EXPERIMENT_NAME has priority over this argument.
  588. logging_dir (`str` or `os.PathLike`, defaults to `"."`):
  589. Location for mlflow logs to be stored.
  590. run_id (`str`, *optional*):
  591. If specified, get the run with the specified UUID and log parameters and metrics under that run. The run’s
  592. end time is unset and its status is set to running, but the run’s other attributes (source_version,
  593. source_type, etc.) are not changed. Environment variable MLFLOW_RUN_ID has priority over this argument.
  594. tags (`Dict[str, str]`, *optional*):
  595. An optional `dict` of `str` keys and values, or a `str` dump from a `dict`, to set as tags on the run. If a
  596. run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are
  597. set on the new run. Environment variable MLFLOW_TAGS has priority over this argument.
  598. nested_run (`bool`, *optional*, defaults to `False`):
  599. Controls whether run is nested in parent run. True creates a nested run. Environment variable
  600. MLFLOW_NESTED_RUN has priority over this argument.
  601. run_name (`str`, *optional*):
  602. Name of new run (stored as a mlflow.runName tag). Used only when `run_id` is unspecified.
  603. description (`str`, *optional*):
  604. An optional string that populates the description box of the run. If a run is being resumed, the
  605. description is set on the resumed run. If a new run is being created, the description is set on the new
  606. run.
  607. """
  608. name = "mlflow"
  609. requires_logging_directory = False
  610. def __init__(
  611. self,
  612. experiment_name: Optional[str] = None,
  613. logging_dir: Optional[Union[str, os.PathLike]] = None,
  614. run_id: Optional[str] = None,
  615. tags: Optional[Union[dict[str, Any], str]] = None,
  616. nested_run: Optional[bool] = False,
  617. run_name: Optional[str] = None,
  618. description: Optional[str] = None,
  619. ):
  620. experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME", experiment_name)
  621. run_id = os.environ.get("MLFLOW_RUN_ID", run_id)
  622. tags = os.environ.get("MLFLOW_TAGS", tags)
  623. if isinstance(tags, str):
  624. tags = json.loads(tags)
  625. nested_run = os.environ.get("MLFLOW_NESTED_RUN", nested_run)
  626. self.experiment_name = experiment_name
  627. self.logging_dir = logging_dir
  628. self.run_id = run_id
  629. self.tags = tags
  630. self.nested_run = nested_run
  631. self.run_name = run_name
  632. self.description = description
  633. @on_main_process
  634. def start(self):
  635. import mlflow
  636. exps = mlflow.search_experiments(filter_string=f"name = '{self.experiment_name}'")
  637. if len(exps) > 0:
  638. if len(exps) > 1:
  639. logger.warning("Multiple experiments with the same name found. Using first one.")
  640. experiment_id = exps[0].experiment_id
  641. else:
  642. experiment_id = mlflow.create_experiment(
  643. name=self.experiment_name,
  644. artifact_location=self.logging_dir,
  645. tags=self.tags,
  646. )
  647. self.active_run = mlflow.start_run(
  648. run_id=self.run_id,
  649. experiment_id=experiment_id,
  650. run_name=self.run_name,
  651. nested=self.nested_run,
  652. tags=self.tags,
  653. description=self.description,
  654. )
  655. logger.debug(f"Initialized mlflow experiment {self.experiment_name}")
  656. logger.debug(
  657. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  658. )
  659. @property
  660. def tracker(self):
  661. return self.active_run
  662. @on_main_process
  663. def store_init_configuration(self, values: dict):
  664. """
  665. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
  666. Args:
  667. values (`dict`):
  668. Values to be stored as initial hyperparameters as key-value pairs.
  669. """
  670. import mlflow
  671. for name, value in list(values.items()):
  672. # internally, all values are converted to str in MLflow
  673. if len(str(value)) > mlflow.utils.validation.MAX_PARAM_VAL_LENGTH:
  674. logger.warning_once(
  675. f'Accelerate is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s'
  676. f" log_param() only accepts values no longer than {mlflow.utils.validation.MAX_PARAM_VAL_LENGTH} characters so we dropped this attribute."
  677. )
  678. del values[name]
  679. values_list = list(values.items())
  680. # MLflow cannot log more than 100 values in one go, so we have to split it
  681. for i in range(0, len(values_list), mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH):
  682. mlflow.log_params(dict(values_list[i : i + mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH]))
  683. logger.debug("Stored initial configuration hyperparameters to MLflow")
  684. @on_main_process
  685. def log(self, values: dict, step: Optional[int]):
  686. """
  687. Logs `values` to the current run.
  688. Args:
  689. values (`dict`):
  690. Values to be logged as key-value pairs.
  691. step (`int`, *optional*):
  692. The run step. If included, the log will be affiliated with this step.
  693. """
  694. metrics = {}
  695. for k, v in values.items():
  696. if isinstance(v, (int, float)):
  697. metrics[k] = v
  698. else:
  699. logger.warning_once(
  700. f'MLflowTracker is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. '
  701. "MLflow's log_metric() only accepts float and int types so we dropped this attribute."
  702. )
  703. import mlflow
  704. mlflow.log_metrics(metrics, step=step)
  705. logger.debug("Successfully logged to mlflow")
  706. @on_main_process
  707. def log_figure(self, figure: Any, artifact_file: str, **save_kwargs):
  708. """
  709. Logs an figure to the current run.
  710. Args:
  711. figure (Any):
  712. The figure to be logged.
  713. artifact_file (`str`, *optional*):
  714. The run-relative artifact file path in posixpath format to which the image is saved.
  715. If not provided, the image is saved to a default location.
  716. **kwargs:
  717. Additional keyword arguments passed to the underlying mlflow.log_image function.
  718. """
  719. import mlflow
  720. mlflow.log_figure(figure=figure, artifact_file=artifact_file, **save_kwargs)
  721. logger.debug("Successfully logged image to mlflow")
  722. @on_main_process
  723. def log_artifacts(self, local_dir: str, artifact_path: Optional[str] = None):
  724. """
  725. Logs an artifacts (all content of a dir) to the current run.
  726. local_dir (`str`):
  727. Path to the directory to be logged as an artifact.
  728. artifact_path (`str`, *optional*):
  729. Directory within the run's artifact directory where the artifact will be logged. If omitted, the
  730. artifact will be logged to the root of the run's artifact directory. The run step. If included, the
  731. artifact will be affiliated with this step.
  732. """
  733. import mlflow
  734. mlflow.log_artifacts(local_dir=local_dir, artifact_path=artifact_path)
  735. logger.debug("Successfully logged artofact to mlflow")
  736. @on_main_process
  737. def log_artifact(self, local_path: str, artifact_path: Optional[str] = None):
  738. """
  739. Logs an artifact (file) to the current run.
  740. local_path (`str`):
  741. Path to the file to be logged as an artifact.
  742. artifact_path (`str`, *optional*):
  743. Directory within the run's artifact directory where the artifact will be logged. If omitted, the
  744. artifact will be logged to the root of the run's artifact directory. The run step. If included, the
  745. artifact will be affiliated with this step.
  746. """
  747. import mlflow
  748. mlflow.log_artifact(local_path=local_path, artifact_path=artifact_path)
  749. logger.debug("Successfully logged artofact to mlflow")
  750. @on_main_process
  751. def finish(self):
  752. """
  753. End the active MLflow run.
  754. """
  755. import mlflow
  756. mlflow.end_run()
  757. class ClearMLTracker(GeneralTracker):
  758. """
  759. A `Tracker` class that supports `clearml`. Should be initialized at the start of your script.
  760. Args:
  761. run_name (`str`, *optional*):
  762. Name of the experiment. Environment variables `CLEARML_PROJECT` and `CLEARML_TASK` have priority over this
  763. argument.
  764. **kwargs (additional keyword arguments, *optional*):
  765. Kwargs passed along to the `Task.__init__` method.
  766. """
  767. name = "clearml"
  768. requires_logging_directory = False
  769. def __init__(self, run_name: Optional[str] = None, **kwargs):
  770. super().__init__()
  771. self.user_provided_run_name = run_name
  772. self._initialized_externally = False
  773. self.init_kwargs = kwargs
  774. @on_main_process
  775. def start(self):
  776. from clearml import Task
  777. current_task = Task.current_task()
  778. if current_task:
  779. self._initialized_externally = True
  780. self.task = current_task
  781. return
  782. task_init_args = {**self.init_kwargs}
  783. task_init_args.setdefault("project_name", os.environ.get("CLEARML_PROJECT", self.user_provided_run_name))
  784. task_init_args.setdefault("task_name", os.environ.get("CLEARML_TASK", self.user_provided_run_name))
  785. self.task = Task.init(**task_init_args)
  786. @property
  787. def tracker(self):
  788. return self.task
  789. @on_main_process
  790. def store_init_configuration(self, values: dict):
  791. """
  792. Connect configuration dictionary to the Task object. Should be run at the beginning of your experiment.
  793. Args:
  794. values (`dict`):
  795. Values to be stored as initial hyperparameters as key-value pairs.
  796. """
  797. return self.task.connect_configuration(values)
  798. @on_main_process
  799. def log(self, values: dict[str, Union[int, float]], step: Optional[int] = None, **kwargs):
  800. """
  801. Logs `values` dictionary to the current run. The dictionary keys must be strings. The dictionary values must be
  802. ints or floats
  803. Args:
  804. values (`Dict[str, Union[int, float]]`):
  805. Values to be logged as key-value pairs. If the key starts with 'eval_'/'test_'/'train_', the value will
  806. be reported under the 'eval'/'test'/'train' series and the respective prefix will be removed.
  807. Otherwise, the value will be reported under the 'train' series, and no prefix will be removed.
  808. step (`int`, *optional*):
  809. If specified, the values will be reported as scalars, with the iteration number equal to `step`.
  810. Otherwise they will be reported as single values.
  811. kwargs:
  812. Additional key word arguments passed along to the `clearml.Logger.report_single_value` or
  813. `clearml.Logger.report_scalar` methods.
  814. """
  815. clearml_logger = self.task.get_logger()
  816. for k, v in values.items():
  817. if not isinstance(v, (int, float)):
  818. logger.warning_once(
  819. "Accelerator is attempting to log a value of "
  820. f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
  821. "This invocation of ClearML logger's report_scalar() "
  822. "is incorrect so we dropped this attribute."
  823. )
  824. continue
  825. if step is None:
  826. clearml_logger.report_single_value(name=k, value=v, **kwargs)
  827. continue
  828. title, series = ClearMLTracker._get_title_series(k)
  829. clearml_logger.report_scalar(title=title, series=series, value=v, iteration=step, **kwargs)
  830. @on_main_process
  831. def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
  832. """
  833. Logs `images` to the current run.
  834. Args:
  835. values (`Dict[str, List[Union[np.ndarray, PIL.Image]]`):
  836. Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
  837. step (`int`, *optional*):
  838. The run step. If included, the log will be affiliated with this step.
  839. kwargs:
  840. Additional key word arguments passed along to the `clearml.Logger.report_image` method.
  841. """
  842. clearml_logger = self.task.get_logger()
  843. for k, v in values.items():
  844. title, series = ClearMLTracker._get_title_series(k)
  845. clearml_logger.report_image(title=title, series=series, iteration=step, image=v, **kwargs)
  846. @on_main_process
  847. def log_table(
  848. self,
  849. table_name: str,
  850. columns: Optional[list[str]] = None,
  851. data: Optional[list[list[Any]]] = None,
  852. dataframe: Any = None,
  853. step: Optional[int] = None,
  854. **kwargs,
  855. ):
  856. """
  857. Log a Table to the task. Can be defined eitherwith `columns` and `data` or with `dataframe`.
  858. Args:
  859. table_name (`str`):
  860. The name of the table
  861. columns (list of `str`, *optional*):
  862. The name of the columns on the table
  863. data (List of List of Any data type, *optional*):
  864. The data to be logged in the table. If `columns` is not specified, then the first entry in data will be
  865. the name of the columns of the table
  866. dataframe (Any data type, *optional*):
  867. The data to be logged in the table
  868. step (`int`, *optional*):
  869. The run step. If included, the log will be affiliated with this step.
  870. kwargs:
  871. Additional key word arguments passed along to the `clearml.Logger.report_table` method.
  872. """
  873. to_report = dataframe
  874. if dataframe is None:
  875. if data is None:
  876. raise ValueError(
  877. "`ClearMLTracker.log_table` requires that `data` to be supplied if `dataframe` is `None`"
  878. )
  879. to_report = [columns] + data if columns else data
  880. title, series = ClearMLTracker._get_title_series(table_name)
  881. self.task.get_logger().report_table(title=title, series=series, table_plot=to_report, iteration=step, **kwargs)
  882. @on_main_process
  883. def finish(self):
  884. """
  885. Close the ClearML task. If the task was initialized externally (e.g. by manually calling `Task.init`), this
  886. function is a noop
  887. """
  888. if self.task and not self._initialized_externally:
  889. self.task.close()
  890. @staticmethod
  891. def _get_title_series(name):
  892. for prefix in ["eval", "test", "train"]:
  893. if name.startswith(prefix + "_"):
  894. return name[len(prefix) + 1 :], prefix
  895. return name, "train"
  896. class DVCLiveTracker(GeneralTracker):
  897. """
  898. A `Tracker` class that supports `dvclive`. Should be initialized at the start of your script.
  899. Args:
  900. run_name (`str`, *optional*):
  901. Ignored for dvclive. See `kwargs` instead.
  902. kwargs:
  903. Additional key word arguments passed along to [`dvclive.Live()`](https://dvc.org/doc/dvclive/live).
  904. Example:
  905. ```py
  906. from accelerate import Accelerator
  907. accelerator = Accelerator(log_with="dvclive")
  908. accelerator.init_trackers(project_name="my_project", init_kwargs={"dvclive": {"dir": "my_directory"}})
  909. ```
  910. """
  911. name = "dvclive"
  912. requires_logging_directory = False
  913. def __init__(self, run_name: Optional[str] = None, live: Optional[Any] = None, **kwargs):
  914. super().__init__()
  915. self.live = live
  916. self.init_kwargs = kwargs
  917. @on_main_process
  918. def start(self):
  919. from dvclive import Live
  920. self.live = self.live if self.live is not None else Live(**self.init_kwargs)
  921. @property
  922. def tracker(self):
  923. return self.live
  924. @on_main_process
  925. def store_init_configuration(self, values: dict):
  926. """
  927. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the
  928. hyperparameters in a yaml file for future use.
  929. Args:
  930. values (Dictionary `str` to `bool`, `str`, `float`, `int`, or a List or Dict of those types):
  931. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  932. `str`, `float`, or `int`.
  933. """
  934. self.live.log_params(values)
  935. @on_main_process
  936. def log(self, values: dict, step: Optional[int] = None, **kwargs):
  937. """
  938. Logs `values` to the current run.
  939. Args:
  940. values (Dictionary `str` to `str`, `float`, or `int`):
  941. Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`.
  942. step (`int`, *optional*):
  943. The run step. If included, the log will be affiliated with this step.
  944. kwargs:
  945. Additional key word arguments passed along to `dvclive.Live.log_metric()`.
  946. """
  947. from dvclive.plots import Metric
  948. if step is not None:
  949. self.live.step = step
  950. for k, v in values.items():
  951. if Metric.could_log(v):
  952. self.live.log_metric(k, v, **kwargs)
  953. else:
  954. logger.warning_once(
  955. "Accelerator attempted to log a value of "
  956. f'"{v}" of type {type(v)} for key "{k}" as a scalar. '
  957. "This invocation of DVCLive's Live.log_metric() "
  958. "is incorrect so we dropped this attribute."
  959. )
  960. self.live.next_step()
  961. @on_main_process
  962. def finish(self):
  963. """
  964. Closes `dvclive.Live()`.
  965. """
  966. self.live.end()
  967. class SwanLabTracker(GeneralTracker):
  968. """
  969. A `Tracker` class that supports `swanlab`. Should be initialized at the start of your script.
  970. Args:
  971. run_name (`str`):
  972. The name of the experiment run.
  973. **kwargs (additional keyword arguments, *optional*):
  974. Additional key word arguments passed along to the `swanlab.init` method.
  975. """
  976. name = "swanlab"
  977. requires_logging_directory = False
  978. main_process_only = False
  979. def __init__(self, run_name: str, **kwargs):
  980. super().__init__()
  981. self.run_name = run_name
  982. self.init_kwargs = kwargs
  983. @on_main_process
  984. def start(self):
  985. import swanlab
  986. self.run = swanlab.init(project=self.run_name, **self.init_kwargs)
  987. swanlab.config["FRAMEWORK"] = "🤗Accelerate" # add accelerate logo in config
  988. logger.debug(f"Initialized SwanLab project {self.run_name}")
  989. logger.debug(
  990. "Make sure to log any initial configurations with `self.store_init_configuration` before training!"
  991. )
  992. @property
  993. def tracker(self):
  994. return self.run
  995. @on_main_process
  996. def store_init_configuration(self, values: dict):
  997. """
  998. Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment.
  999. Args:
  1000. values (Dictionary `str` to `bool`, `str`, `float` or `int`):
  1001. Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`,
  1002. `str`, `float`, `int`, or `None`.
  1003. """
  1004. import swanlab
  1005. swanlab.config.update(values, allow_val_change=True)
  1006. logger.debug("Stored initial configuration hyperparameters to SwanLab")
  1007. @on_main_process
  1008. def log(self, values: dict, step: Optional[int] = None, **kwargs):
  1009. """
  1010. Logs `values` to the current run.
  1011. Args:
  1012. data : Dict[str, DataType]
  1013. Data must be a dict. The key must be a string with 0-9, a-z, A-Z, " ", "_", "-", "/". The value must be a
  1014. `float`, `float convertible object`, `int` or `swanlab.data.BaseType`.
  1015. step : int, optional
  1016. The step number of the current data, if not provided, it will be automatically incremented.
  1017. If step is duplicated, the data will be ignored.
  1018. kwargs:
  1019. Additional key word arguments passed along to the `swanlab.log` method. Likes:
  1020. print_to_console : bool, optional
  1021. Whether to print the data to the console, the default is False.
  1022. """
  1023. self.run.log(values, step=step, **kwargs)
  1024. logger.debug("Successfully logged to SwanLab")
  1025. @on_main_process
  1026. def log_images(self, values: dict, step: Optional[int] = None, **kwargs):
  1027. """
  1028. Logs `images` to the current run.
  1029. Args:
  1030. values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`):
  1031. Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or
  1032. step (`int`, *optional*):
  1033. The run step. If included, the log will be affiliated with this step.
  1034. kwargs:
  1035. Additional key word arguments passed along to the `swanlab.log` method. Likes:
  1036. print_to_console : bool, optional
  1037. Whether to print the data to the console, the default is False.
  1038. """
  1039. import swanlab
  1040. for k, v in values.items():
  1041. self.log({k: [swanlab.Image(image) for image in v]}, step=step, **kwargs)
  1042. logger.debug("Successfully logged images to SwanLab")
  1043. @on_main_process
  1044. def finish(self):
  1045. """
  1046. Closes `swanlab` writer
  1047. """
  1048. self.run.finish()
  1049. logger.debug("SwanLab run closed")
  1050. LOGGER_TYPE_TO_CLASS = {
  1051. "aim": AimTracker,
  1052. "comet_ml": CometMLTracker,
  1053. "mlflow": MLflowTracker,
  1054. "tensorboard": TensorBoardTracker,
  1055. "wandb": WandBTracker,
  1056. "clearml": ClearMLTracker,
  1057. "dvclive": DVCLiveTracker,
  1058. "swanlab": SwanLabTracker,
  1059. "trackio": TrackioTracker,
  1060. }
  1061. def filter_trackers(
  1062. log_with: list[Union[str, LoggerType, GeneralTracker]],
  1063. logging_dir: Optional[Union[str, os.PathLike]] = None,
  1064. ):
  1065. """
  1066. Takes in a list of potential tracker types and checks that:
  1067. - The tracker wanted is available in that environment
  1068. - Filters out repeats of tracker types
  1069. - If `all` is in `log_with`, will return all trackers in the environment
  1070. - If a tracker requires a `logging_dir`, ensures that `logging_dir` is not `None`
  1071. Args:
  1072. log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*):
  1073. A list of loggers to be setup for experiment tracking. Should be one or several of:
  1074. - `"all"`
  1075. - `"tensorboard"`
  1076. - `"wandb"`
  1077. - `"trackio"`
  1078. - `"aim"`
  1079. - `"comet_ml"`
  1080. - `"mlflow"`
  1081. - `"dvclive"`
  1082. - `"swanlab"`
  1083. If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can
  1084. also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`.
  1085. logging_dir (`str`, `os.PathLike`, *optional*):
  1086. A path to a directory for storing logs of locally-compatible loggers.
  1087. """
  1088. loggers = []
  1089. if log_with is not None:
  1090. if not isinstance(log_with, (list, tuple)):
  1091. log_with = [log_with]
  1092. if "all" in log_with or LoggerType.ALL in log_with:
  1093. loggers = [o for o in log_with if issubclass(type(o), GeneralTracker)] + get_available_trackers()
  1094. else:
  1095. for log_type in log_with:
  1096. if log_type not in LoggerType and not issubclass(type(log_type), GeneralTracker):
  1097. raise ValueError(f"Unsupported logging capability: {log_type}. Choose between {LoggerType.list()}")
  1098. if issubclass(type(log_type), GeneralTracker):
  1099. loggers.append(log_type)
  1100. else:
  1101. log_type = LoggerType(log_type)
  1102. if log_type not in loggers:
  1103. if log_type in get_available_trackers():
  1104. tracker_init = LOGGER_TYPE_TO_CLASS[str(log_type)]
  1105. if tracker_init.requires_logging_directory:
  1106. if logging_dir is None:
  1107. raise ValueError(
  1108. f"Logging with `{log_type}` requires a `logging_dir` to be passed in."
  1109. )
  1110. loggers.append(log_type)
  1111. else:
  1112. logger.debug(f"Tried adding logger {log_type}, but package is unavailable in the system.")
  1113. return loggers