metric.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. # Copyright The Lightning team.
  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. # It is needed to distinguish between native float and Metric's' function called float.
  15. # later, this function was used instead of the built-in float type...
  16. import builtins
  17. import functools
  18. import inspect
  19. from abc import ABC, abstractmethod
  20. from collections.abc import Generator, Sequence
  21. from contextlib import contextmanager
  22. from copy import deepcopy
  23. from typing import Any, Callable, ClassVar, List, Optional, Union
  24. import torch
  25. from lightning_utilities import apply_to_collection
  26. from torch import Tensor
  27. from torch.nn import Module
  28. from torchmetrics.utilities.data import (
  29. _flatten,
  30. _squeeze_if_scalar,
  31. dim_zero_cat,
  32. dim_zero_max,
  33. dim_zero_mean,
  34. dim_zero_min,
  35. dim_zero_sum,
  36. )
  37. from torchmetrics.utilities.distributed import gather_all_tensors
  38. from torchmetrics.utilities.exceptions import TorchMetricsUserError
  39. from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_2_1, _TORCH_GREATER_EQUAL_2_3
  40. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE, plot_single_or_multi_val
  41. from torchmetrics.utilities.prints import rank_zero_warn
  42. def jit_distributed_available() -> bool:
  43. """Determine if distributed mode is initialized."""
  44. return torch.distributed.is_available() and torch.distributed.is_initialized()
  45. class Metric(Module, ABC):
  46. """Base class for all metrics present in the Metrics API.
  47. This class is inherited by all metrics and implements the following functionality:
  48. 1. Handles the transfer of metric states to the correct device.
  49. 2. Handles the synchronization of metric states across processes.
  50. 3. Provides properties and methods to control the overall behavior of the metric and its states.
  51. The three core methods of the base class are: ``add_state()``, ``forward()`` and ``reset()`` which should almost
  52. never be overwritten by child classes. Instead, the following methods should be overwritten ``update()`` and
  53. ``compute()``.
  54. Args:
  55. kwargs: additional keyword arguments, see :ref:`Metric kwargs` for more info.
  56. - **compute_on_cpu**:
  57. If metric state should be stored on CPU during computations. Only works for list states.
  58. - **dist_sync_on_step**:
  59. If metric state should synchronize on ``forward()``. Default is ``False``.
  60. - **process_group**:
  61. The process group on which the synchronization is called. Default is the world.
  62. - **dist_sync_fn**:
  63. Function that performs the allgather option on the metric state. Default is a custom
  64. implementation that calls ``torch.distributed.all_gather`` internally.
  65. - **distributed_available_fn**:
  66. Function that checks if the distributed backend is available. Defaults to a
  67. check of ``torch.distributed.is_available()`` and ``torch.distributed.is_initialized()``.
  68. - **sync_on_compute**:
  69. If metric state should synchronize when ``compute`` is called. Default is ``True``.
  70. - **compute_with_cache**:
  71. If results from ``compute`` should be cached. Default is ``True``.
  72. """
  73. __jit_ignored_attributes__: ClassVar[list[str]] = ["device"]
  74. __jit_unused_properties__: ClassVar[list[str]] = [
  75. "is_differentiable",
  76. "higher_is_better",
  77. "plot_lower_bound",
  78. "plot_upper_bound",
  79. "plot_legend_name",
  80. "metric_state",
  81. "_update_called",
  82. ]
  83. is_differentiable: Optional[bool] = None
  84. higher_is_better: Optional[bool] = None
  85. full_state_update: Optional[bool] = None
  86. plot_lower_bound: Optional[float] = None
  87. plot_upper_bound: Optional[float] = None
  88. plot_legend_name: Optional[str] = None
  89. def __init__(
  90. self,
  91. **kwargs: Any,
  92. ) -> None:
  93. super().__init__()
  94. # see (https://github.com/pytorch/pytorch/blob/3e6bb5233f9ca2c5aa55d9cda22a7ee85439aa6e/
  95. # torch/nn/modules/module.py#L227)
  96. torch._C._log_api_usage_once(f"torchmetrics.metric.{self.__class__.__name__}")
  97. # magic patch for `RuntimeError: DataLoader worker (pid(s) 104) exited unexpectedly`
  98. self._TORCH_GREATER_EQUAL_2_1 = bool(_TORCH_GREATER_EQUAL_2_1)
  99. self._device = torch.get_default_device() if _TORCH_GREATER_EQUAL_2_3 else torch.empty(0).device
  100. self._dtype = torch.get_default_dtype()
  101. self.compute_on_cpu = kwargs.pop("compute_on_cpu", False)
  102. if not isinstance(self.compute_on_cpu, bool):
  103. raise ValueError(
  104. f"Expected keyword argument `compute_on_cpu` to be an `bool` but got {self.compute_on_cpu}"
  105. )
  106. self.dist_sync_on_step = kwargs.pop("dist_sync_on_step", False)
  107. if not isinstance(self.dist_sync_on_step, bool):
  108. raise ValueError(
  109. f"Expected keyword argument `dist_sync_on_step` to be an `bool` but got {self.dist_sync_on_step}"
  110. )
  111. self.process_group = kwargs.pop("process_group", None)
  112. self.dist_sync_fn = kwargs.pop("dist_sync_fn", None)
  113. if self.dist_sync_fn is not None and not callable(self.dist_sync_fn):
  114. raise ValueError(
  115. f"Expected keyword argument `dist_sync_fn` to be an callable function but got {self.dist_sync_fn}"
  116. )
  117. self.distributed_available_fn = kwargs.pop("distributed_available_fn", None) or jit_distributed_available
  118. self.sync_on_compute = kwargs.pop("sync_on_compute", True)
  119. if not isinstance(self.sync_on_compute, bool):
  120. raise ValueError(
  121. f"Expected keyword argument `sync_on_compute` to be a `bool` but got {self.sync_on_compute}"
  122. )
  123. self.compute_with_cache = kwargs.pop("compute_with_cache", True)
  124. if not isinstance(self.compute_with_cache, bool):
  125. raise ValueError(
  126. f"Expected keyword argument `compute_with_cache` to be a `bool` but got {self.compute_with_cache}"
  127. )
  128. if kwargs:
  129. kwargs_ = [f"`{a}`" for a in sorted(kwargs)]
  130. raise ValueError(f"Unexpected keyword arguments: {', '.join(kwargs_)}")
  131. # initialize
  132. self._update_signature = inspect.signature(self.update)
  133. self.update: Callable = self._wrap_update(self.update) # type: ignore[method-assign]
  134. self.compute: Callable = self._wrap_compute(self.compute) # type: ignore[method-assign]
  135. self._computed = None
  136. self._forward_cache = None
  137. self._update_count = 0
  138. self._to_sync = self.sync_on_compute
  139. self._should_unsync = True
  140. self._enable_grad = False
  141. self._dtype_convert = False
  142. # initialize state
  143. self._defaults: dict[str, Union[list, Tensor]] = {}
  144. self._persistent: dict[str, bool] = {}
  145. self._reductions: dict[str, Union[str, Callable[..., Any], None]] = {}
  146. # state management
  147. self._is_synced = False
  148. self._cache: Optional[dict[str, Union[List[Tensor], Tensor]]] = None
  149. @property
  150. def _update_called(self) -> bool:
  151. rank_zero_warn(
  152. "This property will be removed in 2.0.0. Use `Metric.updated_called` instead.",
  153. DeprecationWarning,
  154. stacklevel=2,
  155. )
  156. return self.update_called
  157. @property
  158. def update_called(self) -> bool:
  159. """Returns `True` if `update` or `forward` has been called initialization or last `reset`."""
  160. return self._update_count > 0
  161. @property
  162. def update_count(self) -> int:
  163. """Get the number of times `update` and/or `forward` has been called since initialization or last `reset`."""
  164. return self._update_count
  165. @property
  166. def metric_state(self) -> dict[str, Union[List[Tensor], Tensor]]:
  167. """Get the current state of the metric."""
  168. return {attr: getattr(self, attr) for attr in self._defaults}
  169. def add_state(
  170. self,
  171. name: str,
  172. default: Union[list, Tensor],
  173. dist_reduce_fx: Optional[Union[str, Callable]] = None,
  174. persistent: bool = False,
  175. ) -> None:
  176. """Add metric state variable. Only used by subclasses.
  177. Metric state variables are either `:class:`~torch.Tensor` or an empty list, which can be appended to by the
  178. metric. Each state variable must have a unique name associated with it. State variables are accessible as
  179. attributes of the metric i.e, if ``name`` is ``"my_state"`` then its value can be accessed from an instance
  180. ``metric`` as ``metric.my_state``. Metric states behave like buffers and parameters of :class:`~torch.nn.Module`
  181. as they are also updated when ``.to()`` is called. Unlike parameters and buffers, metric states are not by
  182. default saved in the modules :attr:`~torch.nn.Module.state_dict`.
  183. Args:
  184. name: The name of the state variable. The variable will then be accessible at ``self.name``.
  185. default: Default value of the state; can either be a :class:`~torch.Tensor` or an empty list.
  186. The state will be reset to this value when ``self.reset()`` is called.
  187. dist_reduce_fx (Optional): Function to reduce state across multiple processes in distributed mode.
  188. If value is ``"sum"``, ``"mean"``, ``"cat"``, ``"min"`` or ``"max"`` we will use ``torch.sum``,
  189. ``torch.mean``, ``torch.cat``, ``torch.min`` and ``torch.max``` respectively, each with argument
  190. ``dim=0``. Note that the ``"cat"`` reduction only makes sense if the state is a list, and not
  191. a tensor. The user can also pass a custom function in this parameter.
  192. persistent (Optional): whether the state will be saved as part of the modules ``state_dict``.
  193. Default is ``False``.
  194. .. note::
  195. Setting ``dist_reduce_fx`` to None will return the metric state synchronized across different processes.
  196. However, there won't be any reduction function applied to the synchronized metric state.
  197. The metric states would be synced as follows
  198. - If the metric state is :class:`~torch.Tensor`, the synced value will be a stacked :class:`~torch.Tensor`
  199. across the process dimension if the metric state was a :class:`~torch.Tensor`. The original
  200. :class:`~torch.Tensor` metric state retains dimension and hence the synchronized output will be of shape
  201. ``(num_process, ...)``.
  202. - If the metric state is a ``list``, the synced value will be a ``list`` containing the
  203. combined elements from all processes.
  204. .. important::
  205. When passing a custom function to ``dist_reduce_fx``, expect the synchronized metric state to follow
  206. the format discussed in the above note.
  207. .. caution::
  208. The values inserted into a list state are deleted whenever :meth:`~Metric.reset` is called. This allows
  209. device memory to be automatically reallocated, but may produce unexpected effects when referencing list
  210. states. To retain such values after :meth:`~Metric.reset` is called, you must first copy them to another
  211. object.
  212. Raises:
  213. ValueError:
  214. If ``default`` is not a ``tensor`` or an ``empty list``.
  215. ValueError:
  216. If ``dist_reduce_fx`` is not callable or one of ``"mean"``, ``"sum"``, ``"cat"``, ``"min"``,
  217. ``"max"`` or ``None``.
  218. """
  219. if not isinstance(default, (Tensor, list)) or (isinstance(default, list) and default):
  220. raise ValueError("state variable must be a tensor or any empty list (where you can append tensors)")
  221. if dist_reduce_fx == "sum":
  222. dist_reduce_fx = dim_zero_sum
  223. elif dist_reduce_fx == "mean":
  224. dist_reduce_fx = dim_zero_mean
  225. elif dist_reduce_fx == "max":
  226. dist_reduce_fx = dim_zero_max
  227. elif dist_reduce_fx == "min":
  228. dist_reduce_fx = dim_zero_min
  229. elif dist_reduce_fx == "cat":
  230. dist_reduce_fx = dim_zero_cat
  231. elif dist_reduce_fx is not None and not callable(dist_reduce_fx):
  232. raise ValueError("`dist_reduce_fx` must be callable or one of ['mean', 'sum', 'cat', 'min', 'max', None]")
  233. if isinstance(default, Tensor):
  234. default = default.contiguous()
  235. setattr(self, name, default)
  236. self._defaults[name] = deepcopy(default)
  237. self._persistent[name] = persistent
  238. self._reductions[name] = dist_reduce_fx
  239. @torch.jit.unused
  240. def forward(self, *args: Any, **kwargs: Any) -> Any:
  241. """Aggregate and evaluate batch input directly.
  242. Serves the dual purpose of both computing the metric on the current batch of inputs but also add the batch
  243. statistics to the overall accumulating metric state. Input arguments are the exact same as corresponding
  244. ``update`` method. The returned output is the exact same as the output of ``compute``.
  245. Args:
  246. args: Any arguments as required by the metric ``update`` method.
  247. kwargs: Any keyword arguments as required by the metric ``update`` method.
  248. Returns:
  249. The output of the ``compute`` method evaluated on the current batch.
  250. Raises:
  251. TorchMetricsUserError:
  252. If the metric is already synced and ``forward`` is called again.
  253. """
  254. # check if states are already synced
  255. if self._is_synced:
  256. raise TorchMetricsUserError(
  257. "The Metric shouldn't be synced when performing ``forward``. HINT: Did you forget to call ``unsync`` ?."
  258. )
  259. if self.full_state_update or self.full_state_update is None or self.dist_sync_on_step:
  260. self._forward_cache = self._forward_full_state_update(*args, **kwargs)
  261. else:
  262. self._forward_cache = self._forward_reduce_state_update(*args, **kwargs)
  263. return self._forward_cache
  264. def _forward_full_state_update(self, *args: Any, **kwargs: Any) -> Any:
  265. """Forward computation using two calls to `update`.
  266. Doing this secures that metrics that need access to the full metric state during `update` works as expected.
  267. This is the most safe method to use for any metric but also the slower version of the two forward
  268. implementations.
  269. """
  270. # global accumulation
  271. self.update(*args, **kwargs)
  272. _update_count = self._update_count
  273. self._to_sync = self.dist_sync_on_step
  274. # skip restore cache operation from compute as cache is stored below.
  275. self._should_unsync = False
  276. # skip computing on cpu for the batch
  277. _temp_compute_on_cpu = self.compute_on_cpu
  278. self.compute_on_cpu = False
  279. # save context before switch
  280. cache = self._copy_state_dict()
  281. # call reset, update, compute, on single batch
  282. self._enable_grad = True # allow grads for batch computation
  283. self.reset()
  284. self.update(*args, **kwargs)
  285. batch_val = self.compute()
  286. # restore context
  287. for attr, val in cache.items():
  288. setattr(self, attr, val)
  289. self._update_count = _update_count
  290. # restore context
  291. self._is_synced = False
  292. self._should_unsync = True
  293. self._to_sync = self.sync_on_compute
  294. self._computed = None
  295. self._enable_grad = False
  296. self.compute_on_cpu = _temp_compute_on_cpu
  297. if self.compute_on_cpu:
  298. self._move_list_states_to_cpu()
  299. return batch_val
  300. def _forward_reduce_state_update(self, *args: Any, **kwargs: Any) -> Any:
  301. """Forward computation using single call to `update`.
  302. This can be done when the global metric state is a simple reduction of batch states. This can be unsafe for
  303. certain metric cases but is also the fastest way to both accumulate globally and compute locally.
  304. """
  305. # store global state and reset to default
  306. global_state = self._copy_state_dict()
  307. _update_count = self._update_count
  308. self.reset()
  309. # local synchronization settings
  310. self._to_sync = self.dist_sync_on_step
  311. self._should_unsync = False
  312. _temp_compute_on_cpu = self.compute_on_cpu
  313. self.compute_on_cpu = False
  314. self._enable_grad = True # allow grads for batch computation
  315. # calculate batch state and compute batch value
  316. self.update(*args, **kwargs)
  317. batch_val = self.compute()
  318. # reduce batch and global state
  319. self._update_count = _update_count + 1
  320. with torch.no_grad():
  321. self._reduce_states(global_state)
  322. # restore context
  323. self._is_synced = False
  324. self._should_unsync = True
  325. self._to_sync = self.sync_on_compute
  326. self._computed = None
  327. self._enable_grad = False
  328. self.compute_on_cpu = _temp_compute_on_cpu
  329. if self.compute_on_cpu:
  330. self._move_list_states_to_cpu()
  331. return batch_val
  332. def merge_state(self, incoming_state: Union[dict[str, Any], "Metric"]) -> None:
  333. """Merge incoming metric state to the current state of the metric.
  334. Args:
  335. incoming_state:
  336. either a dict containing a metric state similar to the metric itself or an instance of the
  337. metric class.
  338. Raises:
  339. ValueError:
  340. If the incoming state is neither a dict nor an instance of the metric class.
  341. RuntimeError:
  342. If the metric has ``full_state_update=True`` or ``dist_sync_on_step=True``. In these cases, the metric
  343. cannot be merged with another metric state in a simple way. The user should overwrite the method in the
  344. metric class to handle the merge operation.
  345. ValueError:
  346. If the incoming state is a metric instance but the class is different from the current metric class.
  347. Example with a metric instance:
  348. >>> from torchmetrics.aggregation import SumMetric
  349. >>> metric1 = SumMetric()
  350. >>> metric2 = SumMetric()
  351. >>> metric1.update(1)
  352. >>> metric2.update(2)
  353. >>> metric1.merge_state(metric2)
  354. >>> metric1.compute()
  355. tensor(3.)
  356. Example with a dict:
  357. >>> from torchmetrics.aggregation import SumMetric
  358. >>> metric = SumMetric()
  359. >>> metric.update(1)
  360. >>> # SumMetric has one state variable called `sum_value`
  361. >>> metric.merge_state({"sum_value": torch.tensor(2)})
  362. >>> metric.compute()
  363. tensor(3.)
  364. """
  365. if not isinstance(incoming_state, (dict, Metric)):
  366. raise ValueError(
  367. f"Expected incoming state to be a dict or an instance of Metric but got {type(incoming_state)}"
  368. )
  369. if self.full_state_update or self.full_state_update is None or self.dist_sync_on_step:
  370. raise RuntimeError(
  371. "``merge_state`` is not supported for metrics with ``full_state_update=True`` or "
  372. "``dist_sync_on_step=True``. Please overwrite the merge_state method in the metric class."
  373. )
  374. if isinstance(incoming_state, Metric):
  375. this_class = self.__class__
  376. if not isinstance(incoming_state, this_class):
  377. raise ValueError(
  378. f"Expected incoming state to be an instance of {this_class.__name__} but got {type(incoming_state)}"
  379. )
  380. incoming_state = incoming_state.metric_state
  381. self._reduce_states(incoming_state)
  382. def _reduce_states(self, incoming_state: dict[str, Any]) -> None:
  383. """Add an incoming metric state to the current state of the metric.
  384. Args:
  385. incoming_state: a dict containing a metric state similar metric itself
  386. """
  387. for attr in self._defaults:
  388. local_state = getattr(self, attr)
  389. if attr not in incoming_state:
  390. raise ValueError(f"Expected state variable {attr} to be present in incoming state {incoming_state}")
  391. global_state = incoming_state[attr]
  392. reduce_fn = self._reductions[attr]
  393. if reduce_fn == dim_zero_sum:
  394. reduced = global_state + local_state
  395. elif reduce_fn == dim_zero_mean:
  396. reduced = ((self._update_count - 1) * global_state + local_state).float() / self._update_count
  397. elif reduce_fn == dim_zero_max:
  398. reduced = torch.max(global_state, local_state)
  399. elif reduce_fn == dim_zero_min:
  400. reduced = torch.min(global_state, local_state)
  401. elif reduce_fn == dim_zero_cat:
  402. if isinstance(global_state, Tensor):
  403. reduced = torch.cat([global_state, local_state])
  404. else:
  405. reduced = global_state + local_state
  406. elif reduce_fn is None and isinstance(global_state, Tensor):
  407. reduced = torch.stack([global_state, local_state])
  408. elif reduce_fn is None and isinstance(global_state, list):
  409. reduced = _flatten([global_state, local_state])
  410. elif reduce_fn and callable(reduce_fn):
  411. reduced = reduce_fn(torch.stack([global_state, local_state]))
  412. else:
  413. raise TypeError(f"Unsupported reduce_fn: {reduce_fn}")
  414. setattr(self, attr, reduced)
  415. def _sync_dist(self, dist_sync_fn: Callable = gather_all_tensors, process_group: Optional[Any] = None) -> None:
  416. input_dict = {attr: getattr(self, attr) for attr in self._reductions}
  417. for attr, reduction_fn in self._reductions.items():
  418. # pre-concatenate metric states that are lists to reduce number of all_gather operations
  419. if reduction_fn == dim_zero_cat and isinstance(input_dict[attr], list) and len(input_dict[attr]) > 1:
  420. input_dict[attr] = [dim_zero_cat(input_dict[attr])]
  421. # cornor case in distributed settings where a rank have not received any data, create empty to concatenate
  422. if (
  423. self._TORCH_GREATER_EQUAL_2_1
  424. and reduction_fn == dim_zero_cat
  425. and isinstance(input_dict[attr], list)
  426. and len(input_dict[attr]) == 0
  427. ):
  428. input_dict[attr] = [torch.tensor([], device=self.device, dtype=self.dtype)]
  429. output_dict = apply_to_collection(
  430. input_dict,
  431. Tensor,
  432. dist_sync_fn,
  433. group=process_group or self.process_group,
  434. )
  435. for attr, reduction_fn in self._reductions.items():
  436. # pre-processing ops (stack or flatten for inputs)
  437. if isinstance(output_dict[attr], list) and len(output_dict[attr]) == 0:
  438. setattr(self, attr, [])
  439. continue
  440. if isinstance(output_dict[attr][0], Tensor):
  441. output_dict[attr] = torch.stack(output_dict[attr])
  442. elif isinstance(output_dict[attr][0], list):
  443. output_dict[attr] = _flatten(output_dict[attr])
  444. if not (callable(reduction_fn) or reduction_fn is None):
  445. raise TypeError("reduction_fn must be callable or None")
  446. reduced = reduction_fn(output_dict[attr]) if reduction_fn is not None else output_dict[attr]
  447. setattr(self, attr, reduced)
  448. def _wrap_update(self, update: Callable) -> Callable:
  449. @functools.wraps(update)
  450. def wrapped_func(*args: Any, **kwargs: Any) -> None:
  451. self._computed = None
  452. self._update_count += 1
  453. with torch.set_grad_enabled(self._enable_grad):
  454. try:
  455. update(*args, **kwargs)
  456. except RuntimeError as err:
  457. if "Expected all tensors to be on" in str(err):
  458. raise RuntimeError(
  459. "Encountered different devices in metric calculation (see stacktrace for details)."
  460. " This could be due to the metric class not being on the same device as input."
  461. f" Instead of `metric={self.__class__.__name__}(...)` try to do"
  462. f" `metric={self.__class__.__name__}(...).to(device)` where"
  463. " device corresponds to the device of the input."
  464. ) from err
  465. raise err
  466. if self.compute_on_cpu:
  467. self._move_list_states_to_cpu()
  468. return wrapped_func
  469. def _move_list_states_to_cpu(self) -> None:
  470. """Move list states to cpu to save GPU memory."""
  471. for key in self._defaults:
  472. current_val = getattr(self, key)
  473. if isinstance(current_val, Sequence):
  474. setattr(self, key, [cur_v.to("cpu") for cur_v in current_val])
  475. def sync(
  476. self,
  477. dist_sync_fn: Optional[Callable] = None,
  478. process_group: Optional[Any] = None,
  479. should_sync: bool = True,
  480. distributed_available: Optional[Callable] = None,
  481. ) -> None:
  482. """Sync function for manually controlling when metrics states should be synced across processes.
  483. Args:
  484. dist_sync_fn: Function to be used to perform states synchronization
  485. process_group:
  486. Specify the process group on which synchronization is called.
  487. default: `None` (which selects the entire world)
  488. should_sync: Whether to apply to state synchronization. This will have an impact
  489. only when running in a distributed setting.
  490. distributed_available: Function to determine if we are running inside a distributed setting
  491. Raises:
  492. TorchMetricsUserError:
  493. If the metric is already synced and ``sync`` is called again.
  494. """
  495. if self._is_synced and should_sync:
  496. raise TorchMetricsUserError("The Metric has already been synced.")
  497. if distributed_available is None and self.distributed_available_fn is not None:
  498. distributed_available = self.distributed_available_fn
  499. is_distributed = distributed_available() if callable(distributed_available) else None
  500. if not should_sync or not is_distributed:
  501. return
  502. if dist_sync_fn is None:
  503. dist_sync_fn = gather_all_tensors
  504. # cache prior to syncing
  505. self._cache = self._copy_state_dict()
  506. # sync
  507. self._sync_dist(dist_sync_fn, process_group=process_group)
  508. self._is_synced = True
  509. def unsync(self, should_unsync: bool = True) -> None:
  510. """Unsync function for manually controlling when metrics states should be reverted back to their local states.
  511. Args:
  512. should_unsync: Whether to perform unsync
  513. """
  514. if not should_unsync:
  515. return
  516. if not self._is_synced:
  517. raise TorchMetricsUserError("The Metric has already been un-synced.")
  518. if self._cache is None:
  519. raise TorchMetricsUserError("The internal cache should exist to unsync the Metric.")
  520. # if we synced, restore to cache so that we can continue to accumulate un-synced state
  521. for attr, val in self._cache.items():
  522. setattr(self, attr, val)
  523. self._is_synced = False
  524. self._cache = None
  525. @contextmanager
  526. def sync_context(
  527. self,
  528. dist_sync_fn: Optional[Callable] = None,
  529. process_group: Optional[Any] = None,
  530. should_sync: bool = True,
  531. should_unsync: bool = True,
  532. distributed_available: Optional[Callable] = None,
  533. ) -> Generator:
  534. """Context manager to synchronize states.
  535. This context manager is used in distributed setting and makes sure that the local cache states are restored
  536. after yielding the synchronized state.
  537. Args:
  538. dist_sync_fn: Function to be used to perform states synchronization
  539. process_group:
  540. Specify the process group on which synchronization is called.
  541. default: `None` (which selects the entire world)
  542. should_sync: Whether to apply to state synchronization. This will have an impact
  543. only when running in a distributed setting.
  544. should_unsync: Whether to restore the cache state so that the metrics can
  545. continue to be accumulated.
  546. distributed_available: Function to determine if we are running inside a distributed setting
  547. """
  548. self.sync(
  549. dist_sync_fn=dist_sync_fn,
  550. process_group=process_group,
  551. should_sync=should_sync,
  552. distributed_available=distributed_available,
  553. )
  554. yield
  555. self.unsync(should_unsync=self._is_synced and should_unsync)
  556. def _wrap_compute(self, compute: Callable) -> Callable:
  557. @functools.wraps(compute)
  558. def wrapped_func(*args: Any, **kwargs: Any) -> Any:
  559. if not self.update_called:
  560. rank_zero_warn(
  561. f"The ``compute`` method of metric {self.__class__.__name__}"
  562. " was called before the ``update`` method which may lead to errors,"
  563. " as metric states have not yet been updated.",
  564. UserWarning,
  565. )
  566. # return cached value
  567. if self._computed is not None:
  568. return self._computed
  569. # compute relies on the sync context manager to gather the states across processes and apply reduction
  570. # if synchronization happened, the current rank accumulated states will be restored to keep
  571. # accumulation going if ``should_unsync=True``,
  572. with self.sync_context(
  573. dist_sync_fn=self.dist_sync_fn,
  574. should_sync=self._to_sync,
  575. should_unsync=self._should_unsync,
  576. ):
  577. value = _squeeze_if_scalar(compute(*args, **kwargs))
  578. # clone tensor to avoid in-place operations after compute, altering already computed results
  579. value = apply_to_collection(value, Tensor, lambda x: x.clone())
  580. if self.compute_with_cache:
  581. self._computed = value
  582. return value
  583. return wrapped_func
  584. @abstractmethod
  585. def update(self, *_: Any, **__: Any) -> None:
  586. """Override this method to update the state variables of your metric class."""
  587. @abstractmethod
  588. def compute(self) -> Any:
  589. """Override this method to compute the final metric value.
  590. This method will automatically synchronize state variables when running in distributed backend.
  591. """
  592. def plot(self, *_: Any, **__: Any) -> Any:
  593. """Override this method plot the metric value."""
  594. raise NotImplementedError
  595. def _plot(
  596. self,
  597. val: Optional[Union[Tensor, Sequence[Tensor], dict[str, Tensor], Sequence[dict[str, Tensor]]]] = None,
  598. ax: Optional[_AX_TYPE] = None,
  599. ) -> _PLOT_OUT_TYPE:
  600. """Plot a single or multiple values from the metric.
  601. Args:
  602. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  603. If no value is provided, will automatically call `metric.compute` and plot that result.
  604. ax: An matplotlib axis object. If provided will add plot to that axis
  605. Returns:
  606. Figure and Axes object
  607. Raises:
  608. ModuleNotFoundError:
  609. If `matplotlib` is not installed
  610. """
  611. val = val if val is not None else self.compute()
  612. fig, ax = plot_single_or_multi_val(
  613. val,
  614. ax=ax,
  615. higher_is_better=self.higher_is_better,
  616. name=self.__class__.__name__,
  617. lower_bound=self.plot_lower_bound,
  618. upper_bound=self.plot_upper_bound,
  619. legend_name=self.plot_legend_name,
  620. )
  621. return fig, ax
  622. def reset(self) -> None:
  623. """Reset metric state variables to their default value."""
  624. self._update_count = 0
  625. self._forward_cache = None
  626. self._computed = None
  627. for attr, default in self._defaults.items():
  628. current_val = getattr(self, attr)
  629. if isinstance(default, Tensor):
  630. setattr(self, attr, default.detach().clone().to(current_val.device))
  631. else:
  632. getattr(self, attr).clear() # delete/free list items
  633. # reset internal states
  634. self._cache = None
  635. self._is_synced = False
  636. def clone(self) -> "Metric":
  637. """Make a copy of the metric."""
  638. return deepcopy(self)
  639. def __getstate__(self) -> dict[str, Any]:
  640. """Get the current state, including all metric states, for the metric.
  641. Used for loading and saving a metric.
  642. """
  643. # ignore update and compute functions for pickling
  644. return {k: v for k, v in self.__dict__.items() if k not in ["update", "compute", "_update_signature"]}
  645. def __setstate__(self, state: dict[str, Any]) -> None:
  646. """Set the state of the metric, based on a input state.
  647. Used for loading and saving a metric.
  648. """
  649. # manually restore update and compute functions for pickling
  650. self.__dict__.update(state)
  651. self._update_signature = inspect.signature(self.update)
  652. self.update: Callable = self._wrap_update(self.update) # type: ignore[method-assign]
  653. self.compute: Callable = self._wrap_compute(self.compute) # type: ignore[method-assign]
  654. def __setattr__(self, name: str, value: Any) -> None:
  655. """Overwrite default method to prevent specific attributes from being set by user."""
  656. if name in (
  657. "higher_is_better",
  658. "is_differentiable",
  659. "full_state_update",
  660. "plot_lower_bound",
  661. "plot_upper_bound",
  662. "plot_legend_name",
  663. ):
  664. raise RuntimeError(f"Can't change const `{name}`.")
  665. super().__setattr__(name, value)
  666. @property
  667. def device(self) -> "torch.device":
  668. """Return the device of the metric."""
  669. return self._device
  670. @property
  671. def dtype(self) -> "torch.dtype":
  672. """Return the default dtype of the metric."""
  673. return self._dtype
  674. def type(self, dst_type: Union[str, torch.dtype]) -> "Metric":
  675. """Override default and prevent dtype casting.
  676. Please use :meth:`Metric.set_dtype` instead.
  677. """
  678. return self
  679. def float(self) -> "Metric":
  680. """Override default and prevent dtype casting.
  681. Please use :meth:`Metric.set_dtype` instead.
  682. """
  683. return self
  684. def double(self) -> "Metric":
  685. """Override default and prevent dtype casting.
  686. Please use :meth:`Metric.set_dtype` instead.
  687. """
  688. return self
  689. def half(self) -> "Metric":
  690. """Override default and prevent dtype casting.
  691. Please use :meth:`Metric.set_dtype` instead.
  692. """
  693. return self
  694. def set_dtype(self, dst_type: Union[str, torch.dtype]) -> "Metric":
  695. """Transfer all metric state to specific dtype. Special version of standard `type` method.
  696. Arguments:
  697. dst_type: the desired type as string or dtype object
  698. """
  699. self._dtype_convert = True
  700. out = super().type(dst_type)
  701. out._dtype_convert = False
  702. return out
  703. def _apply(self, fn: Callable, exclude_state: Sequence[str] = "") -> Module:
  704. """Overwrite `_apply` function such that we can also move metric states to the correct device.
  705. This method is called by the base ``nn.Module`` class whenever `.to`, `.cuda`, `.float`, `.half` etc. methods
  706. are called. Dtype conversion is guarded and will only happen through the special `set_dtype` method.
  707. Args:
  708. fn: the function to apply
  709. exclude_state: list of state variables to exclude from applying the function, that then needs to be handled
  710. by the metric class itself.
  711. """
  712. this = super()._apply(fn)
  713. fs = str(fn)
  714. cond = any(f in fs for f in ["Module.type", "Module.half", "Module.float", "Module.double", "Module.bfloat16"])
  715. if not self._dtype_convert and cond:
  716. return this
  717. # Also apply fn to metric states and defaults
  718. for key, value in this._defaults.items():
  719. if key in exclude_state:
  720. continue
  721. if isinstance(value, Tensor):
  722. this._defaults[key] = fn(value)
  723. elif isinstance(value, Sequence):
  724. this._defaults[key] = [fn(v) for v in value]
  725. current_val = getattr(this, key)
  726. if isinstance(current_val, Tensor):
  727. setattr(this, key, fn(current_val))
  728. elif isinstance(current_val, Sequence):
  729. setattr(this, key, [fn(cur_v) for cur_v in current_val])
  730. else:
  731. raise TypeError(
  732. f"Expected metric state to be either a Tensor or a list of Tensor, but encountered {current_val}"
  733. )
  734. # make sure to update the device attribute
  735. # if the dummy tensor moves device by fn function we should also update the attribute
  736. _dummy_tensor = fn(torch.zeros(1, device=self.device))
  737. self._device = _dummy_tensor.device
  738. self._dtype = _dummy_tensor.dtype
  739. # Additional apply to forward cache and computed attributes (may be nested)
  740. if this._computed is not None:
  741. this._computed = apply_to_collection(this._computed, Tensor, fn)
  742. if this._forward_cache is not None:
  743. this._forward_cache = apply_to_collection(this._forward_cache, Tensor, fn)
  744. return this
  745. def persistent(self, mode: bool = False) -> None:
  746. """Change post-init if metric states should be saved to its state_dict."""
  747. for key in self._persistent:
  748. self._persistent[key] = mode
  749. def state_dict( # type: ignore[override] # todo
  750. self,
  751. destination: Optional[dict[str, Any]] = None,
  752. prefix: str = "",
  753. keep_vars: bool = False,
  754. ) -> dict[str, Any]:
  755. """Get the current state of metric as an dictionary.
  756. Args:
  757. destination: Optional dictionary, that if provided, the state of module will be updated into the dict and
  758. the same object is returned. Otherwise, an ``OrderedDict`` will be created and returned.
  759. prefix: optional string, a prefix added to parameter and buffer names to compose the keys in state_dict.
  760. keep_vars: by default the :class:`~torch.Tensor` returned in the state dict are detached from autograd.
  761. If set to ``True``, detaching will not be performed.
  762. """
  763. destination: dict[str, Union[torch.Tensor, list, Any]] = super().state_dict(
  764. destination=destination, # type: ignore[arg-type]
  765. prefix=prefix,
  766. keep_vars=keep_vars,
  767. )
  768. # Register metric states to be part of the state_dict
  769. for key in self._defaults:
  770. if not self._persistent[key]:
  771. continue
  772. current_val = getattr(self, key)
  773. if not keep_vars:
  774. if isinstance(current_val, Tensor):
  775. current_val = current_val.detach()
  776. elif isinstance(current_val, list):
  777. current_val = [cur_v.detach() if isinstance(cur_v, Tensor) else cur_v for cur_v in current_val]
  778. destination[prefix + key] = deepcopy(current_val)
  779. return destination
  780. def _copy_state_dict(self) -> dict[str, Union[Tensor, list[Any]]]:
  781. """Copy the current state values."""
  782. cache: dict[str, Union[Tensor, list[Any]]] = {}
  783. for attr in self._defaults:
  784. current_value = getattr(self, attr)
  785. if isinstance(current_value, Tensor):
  786. cache[attr] = current_value.detach().clone().to(current_value.device)
  787. else:
  788. cache[attr] = [ # safely copy (non-graph leaf) Tensor elements
  789. _.detach().clone().to(_.device) if isinstance(_, Tensor) else deepcopy(_) for _ in current_value
  790. ]
  791. return cache
  792. def _load_from_state_dict(
  793. self,
  794. state_dict: dict,
  795. prefix: str,
  796. local_metadata: dict,
  797. strict: bool,
  798. missing_keys: list[str],
  799. unexpected_keys: list[str],
  800. error_msgs: list[str],
  801. ) -> None:
  802. """Load metric states from state_dict."""
  803. for key in self._defaults:
  804. name = prefix + key
  805. if name in state_dict:
  806. setattr(self, key, state_dict.pop(name))
  807. super()._load_from_state_dict(
  808. state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs
  809. )
  810. def _filter_kwargs(self, **kwargs: Any) -> dict[str, Any]:
  811. """Filter kwargs such that they match the update signature of the metric."""
  812. # filter all parameters based on update signature except those of
  813. # types `VAR_POSITIONAL` for `* args` and `VAR_KEYWORD` for `** kwargs`
  814. _params = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
  815. _sign_params = self._update_signature.parameters
  816. filtered_kwargs = {
  817. k: v for k, v in kwargs.items() if (k in _sign_params and _sign_params[k].kind not in _params)
  818. }
  819. exists_var_keyword = any(v.kind == inspect.Parameter.VAR_KEYWORD for v in _sign_params.values())
  820. # if no kwargs filtered, return all kwargs as default
  821. if not filtered_kwargs and not exists_var_keyword:
  822. # no kwargs in update signature -> don't return any kwargs
  823. return {}
  824. if exists_var_keyword:
  825. # kwargs found in update signature -> return all kwargs to be sure to not omit any.
  826. # filtering logic is likely implemented within the update call.
  827. return kwargs
  828. return filtered_kwargs
  829. def __hash__(self) -> int:
  830. """Return an unique hash of the metric.
  831. The hash depends on both the class itself but also the current metric state, which therefore enforces that two
  832. instances of the same metrics never have the same hash even if they have been updated on the same data.
  833. """
  834. # we need to add the id here, since PyTorch requires a module hash to be unique.
  835. # Internally, PyTorch nn.Module relies on that for children discovery
  836. # (see https://github.com/pytorch/pytorch/blob/v1.9.0/torch/nn/modules/module.py#L1544)
  837. # For metrics that include tensors it is not a problem,
  838. # since their hash is unique based on the memory location but we cannot rely on that for every metric.
  839. hash_vals = [self.__class__.__name__, id(self)]
  840. for key in self._defaults:
  841. val = getattr(self, key)
  842. # Special case: allow list values, so long
  843. # as their elements are hashable
  844. if hasattr(val, "__iter__") and not isinstance(val, Tensor):
  845. hash_vals.extend(val)
  846. else:
  847. hash_vals.append(val)
  848. return hash(tuple(hash_vals))
  849. def __add__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  850. """Construct compositional metric using the addition operator."""
  851. return CompositionalMetric(torch.add, self, other)
  852. def __and__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  853. """Construct compositional metric using the logical and operator."""
  854. return CompositionalMetric(torch.bitwise_and, self, other)
  855. def __eq__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric": # type: ignore[override]
  856. """Construct compositional metric using the equal operator."""
  857. return CompositionalMetric(torch.eq, self, other)
  858. def __floordiv__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  859. """Construct compositional metric using the floor division operator."""
  860. return CompositionalMetric(torch.floor_divide, self, other)
  861. def __ge__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  862. """Construct compositional metric using the greater than or equal operator."""
  863. return CompositionalMetric(torch.ge, self, other)
  864. def __gt__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  865. """Construct compositional metric using the greater than operator."""
  866. return CompositionalMetric(torch.gt, self, other)
  867. def __le__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  868. """Construct compositional metric using the less than or equal operator."""
  869. return CompositionalMetric(torch.le, self, other)
  870. def __lt__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  871. """Construct compositional metric using the less than operator."""
  872. return CompositionalMetric(torch.lt, self, other)
  873. def __matmul__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  874. """Construct compositional metric using the matrix multiplication operator."""
  875. return CompositionalMetric(torch.matmul, self, other)
  876. def __mod__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  877. """Construct compositional metric using the remainder operator."""
  878. return CompositionalMetric(torch.fmod, self, other)
  879. def __mul__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  880. """Construct compositional metric using the multiplication operator."""
  881. return CompositionalMetric(torch.mul, self, other)
  882. def __ne__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric": # type: ignore[override]
  883. """Construct compositional metric using the not equal operator."""
  884. return CompositionalMetric(torch.ne, self, other)
  885. def __or__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  886. """Construct compositional metric using the logical or operator."""
  887. return CompositionalMetric(torch.bitwise_or, self, other)
  888. def __pow__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  889. """Construct compositional metric using the exponential/power operator."""
  890. return CompositionalMetric(torch.pow, self, other)
  891. def __radd__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  892. """Construct compositional metric using the addition operator."""
  893. return CompositionalMetric(torch.add, other, self)
  894. def __rand__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  895. """Construct compositional metric using the logical and operator."""
  896. # swap them since bitwise_and only supports that way and it's commutative
  897. return CompositionalMetric(torch.bitwise_and, self, other)
  898. def __rfloordiv__(self, other: "CompositionalMetric") -> "Metric":
  899. """Construct compositional metric using the floor division operator."""
  900. return CompositionalMetric(torch.floor_divide, other, self)
  901. def __rmatmul__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  902. """Construct compositional metric using the matrix multiplication operator."""
  903. return CompositionalMetric(torch.matmul, other, self)
  904. def __rmod__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  905. """Construct compositional metric using the remainder operator."""
  906. return CompositionalMetric(torch.fmod, other, self)
  907. def __rmul__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  908. """Construct compositional metric using the multiplication operator."""
  909. return CompositionalMetric(torch.mul, other, self)
  910. def __ror__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  911. """Construct compositional metric using the logical or operator."""
  912. return CompositionalMetric(torch.bitwise_or, other, self)
  913. def __rpow__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  914. """Construct compositional metric using the exponential/power operator."""
  915. return CompositionalMetric(torch.pow, other, self)
  916. def __rsub__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  917. """Construct compositional metric using the subtraction operator."""
  918. return CompositionalMetric(torch.sub, other, self)
  919. def __rtruediv__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  920. """Construct compositional metric using the true divide operator."""
  921. return CompositionalMetric(torch.true_divide, other, self)
  922. def __rxor__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  923. """Construct compositional metric using the logical xor operator."""
  924. return CompositionalMetric(torch.bitwise_xor, other, self)
  925. def __sub__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  926. """Construct compositional metric using the subtraction operator."""
  927. return CompositionalMetric(torch.sub, self, other)
  928. def __truediv__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  929. """Construct compositional metric using the true divide operator."""
  930. return CompositionalMetric(torch.true_divide, self, other)
  931. def __xor__(self, other: Union["Metric", builtins.float, Tensor]) -> "CompositionalMetric":
  932. """Construct compositional metric using the logical xor operator."""
  933. return CompositionalMetric(torch.bitwise_xor, self, other)
  934. def __abs__(self) -> "CompositionalMetric":
  935. """Construct compositional metric using the absolute operator."""
  936. return CompositionalMetric(torch.abs, self, None)
  937. def __inv__(self) -> "CompositionalMetric":
  938. """Construct compositional metric using the not operator."""
  939. return CompositionalMetric(torch.bitwise_not, self, None)
  940. def __invert__(self) -> "CompositionalMetric":
  941. """Construct compositional metric using the not operator."""
  942. return self.__inv__()
  943. def __neg__(self) -> "CompositionalMetric":
  944. """Construct compositional metric using absolute negative operator."""
  945. return CompositionalMetric(_neg, self, None)
  946. def __pos__(self) -> "CompositionalMetric":
  947. """Construct compositional metric using absolute operator."""
  948. return CompositionalMetric(torch.abs, self, None)
  949. def __getitem__(self, idx: int) -> "CompositionalMetric":
  950. """Construct compositional metric using the get item operator."""
  951. return CompositionalMetric(lambda x: x[idx], self, None)
  952. def __getnewargs__(self) -> tuple:
  953. """Needed method for construction of new metrics __new__ method."""
  954. return tuple(
  955. Metric.__str__(self),
  956. )
  957. __iter__ = None
  958. def _neg(x: Tensor) -> Tensor:
  959. return -torch.abs(x)
  960. class CompositionalMetric(Metric):
  961. """Composition of two metrics with a specific operator which will be executed upon metrics compute."""
  962. def __init__(
  963. self,
  964. operator: Callable,
  965. metric_a: Union[Metric, float, Tensor],
  966. metric_b: Union[Metric, float, Tensor, None],
  967. ) -> None:
  968. """Class for creating compositions of metrics.
  969. This metric class is the output of adding, multiplying etc. any other metric. The metric re-implements the
  970. standard ``update``, ``forward``, ``reset`` and ``compute`` methods to redirect the arguments to the metrics
  971. that formed this composition.
  972. Args:
  973. operator:
  974. The operator taking in one (if metric_b is None) or two arguments. Will be applied to outputs of
  975. metric_a.compute() and (optionally if metric_b is not None) metric_b.compute()
  976. metric_a:
  977. First metric whose compute() result is the first argument of operator
  978. metric_b: second metric whose compute() result is the second argument of operator.
  979. For operators taking in only one input, this should be None.
  980. """
  981. super().__init__()
  982. self.op = operator
  983. if isinstance(metric_a, Tensor):
  984. self.register_buffer("metric_a", metric_a, persistent=False)
  985. else:
  986. self.metric_a = metric_a
  987. if isinstance(metric_b, Tensor):
  988. self.register_buffer("metric_b", metric_b, persistent=False)
  989. else:
  990. self.metric_b = metric_b
  991. def _sync_dist(self, dist_sync_fn: Optional[Callable] = None, process_group: Optional[Any] = None) -> None:
  992. """No syncing required here.
  993. syncing will be done in metric_a and metric_b.
  994. """
  995. def update(self, *args: Any, **kwargs: Any) -> None:
  996. """Redirect the call to the input which the composition was formed from."""
  997. if isinstance(self.metric_a, Metric):
  998. self.metric_a.update(*args, **self.metric_a._filter_kwargs(**kwargs))
  999. if isinstance(self.metric_b, Metric):
  1000. self.metric_b.update(*args, **self.metric_b._filter_kwargs(**kwargs))
  1001. def compute(self) -> Any:
  1002. """Redirect the call to the input which the composition was formed from."""
  1003. # also some parsing for kwargs?
  1004. val_a = self.metric_a.compute() if isinstance(self.metric_a, Metric) else self.metric_a
  1005. val_b = self.metric_b.compute() if isinstance(self.metric_b, Metric) else self.metric_b
  1006. if val_b is None:
  1007. return self.op(val_a)
  1008. return self.op(val_a, val_b)
  1009. @torch.jit.unused
  1010. def forward(self, *args: Any, **kwargs: Any) -> Any:
  1011. """Calculate metric on current batch and accumulate to global state."""
  1012. val_a = (
  1013. self.metric_a(*args, **self.metric_a._filter_kwargs(**kwargs))
  1014. if isinstance(self.metric_a, Metric)
  1015. else self.metric_a
  1016. )
  1017. val_b = (
  1018. self.metric_b(*args, **self.metric_b._filter_kwargs(**kwargs))
  1019. if isinstance(self.metric_b, Metric)
  1020. else self.metric_b
  1021. )
  1022. if val_a is None:
  1023. self._forward_cache = None
  1024. return self._forward_cache
  1025. if val_b is None:
  1026. if isinstance(self.metric_b, Metric):
  1027. self._forward_cache = None
  1028. return self._forward_cache
  1029. # Unary op
  1030. self._forward_cache = self.op(val_a)
  1031. return self._forward_cache
  1032. # Binary op
  1033. self._forward_cache = self.op(val_a, val_b)
  1034. return self._forward_cache
  1035. def reset(self) -> None:
  1036. """Redirect the call to the input which the composition was formed from."""
  1037. if isinstance(self.metric_a, Metric):
  1038. self.metric_a.reset()
  1039. if isinstance(self.metric_b, Metric):
  1040. self.metric_b.reset()
  1041. def persistent(self, mode: bool = False) -> None:
  1042. """Change if metric state is persistent (save as part of state_dict) or not.
  1043. Args:
  1044. mode: bool indicating if all states should be persistent or not
  1045. """
  1046. if isinstance(self.metric_a, Metric):
  1047. self.metric_a.persistent(mode=mode)
  1048. if isinstance(self.metric_b, Metric):
  1049. self.metric_b.persistent(mode=mode)
  1050. def __repr__(self) -> str:
  1051. """Return a representation of the compositional metric, including the two inputs it was formed from."""
  1052. _op_metrics = f"(\n {self.op.__name__}(\n {self.metric_a!r},\n {self.metric_b!r}\n )\n)"
  1053. return self.__class__.__name__ + _op_metrics
  1054. def _wrap_compute(self, compute: Callable) -> Callable:
  1055. """No wrapping necessary for compositional metrics."""
  1056. return compute