We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
`MultioutputWrapper` does not squeeze `kwargs`
Hi there,

`MultioutputWrapper` class provides the option `squeeze_outputs`. If this is set the output should be squeezed on the index select dimension.
Altough this happens for the `args` it does not happen for `kwargs`

Here is are the where it happens, but it is only done for the `args` not for the `kwargs`.
https://github.com/Lightning-AI/torchmetrics/blob/af52ba6a422e9f8c99853396d78882015a3c6fe3/src/torchmetrics/wrappers/multioutput.py#L105-L108

Should be a one-line change. if needed i can provide an PR

Greetings Andi

--- 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/wrappers/multioutput.py`
Content:
```
1 from copy import deepcopy
2 from typing import Any, Callable, List, Optional, Sequence, Tuple, Union
3 
4 import torch
5 from torch import Tensor
6 from torch.nn import ModuleList
7 
8 from torchmetrics import Metric
9 from torchmetrics.utilities import apply_to_collection
10 from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
11 from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
12 
13 if not _MATPLOTLIB_AVAILABLE:
14     __doctest_skip__ = ["MultioutputWrapper.plot"]
15 
16 
17 def _get_nan_indices(*tensors: Tensor) -> Tensor:
18     """Get indices of rows along dim 0 which have NaN values."""
19     if len(tensors) == 0:
20         raise ValueError("Must pass at least one tensor as argument")
21     sentinel = tensors[0]
22     nan_idxs = torch.zeros(len(sentinel), dtype=torch.bool, device=sentinel.device)
23     for tensor in tensors:
24         permuted_tensor = tensor.flatten(start_dim=1)
25         nan_idxs |= torch.any(torch.isnan(permuted_tensor), dim=1)
26     return nan_idxs
27 
28 
29 class MultioutputWrapper(Metric):
30     """Wrap a base metric to enable it to support multiple outputs.
31 
32     Several torchmetrics metrics, such as :class:`torchmetrics.regression.spearman.SpearmanCorrcoef` lack support for
33     multioutput mode. This class wraps such metrics to support computing one metric per output.
34     Unlike specific torchmetric metrics, it doesn't support any aggregation across outputs.
35     This means if you set ``num_outputs`` to 2, ``.compute()`` will return a Tensor of dimension
36     ``(2, ...)`` where ``...`` represents the dimensions the metric returns when not wrapped.
37 
38     In addition to enabling multioutput support for metrics that lack it, this class also supports, albeit in a crude
39     fashion, dealing with missing labels (or other data). When ``remove_nans`` is passed, the class will remove the
40     intersection of NaN containing "rows" upon each update for each output. For example, suppose a user uses
41     `MultioutputWrapper` to wrap :class:`torchmetrics.regression.r2.R2Score` with 2 outputs, one of which occasionally
42     has missing labels for classes like ``R2Score`` is that this class supports removing ``NaN`` values
43     (parameter ``remove_nans``) on a per-output basis. When ``remove_nans`` is passed the wrapper will remove all rows
44 
45     Args:
46         base_metric: Metric being wrapped.
47         num_outputs: Expected dimensionality of the output dimension.
48             This parameter is used to determine the number of distinct metrics we need to track.
49         output_dim:
50             Dimension on which output is expected. Note that while this provides some flexibility, the output dimension
51             must be the same for all inputs to update. This applies even for metrics such as `Accuracy` where the labels
52             can have a different number of dimensions than the predictions. This can be worked around if the output
53             dimension can be set to -1 for both, even if -1 corresponds to different dimensions in different inputs.
54         remove_nans:
55             Whether to remove the intersection of rows containing NaNs from the values passed through to each underlying
56             metric. Proper operation requires all tensors passed to update to have dimension ``(N, ...)`` where N
57             represents the length of the batch or dataset being passed in.
58         squeeze_outputs:
59             If ``True``, will squeeze the 1-item dimensions left after ``index_select`` is applied.
60             This is sometimes unnecessary but harmless for metrics such as `R2Score` but useful
61             for certain classification metrics that can't handle additional 1-item dimensions.
62 
63     Example:
64          >>> # Mimic R2Score in `multioutput`, `raw_values` mode:
65          >>> import torch
66          >>> from torchmetrics.wrappers import MultioutputWrapper
67          >>> from torchmetrics.regression import R2Score
68          >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
69          >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
70          >>> r2score = MultioutputWrapper(R2Score(), 2)
71          >>> r2score(preds, target)
72          tensor([0.9654, 0.9082])
73     """
74 
75     is_differentiable = False
76 
77     def __init__(
78         self,
79         base_metric: Metric,
80         num_outputs: int,
81         output_dim: int = -1,
82         remove_nans: bool = True,
83         squeeze_outputs: bool = True,
84     ) -> None:
85         super().__init__()
86         self.metrics = ModuleList([deepcopy(base_metric) for _ in range(num_outputs)])
87         self.output_dim = output_dim
88         self.remove_nans = remove_nans
89         self.squeeze_outputs = squeeze_outputs
90 
91     def _get_args_kwargs_by_output(self, *args: Tensor, **kwargs: Tensor) -> List[Tuple[Tensor, Tensor]]:
92         """Get args and kwargs reshaped to be output-specific and (maybe) having NaNs stripped out."""
93         args_kwargs_by_output = []
94         for i in range(len(self.metrics)):
95             selected_args = apply_to_collection(
96                 args, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device)
97             )
98             selected_kwargs = apply_to_collection(
99                 kwargs, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device)
100             )
101             if self.remove_nans:
102                 args_kwargs = selected_args + tuple(selected_kwargs.values())
103                 nan_idxs = _get_nan_indices(*args_kwargs)
104                 selected_args = [arg[~nan_idxs] for arg in selected_args]
105                 selected_kwargs = {k: v[~nan_idxs] for k, v in selected_kwargs.items()}
106 
107             if self.squeeze_outputs:
108                 selected_args = [arg.squeeze(self.output_dim) for arg in selected_args]
109             args_kwargs_by_output.append((selected_args, selected_kwargs))
110         return args_kwargs_by_output
111 
112     def update(self, *args: Any, **kwargs: Any) -> None:
113         """Update each underlying metric with the corresponding output."""
114         reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs)
115         for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs):
116             metric.update(*selected_args, **selected_kwargs)
117 
118     def compute(self) -> Tensor:
119         """Compute metrics."""
120         return torch.stack([m.compute() for m in self.metrics], 0)
121 
122     @torch.jit.unused
123     def forward(self, *args: Any, **kwargs: Any) -> Any:
124         """Call underlying forward methods and aggregate the results if they're non-null.
125 
126         We override this method to ensure that state variables get copied over on the underlying metrics.
127         """
128         results = []
129         reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs)
130         for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs):
131             results.append(metric(*selected_args, **selected_kwargs))
132         if results[0] is None:
133             return None
134         return torch.stack(results, 0)
135 
136     def reset(self) -> None:
137         """Reset all underlying metrics."""
138         for metric in self.metrics:
139             metric.reset()
140         super().reset()
141 
142     def _wrap_update(self, update: Callable) -> Callable:
143         """Overwrite to do nothing."""
144         return update
145 
146     def _wrap_compute(self, compute: Callable) -> Callable:
147         """Overwrite to do nothing."""
148         return compute
149 
150     def plot(
151         self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
152     ) -> _PLOT_OUT_TYPE:
153         """Plot a single or multiple values from the metric.
154 
155         Args:
156             val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
157                 If no value is provided, will automatically call `metric.compute` and plot that result.
158             ax: An matplotlib axis object. If provided will add plot to that axis
159 
160         Returns:
161             Figure and Axes object
162 
163         Raises:
164             ModuleNotFoundError:
165                 If `matplotlib` is not installed
166 
167         .. plot::
168             :scale: 75
169 
170             >>> # Example plotting a single value
171             >>> import torch
172             >>> from torchmetrics import MultioutputWrapper, R2Score
173             >>> metric = MultioutputWrapper(R2Score(), 2)
174             >>> metric.update(torch.randn(20, 2), torch.randn(20, 2))
175             >>> fig_, ax_ = metric.plot()
176 
177         .. plot::
178             :scale: 75
179 
180             >>> # Example plotting multiple values
181             >>> import torch
182             >>> from torchmetrics import MultioutputWrapper, R2Score
183             >>> metric = MultioutputWrapper(R2Score(), 2)
184             >>> values = [ ]
185             >>> for _ in range(3):
186             ...     values.append(metric(torch.randn(20, 2), torch.randn(20, 2)))
187             >>> fig_, ax_ = metric.plot(values)
188         """
189         return self._plot(val, ax)
190
```
--- 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/wrappers/multioutput.py b/src/torchmetrics/wrappers/multioutput.py
--- a/src/torchmetrics/wrappers/multioutput.py
+++ b/src/torchmetrics/wrappers/multioutput.py
@@ -106,6 +106,7 @@
 
             if self.squeeze_outputs:
                 selected_args = [arg.squeeze(self.output_dim) for arg in selected_args]
+                selected_kwargs = {k: v.squeeze(self.output_dim) for k, v in selected_kwargs.items()}
             args_kwargs_by_output.append((selected_args, selected_kwargs))
         return args_kwargs_by_output

{"golden_diff": "diff --git a/src/torchmetrics/wrappers/multioutput.py b/src/torchmetrics/wrappers/multioutput.py\n--- a/src/torchmetrics/wrappers/multioutput.py\n+++ b/src/torchmetrics/wrappers/multioutput.py\n@@ -106,6 +106,7 @@\n \n             if self.squeeze_outputs:\n                 selected_args = [arg.squeeze(self.output_dim) for arg in selected_args]\n+                selected_kwargs = {k: v.squeeze(self.output_dim) for k, v in selected_kwargs.items()}\n             args_kwargs_by_output.append((selected_args, selected_kwargs))\n         return args_kwargs_by_output\n", "issue": "`MultioutputWrapper` does not squeeze `kwargs`\nHi there,\r\n\r\n`MultioutputWrapper` class provides the option `squeeze_outputs`. If this is set the output should be squeezed on the index select dimension.\r\nAltough this happens for the `args` it does not happen for `kwargs`\r\n\r\nHere is are the where it happens, but it is only done for the `args` not for the `kwargs`.\r\nhttps://github.com/Lightning-AI/torchmetrics/blob/af52ba6a422e9f8c99853396d78882015a3c6fe3/src/torchmetrics/wrappers/multioutput.py#L105-L108\r\n\r\nShould be a one-line change. if needed i can provide an PR\r\n\r\nGreetings Andi\n", "before_files": [{"content": "from copy import deepcopy\nfrom typing import Any, Callable, List, Optional, Sequence, Tuple, Union\n\nimport torch\nfrom torch import Tensor\nfrom torch.nn import ModuleList\n\nfrom torchmetrics import Metric\nfrom torchmetrics.utilities import apply_to_collection\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"MultioutputWrapper.plot\"]\n\n\ndef _get_nan_indices(*tensors: Tensor) -> Tensor:\n    \"\"\"Get indices of rows along dim 0 which have NaN values.\"\"\"\n    if len(tensors) == 0:\n        raise ValueError(\"Must pass at least one tensor as argument\")\n    sentinel = tensors[0]\n    nan_idxs = torch.zeros(len(sentinel), dtype=torch.bool, device=sentinel.device)\n    for tensor in tensors:\n        permuted_tensor = tensor.flatten(start_dim=1)\n        nan_idxs |= torch.any(torch.isnan(permuted_tensor), dim=1)\n    return nan_idxs\n\n\nclass MultioutputWrapper(Metric):\n    \"\"\"Wrap a base metric to enable it to support multiple outputs.\n\n    Several torchmetrics metrics, such as :class:`torchmetrics.regression.spearman.SpearmanCorrcoef` lack support for\n    multioutput mode. This class wraps such metrics to support computing one metric per output.\n    Unlike specific torchmetric metrics, it doesn't support any aggregation across outputs.\n    This means if you set ``num_outputs`` to 2, ``.compute()`` will return a Tensor of dimension\n    ``(2, ...)`` where ``...`` represents the dimensions the metric returns when not wrapped.\n\n    In addition to enabling multioutput support for metrics that lack it, this class also supports, albeit in a crude\n    fashion, dealing with missing labels (or other data). When ``remove_nans`` is passed, the class will remove the\n    intersection of NaN containing \"rows\" upon each update for each output. For example, suppose a user uses\n    `MultioutputWrapper` to wrap :class:`torchmetrics.regression.r2.R2Score` with 2 outputs, one of which occasionally\n    has missing labels for classes like ``R2Score`` is that this class supports removing ``NaN`` values\n    (parameter ``remove_nans``) on a per-output basis. When ``remove_nans`` is passed the wrapper will remove all rows\n\n    Args:\n        base_metric: Metric being wrapped.\n        num_outputs: Expected dimensionality of the output dimension.\n            This parameter is used to determine the number of distinct metrics we need to track.\n        output_dim:\n            Dimension on which output is expected. Note that while this provides some flexibility, the output dimension\n            must be the same for all inputs to update. This applies even for metrics such as `Accuracy` where the labels\n            can have a different number of dimensions than the predictions. This can be worked around if the output\n            dimension can be set to -1 for both, even if -1 corresponds to different dimensions in different inputs.\n        remove_nans:\n            Whether to remove the intersection of rows containing NaNs from the values passed through to each underlying\n            metric. Proper operation requires all tensors passed to update to have dimension ``(N, ...)`` where N\n            represents the length of the batch or dataset being passed in.\n        squeeze_outputs:\n            If ``True``, will squeeze the 1-item dimensions left after ``index_select`` is applied.\n            This is sometimes unnecessary but harmless for metrics such as `R2Score` but useful\n            for certain classification metrics that can't handle additional 1-item dimensions.\n\n    Example:\n         >>> # Mimic R2Score in `multioutput`, `raw_values` mode:\n         >>> import torch\n         >>> from torchmetrics.wrappers import MultioutputWrapper\n         >>> from torchmetrics.regression import R2Score\n         >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])\n         >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])\n         >>> r2score = MultioutputWrapper(R2Score(), 2)\n         >>> r2score(preds, target)\n         tensor([0.9654, 0.9082])\n    \"\"\"\n\n    is_differentiable = False\n\n    def __init__(\n        self,\n        base_metric: Metric,\n        num_outputs: int,\n        output_dim: int = -1,\n        remove_nans: bool = True,\n        squeeze_outputs: bool = True,\n    ) -> None:\n        super().__init__()\n        self.metrics = ModuleList([deepcopy(base_metric) for _ in range(num_outputs)])\n        self.output_dim = output_dim\n        self.remove_nans = remove_nans\n        self.squeeze_outputs = squeeze_outputs\n\n    def _get_args_kwargs_by_output(self, *args: Tensor, **kwargs: Tensor) -> List[Tuple[Tensor, Tensor]]:\n        \"\"\"Get args and kwargs reshaped to be output-specific and (maybe) having NaNs stripped out.\"\"\"\n        args_kwargs_by_output = []\n        for i in range(len(self.metrics)):\n            selected_args = apply_to_collection(\n                args, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device)\n            )\n            selected_kwargs = apply_to_collection(\n                kwargs, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device)\n            )\n            if self.remove_nans:\n                args_kwargs = selected_args + tuple(selected_kwargs.values())\n                nan_idxs = _get_nan_indices(*args_kwargs)\n                selected_args = [arg[~nan_idxs] for arg in selected_args]\n                selected_kwargs = {k: v[~nan_idxs] for k, v in selected_kwargs.items()}\n\n            if self.squeeze_outputs:\n                selected_args = [arg.squeeze(self.output_dim) for arg in selected_args]\n            args_kwargs_by_output.append((selected_args, selected_kwargs))\n        return args_kwargs_by_output\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Update each underlying metric with the corresponding output.\"\"\"\n        reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs)\n        for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs):\n            metric.update(*selected_args, **selected_kwargs)\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute metrics.\"\"\"\n        return torch.stack([m.compute() for m in self.metrics], 0)\n\n    @torch.jit.unused\n    def forward(self, *args: Any, **kwargs: Any) -> Any:\n        \"\"\"Call underlying forward methods and aggregate the results if they're non-null.\n\n        We override this method to ensure that state variables get copied over on the underlying metrics.\n        \"\"\"\n        results = []\n        reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs)\n        for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs):\n            results.append(metric(*selected_args, **selected_kwargs))\n        if results[0] is None:\n            return None\n        return torch.stack(results, 0)\n\n    def reset(self) -> None:\n        \"\"\"Reset all underlying metrics.\"\"\"\n        for metric in self.metrics:\n            metric.reset()\n        super().reset()\n\n    def _wrap_update(self, update: Callable) -> Callable:\n        \"\"\"Overwrite to do nothing.\"\"\"\n        return update\n\n    def _wrap_compute(self, compute: Callable) -> Callable:\n        \"\"\"Overwrite to do nothing.\"\"\"\n        return compute\n\n    def plot(\n        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None\n    ) -> _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 import MultioutputWrapper, R2Score\n            >>> metric = MultioutputWrapper(R2Score(), 2)\n            >>> metric.update(torch.randn(20, 2), torch.randn(20, 2))\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting multiple values\n            >>> import torch\n            >>> from torchmetrics import MultioutputWrapper, R2Score\n            >>> metric = MultioutputWrapper(R2Score(), 2)\n            >>> values = [ ]\n            >>> for _ in range(3):\n            ...     values.append(metric(torch.randn(20, 2), torch.randn(20, 2)))\n            >>> fig_, ax_ = metric.plot(values)\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/wrappers/multioutput.py"}], "after_files": [{"content": "from copy import deepcopy\nfrom typing import Any, Callable, List, Optional, Sequence, Tuple, Union\n\nimport torch\nfrom torch import Tensor\nfrom torch.nn import ModuleList\n\nfrom torchmetrics import Metric\nfrom torchmetrics.utilities import apply_to_collection\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"MultioutputWrapper.plot\"]\n\n\ndef _get_nan_indices(*tensors: Tensor) -> Tensor:\n    \"\"\"Get indices of rows along dim 0 which have NaN values.\"\"\"\n    if len(tensors) == 0:\n        raise ValueError(\"Must pass at least one tensor as argument\")\n    sentinel = tensors[0]\n    nan_idxs = torch.zeros(len(sentinel), dtype=torch.bool, device=sentinel.device)\n    for tensor in tensors:\n        permuted_tensor = tensor.flatten(start_dim=1)\n        nan_idxs |= torch.any(torch.isnan(permuted_tensor), dim=1)\n    return nan_idxs\n\n\nclass MultioutputWrapper(Metric):\n    \"\"\"Wrap a base metric to enable it to support multiple outputs.\n\n    Several torchmetrics metrics, such as :class:`torchmetrics.regression.spearman.SpearmanCorrcoef` lack support for\n    multioutput mode. This class wraps such metrics to support computing one metric per output.\n    Unlike specific torchmetric metrics, it doesn't support any aggregation across outputs.\n    This means if you set ``num_outputs`` to 2, ``.compute()`` will return a Tensor of dimension\n    ``(2, ...)`` where ``...`` represents the dimensions the metric returns when not wrapped.\n\n    In addition to enabling multioutput support for metrics that lack it, this class also supports, albeit in a crude\n    fashion, dealing with missing labels (or other data). When ``remove_nans`` is passed, the class will remove the\n    intersection of NaN containing \"rows\" upon each update for each output. For example, suppose a user uses\n    `MultioutputWrapper` to wrap :class:`torchmetrics.regression.r2.R2Score` with 2 outputs, one of which occasionally\n    has missing labels for classes like ``R2Score`` is that this class supports removing ``NaN`` values\n    (parameter ``remove_nans``) on a per-output basis. When ``remove_nans`` is passed the wrapper will remove all rows\n\n    Args:\n        base_metric: Metric being wrapped.\n        num_outputs: Expected dimensionality of the output dimension.\n            This parameter is used to determine the number of distinct metrics we need to track.\n        output_dim:\n            Dimension on which output is expected. Note that while this provides some flexibility, the output dimension\n            must be the same for all inputs to update. This applies even for metrics such as `Accuracy` where the labels\n            can have a different number of dimensions than the predictions. This can be worked around if the output\n            dimension can be set to -1 for both, even if -1 corresponds to different dimensions in different inputs.\n        remove_nans:\n            Whether to remove the intersection of rows containing NaNs from the values passed through to each underlying\n            metric. Proper operation requires all tensors passed to update to have dimension ``(N, ...)`` where N\n            represents the length of the batch or dataset being passed in.\n        squeeze_outputs:\n            If ``True``, will squeeze the 1-item dimensions left after ``index_select`` is applied.\n            This is sometimes unnecessary but harmless for metrics such as `R2Score` but useful\n            for certain classification metrics that can't handle additional 1-item dimensions.\n\n    Example:\n         >>> # Mimic R2Score in `multioutput`, `raw_values` mode:\n         >>> import torch\n         >>> from torchmetrics.wrappers import MultioutputWrapper\n         >>> from torchmetrics.regression import R2Score\n         >>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])\n         >>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])\n         >>> r2score = MultioutputWrapper(R2Score(), 2)\n         >>> r2score(preds, target)\n         tensor([0.9654, 0.9082])\n    \"\"\"\n\n    is_differentiable = False\n\n    def __init__(\n        self,\n        base_metric: Metric,\n        num_outputs: int,\n        output_dim: int = -1,\n        remove_nans: bool = True,\n        squeeze_outputs: bool = True,\n    ) -> None:\n        super().__init__()\n        self.metrics = ModuleList([deepcopy(base_metric) for _ in range(num_outputs)])\n        self.output_dim = output_dim\n        self.remove_nans = remove_nans\n        self.squeeze_outputs = squeeze_outputs\n\n    def _get_args_kwargs_by_output(self, *args: Tensor, **kwargs: Tensor) -> List[Tuple[Tensor, Tensor]]:\n        \"\"\"Get args and kwargs reshaped to be output-specific and (maybe) having NaNs stripped out.\"\"\"\n        args_kwargs_by_output = []\n        for i in range(len(self.metrics)):\n            selected_args = apply_to_collection(\n                args, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device)\n            )\n            selected_kwargs = apply_to_collection(\n                kwargs, Tensor, torch.index_select, dim=self.output_dim, index=torch.tensor(i, device=self.device)\n            )\n            if self.remove_nans:\n                args_kwargs = selected_args + tuple(selected_kwargs.values())\n                nan_idxs = _get_nan_indices(*args_kwargs)\n                selected_args = [arg[~nan_idxs] for arg in selected_args]\n                selected_kwargs = {k: v[~nan_idxs] for k, v in selected_kwargs.items()}\n\n            if self.squeeze_outputs:\n                selected_args = [arg.squeeze(self.output_dim) for arg in selected_args]\n                selected_kwargs = {k: v.squeeze(self.output_dim) for k, v in selected_kwargs.items()}\n            args_kwargs_by_output.append((selected_args, selected_kwargs))\n        return args_kwargs_by_output\n\n    def update(self, *args: Any, **kwargs: Any) -> None:\n        \"\"\"Update each underlying metric with the corresponding output.\"\"\"\n        reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs)\n        for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs):\n            metric.update(*selected_args, **selected_kwargs)\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute metrics.\"\"\"\n        return torch.stack([m.compute() for m in self.metrics], 0)\n\n    @torch.jit.unused\n    def forward(self, *args: Any, **kwargs: Any) -> Any:\n        \"\"\"Call underlying forward methods and aggregate the results if they're non-null.\n\n        We override this method to ensure that state variables get copied over on the underlying metrics.\n        \"\"\"\n        results = []\n        reshaped_args_kwargs = self._get_args_kwargs_by_output(*args, **kwargs)\n        for metric, (selected_args, selected_kwargs) in zip(self.metrics, reshaped_args_kwargs):\n            results.append(metric(*selected_args, **selected_kwargs))\n        if results[0] is None:\n            return None\n        return torch.stack(results, 0)\n\n    def reset(self) -> None:\n        \"\"\"Reset all underlying metrics.\"\"\"\n        for metric in self.metrics:\n            metric.reset()\n        super().reset()\n\n    def _wrap_update(self, update: Callable) -> Callable:\n        \"\"\"Overwrite to do nothing.\"\"\"\n        return update\n\n    def _wrap_compute(self, compute: Callable) -> Callable:\n        \"\"\"Overwrite to do nothing.\"\"\"\n        return compute\n\n    def plot(\n        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None\n    ) -> _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 import MultioutputWrapper, R2Score\n            >>> metric = MultioutputWrapper(R2Score(), 2)\n            >>> metric.update(torch.randn(20, 2), torch.randn(20, 2))\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting multiple values\n            >>> import torch\n            >>> from torchmetrics import MultioutputWrapper, R2Score\n            >>> metric = MultioutputWrapper(R2Score(), 2)\n            >>> values = [ ]\n            >>> for _ in range(3):\n            ...     values.append(metric(torch.randn(20, 2), torch.randn(20, 2)))\n            >>> fig_, ax_ = metric.plot(values)\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/wrappers/multioutput.py"}]}