---
title: torchmetrics.Metric
description: >-
  The base Metric class is an abstract base class that are used as the building
  block for all other Module
canonical: 'https://lightning.ai/docs/torchmetrics/stable/api-reference/metric'
---
# torchmetrics.Metric {#torchmetrics-metric}

The base `Metric` class is an abstract base class that are used as the building block for all other Module
metrics.

### `class torchmetrics.Metric(**kwargs)` {#class-torchmetrics-metric-kwargs}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L52-L1181)

Base class for all metrics present in the Metrics API.

This class is inherited by all metrics and implements the following functionality:

1.  Handles the transfer of metric states to the correct device.
    
2.  Handles the synchronization of metric states across processes.
    
3.  Provides properties and methods to control the overall behavior of the metric and its states.
    

The three core methods of the base class are: `add_state()`, `forward()` and `reset()` which should almost never be overwritten by child classes. Instead, the following methods should be overwritten `update()` and `compute()`.

Parameters:

**kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) –

additional keyword arguments, see [Advanced metric settings](/docs/torchmetrics/1.9.0/api-reference/overview.md#metric-kwargs) for more info.

*   **compute\_on\_cpu**:
    
    If metric state should be stored on CPU during computations. Only works for list states.
    
*   **dist\_sync\_on\_step**:
    
    If metric state should synchronize on `forward()`. Default is `False`.
    
*   **process\_group**:
    
    The process group on which the synchronization is called. Default is the world.
    
*   **dist\_sync\_fn**:
    
    Function that performs the allgather option on the metric state. Default is a custom implementation that calls `torch.distributed.all_gather` internally.
    
*   **distributed\_available\_fn**:
    
    Function that checks if the distributed backend is available. Defaults to a check of `torch.distributed.is_available()` and `torch.distributed.is_initialized()`.
    
*   **sync\_on\_compute**:
    
    If metric state should synchronize when `compute` is called. Default is `True`.
    
*   **compute\_with\_cache**:
    
    If results from `compute` should be cached. Default is `True`.
    

#### `add_state(name, default, dist_reduce_fx=None, persistent=False)` {#add-state-name-default-dist-reduce-fx-none-persistent-false}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L201-L284)

Add metric state variable. Only used by subclasses.

Metric state variables are either :class:\`~torch.Tensor or an empty list, which can be appended to by the metric. Each state variable must have a unique name associated with it. State variables are accessible as attributes of the metric i.e, if `name` is `"my_state"` then its value can be accessed from an instance `metric` as `metric.my_state`. Metric states behave like buffers and parameters of [`Module`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module "(in PyTorch v2.15)") as they are also updated when `.to()` is called. Unlike parameters and buffers, metric states are not by default saved in the modules [`state_dict`](https://docs.pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.state_dict "(in PyTorch v2.15)").

Parameters:

*   **name** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – The name of the state variable. The variable will then be accessible at `self.name`.
    
*   **default** (`Union`\[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list "(in Python v3.15)"), [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\]) – Default value of the state; can either be a [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") or an empty list. The state will be reset to this value when `self.reset()` is called.
    
*   **dist\_reduce\_fx** (_Optional_) – Function to reduce state across multiple processes in distributed mode. If value is `"sum"`, `"mean"`, `"cat"`, `"min"` or `"max"` we will use `torch.sum`, `torch.mean`, `torch.cat`, `torch.min` and `` torch.max` `` respectively, each with argument `dim=0`. Note that the `"cat"` reduction only makes sense if the state is a list, and not a tensor. The user can also pass a custom function in this parameter.
    
*   **persistent** (_Optional_) – whether the state will be saved as part of the modules `state_dict`. Default is `False`.
    

Return type:

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

Note

Setting `dist_reduce_fx` to None will return the metric state synchronized across different processes. However, there won’t be any reduction function applied to the synchronized metric state.

The metric states would be synced as follows

*   If the metric state is [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), the synced value will be a stacked [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") across the process dimension if the metric state was a [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"). The original [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") metric state retains dimension and hence the synchronized output will be of shape `(num_process, ...)`.
    
*   If the metric state is a `list`, the synced value will be a `list` containing the combined elements from all processes.
    

Important

When passing a custom function to `dist_reduce_fx`, expect the synchronized metric state to follow the format discussed in the above note.

Caution

The values inserted into a list state are deleted whenever [`reset()`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric.reset "torchmetrics.Metric.reset") is called. This allows device memory to be automatically reallocated, but may produce unexpected effects when referencing list states. To retain such values after [`reset()`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric.reset "torchmetrics.Metric.reset") is called, you must first copy them to another object.

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `default` is not a `tensor` or an `empty list`.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `dist_reduce_fx` is not callable or one of `"mean"`, `"sum"`, `"cat"`, `"min"`, `"max"` or `None`.
    

#### `clone()` {#clone}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L775-L777)

Make a copy of the metric.

Return type:

[`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")

#### `abstract compute()` {#abstract-compute}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L714-L720)

Override this method to compute the final metric value.

This method will automatically synchronize state variables when running in distributed backend.

Return type:

[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")

#### `double()` {#double}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L839-L845)

Override default and prevent dtype casting.

Please use [`Metric.set_dtype()`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric.set_dtype "torchmetrics.Metric.set_dtype") instead.

Return type:

[`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")

#### `float()` {#float}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L831-L837)

Override default and prevent dtype casting.

Please use [`Metric.set_dtype()`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric.set_dtype "torchmetrics.Metric.set_dtype") instead.

Return type:

[`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")

#### `forward(*args, **kwargs)` {#forward-args-kwargs}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L286-L317)

Aggregate and evaluate batch input directly.

Serves the dual purpose of both computing the metric on the current batch of inputs but also add the batch statistics to the overall accumulating metric state. Input arguments are the exact same as corresponding `update` method. The returned output is the exact same as the output of `compute`.

Parameters:

*   **args** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Any arguments as required by the metric `update` method.
    
*   **kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Any keyword arguments as required by the metric `update` method.
    

Return type:

[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")

Returns:

The output of the `compute` method evaluated on the current batch.

Raises:

[**TorchMetricsUserError**](/docs/torchmetrics/1.9.0/api-reference/utilities.md#torchmetrics.utilities.exceptions.TorchMetricsUserError "torchmetrics.utilities.exceptions.TorchMetricsUserError") – If the metric is already synced and `forward` is called again.

#### `half()` {#half}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L847-L853)

Override default and prevent dtype casting.

Please use [`Metric.set_dtype()`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric.set_dtype "torchmetrics.Metric.set_dtype") instead.

Return type:

[`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")

#### `merge_state(incoming_state)` {#merge-state-incoming-state}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L404-L463)

Merge incoming metric state to the current state of the metric.

Parameters:

**incoming\_state** (`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)")\], [`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")\]) – either a dict containing a metric state similar to the metric itself or an instance of the metric class.

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If the incoming state is neither a dict nor an instance of the metric class.
    
*   [**RuntimeError**](https://docs.python.org/3/builtins/exceptions.html#RuntimeError "(in Python v3.15)") – If the metric has `full_state_update=True` or `dist_sync_on_step=True`. In these cases, the metric cannot be merged with another metric state in a simple way. The user should overwrite the method in the metric class to handle the merge operation.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If the incoming state is a metric instance but the class is different from the current metric class.
    

Example with a metric instance: :rtype: [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")

```python
>>> from torchmetrics.aggregation import SumMetric
>>> metric1 = SumMetric()
>>> metric2 = SumMetric()
>>> metric1.update(1)
>>> metric2.update(2)
>>> metric1.merge_state(metric2)
>>> metric1.compute()
tensor(3.)
```

Example with a dict:

```python
>>> from torchmetrics.aggregation import SumMetric
>>> metric = SumMetric()
>>> metric.update(1)
>>> # SumMetric has one state variable called `sum_value`
>>> metric.merge_state({"sum_value": torch.tensor(2)})
>>> metric.compute()
tensor(3.)
```

#### `persistent(mode=False)` {#persistent-mode-false}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L919-L922)

Change post-init if metric states should be saved to its state\_dict.

Return type:

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

#### `plot(*_, **__)` {#plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L722-L724)

Override this method plot the metric value.

Return type:

[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")

#### `reset()` {#reset}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L758-L773)

Reset metric state variables to their default value.

Return type:

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

#### `set_dtype(dst_type)` {#set-dtype-dst-type}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L855-L865)

Transfer all metric state to specific dtype. Special version of standard type method.

Parameters:

**dst\_type** (`Union`\[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)"), [`dtype`](https://docs.pytorch.org/docs/stable/tensor_attributes.html#torch.dtype "(in PyTorch v2.15)")\]) – the desired type as string or dtype object

Return type:

[`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")

#### `state_dict(destination=None, prefix='', keep_vars=False)` {#state-dict-destination-none-prefix-keep-vars-false}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L924-L956)

Get the current state of metric as an dictionary.

Parameters:

*   **destination** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`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)")\]\]) – Optional dictionary, that if provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an `OrderedDict` will be created and returned.
    
*   **prefix** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) – optional string, a prefix added to parameter and buffer names to compose the keys in state\_dict.
    
*   **keep\_vars** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – by default the [`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)") returned in the state dict are detached from autograd. If set to `True`, detaching will not be performed.
    

Return type:

[`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)")\]

#### `sync(dist_sync_fn=None, process_group=None, should_sync=True, distributed_available=None)` {#sync-dist-sync-fn-none-process-group-none-should-sync-true-distributed-available-none}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L573-L615)

Sync function for manually controlling when metrics states should be synced across processes.

Parameters:

*   **dist\_sync\_fn** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\]) – Function to be used to perform states synchronization
    
*   **process\_group** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – Specify the process group on which synchronization is called. default: None (which selects the entire world)
    
*   **should\_sync** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to apply to state synchronization. This will have an impact only when running in a distributed setting.
    
*   **distributed\_available** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\]) – Function to determine if we are running inside a distributed setting
    

Raises:

[**TorchMetricsUserError**](/docs/torchmetrics/1.9.0/api-reference/utilities.md#torchmetrics.utilities.exceptions.TorchMetricsUserError "torchmetrics.utilities.exceptions.TorchMetricsUserError") – If the metric is already synced and `sync` is called again.

Return type:

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

#### `sync_context(dist_sync_fn=None, process_group=None, should_sync=True, should_unsync=True, distributed_available=None)` {#sync-context-dist-sync-fn-none-process-group-none-should-sync-true-should-unsync-true-distributed-available-none}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/../home/runner/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/lib/python3.10/contextlib.py#L639-L674)

Context manager to synchronize states.

This context manager is used in distributed setting and makes sure that the local cache states are restored after yielding the synchronized state.

Parameters:

*   **dist\_sync\_fn** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\]) – Function to be used to perform states synchronization
    
*   **process\_group** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")\]) – Specify the process group on which synchronization is called. default: None (which selects the entire world)
    
*   **should\_sync** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to apply to state synchronization. This will have an impact only when running in a distributed setting.
    
*   **should\_unsync** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to restore the cache state so that the metrics can continue to be accumulated.
    
*   **distributed\_available** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.15)")\]) – Function to determine if we are running inside a distributed setting
    

Return type:

[`Generator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Generator "(in Python v3.15)")

#### `type(dst_type)` {#type-dst-type}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L823-L829)

Override default and prevent dtype casting.

Please use [`Metric.set_dtype()`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric.set_dtype "torchmetrics.Metric.set_dtype") instead.

Return type:

[`Metric`](/docs/torchmetrics/1.9.0/api-reference/metric.md#torchmetrics.Metric "torchmetrics.metric.Metric")

#### `unsync(should_unsync=True)` {#unsync-should-unsync-true}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L617-L637)

Unsync function for manually controlling when metrics states should be reverted back to their local states.

Parameters:

**should\_unsync** ([`bool`](https://docs.python.org/3/builtins/functions.html#bool "(in Python v3.15)")) – Whether to perform unsync

Return type:

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

#### `abstract update(*_, **__)` {#abstract-update}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/metric.py#L710-L712)

Override this method to update the state variables of your metric class.

Return type:

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

#### `property device: device` {#property-device-device}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/torchmetrics.py)

Return the device of the metric.

#### `property dtype: dtype` {#property-dtype-dtype}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/torchmetrics.py)

Return the default dtype of the metric.

#### `property metric_state: dict[str, Union[List[torch.Tensor], torch.Tensor]]` {#property-metric-state-dict-str-union-list-torch-tensor-torch-tensor}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/torchmetrics.py)

Get the current state of the metric.

#### `property update_called: bool` {#property-update-called-bool}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/torchmetrics.py)

Returns True if update or forward has been called initialization or last reset.

#### `property update_count: int` {#property-update-count-int}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/torchmetrics.py)

Get the number of times update and/or forward has been called since initialization or last reset.

---

**Navigation**

- Parent: [API Reference](/docs/torchmetrics/1.9.0/api-reference.md)
