We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Small typo in PESQ docs
## 📚 Documentation

[Perceptual Evaluation Of Speech Quality (PESQ) documentation](https://torchmetrics.readthedocs.io/en/stable/audio/perceptual_evaluation_speech_quality.html) states following for both Module Interface and Functional Interface:
Raises ModuleNotFoundError – If **peqs** package is not installed.


--- 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/functional/audio/pesq.py`
Content:
```
1 # Copyright The PyTorch 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 import numpy as np
15 import torch
16 from torch import Tensor
17 
18 from torchmetrics.utilities.checks import _check_same_shape
19 from torchmetrics.utilities.imports import _MULTIPROCESSING_AVAILABLE, _PESQ_AVAILABLE
20 
21 if _PESQ_AVAILABLE:
22     import pesq as pesq_backend
23 else:
24     pesq_backend = None
25 
26 
27 __doctest_requires__ = {("perceptual_evaluation_speech_quality",): ["pesq"]}
28 
29 
30 def perceptual_evaluation_speech_quality(
31     preds: Tensor,
32     target: Tensor,
33     fs: int,
34     mode: str,
35     keep_same_device: bool = False,
36     n_processes: int = 1,
37 ) -> Tensor:
38     r"""Calculates `Perceptual Evaluation of Speech Quality`_ (PESQ). It's a recognized industry standard for audio
39     quality that takes into considerations characteristics such as: audio sharpness, call volume, background noise,
40     clipping, audio interference ect. PESQ returns a score between -0.5 and 4.5 with the higher scores indicating a
41     better quality.
42 
43     This metric is a wrapper for the `pesq package`_. Note that input will be moved to `cpu` to perform the metric
44     calculation.
45 
46     .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install
47         torchmetrics[audio]`` or ``pip install pesq``. Note that ``pesq`` will compile with your currently
48         installed version of numpy, meaning that if you upgrade numpy at some point in the future you will
49         most likely have to reinstall ``pesq``.
50 
51     Args:
52         preds: float tensor with shape ``(...,time)``
53         target: float tensor with shape ``(...,time)``
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 specifiying 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 
60     Returns:
61         Float tensor with shape ``(...,)`` of PESQ values per sample
62 
63     Raises:
64         ModuleNotFoundError:
65             If ``peqs`` package is not installed
66         ValueError:
67             If ``fs`` is not either  ``8000`` or ``16000``
68         ValueError:
69             If ``mode`` is not either ``"wb"`` or ``"nb"``
70         RuntimeError:
71             If ``preds`` and ``target`` does not have the same shape
72 
73     Example:
74         >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality
75         >>> import torch
76         >>> g = torch.manual_seed(1)
77         >>> preds = torch.randn(8000)
78         >>> target = torch.randn(8000)
79         >>> perceptual_evaluation_speech_quality(preds, target, 8000, 'nb')
80         tensor(2.2076)
81         >>> perceptual_evaluation_speech_quality(preds, target, 16000, 'wb')
82         tensor(1.7359)
83     """
84     if not _PESQ_AVAILABLE:
85         raise ModuleNotFoundError(
86             "PESQ metric requires that pesq is installed."
87             " Either install as `pip install torchmetrics[audio]` or `pip install pesq`."
88         )
89     if fs not in (8000, 16000):
90         raise ValueError(f"Expected argument `fs` to either be 8000 or 16000 but got {fs}")
91     if mode not in ("wb", "nb"):
92         raise ValueError(f"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}")
93     _check_same_shape(preds, target)
94 
95     if preds.ndim == 1:
96         pesq_val_np = pesq_backend.pesq(fs, target.detach().cpu().numpy(), preds.detach().cpu().numpy(), mode)
97         pesq_val = torch.tensor(pesq_val_np)
98     else:
99         preds_np = preds.reshape(-1, preds.shape[-1]).detach().cpu().numpy()
100         target_np = target.reshape(-1, preds.shape[-1]).detach().cpu().numpy()
101 
102         if _MULTIPROCESSING_AVAILABLE and n_processes != 1:
103             pesq_val_np = pesq_backend.pesq_batch(fs, target_np, preds_np, mode, n_processor=n_processes)
104             pesq_val_np = np.array(pesq_val_np)
105         else:
106             pesq_val_np = np.empty(shape=(preds_np.shape[0]))
107             for b in range(preds_np.shape[0]):
108                 pesq_val_np[b] = pesq_backend.pesq(fs, target_np[b, :], preds_np[b, :], mode)
109         pesq_val = torch.from_numpy(pesq_val_np)
110         pesq_val = pesq_val.reshape(preds.shape[:-1])
111 
112     if keep_same_device:
113         pesq_val = pesq_val.to(preds.device)
114 
115     return pesq_val
116
```

Path: `src/torchmetrics/audio/pesq.py`
Content:
```
1 # Copyright The PyTorch 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
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 _PESQ_AVAILABLE
21 
22 __doctest_requires__ = {"PerceptualEvaluationSpeechQuality": ["pesq"]}
23 
24 
25 class PerceptualEvaluationSpeechQuality(Metric):
26     """Calculates `Perceptual Evaluation of Speech Quality`_ (PESQ). It's a recognized industry standard for audio
27     quality that takes into considerations characteristics such as: audio sharpness, call volume, background noise,
28     clipping, audio interference ect. PESQ returns a score between -0.5 and 4.5 with the higher scores indicating a
29     better quality.
30 
31     This metric is a wrapper for the `pesq package`_. Note that input will be moved to ``cpu`` to perform the metric
32     calculation.
33 
34     As input to ``forward`` and ``update`` the metric accepts the following input
35 
36     - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
37     - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
38 
39     As output of `forward` and `compute` the metric returns the following output
40 
41     - ``pesq`` (:class:`~torch.Tensor`): float tensor with shape ``(...,)`` of PESQ value per sample
42 
43     .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install
44         torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently
45         installed version of numpy, meaning that if you upgrade numpy at some point in the future you will
46         most likely have to reinstall ``pesq``.
47 
48     Args:
49         fs: sampling frequency, should be 16000 or 8000 (Hz)
50         mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)
51         keep_same_device: whether to move the pesq value to the device of preds
52         n_processes: integer specifiying the number of processes to run in parallel for the metric calculation.
53             Only applies to batches of data and if ``multiprocessing`` package is installed.
54         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
55 
56     Raises:
57         ModuleNotFoundError:
58             If ``peqs`` package is not installed
59         ValueError:
60             If ``fs`` is not either  ``8000`` or ``16000``
61         ValueError:
62             If ``mode`` is not either ``"wb"`` or ``"nb"``
63 
64     Example:
65         >>> from torchmetrics.audio.pesq import PerceptualEvaluationSpeechQuality
66         >>> import torch
67         >>> g = torch.manual_seed(1)
68         >>> preds = torch.randn(8000)
69         >>> target = torch.randn(8000)
70         >>> nb_pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')
71         >>> nb_pesq(preds, target)
72         tensor(2.2076)
73         >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')
74         >>> wb_pesq(preds, target)
75         tensor(1.7359)
76     """
77 
78     sum_pesq: Tensor
79     total: Tensor
80     full_state_update: bool = False
81     is_differentiable: bool = False
82     higher_is_better: bool = True
83 
84     def __init__(
85         self,
86         fs: int,
87         mode: str,
88         n_processes: int = 1,
89         **kwargs: Any,
90     ) -> None:
91         super().__init__(**kwargs)
92         if not _PESQ_AVAILABLE:
93             raise ModuleNotFoundError(
94                 "PerceptualEvaluationSpeechQuality metric requires that `pesq` is installed."
95                 " Either install as `pip install torchmetrics[audio]` or `pip install pesq`."
96             )
97         if fs not in (8000, 16000):
98             raise ValueError(f"Expected argument `fs` to either be 8000 or 16000 but got {fs}")
99         self.fs = fs
100         if mode not in ("wb", "nb"):
101             raise ValueError(f"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}")
102         self.mode = mode
103         if not isinstance(n_processes, int) and n_processes <= 0:
104             raise ValueError(f"Expected argument `n_processes` to be an int larger than 0 but got {n_processes}")
105         self.n_processes = n_processes
106 
107         self.add_state("sum_pesq", default=tensor(0.0), dist_reduce_fx="sum")
108         self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
109 
110     def update(self, preds: Tensor, target: Tensor) -> None:
111         """Update state with predictions and targets."""
112         pesq_batch = perceptual_evaluation_speech_quality(
113             preds, target, self.fs, self.mode, False, self.n_processes
114         ).to(self.sum_pesq.device)
115 
116         self.sum_pesq += pesq_batch.sum()
117         self.total += pesq_batch.numel()
118 
119     def compute(self) -> Tensor:
120         """Computes metric."""
121         return self.sum_pesq / self.total
122
```
--- 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
@@ -55,7 +55,7 @@
 
     Raises:
         ModuleNotFoundError:
-            If ``peqs`` package is not installed
+            If ``pesq`` package is not installed
         ValueError:
             If ``fs`` is not either  ``8000`` or ``16000``
         ValueError:
diff --git a/src/torchmetrics/functional/audio/pesq.py b/src/torchmetrics/functional/audio/pesq.py
--- a/src/torchmetrics/functional/audio/pesq.py
+++ b/src/torchmetrics/functional/audio/pesq.py
@@ -62,13 +62,13 @@
 
     Raises:
         ModuleNotFoundError:
-            If ``peqs`` package is not installed
+            If ``pesq`` package is not installed
         ValueError:
             If ``fs`` is not either  ``8000`` or ``16000``
         ValueError:
             If ``mode`` is not either ``"wb"`` or ``"nb"``
         RuntimeError:
-            If ``preds`` and ``target`` does not have the same shape
+            If ``preds`` and ``target`` do not have the same shape
 
     Example:
         >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality

{"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@@ -55,7 +55,7 @@\n \n     Raises:\n         ModuleNotFoundError:\n-            If ``peqs`` package is not installed\n+            If ``pesq`` package is not installed\n         ValueError:\n             If ``fs`` is not either  ``8000`` or ``16000``\n         ValueError:\ndiff --git a/src/torchmetrics/functional/audio/pesq.py b/src/torchmetrics/functional/audio/pesq.py\n--- a/src/torchmetrics/functional/audio/pesq.py\n+++ b/src/torchmetrics/functional/audio/pesq.py\n@@ -62,13 +62,13 @@\n \n     Raises:\n         ModuleNotFoundError:\n-            If ``peqs`` package is not installed\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         RuntimeError:\n-            If ``preds`` and ``target`` does not have the same shape\n+            If ``preds`` and ``target`` do not have the same shape\n \n     Example:\n         >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality\n", "issue": "Small typo in PESQ docs\n## \ud83d\udcda Documentation\r\n\r\n[Perceptual Evaluation Of Speech Quality (PESQ) documentation](https://torchmetrics.readthedocs.io/en/stable/audio/perceptual_evaluation_speech_quality.html) states following for both Module Interface and Functional Interface:\r\nRaises ModuleNotFoundError \u2013 If **peqs** package is not installed.\r\n\n", "before_files": [{"content": "# Copyright The PyTorch 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.\nimport numpy as np\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.utilities.checks import _check_same_shape\nfrom torchmetrics.utilities.imports import _MULTIPROCESSING_AVAILABLE, _PESQ_AVAILABLE\n\nif _PESQ_AVAILABLE:\n    import pesq as pesq_backend\nelse:\n    pesq_backend = None\n\n\n__doctest_requires__ = {(\"perceptual_evaluation_speech_quality\",): [\"pesq\"]}\n\n\ndef perceptual_evaluation_speech_quality(\n    preds: Tensor,\n    target: Tensor,\n    fs: int,\n    mode: str,\n    keep_same_device: bool = False,\n    n_processes: int = 1,\n) -> Tensor:\n    r\"\"\"Calculates `Perceptual Evaluation of Speech Quality`_ (PESQ). It's a recognized industry standard for audio\n    quality that takes into considerations characteristics such as: audio sharpness, call volume, background noise,\n    clipping, audio interference ect. PESQ returns a score between -0.5 and 4.5 with the higher scores indicating a\n    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    .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install\n        torchmetrics[audio]`` or ``pip install pesq``. Note that ``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        preds: float tensor with shape ``(...,time)``\n        target: float tensor with shape ``(...,time)``\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 specifiying 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\n    Returns:\n        Float tensor with shape ``(...,)`` of PESQ values per sample\n\n    Raises:\n        ModuleNotFoundError:\n            If ``peqs`` 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        RuntimeError:\n            If ``preds`` and ``target`` does not have the same shape\n\n    Example:\n        >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality\n        >>> import torch\n        >>> g = torch.manual_seed(1)\n        >>> preds = torch.randn(8000)\n        >>> target = torch.randn(8000)\n        >>> perceptual_evaluation_speech_quality(preds, target, 8000, 'nb')\n        tensor(2.2076)\n        >>> perceptual_evaluation_speech_quality(preds, target, 16000, 'wb')\n        tensor(1.7359)\n    \"\"\"\n    if not _PESQ_AVAILABLE:\n        raise ModuleNotFoundError(\n            \"PESQ 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    if mode not in (\"wb\", \"nb\"):\n        raise ValueError(f\"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}\")\n    _check_same_shape(preds, target)\n\n    if preds.ndim == 1:\n        pesq_val_np = pesq_backend.pesq(fs, target.detach().cpu().numpy(), preds.detach().cpu().numpy(), mode)\n        pesq_val = torch.tensor(pesq_val_np)\n    else:\n        preds_np = preds.reshape(-1, preds.shape[-1]).detach().cpu().numpy()\n        target_np = target.reshape(-1, preds.shape[-1]).detach().cpu().numpy()\n\n        if _MULTIPROCESSING_AVAILABLE and n_processes != 1:\n            pesq_val_np = pesq_backend.pesq_batch(fs, target_np, preds_np, mode, n_processor=n_processes)\n            pesq_val_np = np.array(pesq_val_np)\n        else:\n            pesq_val_np = np.empty(shape=(preds_np.shape[0]))\n            for b in range(preds_np.shape[0]):\n                pesq_val_np[b] = pesq_backend.pesq(fs, target_np[b, :], preds_np[b, :], mode)\n        pesq_val = torch.from_numpy(pesq_val_np)\n        pesq_val = pesq_val.reshape(preds.shape[:-1])\n\n    if keep_same_device:\n        pesq_val = pesq_val.to(preds.device)\n\n    return pesq_val\n", "path": "src/torchmetrics/functional/audio/pesq.py"}, {"content": "# Copyright The PyTorch 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\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 _PESQ_AVAILABLE\n\n__doctest_requires__ = {\"PerceptualEvaluationSpeechQuality\": [\"pesq\"]}\n\n\nclass PerceptualEvaluationSpeechQuality(Metric):\n    \"\"\"Calculates `Perceptual Evaluation of Speech Quality`_ (PESQ). It's a recognized industry standard for audio\n    quality that takes into considerations characteristics such as: audio sharpness, call volume, background noise,\n    clipping, audio interference ect. PESQ returns a score between -0.5 and 4.5 with the higher scores indicating a\n    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 specifiying 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 ``peqs`` 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        >>> from torchmetrics.audio.pesq import PerceptualEvaluationSpeechQuality\n        >>> import torch\n        >>> g = torch.manual_seed(1)\n        >>> preds = torch.randn(8000)\n        >>> target = torch.randn(8000)\n        >>> nb_pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')\n        >>> nb_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    sum_pesq: Tensor\n    total: Tensor\n    full_state_update: bool = False\n    is_differentiable: bool = False\n    higher_is_better: bool = True\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        \"\"\"Computes metric.\"\"\"\n        return self.sum_pesq / self.total\n", "path": "src/torchmetrics/audio/pesq.py"}], "after_files": [{"content": "# Copyright The PyTorch 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.\nimport numpy as np\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.utilities.checks import _check_same_shape\nfrom torchmetrics.utilities.imports import _MULTIPROCESSING_AVAILABLE, _PESQ_AVAILABLE\n\nif _PESQ_AVAILABLE:\n    import pesq as pesq_backend\nelse:\n    pesq_backend = None\n\n\n__doctest_requires__ = {(\"perceptual_evaluation_speech_quality\",): [\"pesq\"]}\n\n\ndef perceptual_evaluation_speech_quality(\n    preds: Tensor,\n    target: Tensor,\n    fs: int,\n    mode: str,\n    keep_same_device: bool = False,\n    n_processes: int = 1,\n) -> Tensor:\n    r\"\"\"Calculates `Perceptual Evaluation of Speech Quality`_ (PESQ). It's a recognized industry standard for audio\n    quality that takes into considerations characteristics such as: audio sharpness, call volume, background noise,\n    clipping, audio interference ect. PESQ returns a score between -0.5 and 4.5 with the higher scores indicating a\n    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    .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install\n        torchmetrics[audio]`` or ``pip install pesq``. Note that ``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        preds: float tensor with shape ``(...,time)``\n        target: float tensor with shape ``(...,time)``\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 specifiying 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\n    Returns:\n        Float tensor with shape ``(...,)`` of PESQ values per sample\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        RuntimeError:\n            If ``preds`` and ``target`` do not have the same shape\n\n    Example:\n        >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality\n        >>> import torch\n        >>> g = torch.manual_seed(1)\n        >>> preds = torch.randn(8000)\n        >>> target = torch.randn(8000)\n        >>> perceptual_evaluation_speech_quality(preds, target, 8000, 'nb')\n        tensor(2.2076)\n        >>> perceptual_evaluation_speech_quality(preds, target, 16000, 'wb')\n        tensor(1.7359)\n    \"\"\"\n    if not _PESQ_AVAILABLE:\n        raise ModuleNotFoundError(\n            \"PESQ 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    if mode not in (\"wb\", \"nb\"):\n        raise ValueError(f\"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}\")\n    _check_same_shape(preds, target)\n\n    if preds.ndim == 1:\n        pesq_val_np = pesq_backend.pesq(fs, target.detach().cpu().numpy(), preds.detach().cpu().numpy(), mode)\n        pesq_val = torch.tensor(pesq_val_np)\n    else:\n        preds_np = preds.reshape(-1, preds.shape[-1]).detach().cpu().numpy()\n        target_np = target.reshape(-1, preds.shape[-1]).detach().cpu().numpy()\n\n        if _MULTIPROCESSING_AVAILABLE and n_processes != 1:\n            pesq_val_np = pesq_backend.pesq_batch(fs, target_np, preds_np, mode, n_processor=n_processes)\n            pesq_val_np = np.array(pesq_val_np)\n        else:\n            pesq_val_np = np.empty(shape=(preds_np.shape[0]))\n            for b in range(preds_np.shape[0]):\n                pesq_val_np[b] = pesq_backend.pesq(fs, target_np[b, :], preds_np[b, :], mode)\n        pesq_val = torch.from_numpy(pesq_val_np)\n        pesq_val = pesq_val.reshape(preds.shape[:-1])\n\n    if keep_same_device:\n        pesq_val = pesq_val.to(preds.device)\n\n    return pesq_val\n", "path": "src/torchmetrics/functional/audio/pesq.py"}, {"content": "# Copyright The PyTorch 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\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 _PESQ_AVAILABLE\n\n__doctest_requires__ = {\"PerceptualEvaluationSpeechQuality\": [\"pesq\"]}\n\n\nclass PerceptualEvaluationSpeechQuality(Metric):\n    \"\"\"Calculates `Perceptual Evaluation of Speech Quality`_ (PESQ). It's a recognized industry standard for audio\n    quality that takes into considerations characteristics such as: audio sharpness, call volume, background noise,\n    clipping, audio interference ect. PESQ returns a score between -0.5 and 4.5 with the higher scores indicating a\n    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 specifiying 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        >>> from torchmetrics.audio.pesq import PerceptualEvaluationSpeechQuality\n        >>> import torch\n        >>> g = torch.manual_seed(1)\n        >>> preds = torch.randn(8000)\n        >>> target = torch.randn(8000)\n        >>> nb_pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')\n        >>> nb_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    sum_pesq: Tensor\n    total: Tensor\n    full_state_update: bool = False\n    is_differentiable: bool = False\n    higher_is_better: bool = True\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        \"\"\"Computes metric.\"\"\"\n        return self.sum_pesq / self.total\n", "path": "src/torchmetrics/audio/pesq.py"}]}