We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Inconsistent docs and code output for `PerceptualEvaluationSpeechQuality `
## 🐛 Bug
[related to #1092]

The [docs](https://torchmetrics.readthedocs.io/en/stable/audio/perceptual_evaluation_speech_quality.html) for PESQ metric class state that 
> As output of _forward_ and _compute_ the metric returns the following output `pesq` (Tensor): float tensor with shape (...,) of PESQ value per sample.

However, I always get one value, no matter the `batch_size`, as if the metric was being averaged.

### To Reproduce

```python
import torch 
from torchmetrics.audio import PerceptualEvaluationSpeechQuality as PESQ

pesq = PESQ(fs=16000, mode="wb")

# create data
batch_size = 4
audio_size = 12345
preds = torch.FloatTensor(batch_size, audio_size).uniform_(-1, 1)
target = torch.FloatTensor(batch_size, audio_size).uniform_(-1, 1)
print("preds.shape:", preds.shape)
#>preds.shape: torch.Size([4, 12345])

# compute metric
pesq_score = pesq.forward(preds, target)
print("pesq_score:", pesq_score)
#>pesq_score: tensor(1.5049)
```
I expected the output to be of shape `torch.Size([4])`.
Same behaviour for `pesq.update(preds, target)` followed by `pesq.compute()`.

The functional counterpart returns a result [as documented](https://torchmetrics.readthedocs.io/en/stable/audio/perceptual_evaluation_speech_quality.html#torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality):
```python
import torch 
from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality as F_PESQ

n = 4
preds = torch.FloatTensor(n, 12345).uniform_(-1, 1)
target = torch.FloatTensor(n, 12345).uniform_(-1, 1)

pesq_score = F_PESQ(preds=preds, target=target, fs=16000, mode="wb")
print("pesq_score:", pesq_score)
#> pesq_score: tensor([1.5882, 1.5080, 1.5149, 1.5997])
```

### Environment

```
Linux
python==3.10.12
torch==2.0.1
torchmetrics== 1.1.2
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/torchmetrics/audio/pesq.py`
Content:
```
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 typing import Any, Optional, Sequence, Union
15 
16 from torch import Tensor, tensor
17 
18 from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality
19 from torchmetrics.metric import Metric
20 from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _PESQ_AVAILABLE
21 from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
22 
23 __doctest_requires__ = {"PerceptualEvaluationSpeechQuality": ["pesq"]}
24 
25 if not _MATPLOTLIB_AVAILABLE:
26     __doctest_skip__ = ["PerceptualEvaluationSpeechQuality.plot"]
27 
28 
29 class PerceptualEvaluationSpeechQuality(Metric):
30     """Calculate `Perceptual Evaluation of Speech Quality`_ (PESQ).
31 
32     It's a recognized industry standard for audio quality that takes into considerations characteristics such as:
33     audio sharpness, call volume, background noise, clipping, audio interference etc. PESQ returns a score between
34     -0.5 and 4.5 with the higher scores indicating a better quality.
35 
36     This metric is a wrapper for the `pesq package`_. Note that input will be moved to ``cpu`` to perform the metric
37     calculation.
38 
39     As input to ``forward`` and ``update`` the metric accepts the following input
40 
41     - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
42     - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
43 
44     As output of `forward` and `compute` the metric returns the following output
45 
46     - ``pesq`` (:class:`~torch.Tensor`): float tensor with shape ``(...,)`` of PESQ value per sample
47 
48     .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install
49         torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently
50         installed version of numpy, meaning that if you upgrade numpy at some point in the future you will
51         most likely have to reinstall ``pesq``.
52 
53     Args:
54         fs: sampling frequency, should be 16000 or 8000 (Hz)
55         mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)
56         keep_same_device: whether to move the pesq value to the device of preds
57         n_processes: integer specifying the number of processes to run in parallel for the metric calculation.
58             Only applies to batches of data and if ``multiprocessing`` package is installed.
59         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
60 
61     Raises:
62         ModuleNotFoundError:
63             If ``pesq`` package is not installed
64         ValueError:
65             If ``fs`` is not either  ``8000`` or ``16000``
66         ValueError:
67             If ``mode`` is not either ``"wb"`` or ``"nb"``
68 
69     Example:
70         >>> import torch
71         >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
72         >>> g = torch.manual_seed(1)
73         >>> preds = torch.randn(8000)
74         >>> target = torch.randn(8000)
75         >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')
76         >>> pesq(preds, target)
77         tensor(2.2076)
78         >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')
79         >>> wb_pesq(preds, target)
80         tensor(1.7359)
81 
82     """
83 
84     sum_pesq: Tensor
85     total: Tensor
86     full_state_update: bool = False
87     is_differentiable: bool = False
88     higher_is_better: bool = True
89     plot_lower_bound: float = -0.5
90     plot_upper_bound: float = 4.5
91 
92     def __init__(
93         self,
94         fs: int,
95         mode: str,
96         n_processes: int = 1,
97         **kwargs: Any,
98     ) -> None:
99         super().__init__(**kwargs)
100         if not _PESQ_AVAILABLE:
101             raise ModuleNotFoundError(
102                 "PerceptualEvaluationSpeechQuality metric requires that `pesq` is installed."
103                 " Either install as `pip install torchmetrics[audio]` or `pip install pesq`."
104             )
105         if fs not in (8000, 16000):
106             raise ValueError(f"Expected argument `fs` to either be 8000 or 16000 but got {fs}")
107         self.fs = fs
108         if mode not in ("wb", "nb"):
109             raise ValueError(f"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}")
110         self.mode = mode
111         if not isinstance(n_processes, int) and n_processes <= 0:
112             raise ValueError(f"Expected argument `n_processes` to be an int larger than 0 but got {n_processes}")
113         self.n_processes = n_processes
114 
115         self.add_state("sum_pesq", default=tensor(0.0), dist_reduce_fx="sum")
116         self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
117 
118     def update(self, preds: Tensor, target: Tensor) -> None:
119         """Update state with predictions and targets."""
120         pesq_batch = perceptual_evaluation_speech_quality(
121             preds, target, self.fs, self.mode, False, self.n_processes
122         ).to(self.sum_pesq.device)
123 
124         self.sum_pesq += pesq_batch.sum()
125         self.total += pesq_batch.numel()
126 
127     def compute(self) -> Tensor:
128         """Compute metric."""
129         return self.sum_pesq / self.total
130 
131     def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
132         """Plot a single or multiple values from the metric.
133 
134         Args:
135             val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
136                 If no value is provided, will automatically call `metric.compute` and plot that result.
137             ax: An matplotlib axis object. If provided will add plot to that axis
138 
139         Returns:
140             Figure and Axes object
141 
142         Raises:
143             ModuleNotFoundError:
144                 If `matplotlib` is not installed
145 
146         .. plot::
147             :scale: 75
148 
149             >>> # Example plotting a single value
150             >>> import torch
151             >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
152             >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
153             >>> metric.update(torch.rand(8000), torch.rand(8000))
154             >>> fig_, ax_ = metric.plot()
155 
156         .. plot::
157             :scale: 75
158 
159             >>> # Example plotting multiple values
160             >>> import torch
161             >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
162             >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
163             >>> values = [ ]
164             >>> for _ in range(10):
165             ...     values.append(metric(torch.rand(8000), torch.rand(8000)))
166             >>> fig_, ax_ = metric.plot(values)
167 
168         """
169         return self._plot(val, ax)
170
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/torchmetrics/audio/pesq.py b/src/torchmetrics/audio/pesq.py
--- a/src/torchmetrics/audio/pesq.py
+++ b/src/torchmetrics/audio/pesq.py
@@ -43,13 +43,17 @@
 
     As output of `forward` and `compute` the metric returns the following output
 
-    - ``pesq`` (:class:`~torch.Tensor`): float tensor with shape ``(...,)`` of PESQ value per sample
+    - ``pesq`` (:class:`~torch.Tensor`): float tensor of PESQ value reduced across the batch
 
     .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install
         torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently
         installed version of numpy, meaning that if you upgrade numpy at some point in the future you will
         most likely have to reinstall ``pesq``.
 
+    .. note:: the ``forward`` and ``compute`` methods in this class return a single (reduced) PESQ value
+        for a batch. To obtain a PESQ value for each sample, you may use the functional counterpart in
+        :func:`~torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality`.
+
     Args:
         fs: sampling frequency, should be 16000 or 8000 (Hz)
         mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)

{"golden_diff": "diff --git a/src/torchmetrics/audio/pesq.py b/src/torchmetrics/audio/pesq.py\n--- a/src/torchmetrics/audio/pesq.py\n+++ b/src/torchmetrics/audio/pesq.py\n@@ -43,13 +43,17 @@\n \n     As output of `forward` and `compute` the metric returns the following output\n \n-    - ``pesq`` (:class:`~torch.Tensor`): float tensor with shape ``(...,)`` of PESQ value per sample\n+    - ``pesq`` (:class:`~torch.Tensor`): float tensor of PESQ value reduced across the batch\n \n     .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install\n         torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently\n         installed version of numpy, meaning that if you upgrade numpy at some point in the future you will\n         most likely have to reinstall ``pesq``.\n \n+    .. note:: the ``forward`` and ``compute`` methods in this class return a single (reduced) PESQ value\n+        for a batch. To obtain a PESQ value for each sample, you may use the functional counterpart in\n+        :func:`~torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality`.\n+\n     Args:\n         fs: sampling frequency, should be 16000 or 8000 (Hz)\n         mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)\n", "issue": "Inconsistent docs and code output for `PerceptualEvaluationSpeechQuality `\n## \ud83d\udc1b Bug\r\n[related to #1092]\r\n\r\nThe [docs](https://torchmetrics.readthedocs.io/en/stable/audio/perceptual_evaluation_speech_quality.html) for PESQ metric class state that \r\n> As output of _forward_ and _compute_ the metric returns the following output `pesq` (Tensor): float tensor with shape (...,) of PESQ value per sample.\r\n\r\nHowever, I always get one value, no matter the `batch_size`, as if the metric was being averaged.\r\n\r\n### To Reproduce\r\n\r\n```python\r\nimport torch \r\nfrom torchmetrics.audio import PerceptualEvaluationSpeechQuality as PESQ\r\n\r\npesq = PESQ(fs=16000, mode=\"wb\")\r\n\r\n# create data\r\nbatch_size = 4\r\naudio_size = 12345\r\npreds = torch.FloatTensor(batch_size, audio_size).uniform_(-1, 1)\r\ntarget = torch.FloatTensor(batch_size, audio_size).uniform_(-1, 1)\r\nprint(\"preds.shape:\", preds.shape)\r\n#>preds.shape: torch.Size([4, 12345])\r\n\r\n# compute metric\r\npesq_score = pesq.forward(preds, target)\r\nprint(\"pesq_score:\", pesq_score)\r\n#>pesq_score: tensor(1.5049)\r\n```\r\nI expected the output to be of shape `torch.Size([4])`.\r\nSame behaviour for `pesq.update(preds, target)` followed by `pesq.compute()`.\r\n\r\nThe functional counterpart returns a result [as documented](https://torchmetrics.readthedocs.io/en/stable/audio/perceptual_evaluation_speech_quality.html#torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality):\r\n```python\r\nimport torch \r\nfrom torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality as F_PESQ\r\n\r\nn = 4\r\npreds = torch.FloatTensor(n, 12345).uniform_(-1, 1)\r\ntarget = torch.FloatTensor(n, 12345).uniform_(-1, 1)\r\n\r\npesq_score = F_PESQ(preds=preds, target=target, fs=16000, mode=\"wb\")\r\nprint(\"pesq_score:\", pesq_score)\r\n#> pesq_score: tensor([1.5882, 1.5080, 1.5149, 1.5997])\r\n```\r\n\r\n### Environment\r\n\r\n```\r\nLinux\r\npython==3.10.12\r\ntorch==2.0.1\r\ntorchmetrics== 1.1.2\r\n```\n", "before_files": [{"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, Optional, Sequence, Union\n\nfrom torch import Tensor, tensor\n\nfrom torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _PESQ_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\n__doctest_requires__ = {\"PerceptualEvaluationSpeechQuality\": [\"pesq\"]}\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"PerceptualEvaluationSpeechQuality.plot\"]\n\n\nclass PerceptualEvaluationSpeechQuality(Metric):\n    \"\"\"Calculate `Perceptual Evaluation of Speech Quality`_ (PESQ).\n\n    It's a recognized industry standard for audio quality that takes into considerations characteristics such as:\n    audio sharpness, call volume, background noise, clipping, audio interference etc. PESQ returns a score between\n    -0.5 and 4.5 with the higher scores indicating a better quality.\n\n    This metric is a wrapper for the `pesq package`_. Note that input will be moved to ``cpu`` to perform the metric\n    calculation.\n\n    As input to ``forward`` and ``update`` the metric accepts the following input\n\n    - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``\n    - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``\n\n    As output of `forward` and `compute` the metric returns the following output\n\n    - ``pesq`` (:class:`~torch.Tensor`): float tensor with shape ``(...,)`` of PESQ value per sample\n\n    .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install\n        torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently\n        installed version of numpy, meaning that if you upgrade numpy at some point in the future you will\n        most likely have to reinstall ``pesq``.\n\n    Args:\n        fs: sampling frequency, should be 16000 or 8000 (Hz)\n        mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)\n        keep_same_device: whether to move the pesq value to the device of preds\n        n_processes: integer specifying the number of processes to run in parallel for the metric calculation.\n            Only applies to batches of data and if ``multiprocessing`` package is installed.\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Raises:\n        ModuleNotFoundError:\n            If ``pesq`` package is not installed\n        ValueError:\n            If ``fs`` is not either  ``8000`` or ``16000``\n        ValueError:\n            If ``mode`` is not either ``\"wb\"`` or ``\"nb\"``\n\n    Example:\n        >>> import torch\n        >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality\n        >>> g = torch.manual_seed(1)\n        >>> preds = torch.randn(8000)\n        >>> target = torch.randn(8000)\n        >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')\n        >>> pesq(preds, target)\n        tensor(2.2076)\n        >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')\n        >>> wb_pesq(preds, target)\n        tensor(1.7359)\n\n    \"\"\"\n\n    sum_pesq: Tensor\n    total: Tensor\n    full_state_update: bool = False\n    is_differentiable: bool = False\n    higher_is_better: bool = True\n    plot_lower_bound: float = -0.5\n    plot_upper_bound: float = 4.5\n\n    def __init__(\n        self,\n        fs: int,\n        mode: str,\n        n_processes: int = 1,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        if not _PESQ_AVAILABLE:\n            raise ModuleNotFoundError(\n                \"PerceptualEvaluationSpeechQuality metric requires that `pesq` is installed.\"\n                \" Either install as `pip install torchmetrics[audio]` or `pip install pesq`.\"\n            )\n        if fs not in (8000, 16000):\n            raise ValueError(f\"Expected argument `fs` to either be 8000 or 16000 but got {fs}\")\n        self.fs = fs\n        if mode not in (\"wb\", \"nb\"):\n            raise ValueError(f\"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}\")\n        self.mode = mode\n        if not isinstance(n_processes, int) and n_processes <= 0:\n            raise ValueError(f\"Expected argument `n_processes` to be an int larger than 0 but got {n_processes}\")\n        self.n_processes = n_processes\n\n        self.add_state(\"sum_pesq\", default=tensor(0.0), dist_reduce_fx=\"sum\")\n        self.add_state(\"total\", default=tensor(0), dist_reduce_fx=\"sum\")\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update state with predictions and targets.\"\"\"\n        pesq_batch = perceptual_evaluation_speech_quality(\n            preds, target, self.fs, self.mode, False, self.n_processes\n        ).to(self.sum_pesq.device)\n\n        self.sum_pesq += pesq_batch.sum()\n        self.total += pesq_batch.numel()\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute metric.\"\"\"\n        return self.sum_pesq / self.total\n\n    def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:\n        \"\"\"Plot a single or multiple values from the metric.\n\n        Args:\n            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.\n                If no value is provided, will automatically call `metric.compute` and plot that result.\n            ax: An matplotlib axis object. If provided will add plot to that axis\n\n        Returns:\n            Figure and Axes object\n\n        Raises:\n            ModuleNotFoundError:\n                If `matplotlib` is not installed\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting a single value\n            >>> import torch\n            >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality\n            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')\n            >>> metric.update(torch.rand(8000), torch.rand(8000))\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting multiple values\n            >>> import torch\n            >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality\n            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')\n            >>> values = [ ]\n            >>> for _ in range(10):\n            ...     values.append(metric(torch.rand(8000), torch.rand(8000)))\n            >>> fig_, ax_ = metric.plot(values)\n\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/audio/pesq.py"}], "after_files": [{"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, Optional, Sequence, Union\n\nfrom torch import Tensor, tensor\n\nfrom torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _PESQ_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\n__doctest_requires__ = {\"PerceptualEvaluationSpeechQuality\": [\"pesq\"]}\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"PerceptualEvaluationSpeechQuality.plot\"]\n\n\nclass PerceptualEvaluationSpeechQuality(Metric):\n    \"\"\"Calculate `Perceptual Evaluation of Speech Quality`_ (PESQ).\n\n    It's a recognized industry standard for audio quality that takes into considerations characteristics such as:\n    audio sharpness, call volume, background noise, clipping, audio interference etc. PESQ returns a score between\n    -0.5 and 4.5 with the higher scores indicating a better quality.\n\n    This metric is a wrapper for the `pesq package`_. Note that input will be moved to ``cpu`` to perform the metric\n    calculation.\n\n    As input to ``forward`` and ``update`` the metric accepts the following input\n\n    - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``\n    - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``\n\n    As output of `forward` and `compute` the metric returns the following output\n\n    - ``pesq`` (:class:`~torch.Tensor`): float tensor of PESQ value reduced across the batch\n\n    .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install\n        torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently\n        installed version of numpy, meaning that if you upgrade numpy at some point in the future you will\n        most likely have to reinstall ``pesq``.\n\n    .. note:: the ``forward`` and ``compute`` methods in this class return a single (reduced) PESQ value\n        for a batch. To obtain a PESQ value for each sample, you may use the functional counterpart in\n        :func:`~torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality`.\n\n    Args:\n        fs: sampling frequency, should be 16000 or 8000 (Hz)\n        mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)\n        keep_same_device: whether to move the pesq value to the device of preds\n        n_processes: integer specifying the number of processes to run in parallel for the metric calculation.\n            Only applies to batches of data and if ``multiprocessing`` package is installed.\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Raises:\n        ModuleNotFoundError:\n            If ``pesq`` package is not installed\n        ValueError:\n            If ``fs`` is not either  ``8000`` or ``16000``\n        ValueError:\n            If ``mode`` is not either ``\"wb\"`` or ``\"nb\"``\n\n    Example:\n        >>> import torch\n        >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality\n        >>> g = torch.manual_seed(1)\n        >>> preds = torch.randn(8000)\n        >>> target = torch.randn(8000)\n        >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')\n        >>> pesq(preds, target)\n        tensor(2.2076)\n        >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')\n        >>> wb_pesq(preds, target)\n        tensor(1.7359)\n\n    \"\"\"\n\n    sum_pesq: Tensor\n    total: Tensor\n    full_state_update: bool = False\n    is_differentiable: bool = False\n    higher_is_better: bool = True\n    plot_lower_bound: float = -0.5\n    plot_upper_bound: float = 4.5\n\n    def __init__(\n        self,\n        fs: int,\n        mode: str,\n        n_processes: int = 1,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        if not _PESQ_AVAILABLE:\n            raise ModuleNotFoundError(\n                \"PerceptualEvaluationSpeechQuality metric requires that `pesq` is installed.\"\n                \" Either install as `pip install torchmetrics[audio]` or `pip install pesq`.\"\n            )\n        if fs not in (8000, 16000):\n            raise ValueError(f\"Expected argument `fs` to either be 8000 or 16000 but got {fs}\")\n        self.fs = fs\n        if mode not in (\"wb\", \"nb\"):\n            raise ValueError(f\"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}\")\n        self.mode = mode\n        if not isinstance(n_processes, int) and n_processes <= 0:\n            raise ValueError(f\"Expected argument `n_processes` to be an int larger than 0 but got {n_processes}\")\n        self.n_processes = n_processes\n\n        self.add_state(\"sum_pesq\", default=tensor(0.0), dist_reduce_fx=\"sum\")\n        self.add_state(\"total\", default=tensor(0), dist_reduce_fx=\"sum\")\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update state with predictions and targets.\"\"\"\n        pesq_batch = perceptual_evaluation_speech_quality(\n            preds, target, self.fs, self.mode, False, self.n_processes\n        ).to(self.sum_pesq.device)\n\n        self.sum_pesq += pesq_batch.sum()\n        self.total += pesq_batch.numel()\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute metric.\"\"\"\n        return self.sum_pesq / self.total\n\n    def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:\n        \"\"\"Plot a single or multiple values from the metric.\n\n        Args:\n            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.\n                If no value is provided, will automatically call `metric.compute` and plot that result.\n            ax: An matplotlib axis object. If provided will add plot to that axis\n\n        Returns:\n            Figure and Axes object\n\n        Raises:\n            ModuleNotFoundError:\n                If `matplotlib` is not installed\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting a single value\n            >>> import torch\n            >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality\n            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')\n            >>> metric.update(torch.rand(8000), torch.rand(8000))\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting multiple values\n            >>> import torch\n            >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality\n            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')\n            >>> values = [ ]\n            >>> for _ in range(10):\n            ...     values.append(metric(torch.rand(8000), torch.rand(8000)))\n            >>> fig_, ax_ = metric.plot(values)\n\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/audio/pesq.py"}]}