logger.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. from __future__ import annotations
  2. import os
  3. from argparse import Namespace
  4. from collections.abc import Mapping
  5. from pathlib import Path
  6. from typing import TYPE_CHECKING, Any, Literal
  7. from packaging import version
  8. from typing_extensions import override
  9. import wandb
  10. from wandb import Artifact
  11. from wandb.sdk.lib import telemetry
  12. try:
  13. import lightning
  14. import torch.nn as nn
  15. from lightning.fabric.loggers.logger import Logger, rank_zero_experiment
  16. from lightning.fabric.utilities.exceptions import MisconfigurationException
  17. from lightning.fabric.utilities.logger import (
  18. _add_prefix,
  19. _convert_params,
  20. _sanitize_callable_params,
  21. )
  22. from lightning.fabric.utilities.rank_zero import rank_zero_only, rank_zero_warn
  23. from lightning.fabric.utilities.types import _PATH
  24. from torch import Tensor
  25. from torch.nn import Module
  26. if version.parse(lightning.__version__) > version.parse("2.1.3"):
  27. wandb.termwarn(
  28. """This integration is tested and supported for lightning Fabric 2.1.3.
  29. Please report any issues to https://github.com/wandb/wandb/issues with the tag `lightning-fabric`.""",
  30. repeat=False,
  31. )
  32. if TYPE_CHECKING:
  33. from lightning.pytorch.callbacks.model_checkpoint import ModelCheckpoint
  34. except ImportError as e:
  35. wandb.Error(e)
  36. class WandbLogger(Logger):
  37. r"""Log using `Weights and Biases <https://docs.wandb.ai/models/integrations/lightning>`_.
  38. **Installation and set-up**
  39. Install with pip:
  40. .. code-block:: bash
  41. pip install wandb
  42. Create a `WandbLogger` instance:
  43. .. code-block:: python
  44. from lightning.fabric.loggers import WandbLogger
  45. wandb_logger = WandbLogger(project="MNIST")
  46. Pass the logger instance to the `Trainer`:
  47. .. code-block:: python
  48. trainer = Trainer(logger=wandb_logger)
  49. A new W&B run will be created when training starts if you have not created one manually before with `wandb.init()`.
  50. **Log metrics**
  51. Log from :class:`~lightning.pytorch.core.LightningModule`:
  52. .. code-block:: python
  53. class LitModule(LightningModule):
  54. def training_step(self, batch, batch_idx):
  55. self.log("train/loss", loss)
  56. Use directly wandb module:
  57. .. code-block:: python
  58. wandb.log({"train/loss": loss})
  59. **Log hyper-parameters**
  60. Save :class:`~lightning.pytorch.core.LightningModule` parameters:
  61. .. code-block:: python
  62. class LitModule(LightningModule):
  63. def __init__(self, *args, **kwarg):
  64. self.save_hyperparameters()
  65. Add other config parameters:
  66. .. code-block:: python
  67. # add one parameter
  68. wandb_logger.experiment.config["key"] = value
  69. # add multiple parameters
  70. wandb_logger.experiment.config.update({key1: val1, key2: val2})
  71. # use directly wandb module
  72. wandb.config["key"] = value
  73. wandb.config.update()
  74. **Log gradients, parameters and model topology**
  75. Call the `watch` method for automatically tracking gradients:
  76. .. code-block:: python
  77. # log gradients and model topology
  78. wandb_logger.watch(model)
  79. # log gradients, parameter histogram and model topology
  80. wandb_logger.watch(model, log="all")
  81. # change log frequency of gradients and parameters (100 steps by default)
  82. wandb_logger.watch(model, log_freq=500)
  83. # do not log graph (in case of errors)
  84. wandb_logger.watch(model, log_graph=False)
  85. The `watch` method adds hooks to the model which can be removed at the end of training:
  86. .. code-block:: python
  87. wandb_logger.experiment.unwatch(model)
  88. **Log model checkpoints**
  89. Log model checkpoints at the end of training:
  90. .. code-block:: python
  91. wandb_logger = WandbLogger(log_model=True)
  92. Log model checkpoints as they get created during training:
  93. .. code-block:: python
  94. wandb_logger = WandbLogger(log_model="all")
  95. Custom checkpointing can be set up through :class:`~lightning.pytorch.callbacks.ModelCheckpoint`:
  96. .. code-block:: python
  97. # log model only if `val_accuracy` increases
  98. wandb_logger = WandbLogger(log_model="all")
  99. checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max")
  100. trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback])
  101. `latest` and `best` aliases are automatically set to easily retrieve a model checkpoint:
  102. .. code-block:: python
  103. # reference can be retrieved in artifacts panel
  104. # "VERSION" can be a version (ex: "v2") or an alias ("latest or "best")
  105. checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION"
  106. # download checkpoint locally (if not already cached)
  107. run = wandb.init(project="MNIST")
  108. artifact = run.use_artifact(checkpoint_reference, type="model")
  109. artifact_dir = artifact.download()
  110. # load checkpoint
  111. model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt")
  112. **Log media**
  113. Log text with:
  114. .. code-block:: python
  115. # using columns and data
  116. columns = ["input", "label", "prediction"]
  117. data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]]
  118. wandb_logger.log_text(key="samples", columns=columns, data=data)
  119. # using a pandas DataFrame
  120. wandb_logger.log_text(key="samples", dataframe=my_dataframe)
  121. Log images with:
  122. .. code-block:: python
  123. # using tensors, numpy arrays or PIL images
  124. wandb_logger.log_image(key="samples", images=[img1, img2])
  125. # adding captions
  126. wandb_logger.log_image(
  127. key="samples", images=[img1, img2], caption=["tree", "person"]
  128. )
  129. # using file path
  130. wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"])
  131. More arguments can be passed for logging segmentation masks and bounding boxes. Refer to
  132. `Image Overlays documentation <https://docs.wandb.ai/models/track/log/media#image-overlays>`_.
  133. **Log Tables**
  134. `W&B Tables <https://docs.wandb.ai/models/tables/visualize-tables>`_ can be used to log,
  135. query and analyze tabular data.
  136. They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing,
  137. understanding and sharing any form of data, from datasets to model predictions.
  138. .. code-block:: python
  139. columns = ["caption", "image", "sound"]
  140. data = [
  141. ["cheese", wandb.Image(img_1), wandb.Audio(snd_1)],
  142. ["wine", wandb.Image(img_2), wandb.Audio(snd_2)],
  143. ]
  144. wandb_logger.log_table(key="samples", columns=columns, data=data)
  145. **Downloading and Using Artifacts**
  146. To download an artifact without starting a run, call the ``download_artifact``
  147. function on the class:
  148. .. code-block:: python
  149. artifact_dir = wandb_logger.download_artifact(artifact="path/to/artifact")
  150. To download an artifact and link it to an ongoing run call the ``download_artifact``
  151. function on the logger instance:
  152. .. code-block:: python
  153. class MyModule(LightningModule):
  154. def any_lightning_module_function_or_hook(self):
  155. self.logger.download_artifact(artifact="path/to/artifact")
  156. To link an artifact from a previous run you can use ``use_artifact`` function:
  157. .. code-block:: python
  158. wandb_logger.use_artifact(artifact="path/to/artifact")
  159. See Also:
  160. - `Demo in Google Colab <http://wandb.me/lightning>`__ with hyperparameter search and model logging
  161. - `W&B Documentation <https://docs.wandb.ai/models/integrations/lightning>`__
  162. Args:
  163. name: Display name for the run.
  164. save_dir: Path where data is saved.
  165. version: Sets the version, mainly used to resume a previous run.
  166. offline: Run offline (data can be streamed later to wandb servers).
  167. dir: Same as save_dir.
  168. id: Same as version.
  169. anonymous: Enables or explicitly disables anonymous logging.
  170. project: The name of the project to which this run will belong. If not set, the environment variable
  171. `WANDB_PROJECT` will be used as a fallback. If both are not set, it defaults to ``'lightning_logs'``.
  172. log_model: Log checkpoints created by :class:`~lightning.pytorch.callbacks.ModelCheckpoint`
  173. as W&B artifacts. `latest` and `best` aliases are automatically set.
  174. * if ``log_model == 'all'``, checkpoints are logged during training.
  175. * if ``log_model == True``, checkpoints are logged at the end of training, except when
  176. `~lightning.pytorch.callbacks.ModelCheckpoint.save_top_k` ``== -1``
  177. which also logs every checkpoint during training.
  178. * if ``log_model == False`` (default), no checkpoint is logged.
  179. prefix: A string to put at the beginning of metric keys.
  180. experiment: WandB experiment object. Automatically set when creating a run.
  181. checkpoint_name: Name of the model checkpoint artifact being logged.
  182. log_checkpoint_on: When to log model checkpoints as W&B artifacts. Only used if ``log_model`` is ``True``.
  183. Options: ``"success"``, ``"all"``. Default: ``"success"``.
  184. \**kwargs: Arguments passed to :func:`wandb.init` like `entity`, `group`, `tags`, etc.
  185. Raises:
  186. ModuleNotFoundError:
  187. If required WandB package is not installed on the device.
  188. MisconfigurationException:
  189. If both ``log_model`` and ``offline`` is set to ``True``.
  190. """
  191. LOGGER_JOIN_CHAR = "-"
  192. def __init__(
  193. self,
  194. name: str | None = None,
  195. save_dir: _PATH = ".",
  196. version: str | None = None,
  197. offline: bool = False,
  198. dir: _PATH | None = None,
  199. id: str | None = None,
  200. anonymous: bool | None = None,
  201. project: str | None = None,
  202. log_model: Literal["all"] | bool = False,
  203. experiment: wandb.Run | None = None,
  204. prefix: str = "",
  205. checkpoint_name: str | None = None,
  206. log_checkpoint_on: Literal["success"] | Literal["all"] = "success",
  207. **kwargs: Any,
  208. ) -> None:
  209. if offline and log_model:
  210. raise MisconfigurationException(
  211. f"Providing log_model={log_model} and offline={offline} is an invalid configuration"
  212. " since model checkpoints cannot be uploaded in offline mode.\n"
  213. "Hint: Set `offline=False` to log your model."
  214. )
  215. super().__init__()
  216. self._offline = offline
  217. self._log_model = log_model
  218. self._prefix = prefix
  219. self._experiment = experiment
  220. self._logged_model_time: dict[str, float] = {}
  221. self._checkpoint_callback: ModelCheckpoint | None = None
  222. # paths are processed as strings
  223. if save_dir is not None:
  224. save_dir = os.fspath(save_dir)
  225. elif dir is not None:
  226. dir = os.fspath(dir)
  227. project = project or os.environ.get("WANDB_PROJECT", "lightning_fabric_logs")
  228. # set wandb init arguments
  229. self._wandb_init: dict[str, Any] = {
  230. "name": name,
  231. "project": project,
  232. "dir": save_dir or dir,
  233. "id": version or id,
  234. "resume": "allow",
  235. "anonymous": ("allow" if anonymous else None),
  236. }
  237. self._wandb_init.update(**kwargs)
  238. # extract parameters
  239. self._project = self._wandb_init.get("project")
  240. self._save_dir = self._wandb_init.get("dir")
  241. self._name = self._wandb_init.get("name")
  242. self._id = self._wandb_init.get("id")
  243. self._checkpoint_name = checkpoint_name
  244. self._log_checkpoint_on = log_checkpoint_on
  245. def __getstate__(self) -> dict[str, Any]:
  246. # Hack: If the 'spawn' launch method is used, the logger will get pickled and this `__getstate__` gets called.
  247. # We create an experiment here in the main process, and attach to it in the worker process.
  248. # Using wandb-service, we persist the same experiment even if multiple `Trainer.fit/test/validate` calls
  249. # are made.
  250. _ = self.experiment
  251. state = self.__dict__.copy()
  252. # args needed to reload correct experiment
  253. if self._experiment is not None:
  254. state["_id"] = getattr(self._experiment, "id", None)
  255. state["_attach_id"] = getattr(self._experiment, "_attach_id", None)
  256. state["_name"] = self._experiment.name
  257. # cannot be pickled
  258. state["_experiment"] = None
  259. return state
  260. @property
  261. @rank_zero_experiment
  262. def experiment(self) -> wandb.Run:
  263. r"""Actual wandb object.
  264. To use wandb features in your :class:`~lightning.pytorch.core.LightningModule`, do the
  265. following.
  266. Example::
  267. .. code-block:: python
  268. self.logger.experiment.some_wandb_function()
  269. """
  270. if self._experiment is None:
  271. if self._offline:
  272. os.environ["WANDB_MODE"] = "dryrun"
  273. attach_id = getattr(self, "_attach_id", None)
  274. if wandb.run is not None:
  275. # wandb process already created in this instance
  276. rank_zero_warn(
  277. "There is a wandb run already in progress and newly created instances of `WandbLogger` will reuse"
  278. " this run. If this is not desired, call `wandb.finish()` before instantiating `WandbLogger`."
  279. )
  280. self._experiment = wandb.run
  281. elif attach_id is not None and hasattr(wandb, "_attach"):
  282. # attach to wandb process referenced
  283. self._experiment = wandb._attach(attach_id)
  284. else:
  285. # create new wandb process
  286. self._experiment = wandb.init(**self._wandb_init)
  287. # define default x-axis
  288. if isinstance(self._experiment, wandb.Run) and getattr(
  289. self._experiment, "define_metric", None
  290. ):
  291. self._experiment.define_metric("trainer/global_step")
  292. self._experiment.define_metric(
  293. "*", step_metric="trainer/global_step", step_sync=True
  294. )
  295. self._experiment._label(repo="lightning_fabric_logger") # pylint: disable=protected-access
  296. with telemetry.context(run=self._experiment) as tel:
  297. tel.feature.lightning_fabric_logger = True
  298. return self._experiment
  299. def watch(
  300. self,
  301. model: nn.Module,
  302. log: str = "gradients",
  303. log_freq: int = 100,
  304. log_graph: bool = True,
  305. ) -> None:
  306. self.experiment.watch(model, log=log, log_freq=log_freq, log_graph=log_graph)
  307. @override
  308. @rank_zero_only
  309. def log_hyperparams(self, params: dict[str, Any] | Namespace) -> None: # type: ignore[override]
  310. params = _convert_params(params)
  311. params = _sanitize_callable_params(params)
  312. self.experiment.config.update(params, allow_val_change=True)
  313. @override
  314. @rank_zero_only
  315. def log_metrics(
  316. self, metrics: Mapping[str, float], step: int | None = None
  317. ) -> None:
  318. assert rank_zero_only.rank == 0, "experiment tried to log from global_rank != 0"
  319. metrics = _add_prefix(metrics, self._prefix, self.LOGGER_JOIN_CHAR)
  320. if step is not None:
  321. self.experiment.log(dict(metrics, **{"trainer/global_step": step}))
  322. else:
  323. self.experiment.log(metrics)
  324. @rank_zero_only
  325. def log_table(
  326. self,
  327. key: str,
  328. columns: list[str] | None = None,
  329. data: list[list[Any]] | None = None,
  330. dataframe: Any = None,
  331. step: int | None = None,
  332. ) -> None:
  333. """Log a Table containing any object type (text, image, audio, video, molecule, html, etc).
  334. Can be defined either with `columns` and `data` or with `dataframe`.
  335. """
  336. metrics = {key: wandb.Table(columns=columns, data=data, dataframe=dataframe)}
  337. self.log_metrics(metrics, step)
  338. @rank_zero_only
  339. def log_text(
  340. self,
  341. key: str,
  342. columns: list[str] | None = None,
  343. data: list[list[str]] | None = None,
  344. dataframe: Any = None,
  345. step: int | None = None,
  346. ) -> None:
  347. """Log text as a Table.
  348. Can be defined either with `columns` and `data` or with `dataframe`.
  349. """
  350. self.log_table(key, columns, data, dataframe, step)
  351. @rank_zero_only
  352. def log_html(
  353. self, key: str, htmls: list[Any], step: int | None = None, **kwargs: Any
  354. ) -> None:
  355. """Log html files.
  356. Optional kwargs are lists passed to each html (ex: inject).
  357. """
  358. if not isinstance(htmls, list):
  359. raise TypeError(f'Expected a list as "htmls", found {type(htmls)}')
  360. n = len(htmls)
  361. for k, v in kwargs.items():
  362. if len(v) != n:
  363. raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
  364. kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
  365. metrics = {
  366. key: [wandb.Html(html, **kwarg) for html, kwarg in zip(htmls, kwarg_list)]
  367. }
  368. self.log_metrics(metrics, step) # type: ignore[arg-type]
  369. @rank_zero_only
  370. def log_image(
  371. self, key: str, images: list[Any], step: int | None = None, **kwargs: Any
  372. ) -> None:
  373. """Log images (tensors, numpy arrays, PIL Images or file paths).
  374. Optional kwargs are lists passed to each image (ex: caption, masks, boxes).
  375. """
  376. if not isinstance(images, list):
  377. raise TypeError(f'Expected a list as "images", found {type(images)}')
  378. n = len(images)
  379. for k, v in kwargs.items():
  380. if len(v) != n:
  381. raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
  382. kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
  383. metrics = {
  384. key: [wandb.Image(img, **kwarg) for img, kwarg in zip(images, kwarg_list)]
  385. }
  386. self.log_metrics(metrics, step) # type: ignore[arg-type]
  387. @rank_zero_only
  388. def log_audio(
  389. self, key: str, audios: list[Any], step: int | None = None, **kwargs: Any
  390. ) -> None:
  391. r"""Log audios (numpy arrays, or file paths).
  392. Args:
  393. key: The key to be used for logging the audio files
  394. audios: The list of audio file paths, or numpy arrays to be logged
  395. step: The step number to be used for logging the audio files
  396. \**kwargs: Optional kwargs are lists passed to each ``Wandb.Audio`` instance (ex: caption, sample_rate).
  397. Optional kwargs are lists passed to each audio (ex: caption, sample_rate).
  398. """
  399. if not isinstance(audios, list):
  400. raise TypeError(f'Expected a list as "audios", found {type(audios)}')
  401. n = len(audios)
  402. for k, v in kwargs.items():
  403. if len(v) != n:
  404. raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
  405. kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
  406. metrics = {
  407. key: [
  408. wandb.Audio(audio, **kwarg) for audio, kwarg in zip(audios, kwarg_list)
  409. ]
  410. }
  411. self.log_metrics(metrics, step) # type: ignore[arg-type]
  412. @rank_zero_only
  413. def log_video(
  414. self, key: str, videos: list[Any], step: int | None = None, **kwargs: Any
  415. ) -> None:
  416. """Log videos (numpy arrays, or file paths).
  417. Args:
  418. key: The key to be used for logging the video files
  419. videos: The list of video file paths, or numpy arrays to be logged
  420. step: The step number to be used for logging the video files
  421. **kwargs: Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format).
  422. Optional kwargs are lists passed to each video (ex: caption, fps, format).
  423. """
  424. if not isinstance(videos, list):
  425. raise TypeError(f'Expected a list as "videos", found {type(videos)}')
  426. n = len(videos)
  427. for k, v in kwargs.items():
  428. if len(v) != n:
  429. raise ValueError(f"Expected {n} items but only found {len(v)} for {k}")
  430. kwarg_list = [{k: kwargs[k][i] for k in kwargs} for i in range(n)]
  431. metrics = {
  432. key: [
  433. wandb.Video(video, **kwarg) for video, kwarg in zip(videos, kwarg_list)
  434. ]
  435. }
  436. self.log_metrics(metrics, step) # type: ignore[arg-type]
  437. @property
  438. @override
  439. def save_dir(self) -> str | None:
  440. """Gets the save directory.
  441. Returns:
  442. The path to the save directory.
  443. """
  444. return self._save_dir
  445. @property
  446. @override
  447. def name(self) -> str | None:
  448. """The project name of this experiment.
  449. Returns:
  450. The name of the project the current experiment belongs to. This name is not the same as `wandb.Run`'s
  451. name. To access wandb's internal experiment name, use ``logger.experiment.name`` instead.
  452. """
  453. return self._project
  454. @property
  455. @override
  456. def version(self) -> str | None:
  457. """Gets the id of the experiment.
  458. Returns:
  459. The id of the experiment if the experiment exists else the id given to the constructor.
  460. """
  461. # don't create an experiment if we don't have one
  462. return self._experiment.id if self._experiment else self._id
  463. @property
  464. def log_dir(self) -> str | None:
  465. """Gets the save directory.
  466. Returns:
  467. The path to the save directory.
  468. """
  469. return self.save_dir
  470. @property
  471. def group_separator(self) -> str:
  472. """Return the default separator used by the logger to group the data into subfolders."""
  473. return self.LOGGER_JOIN_CHAR
  474. @property
  475. def root_dir(self) -> str | None:
  476. """Return the root directory.
  477. Return the root directory where all versions of an experiment get saved, or `None` if the logger does not
  478. save data locally.
  479. """
  480. return self.save_dir.parent if self.save_dir else None
  481. def log_graph(self, model: Module, input_array: Tensor | None = None) -> None:
  482. """Record model graph.
  483. Args:
  484. model: the model with an implementation of ``forward``.
  485. input_array: input passes to `model.forward`
  486. This is a noop function and does not perform any operation.
  487. """
  488. return
  489. @override
  490. def after_save_checkpoint(self, checkpoint_callback: ModelCheckpoint) -> None:
  491. # log checkpoints as artifacts
  492. if (
  493. self._log_model == "all"
  494. or self._log_model is True
  495. and checkpoint_callback.save_top_k == -1
  496. ):
  497. # TODO: Replace with new Fabric Checkpoints system
  498. self._scan_and_log_pytorch_checkpoints(checkpoint_callback)
  499. elif self._log_model is True:
  500. self._checkpoint_callback = checkpoint_callback
  501. @staticmethod
  502. @rank_zero_only
  503. def download_artifact(
  504. artifact: str,
  505. save_dir: _PATH | None = None,
  506. artifact_type: str | None = None,
  507. use_artifact: bool | None = True,
  508. ) -> str:
  509. """Downloads an artifact from the wandb server.
  510. Args:
  511. artifact: The path of the artifact to download.
  512. save_dir: The directory to save the artifact to.
  513. artifact_type: The type of artifact to download.
  514. use_artifact: Whether to add an edge between the artifact graph.
  515. Returns:
  516. The path to the downloaded artifact.
  517. """
  518. if wandb.run is not None and use_artifact:
  519. artifact = wandb.run.use_artifact(artifact)
  520. else:
  521. api = wandb.Api()
  522. artifact = api.artifact(artifact, type=artifact_type)
  523. save_dir = None if save_dir is None else os.fspath(save_dir)
  524. return artifact.download(root=save_dir)
  525. def use_artifact(self, artifact: str, artifact_type: str | None = None) -> Artifact:
  526. """Logs to the wandb dashboard that the mentioned artifact is used by the run.
  527. Args:
  528. artifact: The path of the artifact.
  529. artifact_type: The type of artifact being used.
  530. Returns:
  531. wandb Artifact object for the artifact.
  532. """
  533. return self.experiment.use_artifact(artifact, type=artifact_type)
  534. @override
  535. @rank_zero_only
  536. def save(self) -> None:
  537. """Save log data."""
  538. self.experiment.log({}, commit=True)
  539. @override
  540. @rank_zero_only
  541. def finalize(self, status: str) -> None:
  542. if self._log_checkpoint_on == "success" and status != "success":
  543. # Currently, checkpoints only get logged on success
  544. return
  545. # log checkpoints as artifacts
  546. if (
  547. self._checkpoint_callback
  548. and self._experiment is not None
  549. and self._log_checkpoint_on in ["success", "all"]
  550. ):
  551. self._scan_and_log_pytorch_checkpoints(self._checkpoint_callback)
  552. def _scan_and_log_pytorch_checkpoints(
  553. self, checkpoint_callback: ModelCheckpoint
  554. ) -> None:
  555. from lightning.pytorch.loggers.utilities import _scan_checkpoints
  556. # get checkpoints to be saved with associated score
  557. checkpoints = _scan_checkpoints(checkpoint_callback, self._logged_model_time)
  558. # log iteratively all new checkpoints
  559. for t, p, s, _ in checkpoints:
  560. metadata = {
  561. "score": s.item() if isinstance(s, Tensor) else s,
  562. "original_filename": Path(p).name,
  563. checkpoint_callback.__class__.__name__: {
  564. k: getattr(checkpoint_callback, k)
  565. for k in [
  566. "monitor",
  567. "mode",
  568. "save_last",
  569. "save_top_k",
  570. "save_weights_only",
  571. "_every_n_train_steps",
  572. ]
  573. # ensure it does not break if `ModelCheckpoint` args change
  574. if hasattr(checkpoint_callback, k)
  575. },
  576. }
  577. if not self._checkpoint_name:
  578. self._checkpoint_name = f"model-{self.experiment.id}"
  579. artifact = wandb.Artifact(
  580. name=self._checkpoint_name, type="model", metadata=metadata
  581. )
  582. artifact.add_file(p, name="model.ckpt")
  583. aliases = (
  584. ["latest", "best"]
  585. if p == checkpoint_callback.best_model_path
  586. else ["latest"]
  587. )
  588. self.experiment.log_model(artifact, aliases=aliases)
  589. # remember logged models - timestamp needed in case filename didn't change (lastkckpt or custom name)
  590. self._logged_model_time[p] = t