pit.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. from collections.abc import Sequence
  15. from typing import Any, Callable, Optional, Union
  16. from torch import Tensor, tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.audio.pit import permutation_invariant_training
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  21. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  22. __doctest_requires__ = {"PermutationInvariantTraining": ["pit"]}
  23. if not _MATPLOTLIB_AVAILABLE:
  24. __doctest_skip__ = ["PermutationInvariantTraining.plot"]
  25. class PermutationInvariantTraining(Metric):
  26. """Calculate `Permutation invariant training`_ (PIT).
  27. This metric can evaluate models for speaker independent multi-talker speech separation in a permutation
  28. invariant way.
  29. As input to ``forward`` and ``update`` the metric accepts the following input
  30. - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(batch_size,num_speakers,...)``
  31. - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(batch_size,num_speakers,...)``
  32. As output of `forward` and `compute` the metric returns the following output
  33. - ``pesq`` (:class:`~torch.Tensor`): float scalar tensor with average PESQ value over samples
  34. Args:
  35. metric_func:
  36. a metric function accept a batch of target and estimate.
  37. if `mode`==`'speaker-wise'`, then ``metric_func(preds[:, i, ...], target[:, j, ...])`` is called
  38. and expected to return a batch of metric tensors ``(batch,)``;
  39. if `mode`==`'permutation-wise'`, then ``metric_func(preds[:, p, ...], target[:, :, ...])`` is called,
  40. where `p` is one possible permutation, e.g. [0,1] or [1,0] for 2-speaker case, and expected to return
  41. a batch of metric tensors ``(batch,)``;
  42. mode:
  43. can be `'speaker-wise'` or `'permutation-wise'`.
  44. eval_func:
  45. the function to find the best permutation, can be 'min' or 'max', i.e. the smaller the better
  46. or the larger the better.
  47. kwargs: Additional keyword arguments for either the ``metric_func`` or distributed communication,
  48. see :ref:`Metric kwargs` for more info.
  49. Example:
  50. >>> from torch import randn
  51. >>> from torchmetrics.audio import PermutationInvariantTraining
  52. >>> from torchmetrics.functional.audio import scale_invariant_signal_noise_ratio
  53. >>> preds = randn(3, 2, 5) # [batch, spk, time]
  54. >>> target = randn(3, 2, 5) # [batch, spk, time]
  55. >>> pit = PermutationInvariantTraining(scale_invariant_signal_noise_ratio,
  56. ... mode="speaker-wise", eval_func="max")
  57. >>> pit(preds, target)
  58. tensor(-2.1065)
  59. """
  60. full_state_update: bool = False
  61. is_differentiable: bool = True
  62. sum_pit_metric: Tensor
  63. total: Tensor
  64. plot_lower_bound: Optional[float] = None
  65. plot_upper_bound: Optional[float] = None
  66. def __init__(
  67. self,
  68. metric_func: Callable,
  69. mode: Literal["speaker-wise", "permutation-wise"] = "speaker-wise",
  70. eval_func: Literal["max", "min"] = "max",
  71. **kwargs: Any,
  72. ) -> None:
  73. base_kwargs: dict[str, Any] = {
  74. "dist_sync_on_step": kwargs.pop("dist_sync_on_step", False),
  75. "process_group": kwargs.pop("process_group", None),
  76. "dist_sync_fn": kwargs.pop("dist_sync_fn", None),
  77. }
  78. super().__init__(**base_kwargs)
  79. self.metric_func = metric_func
  80. self.mode = mode
  81. self.eval_func = eval_func
  82. self.kwargs = kwargs
  83. self.add_state("sum_pit_metric", default=tensor(0.0), dist_reduce_fx="sum")
  84. self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
  85. def update(self, preds: Tensor, target: Tensor) -> None:
  86. """Update state with predictions and targets."""
  87. pit_metric = permutation_invariant_training(
  88. preds, target, self.metric_func, self.mode, self.eval_func, **self.kwargs
  89. )[0]
  90. self.sum_pit_metric += pit_metric.sum()
  91. self.total += pit_metric.numel()
  92. def compute(self) -> Tensor:
  93. """Compute metric."""
  94. return self.sum_pit_metric / self.total
  95. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  96. """Plot a single or multiple values from the metric.
  97. Args:
  98. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  99. If no value is provided, will automatically call `metric.compute` and plot that result.
  100. ax: An matplotlib axis object. If provided will add plot to that axis
  101. Returns:
  102. Figure and Axes object
  103. Raises:
  104. ModuleNotFoundError:
  105. If `matplotlib` is not installed
  106. .. plot::
  107. :scale: 75
  108. >>> # Example plotting a single value
  109. >>> import torch
  110. >>> from torchmetrics.audio import PermutationInvariantTraining
  111. >>> from torchmetrics.functional.audio import scale_invariant_signal_noise_ratio
  112. >>> preds = torch.randn(3, 2, 5) # [batch, spk, time]
  113. >>> target = torch.randn(3, 2, 5) # [batch, spk, time]
  114. >>> metric = PermutationInvariantTraining(scale_invariant_signal_noise_ratio,
  115. ... mode="speaker-wise", eval_func="max")
  116. >>> metric.update(preds, target)
  117. >>> fig_, ax_ = metric.plot()
  118. .. plot::
  119. :scale: 75
  120. >>> # Example plotting multiple values
  121. >>> import torch
  122. >>> from torchmetrics.audio import PermutationInvariantTraining
  123. >>> from torchmetrics.functional.audio import scale_invariant_signal_noise_ratio
  124. >>> preds = torch.randn(3, 2, 5) # [batch, spk, time]
  125. >>> target = torch.randn(3, 2, 5) # [batch, spk, time]
  126. >>> metric = PermutationInvariantTraining(scale_invariant_signal_noise_ratio,
  127. ... mode="speaker-wise", eval_func="max")
  128. >>> values = [ ]
  129. >>> for _ in range(10):
  130. ... values.append(metric(preds, target))
  131. >>> fig_, ax_ = metric.plot(values)
  132. """
  133. return self._plot(val, ax)