---
title: comet
description: 'Track your parameters, metrics, source code and more using Comet.'
canonical: >-
  https://lightning.ai/docs/pytorch/stable/optional-api/api/lightning.pytorch.loggers.comet
---
# comet {#comet}

Classes

- [`CometLogger`](#lightning.pytorch.loggers.comet.CometLogger) — Track your parameters, metrics, source code and more using Comet.

## Comet Logger {#comet-logger}

### `class lightning.pytorch.loggers.comet.CometLogger(*, api_key=None, workspace=None, project=None, experiment_key=None, mode=None, online=None, prefix=None, **kwargs)` {#lightning.pytorch.loggers.comet.CometLogger}

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")

Track your parameters, metrics, source code and more using [Comet](https://www.comet.com/?utm_source=lightning.pytorch&utm_medium=referral).

Install it with pip:

```bash
pip install comet-ml
```

Comet requires either an API Key (online mode) or a local directory path (offline mode).

**ONLINE MODE**

```python
import os
from lightning.pytorch import Trainer
from lightning.pytorch.loggers import CometLogger

# arguments made to CometLogger are passed on to the comet_ml.Experiment class
comet_logger = CometLogger(
    api_key=os.environ.get("COMET_API_KEY"),  # Optional
    workspace=os.environ.get("COMET_WORKSPACE"),  # Optional
    project="default_project",  # Optional
    experiment_key=os.environ.get("COMET_EXPERIMENT_KEY"),  # Optional
    name="lightning_logs",  # Optional
)
trainer = Trainer(logger=comet_logger)
```

**OFFLINE MODE**

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

# arguments made to CometLogger are passed on to the comet_ml.Experiment class
comet_logger = CometLogger(
    workspace=os.environ.get("COMET_WORKSPACE"),  # Optional
    project="default_project",  # Optional
    name="lightning_logs",  # Optional
    online=False
)
trainer = Trainer(logger=comet_logger)
```

**Log Hyperparameters:**

Log parameters used to initialize a [`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 __init__(self, *args, **kwarg):
        self.save_hyperparameters()
```

Log other Experiment Parameters

```python
# log a single parameter
logger.log_hyperparams({"batch_size": 16})

# log multiple parameters
logger.log_hyperparams({"batch_size": 16, "learning_rate": 0.001})

# log nested parameters
logger.log_hyperparams({"specific": {'param': {'subparam': "value"}}})
```

**Log Metrics:**

```python
# log a single metric
logger.log_metrics({"train/loss": 0.001})

# add multiple metrics
logger.log_metrics({"train/loss": 0.001, "val/loss": 0.002})

# add nested metrics
logger.log_metrics({"specific": {'metric': {'submetric': "value"}}})
```

**Access the Comet Experiment object:**

You can gain access to the underlying Comet [Experiment](https://www.comet.com/docs/v2/api-and-sdk/python-sdk/reference/Experiment/) object and its methods through the `logger.experiment` property. This will let you use the additional logging features provided by the Comet SDK.

Some examples of data you can log through the Experiment object:

Log Image data:

```python
img = PIL.Image.open("<path to image>")
logger.experiment.log_image(img, file_name="my_image.png")
```

Log Text data:

```python
text = "Lightning is awesome!"
logger.experiment.log_text(text)
```

Log Audio data:

```python
audio = "<path to audio data>"
logger.experiment.log_audio(audio, file_name="my_audio.wav")
```

Log arbitrary data assets:

You can log any type of data to Comet as an asset. These can be model checkpoints, datasets, debug logs, etc.

```python
logger.experiment.log_asset("<path to your asset>", file_name="my_data.pkl")
```

Log Models to Comet’s Model Registry:

```python
logger.experiment.log_model(name="my-model", "<path to your model>")
```

See also

*   [Demo in Google Colab](https://tinyurl.com/22phzw5s)
    
*   [Comet Documentation](https://www.comet.com/docs/v2/integrations/ml-frameworks/pytorch-lightning/)
    

Parameters:

*   **api\_key** ([`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)")\]) – Comet API key. It’s recommended to configure the API Key with comet login.
    
*   **workspace** ([`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)")\]) – Comet workspace name. If not provided, uses the default workspace.
    
*   **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)")\]) – Comet project name. Defaults to Uncategorized.
    
*   **experiment\_key** ([`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 Experiment identifier to be used for logging. This is used either to append data to an Existing Experiment or to control the key of new experiments (for example to match another identifier). Must be an alphanumeric string whose length is between 32 and 50 characters.
    
*   **mode** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Literal`](https://docs.python.org/3/library/typing.html#typing.Literal "(in Python v3.15)")\[`'get_or_create'`, `'get'`, `'create'`\]\]) – Control how the Comet experiment is started. \* `"get_or_create"`: Starts a fresh experiment if required, or persists logging to an existing one. \* `"get"`: Continue logging to an existing experiment identified by the `experiment_key` value. \* `"create"`: Always creates of a new experiment, useful for HPO sweeps.
    
*   **online** ([`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)")\]) – If True, the data will be logged to Comet server, otherwise it will be stored locally in an offline experiment. Default is `True`.
    
*   **prefix** ([`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 prefix to add to names of the logged metrics. example: prefix=\`exp1\`, then metric name will be logged as exp1\_metric\_name
    
*   **\*\*kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional arguments like name, log\_code, offline\_directory etc. used by `CometExperiment` can be passed as keyword arguments in this logger.
    

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If required Comet package is not installed on the device.

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

We will not end experiment (will not call self.\_experiment.end()) here to have an ability to continue using it after training is complete but instead of ending we will upload/save all the data.

Return type:

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

#### `log_graph(model, input_array=None)` {#lightning.pytorch.loggers.comet.CometLogger.log_graph}

Record model graph.

Parameters:

*   **model** ([`Module`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.15)")) – the model with an implementation of `forward`.
    
*   **input\_array** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]) – input passes to model.forward
    

Return type:

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

#### `log_hyperparams(params)` {#lightning.pytorch.loggers.comet.CometLogger.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_metrics(metrics, step=None)` {#lightning.pytorch.loggers.comet.CometLogger.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)"), `Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.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)")

#### `property experiment: Union[comet_ml.Experiment, comet_ml.ExistingExperiment, comet_ml.OfflineExperiment]` {#lightning.pytorch.loggers.comet.CometLogger.experiment}

Actual Comet object. To use Comet 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
self.logger.experiment.some_comet_function()
```

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

Gets the project name.

Returns:

The project name if it is specified.

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

Gets the save directory.

Returns:

The path to the save directory.

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

Gets the version.

Returns:

The experiment key if present

---

**Navigation**

- Parent: [Api](/docs/pytorch/2.6.6/optional-api/api.md)
