We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Pearson Correlation Coefficient fails when updating one batch at a time
## 🐛 Bug

The `PearsonCorrCoef` fails when using a single batch per update.

### To Reproduce
```python
import torch
from torchmetrics import PearsonCorrCoef

metric = PearsonCorrCoef()

# Works
metric(torch.tensor([3.0, -0.5, 2.0, 7.0]), torch.tensor([2.5, 0.0, 2.0, 8.0]))
print(metric.compute())  # tensor(0.9849)

metric.reset()

# Doesn't work.
metric(torch.tensor([3.0]), torch.tensor([2.5]))
metric(torch.tensor([-0.5]), torch.tensor([0.0]))
metric(torch.tensor([2.0]), torch.tensor([2.0]))
metric(torch.tensor([7.0]), torch.tensor([8.0]))
print(metric.compute())  # tensor(nan)
```

### Expected behavior

Both ways of updating the metric should work.

### Environment
Python 3.10
torchmetrics==1.03
torch==2.01


--- 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/regression/pearson.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 import math
15 from typing import Tuple
16 
17 import torch
18 from torch import Tensor
19 
20 from torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs
21 from torchmetrics.utilities import rank_zero_warn
22 from torchmetrics.utilities.checks import _check_same_shape
23 
24 
25 def _pearson_corrcoef_update(
26     preds: Tensor,
27     target: Tensor,
28     mean_x: Tensor,
29     mean_y: Tensor,
30     var_x: Tensor,
31     var_y: Tensor,
32     corr_xy: Tensor,
33     n_prior: Tensor,
34     num_outputs: int,
35 ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
36     """Update and returns variables required to compute Pearson Correlation Coefficient.
37 
38     Check for same shape of input tensors.
39 
40     Args:
41         preds: estimated scores
42         target: ground truth scores
43         mean_x: current mean estimate of x tensor
44         mean_y: current mean estimate of y tensor
45         var_x: current variance estimate of x tensor
46         var_y: current variance estimate of y tensor
47         corr_xy: current covariance estimate between x and y tensor
48         n_prior: current number of observed observations
49         num_outputs: Number of outputs in multioutput setting
50 
51     """
52     # Data checking
53     _check_same_shape(preds, target)
54     _check_data_shape_to_num_outputs(preds, target, num_outputs)
55     cond = n_prior.mean() > 0
56 
57     n_obs = preds.shape[0]
58     if cond:
59         mx_new = (n_prior * mean_x + preds.sum(0)) / (n_prior + n_obs)
60         my_new = (n_prior * mean_y + target.sum(0)) / (n_prior + n_obs)
61     else:
62         mx_new = preds.mean(0)
63         my_new = target.mean(0)
64 
65     n_prior += n_obs
66 
67     if cond:
68         var_x += ((preds - mx_new) * (preds - mean_x)).sum(0)
69         var_y += ((target - my_new) * (target - mean_y)).sum(0)
70 
71     else:
72         var_x += preds.var(0) * (n_obs - 1)
73         var_y += target.var(0) * (n_obs - 1)
74     corr_xy += ((preds - mx_new) * (target - mean_y)).sum(0)
75     mean_x = mx_new
76     mean_y = my_new
77 
78     return mean_x, mean_y, var_x, var_y, corr_xy, n_prior
79 
80 
81 def _pearson_corrcoef_compute(
82     var_x: Tensor,
83     var_y: Tensor,
84     corr_xy: Tensor,
85     nb: Tensor,
86 ) -> Tensor:
87     """Compute the final pearson correlation based on accumulated statistics.
88 
89     Args:
90         var_x: variance estimate of x tensor
91         var_y: variance estimate of y tensor
92         corr_xy: covariance estimate between x and y tensor
93         nb: number of observations
94 
95     """
96     var_x /= nb - 1
97     var_y /= nb - 1
98     corr_xy /= nb - 1
99     # if var_x, var_y is float16 and on cpu, make it bfloat16 as sqrt is not supported for float16
100     # on cpu, remove this after https://github.com/pytorch/pytorch/issues/54774 is fixed
101     if var_x.dtype == torch.float16 and var_x.device == torch.device("cpu"):
102         var_x = var_x.bfloat16()
103         var_y = var_y.bfloat16()
104 
105     bound = math.sqrt(torch.finfo(var_x.dtype).eps)
106     if (var_x < bound).any() or (var_y < bound).any():
107         rank_zero_warn(
108             "The variance of predictions or target is close to zero. This can cause instability in Pearson correlation"
109             "coefficient, leading to wrong results. Consider re-scaling the input if possible or computing using a"
110             f"larger dtype (currently using {var_x.dtype}).",
111             UserWarning,
112         )
113 
114     corrcoef = (corr_xy / (var_x * var_y).sqrt()).squeeze()
115     return torch.clamp(corrcoef, -1.0, 1.0)
116 
117 
118 def pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor:
119     """Compute pearson correlation coefficient.
120 
121     Args:
122         preds: estimated scores
123         target: ground truth scores
124 
125     Example (single output regression):
126         >>> from torchmetrics.functional.regression import pearson_corrcoef
127         >>> target = torch.tensor([3, -0.5, 2, 7])
128         >>> preds = torch.tensor([2.5, 0.0, 2, 8])
129         >>> pearson_corrcoef(preds, target)
130         tensor(0.9849)
131 
132     Example (multi output regression):
133         >>> from torchmetrics.functional.regression import pearson_corrcoef
134         >>> target = torch.tensor([[3, -0.5], [2, 7]])
135         >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
136         >>> pearson_corrcoef(preds, target)
137         tensor([1., 1.])
138 
139     """
140     d = preds.shape[1] if preds.ndim == 2 else 1
141     _temp = torch.zeros(d, dtype=preds.dtype, device=preds.device)
142     mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone()
143     var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone()
144     _, _, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update(
145         preds, target, mean_x, mean_y, var_x, var_y, corr_xy, nb, num_outputs=1 if preds.ndim == 1 else preds.shape[-1]
146     )
147     return _pearson_corrcoef_compute(var_x, var_y, corr_xy, nb)
148
```
--- 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/functional/regression/pearson.py b/src/torchmetrics/functional/regression/pearson.py
--- a/src/torchmetrics/functional/regression/pearson.py
+++ b/src/torchmetrics/functional/regression/pearson.py
@@ -52,9 +52,9 @@
     # Data checking
     _check_same_shape(preds, target)
     _check_data_shape_to_num_outputs(preds, target, num_outputs)
-    cond = n_prior.mean() > 0
-
     n_obs = preds.shape[0]
+    cond = n_prior.mean() > 0 or n_obs == 1
+
     if cond:
         mx_new = (n_prior * mean_x + preds.sum(0)) / (n_prior + n_obs)
         my_new = (n_prior * mean_y + target.sum(0)) / (n_prior + n_obs)
@@ -67,7 +67,6 @@
     if cond:
         var_x += ((preds - mx_new) * (preds - mean_x)).sum(0)
         var_y += ((target - my_new) * (target - mean_y)).sum(0)
-
     else:
         var_x += preds.var(0) * (n_obs - 1)
         var_y += target.var(0) * (n_obs - 1)

{"golden_diff": "diff --git a/src/torchmetrics/functional/regression/pearson.py b/src/torchmetrics/functional/regression/pearson.py\n--- a/src/torchmetrics/functional/regression/pearson.py\n+++ b/src/torchmetrics/functional/regression/pearson.py\n@@ -52,9 +52,9 @@\n     # Data checking\n     _check_same_shape(preds, target)\n     _check_data_shape_to_num_outputs(preds, target, num_outputs)\n-    cond = n_prior.mean() > 0\n-\n     n_obs = preds.shape[0]\n+    cond = n_prior.mean() > 0 or n_obs == 1\n+\n     if cond:\n         mx_new = (n_prior * mean_x + preds.sum(0)) / (n_prior + n_obs)\n         my_new = (n_prior * mean_y + target.sum(0)) / (n_prior + n_obs)\n@@ -67,7 +67,6 @@\n     if cond:\n         var_x += ((preds - mx_new) * (preds - mean_x)).sum(0)\n         var_y += ((target - my_new) * (target - mean_y)).sum(0)\n-\n     else:\n         var_x += preds.var(0) * (n_obs - 1)\n         var_y += target.var(0) * (n_obs - 1)\n", "issue": "Pearson Correlation Coefficient fails when updating one batch at a time\n## \ud83d\udc1b Bug\r\n\r\nThe `PearsonCorrCoef` fails when using a single batch per update.\r\n\r\n### To Reproduce\r\n```python\r\nimport torch\r\nfrom torchmetrics import PearsonCorrCoef\r\n\r\nmetric = PearsonCorrCoef()\r\n\r\n# Works\r\nmetric(torch.tensor([3.0, -0.5, 2.0, 7.0]), torch.tensor([2.5, 0.0, 2.0, 8.0]))\r\nprint(metric.compute())  # tensor(0.9849)\r\n\r\nmetric.reset()\r\n\r\n# Doesn't work.\r\nmetric(torch.tensor([3.0]), torch.tensor([2.5]))\r\nmetric(torch.tensor([-0.5]), torch.tensor([0.0]))\r\nmetric(torch.tensor([2.0]), torch.tensor([2.0]))\r\nmetric(torch.tensor([7.0]), torch.tensor([8.0]))\r\nprint(metric.compute())  # tensor(nan)\r\n```\r\n\r\n### Expected behavior\r\n\r\nBoth ways of updating the metric should work.\r\n\r\n### Environment\r\nPython 3.10\r\ntorchmetrics==1.03\r\ntorch==2.01\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.\nimport math\nfrom typing import Tuple\n\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs\nfrom torchmetrics.utilities import rank_zero_warn\nfrom torchmetrics.utilities.checks import _check_same_shape\n\n\ndef _pearson_corrcoef_update(\n    preds: Tensor,\n    target: Tensor,\n    mean_x: Tensor,\n    mean_y: Tensor,\n    var_x: Tensor,\n    var_y: Tensor,\n    corr_xy: Tensor,\n    n_prior: Tensor,\n    num_outputs: int,\n) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:\n    \"\"\"Update and returns variables required to compute Pearson Correlation Coefficient.\n\n    Check for same shape of input tensors.\n\n    Args:\n        preds: estimated scores\n        target: ground truth scores\n        mean_x: current mean estimate of x tensor\n        mean_y: current mean estimate of y tensor\n        var_x: current variance estimate of x tensor\n        var_y: current variance estimate of y tensor\n        corr_xy: current covariance estimate between x and y tensor\n        n_prior: current number of observed observations\n        num_outputs: Number of outputs in multioutput setting\n\n    \"\"\"\n    # Data checking\n    _check_same_shape(preds, target)\n    _check_data_shape_to_num_outputs(preds, target, num_outputs)\n    cond = n_prior.mean() > 0\n\n    n_obs = preds.shape[0]\n    if cond:\n        mx_new = (n_prior * mean_x + preds.sum(0)) / (n_prior + n_obs)\n        my_new = (n_prior * mean_y + target.sum(0)) / (n_prior + n_obs)\n    else:\n        mx_new = preds.mean(0)\n        my_new = target.mean(0)\n\n    n_prior += n_obs\n\n    if cond:\n        var_x += ((preds - mx_new) * (preds - mean_x)).sum(0)\n        var_y += ((target - my_new) * (target - mean_y)).sum(0)\n\n    else:\n        var_x += preds.var(0) * (n_obs - 1)\n        var_y += target.var(0) * (n_obs - 1)\n    corr_xy += ((preds - mx_new) * (target - mean_y)).sum(0)\n    mean_x = mx_new\n    mean_y = my_new\n\n    return mean_x, mean_y, var_x, var_y, corr_xy, n_prior\n\n\ndef _pearson_corrcoef_compute(\n    var_x: Tensor,\n    var_y: Tensor,\n    corr_xy: Tensor,\n    nb: Tensor,\n) -> Tensor:\n    \"\"\"Compute the final pearson correlation based on accumulated statistics.\n\n    Args:\n        var_x: variance estimate of x tensor\n        var_y: variance estimate of y tensor\n        corr_xy: covariance estimate between x and y tensor\n        nb: number of observations\n\n    \"\"\"\n    var_x /= nb - 1\n    var_y /= nb - 1\n    corr_xy /= nb - 1\n    # if var_x, var_y is float16 and on cpu, make it bfloat16 as sqrt is not supported for float16\n    # on cpu, remove this after https://github.com/pytorch/pytorch/issues/54774 is fixed\n    if var_x.dtype == torch.float16 and var_x.device == torch.device(\"cpu\"):\n        var_x = var_x.bfloat16()\n        var_y = var_y.bfloat16()\n\n    bound = math.sqrt(torch.finfo(var_x.dtype).eps)\n    if (var_x < bound).any() or (var_y < bound).any():\n        rank_zero_warn(\n            \"The variance of predictions or target is close to zero. This can cause instability in Pearson correlation\"\n            \"coefficient, leading to wrong results. Consider re-scaling the input if possible or computing using a\"\n            f\"larger dtype (currently using {var_x.dtype}).\",\n            UserWarning,\n        )\n\n    corrcoef = (corr_xy / (var_x * var_y).sqrt()).squeeze()\n    return torch.clamp(corrcoef, -1.0, 1.0)\n\n\ndef pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor:\n    \"\"\"Compute pearson correlation coefficient.\n\n    Args:\n        preds: estimated scores\n        target: ground truth scores\n\n    Example (single output regression):\n        >>> from torchmetrics.functional.regression import pearson_corrcoef\n        >>> target = torch.tensor([3, -0.5, 2, 7])\n        >>> preds = torch.tensor([2.5, 0.0, 2, 8])\n        >>> pearson_corrcoef(preds, target)\n        tensor(0.9849)\n\n    Example (multi output regression):\n        >>> from torchmetrics.functional.regression import pearson_corrcoef\n        >>> target = torch.tensor([[3, -0.5], [2, 7]])\n        >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])\n        >>> pearson_corrcoef(preds, target)\n        tensor([1., 1.])\n\n    \"\"\"\n    d = preds.shape[1] if preds.ndim == 2 else 1\n    _temp = torch.zeros(d, dtype=preds.dtype, device=preds.device)\n    mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone()\n    var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone()\n    _, _, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update(\n        preds, target, mean_x, mean_y, var_x, var_y, corr_xy, nb, num_outputs=1 if preds.ndim == 1 else preds.shape[-1]\n    )\n    return _pearson_corrcoef_compute(var_x, var_y, corr_xy, nb)\n", "path": "src/torchmetrics/functional/regression/pearson.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.\nimport math\nfrom typing import Tuple\n\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.functional.regression.utils import _check_data_shape_to_num_outputs\nfrom torchmetrics.utilities import rank_zero_warn\nfrom torchmetrics.utilities.checks import _check_same_shape\n\n\ndef _pearson_corrcoef_update(\n    preds: Tensor,\n    target: Tensor,\n    mean_x: Tensor,\n    mean_y: Tensor,\n    var_x: Tensor,\n    var_y: Tensor,\n    corr_xy: Tensor,\n    n_prior: Tensor,\n    num_outputs: int,\n) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:\n    \"\"\"Update and returns variables required to compute Pearson Correlation Coefficient.\n\n    Check for same shape of input tensors.\n\n    Args:\n        preds: estimated scores\n        target: ground truth scores\n        mean_x: current mean estimate of x tensor\n        mean_y: current mean estimate of y tensor\n        var_x: current variance estimate of x tensor\n        var_y: current variance estimate of y tensor\n        corr_xy: current covariance estimate between x and y tensor\n        n_prior: current number of observed observations\n        num_outputs: Number of outputs in multioutput setting\n\n    \"\"\"\n    # Data checking\n    _check_same_shape(preds, target)\n    _check_data_shape_to_num_outputs(preds, target, num_outputs)\n    n_obs = preds.shape[0]\n    cond = n_prior.mean() > 0 or n_obs == 1\n\n    if cond:\n        mx_new = (n_prior * mean_x + preds.sum(0)) / (n_prior + n_obs)\n        my_new = (n_prior * mean_y + target.sum(0)) / (n_prior + n_obs)\n    else:\n        mx_new = preds.mean(0)\n        my_new = target.mean(0)\n\n    n_prior += n_obs\n\n    if cond:\n        var_x += ((preds - mx_new) * (preds - mean_x)).sum(0)\n        var_y += ((target - my_new) * (target - mean_y)).sum(0)\n    else:\n        var_x += preds.var(0) * (n_obs - 1)\n        var_y += target.var(0) * (n_obs - 1)\n    corr_xy += ((preds - mx_new) * (target - mean_y)).sum(0)\n    mean_x = mx_new\n    mean_y = my_new\n\n    return mean_x, mean_y, var_x, var_y, corr_xy, n_prior\n\n\ndef _pearson_corrcoef_compute(\n    var_x: Tensor,\n    var_y: Tensor,\n    corr_xy: Tensor,\n    nb: Tensor,\n) -> Tensor:\n    \"\"\"Compute the final pearson correlation based on accumulated statistics.\n\n    Args:\n        var_x: variance estimate of x tensor\n        var_y: variance estimate of y tensor\n        corr_xy: covariance estimate between x and y tensor\n        nb: number of observations\n\n    \"\"\"\n    var_x /= nb - 1\n    var_y /= nb - 1\n    corr_xy /= nb - 1\n    # if var_x, var_y is float16 and on cpu, make it bfloat16 as sqrt is not supported for float16\n    # on cpu, remove this after https://github.com/pytorch/pytorch/issues/54774 is fixed\n    if var_x.dtype == torch.float16 and var_x.device == torch.device(\"cpu\"):\n        var_x = var_x.bfloat16()\n        var_y = var_y.bfloat16()\n\n    bound = math.sqrt(torch.finfo(var_x.dtype).eps)\n    if (var_x < bound).any() or (var_y < bound).any():\n        rank_zero_warn(\n            \"The variance of predictions or target is close to zero. This can cause instability in Pearson correlation\"\n            \"coefficient, leading to wrong results. Consider re-scaling the input if possible or computing using a\"\n            f\"larger dtype (currently using {var_x.dtype}).\",\n            UserWarning,\n        )\n\n    corrcoef = (corr_xy / (var_x * var_y).sqrt()).squeeze()\n    return torch.clamp(corrcoef, -1.0, 1.0)\n\n\ndef pearson_corrcoef(preds: Tensor, target: Tensor) -> Tensor:\n    \"\"\"Compute pearson correlation coefficient.\n\n    Args:\n        preds: estimated scores\n        target: ground truth scores\n\n    Example (single output regression):\n        >>> from torchmetrics.functional.regression import pearson_corrcoef\n        >>> target = torch.tensor([3, -0.5, 2, 7])\n        >>> preds = torch.tensor([2.5, 0.0, 2, 8])\n        >>> pearson_corrcoef(preds, target)\n        tensor(0.9849)\n\n    Example (multi output regression):\n        >>> from torchmetrics.functional.regression import pearson_corrcoef\n        >>> target = torch.tensor([[3, -0.5], [2, 7]])\n        >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])\n        >>> pearson_corrcoef(preds, target)\n        tensor([1., 1.])\n\n    \"\"\"\n    d = preds.shape[1] if preds.ndim == 2 else 1\n    _temp = torch.zeros(d, dtype=preds.dtype, device=preds.device)\n    mean_x, mean_y, var_x = _temp.clone(), _temp.clone(), _temp.clone()\n    var_y, corr_xy, nb = _temp.clone(), _temp.clone(), _temp.clone()\n    _, _, var_x, var_y, corr_xy, nb = _pearson_corrcoef_update(\n        preds, target, mean_x, mean_y, var_x, var_y, corr_xy, nb, num_outputs=1 if preds.ndim == 1 else preds.shape[-1]\n    )\n    return _pearson_corrcoef_compute(var_x, var_y, corr_xy, nb)\n", "path": "src/torchmetrics/functional/regression/pearson.py"}]}