---
title: WandbLogger
description: Log using Weights and Biases.
canonical: >-
  https://lightning.ai/docs/pytorch/stable/reference/generated/lightning.pytorch.loggers.WandbLogger
---
# WandbLogger {#wandblogger}

### `class lightning.pytorch.loggers.WandbLogger(name=None, save_dir='.', version=None, offline=False, dir=None, id=None, anonymous=None, project=None, log_model=False, experiment=None, prefix='', checkpoint_name=None, add_file_policy='mutable', **kwargs)` {#lightning.pytorch.loggers.WandbLogger}

Bases: [`Logger`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.loggers.logger.md#lightning.pytorch.loggers.logger.Logger "lightning.pytorch.loggers.logger.Logger")

Log using [Weights and Biases](https://docs.wandb.ai/guides/integrations/lightning).

**Installation and set-up**

Install with pip:

```bash
pip install wandb
```

Create a WandbLogger instance:

```python
from lightning.pytorch.loggers import WandbLogger

wandb_logger = WandbLogger(project="MNIST")
```

Pass the logger instance to the Trainer:

```python
trainer = Trainer(logger=wandb_logger)
```

A new W&B run will be created when training starts if you have not created one manually before with wandb.init().

**Log metrics**

Log from [`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule"):

```python
class LitModule(LightningModule):
    def training_step(self, batch, batch_idx):
        self.log("train/loss", loss)
```

Use directly wandb module:

```python
wandb.log({"train/loss": loss})
```

**Log hyper-parameters**

Save [`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") parameters:

```python
class LitModule(LightningModule):
    def __init__(self, *args, **kwarg):
        self.save_hyperparameters()
```

Add other config parameters:

```python
# add one parameter
wandb_logger.experiment.config["key"] = value

# add multiple parameters
wandb_logger.experiment.config.update({key1: val1, key2: val2})

# use directly wandb module
wandb.config["key"] = value
wandb.config.update()
```

**Log gradients, parameters and model topology**

Call the watch method for automatically tracking gradients:

```python
# log gradients and model topology
wandb_logger.watch(model)

# log gradients, parameter histogram and model topology
wandb_logger.watch(model, log="all")

# change log frequency of gradients and parameters (100 steps by default)
wandb_logger.watch(model, log_freq=500)

# do not log graph (in case of errors)
wandb_logger.watch(model, log_graph=False)
```

The watch method adds hooks to the model which can be removed at the end of training:

```python
wandb_logger.experiment.unwatch(model)
```

**Log model checkpoints**

Log model checkpoints at the end of training:

```python
wandb_logger = WandbLogger(log_model=True)
```

Log model checkpoints as they get created during training:

```python
wandb_logger = WandbLogger(log_model="all")
```

Custom checkpointing can be set up through [`ModelCheckpoint`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint "lightning.pytorch.callbacks.ModelCheckpoint"):

```python
# log model only if `val_accuracy` increases
wandb_logger = WandbLogger(log_model="all")
checkpoint_callback = ModelCheckpoint(monitor="val_accuracy", mode="max")
trainer = Trainer(logger=wandb_logger, callbacks=[checkpoint_callback])
```

latest and best aliases are automatically set to easily retrieve a model checkpoint:

```python
# reference can be retrieved in artifacts panel
# "VERSION" can be a version (ex: "v2") or an alias ("latest or "best")
checkpoint_reference = "USER/PROJECT/MODEL-RUN_ID:VERSION"

# download checkpoint locally (if not already cached)
run = wandb.init(project="MNIST")
artifact = run.use_artifact(checkpoint_reference, type="model")
artifact_dir = artifact.download()

# load checkpoint
model = LitModule.load_from_checkpoint(Path(artifact_dir) / "model.ckpt")
```

**Log media**

Log text with:

```python
# using columns and data
columns = ["input", "label", "prediction"]
data = [["cheese", "english", "english"], ["fromage", "french", "spanish"]]
wandb_logger.log_text(key="samples", columns=columns, data=data)

# using a pandas DataFrame
wandb_logger.log_text(key="samples", dataframe=my_dataframe)
```

Log images with:

```python
# using tensors, numpy arrays or PIL images
wandb_logger.log_image(key="samples", images=[img1, img2])

# adding captions
wandb_logger.log_image(key="samples", images=[img1, img2], caption=["tree", "person"])

# using file path
wandb_logger.log_image(key="samples", images=["img_1.jpg", "img_2.jpg"])
```

More arguments can be passed for logging segmentation masks and bounding boxes. Refer to [Image Overlays documentation](https://docs.wandb.ai/guides/track/log/media#image-overlays).

**Log Tables**

[W&B Tables](https://docs.wandb.ai/guides/tables/visualize-tables) can be used to log, query and analyze tabular data.

They support any type of media (text, image, video, audio, molecule, html, etc) and are great for storing, understanding and sharing any form of data, from datasets to model predictions.

```python
columns = ["caption", "image", "sound"]
data = [["cheese", wandb.Image(img_1), wandb.Audio(snd_1)], ["wine", wandb.Image(img_2), wandb.Audio(snd_2)]]
wandb_logger.log_table(key="samples", columns=columns, data=data)
```

**Downloading and Using Artifacts**

To download an artifact without starting a run, call the `download_artifact` function on the class:

```python
from lightning.pytorch.loggers import WandbLogger

artifact_dir = WandbLogger.download_artifact(artifact="path/to/artifact")
```

To download an artifact and link it to an ongoing run call the `download_artifact` function on the logger instance:

```python
class MyModule(LightningModule):
    def any_lightning_module_function_or_hook(self):
        self.logger.download_artifact(artifact="path/to/artifact")
```

To link an artifact from a previous run you can use `use_artifact` function:

```python
from lightning.pytorch.loggers import WandbLogger

wandb_logger = WandbLogger(project="my_project", name="my_run")
wandb_logger.use_artifact(artifact="path/to/artifact")
```

See also

*   [Demo in Google Colab](http://wandb.me/lightning) with hyperparameter search and model logging
    
*   [W&B Documentation](https://docs.wandb.ai/guides/integrations/lightning)
    

Parameters:

*   **name** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – Display name for the run.
    
*   **save\_dir** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)")\]) – Path where data is saved.
    
*   **version** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – Sets the version, mainly used to resume a previous run.
    
*   **offline** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Run offline (data can be streamed later to wandb servers).
    
*   **dir** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Same as save\_dir.
    
*   **id** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – Same as version.
    
*   **anonymous** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – Enables or explicitly disables anonymous logging.
    
*   **project** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The name of the project to which this run will belong. If not set, the environment variable WANDB\_PROJECT will be used as a fallback. If both are not set, it defaults to `'lightning_logs'`.
    
*   **log\_model** (`Union`\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'all'`\], [`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) –
    
    Log checkpoints created by [`ModelCheckpoint`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint "lightning.pytorch.callbacks.ModelCheckpoint") as W&B artifacts. latest and best aliases are automatically set.
    
    *   if `log_model == 'all'`, checkpoints are logged during training.
        
    *   if `log_model == True`, checkpoints are logged at the end of training, except when [`save_top_k`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint.params.save_top_k "lightning.pytorch.callbacks.ModelCheckpoint") `== -1` which also logs every checkpoint during training.
        
    *   if `log_model == False` (default), no checkpoint is logged.
        
    
*   **prefix** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – A string to put at the beginning of metric keys.
    
*   **experiment** (`Union`\[`Run`, `RunDisabled`, [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – WandB experiment object. Automatically set when creating a run.
    
*   **checkpoint\_name** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – Name of the model checkpoint artifact being logged.
    
*   **add\_file\_policy** ([`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'mutable'`, `'immutable'`\]) – If “mutable”, copies file to tempdirectory before upload.
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Arguments passed to `wandb.init()` like entity, group, tags, etc.
    

Raises:

*   [**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If required WandB package is not installed on the device.
    
*   **MisconfigurationException** – If both `log_model` and `offline` is set to `True`.
    

#### `after_save_checkpoint(checkpoint_callback)` {#lightning.pytorch.loggers.WandbLogger.after_save_checkpoint}

Called after model checkpoint callback saves a new checkpoint.

Parameters:

**checkpoint\_callback** ([`ModelCheckpoint`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.callbacks.ModelCheckpoint.md#lightning.pytorch.callbacks.ModelCheckpoint "lightning.pytorch.callbacks.model_checkpoint.ModelCheckpoint")) – the model checkpoint callback instance

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `static download_artifact(artifact, save_dir=None, artifact_type=None, use_artifact=True)` {#lightning.pytorch.loggers.WandbLogger.download_artifact}

Downloads an artifact from the wandb server.

Parameters:

*   **artifact** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – The path of the artifact to download.
    
*   **save\_dir** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path "(in Python v3.15)"), [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – The directory to save the artifact to.
    
*   **artifact\_type** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The type of artifact to download.
    
*   **use\_artifact** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")\]) – Whether to add an edge between the artifact graph.
    

Return type:

[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")

Returns:

The path to the downloaded artifact.

#### `finalize(status)` {#lightning.pytorch.loggers.WandbLogger.finalize}

Do any processing that is necessary to finalize an experiment.

Parameters:

**status** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – Status that the experiment finished with (e.g. success, failed, aborted)

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `log_audio(key, audios, step=None, **kwargs)` {#lightning.pytorch.loggers.WandbLogger.log_audio}

Log audios (numpy arrays, or file paths).

Parameters:

*   **key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – The key to be used for logging the audio files
    
*   **audios** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – The list of audio file paths, or numpy arrays to be logged
    
*   **step** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – The step number to be used for logging the audio files
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Optional kwargs are lists passed to each `Wandb.Audio` instance (ex: caption, sample\_rate).
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Optional kwargs are lists passed to each audio (ex: caption, sample\_rate).

#### `log_hyperparams(params)` {#lightning.pytorch.loggers.WandbLogger.log_hyperparams}

Record hyperparameters.

Parameters:

*   **params** (`Union`\[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\], [`Namespace`](https://docs.python.org/3/library/argparse.html#argparse.Namespace "(in Python v3.15)")\]) – [`Namespace`](https://docs.python.org/3/library/argparse.html#argparse.Namespace "(in Python v3.15)") or Dict containing the hyperparameters
    
*   **args** – Optional positional arguments, depends on the specific logger being used
    
*   **kwargs** – Optional keyword arguments, depends on the specific logger being used
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `log_image(key, images, step=None, **kwargs)` {#lightning.pytorch.loggers.WandbLogger.log_image}

Log images (tensors, numpy arrays, PIL Images or file paths).

Optional kwargs are lists passed to each image (ex: caption, masks, boxes).

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `log_metrics(metrics, step=None)` {#lightning.pytorch.loggers.WandbLogger.log_metrics}

Records metrics. This method logs metrics as soon as it received them.

Parameters:

*   **metrics** ([`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`float`](https://docs.python.org/3/builtins/functions.html#float "(in Python v3.15)")\]) – Dictionary with metric names as keys and measured quantities as values
    
*   **step** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – Step number at which the metrics should be recorded
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `log_table(key, columns=None, data=None, dataframe=None, step=None)` {#lightning.pytorch.loggers.WandbLogger.log_table}

Log a Table containing any object type (text, image, audio, video, molecule, html, etc).

Can be defined either with columns and data or with dataframe.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `log_text(key, columns=None, data=None, dataframe=None, step=None)` {#lightning.pytorch.loggers.WandbLogger.log_text}

Log text as a Table.

Can be defined either with columns and data or with dataframe.

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

#### `log_video(key, videos, step=None, **kwargs)` {#lightning.pytorch.loggers.WandbLogger.log_video}

Log videos (numpy arrays, or file paths).

Parameters:

*   **key** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – The key to be used for logging the video files
    
*   **videos** ([`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – The list of video file paths, or numpy arrays to be logged
    
*   **step** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")\]) – The step number to be used for logging the video files
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Optional kwargs are lists passed to each Wandb.Video instance (ex: caption, fps, format).
    

Return type:

[`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

Optional kwargs are lists passed to each video (ex: caption, fps, format).

#### `use_artifact(artifact, artifact_type=None)` {#lightning.pytorch.loggers.WandbLogger.use_artifact}

Logs to the wandb dashboard that the mentioned artifact is used by the run.

Parameters:

*   **artifact** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – The path of the artifact.
    
*   **artifact\_type** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")\]) – The type of artifact being used.
    

Return type:

`Artifact`

Returns:

wandb Artifact object for the artifact.

#### `property experiment: Union[wandb.wandb_run.Run, wandb.sdk.lib.RunDisabled]` {#lightning.pytorch.loggers.WandbLogger.experiment}

Actual wandb object. To use wandb features in your [`LightningModule`](/docs/pytorch/2.6.6/optional-api/api/lightning.pytorch.core.LightningModule.md#lightning.pytorch.core.LightningModule "lightning.pytorch.core.LightningModule") do the following.

Example:

```python
.. code-block:: python
```

> self.logger.experiment.some\_wandb\_function()

#### `property name: Optional[str]` {#lightning.pytorch.loggers.WandbLogger.name}

The project name of this experiment.

Returns:

The name of the project the current experiment belongs to. This name is not the same as wandb.Run’s name. To access wandb’s internal experiment name, use `logger.experiment.name` instead.

#### `property save_dir: Optional[str]` {#lightning.pytorch.loggers.WandbLogger.save_dir}

Gets the save directory.

Returns:

The path to the save directory.

#### `property version: Optional[str]` {#lightning.pytorch.loggers.WandbLogger.version}

Gets the id of the experiment.

Returns:

The id of the experiment if the experiment exists else the id given to the constructor.

---

**Navigation**

- Parent: [Generated](/docs/pytorch/2.6.6/reference/generated.md)
