Repository: Lightning-AI/torchmetrics (language: python)

Issue:
Maybe a new patch release?
### Motivation

A new release will help since there were some refactoring in the segmentation metrics. 

Thanks a lot 🙏  


Discussion / hints:

Fix patch:
diff --git a/.azure/gpu-integrations.yml b/.azure/gpu-integrations.yml
index 55b05cb369c..8478ab6d3e0 100644
--- a/.azure/gpu-integrations.yml
+++ b/.azure/gpu-integrations.yml
@@ -22,8 +22,8 @@ jobs:
           torch-ver: "1.13"
           requires: "oldest"
         "torch | 2.x":
-          docker-image: "pytorch/pytorch:2.3.0-cuda12.1-cudnn8-runtime"
-          torch-ver: "2.3"
+          docker-image: "pytorch/pytorch:2.4.0-cuda12.1-cudnn9-runtime"
+          torch-ver: "2.4"
     # how long to run the job before automatically cancelling
     timeoutInMinutes: "40"
     # how much time to give 'run always even if cancelled tasks' before stopping them
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index 150f7849963..928a3b2dfaf 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -19,8 +19,10 @@ Steps to reproduce the behavior...
 <details>
   <summary>Code sample</summary>
 
-<!-- Ideally attach a minimal code sample to reproduce the decried issue.
-Minimal means having the shortest code but still preserving the bug. -->
+```python
+# Ideally attach a minimal code sample to reproduce the decried issue.
+# Minimal means having the shortest code but still preserving the bug.
+```
 
 </details>
 
@@ -30,9 +32,9 @@ Minimal means having the shortest code but still preserving the bug. -->
 
 ### Environment
 
-- TorchMetrics version (and how you installed TM, e.g. `conda`, `pip`, build from source):
-- Python & PyTorch Version (e.g., 1.0):
-- Any other relevant information such as OS (e.g., Linux):
+- TorchMetrics version (if build from source, add commit SHA): ???
+- Python & PyTorch Version (e.g., 1.0): ???
+- Any other relevant information such as OS (e.g., Linux): ???
 
 ### Additional context
 
diff --git a/.github/workflows/ci-checks.yml b/.github/workflows/ci-checks.yml
index 2e8b275ddd6..3c7c3eb69f1 100644
--- a/.github/workflows/ci-checks.yml
+++ b/.github/workflows/ci-checks.yml
@@ -13,19 +13,19 @@ concurrency:
 
 jobs:
   check-code:
-    uses: Lightning-AI/utilities/.github/workflows/check-typing.yml@v0.11.6
+    uses: Lightning-AI/utilities/.github/workflows/check-typing.yml@v0.11.7
     with:
-      actions-ref: v0.11.6
+      actions-ref: v0.11.7
       extra-typing: "typing"
 
   check-schema:
-    uses: Lightning-AI/utilities/.github/workflows/check-schema.yml@v0.11.6
+    uses: Lightning-AI/utilities/.github/workflows/check-schema.yml@v0.11.7
 
   check-package:
     if: github.event.pull_request.draft == false
-    uses: Lightning-AI/utilities/.github/workflows/check-package.yml@v0.11.6
+    uses: Lightning-AI/utilities/.github/workflows/check-package.yml@v0.11.7
     with:
-      actions-ref: v0.11.6
+      actions-ref: v0.11.7
       artifact-name: dist-packages-${{ github.sha }}
       import-name: "torchmetrics"
       testing-matrix: |
@@ -35,7 +35,7 @@ jobs:
         }
 
   check-md-links:
-    uses: Lightning-AI/utilities/.github/workflows/check-md-links.yml@v0.11.6
+    uses: Lightning-AI/utilities/.github/workflows/check-md-links.yml@v0.11.7
     with:
       base-branch: master
       config-file: ".github/markdown-links-config.json"
diff --git a/.github/workflows/clear-cache.yml b/.github/workflows/clear-cache.yml
index 53a68bedfa3..ecd7c6e3ff3 100644
--- a/.github/workflows/clear-cache.yml
+++ b/.github/workflows/clear-cache.yml
@@ -1,23 +1,40 @@
-name: Clear cache weekly
+name: Clear cache ...
 
 on:
+  pull_request:
+    paths:
+      - ".github/workflows/clear-cache.yml"
   workflow_dispatch:
     inputs:
       pattern:
         description: "pattern for cleaning cache"
-        default: "pip|conda"
+        default: "pip-|conda"
         required: false
         type: string
+      age-days:
+        description: "setting the age of caches in days to be dropped"
+        required: true
+        type: number
+        default: 5
+  schedule:
+    # on Sundays
+    - cron: "0 0 * * 0"
 
 jobs:
   cron-clear:
-    if: github.event_name == 'schedule'
-    uses: Lightning-AI/utilities/.github/workflows/clear-cache.yml@v0.11.6
+    if: github.event_name == 'schedule' || github.event_name == 'pull_request'
+    uses: Lightning-AI/utilities/.github/workflows/cleanup-caches.yml@v0.11.7
     with:
+      scripts-ref: v0.11.7
+      dry-run: ${{ github.event_name == 'pull_request' }}
       pattern: "pip-latest"
+      age-days: 7
 
   direct-clear:
-    if: github.event_name == 'workflow_dispatch'
-    uses: Lightning-AI/utilities/.github/workflows/clear-cache.yml@v0.11.6
+    if: github.event_name == 'workflow_dispatch' || github.event_name == 'pull_request'
+    uses: Lightning-AI/utilities/.github/workflows/cleanup-caches.yml@v0.11.7
     with:
-      pattern: ${{ inputs.pattern }}
+      scripts-ref: v0.11.7
+      dry-run: ${{ github.event_name == 'pull_request' }}
+      pattern: ${{ inputs.pattern || 'pypi_wheels' }} # setting str in case of PR / debugging
+      age-days: ${{ fromJSON(inputs.age-days) || 0 }} # setting 0 in case of PR / debugging
diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml
index b3af59d6483..2c17c5ee68d 100644
--- a/.github/workflows/docker-build.yml
+++ b/.github/workflows/docker-build.yml
@@ -72,8 +72,9 @@ jobs:
           - { python: "3.10", pytorch: "2.2", cuda: "12.1.1", ubuntu: "22.04" }
           - { python: "3.11", pytorch: "2.2", cuda: "12.1.1", ubuntu: "22.04" }
           - { python: "3.11", pytorch: "2.3", cuda: "12.1.1", ubuntu: "22.04" }
-          # the future version - test or RC version
           - { python: "3.11", pytorch: "2.4", cuda: "12.1.1", ubuntu: "22.04" }
+          # the future version - test or RC version
+          #- { python: "3.11", pytorch: "2.5", cuda: "12.1.1", ubuntu: "22.04" }
     steps:
       - uses: actions/checkout@v4
 
diff --git a/.github/workflows/docs-build.yml b/.github/workflows/docs-build.yml
index 154dc88b413..869c7194632 100644
--- a/.github/workflows/docs-build.yml
+++ b/.github/workflows/docs-build.yml
@@ -48,18 +48,11 @@ jobs:
           pytorch-version: ${{ matrix.pytorch-version }}
           pypi-dir: ${{ env.PYPI_CACHE }}
 
-      - name: Install Latex
-        if: ${{ matrix.target == 'html' }}
-        # install Texlive, see https://linuxconfig.org/how-to-install-latex-on-ubuntu-20-04-focal-fossa-linux
-        run: |
-          sudo apt-get update --fix-missing
-          sudo apt-get install -y \
-            texlive-latex-extra texlive-pictures texlive-fonts-recommended dvipng cm-super
-
       - name: Install package & dependencies
         run: |
           make get-sphinx-template
-          pip install . -U -r requirements/_docs.txt \
+          # install with -e so the path to source link comes from this project not from the installed package
+          pip install -e . -U -r requirements/_docs.txt \
             --find-links="${PYPI_CACHE}" --find-links="${TORCH_URL}"
       - run: pip list
       - name: Full build for deployment
@@ -67,7 +60,10 @@ jobs:
         run: echo "SPHINX_FETCH_ASSETS=1" >> $GITHUB_ENV
       - name: make ${{ matrix.target }}
         working-directory: ./docs
-        run: make ${{ matrix.target }} --debug --jobs $(nproc) SPHINXOPTS="-W --keep-going"
+        run: |
+          pwd
+          ls -la
+          make ${{ matrix.target }} --debug --jobs $(nproc) SPHINXOPTS="-W --keep-going"
 
       - name: Upload built docs
         if: ${{ matrix.target == 'html' && github.event_name != 'pull_request' }}
diff --git a/.github/workflows/publish-pkg.yml b/.github/workflows/publish-pkg.yml
index b46277c7e26..34d9d9f6545 100644
--- a/.github/workflows/publish-pkg.yml
+++ b/.github/workflows/publish-pkg.yml
@@ -67,7 +67,7 @@ jobs:
       - run: ls -lh dist/
       # We do this, since failures on test.pypi aren't that bad
       - name: Publish to Test PyPI
-        uses: pypa/gh-action-pypi-publish@v1.9.0
+        uses: pypa/gh-action-pypi-publish@v1.10.0
         with:
           user: __token__
           password: ${{ secrets.test_pypi_password }}
@@ -94,7 +94,7 @@ jobs:
           path: dist
       - run: ls -lh dist/
       - name: Publish distribution 📦 to PyPI
-        uses: pypa/gh-action-pypi-publish@v1.9.0
+        uses: pypa/gh-action-pypi-publish@v1.10.0
         with:
           user: __token__
           password: ${{ secrets.pypi_password }}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7da42fbcb0e..95a6d3d8e82 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ---
 
+## [1.4.2] - 2022-09-12
+
+### Added
+
+- Re-adding `Chrf` implementation ([#2701](https://github.com/Lightning-AI/torchmetrics/pull/2701))
+
+### Fixed
+
+- Fixed wrong aggregation in `segmentation.MeanIoU` ([#2698](https://github.com/Lightning-AI/torchmetrics/pull/2698))
+- Fixed handling zero division error in binary IoU (Jaccard index) calculation ([#2726](https://github.com/Lightning-AI/torchmetrics/pull/2726))
+- Corrected the padding related calculation errors in SSIM ([#2721](https://github.com/Lightning-AI/torchmetrics/pull/2721))
+- Fixed compatibility of audio domain with new `scipy` ([#2733](https://github.com/Lightning-AI/torchmetrics/pull/2733))
+- Fixed how `prefix`/`postfix` works in `MultitaskWrapper` ([#2722](https://github.com/Lightning-AI/torchmetrics/pull/2722))
+- Fixed flakiness in tests related to `torch.unique` with `dim=None` ([#2650](https://github.com/Lightning-AI/torchmetrics/pull/2650))
+
+
 ## [1.4.1] - 2024-08-02
 
 ### Changed
diff --git a/docs/source/conf.py b/docs/source/conf.py
index ae31f2bbce6..e6575d91b24 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -254,6 +254,11 @@ def _set_root_image_path(page_path: str) -> None:
     ),
 ]
 
+# MathJax configuration
+mathjax3_config = {
+    "tex": {"packages": {"[+]": ["ams", "newcommand", "configMacros"]}},
+}
+
 # -- Options for Epub output -------------------------------------------------
 
 # Bibliographic Dublin Core info.
@@ -343,8 +348,7 @@ def package_list_from_file(file: str) -> list[str]:
 autodoc_mock_imports = MOCK_PACKAGES
 
 
-# Resolve function
-# This function is used to populate the (source) links in the API
+# Resolve function - this function is used to populate the (source) links in the API
 def linkcode_resolve(domain, info) -> Optional[str]:  # noqa: ANN001
     return _linkcode_resolve(domain, info=info, github_user="Lightning-AI", github_repo="torchmetrics")
 
diff --git a/docs/source/links.rst b/docs/source/links.rst
index f1057bc3169..e6928e0397a 100644
--- a/docs/source/links.rst
+++ b/docs/source/links.rst
@@ -91,7 +91,7 @@
 .. _CER: https://rechtsprechung-im-ostseeraum.archiv.uni-greifswald.de/word-error-rate-character-error-rate-how-to-evaluate-a-model
 .. _MER: https://www.isca-speech.org/archive/interspeech_2004/morris04_interspeech.html
 .. _WIL: https://www.isca-speech.org/archive/interspeech_2004/morris04_interspeech.html
-.. _WIP: https://infoscience.epfl.ch/entities/publication/9983d013-8239-422e-a3f7-a1500d309474
+.. _WIP: https://www.isca-archive.org/interspeech_2004/morris04_interspeech.pdf
 .. _TV: https://en.wikipedia.org/wiki/Total_variation_denoising
 .. _InfoLM: https://arxiv.org/abs/2112.01589
 .. _alpha divergence: https://static.renyi.hu/renyi_cikkek/1961_on_measures_of_entropy_and_information.pdf
diff --git a/docs/source/multimodal/clip_iqa.rst b/docs/source/multimodal/clip_iqa.rst
index 074f35a50bf..59734b5a05b 100644
--- a/docs/source/multimodal/clip_iqa.rst
+++ b/docs/source/multimodal/clip_iqa.rst
@@ -1,7 +1,7 @@
 .. customcarditem::
    :header: CLIP IQA
    :image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/image_classification.svg
-   :tags: Image
+   :tags: Multimodal
 
 .. include:: ../links.rst
 
diff --git a/docs/source/multimodal/clip_score.rst b/docs/source/multimodal/clip_score.rst
index 60166403fd0..12fe0fa2815 100644
--- a/docs/source/multimodal/clip_score.rst
+++ b/docs/source/multimodal/clip_score.rst
@@ -1,7 +1,7 @@
 .. customcarditem::
    :header: CLIP Score
    :image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/image_classification.svg
-   :tags: Image
+   :tags: Multimodal
 
 .. include:: ../links.rst
 
diff --git a/docs/source/pages/lightning.rst b/docs/source/pages/lightning.rst
index 7f1bc70363b..09ceafb331f 100644
--- a/docs/source/pages/lightning.rst
+++ b/docs/source/pages/lightning.rst
@@ -3,6 +3,7 @@
     import torch
     from torch.nn import Module
     from lightning.pytorch import LightningModule
+    from lightning.pytorch.utilities import rank_zero_only
     from torchmetrics import Metric
 
 #################################
@@ -193,6 +194,29 @@ The following contains a list of pitfalls to be aware of:
   Because the object is logged in the first case, Lightning will reset the metric before calling the second line leading
   to errors or nonsense results.
 
+* If you decorate a lightning method with the ``rank_zero_only`` decorator with the goal of only calculating a particular
+    metric on the main process, you need to disable the default behavior of the metric to synchronize the metric values
+    across all processes. This can be done by setting the ``sync_on_compute`` flag to ``False`` when initializing the
+    metric. Not doing so can lead to race conditions and processes hanging.
+
+.. testcode:: python
+
+    class MyModule(LightningModule):
+
+        def __init__(self, num_classes):
+            ...
+            self.metric = torchmetrics.image.FrechetInceptionDistance(sync_on_compute=False)
+
+        @rank_zero_only
+        def validation_step(self, batch, batch_idx):
+            image, target = batch
+            generated_image = self(x)
+            ...
+            self.metric(image, real=True)
+            self.metric(generated_image, real=False)
+            val = self.metric.compute()  # this will only be called on the main process
+            self.log('val_fid', val)
+
 * Calling ``self.log("val", self.metric(preds, target))`` with the intention of logging the metric object. Because
   ``self.metric(preds, target)`` corresponds to calling the forward method, this will return a tensor and not the
   metric object. Such logging will be wrong in this case. Instead, it is essential to separate into several lines:
diff --git a/docs/source/regression/kl_divergence.rst b/docs/source/regression/kl_divergence.rst
index 4e65ba6fb01..7f5761ad9a8 100644
--- a/docs/source/regression/kl_divergence.rst
+++ b/docs/source/regression/kl_divergence.rst
@@ -1,7 +1,7 @@
 .. customcarditem::
    :header: KL Divergence
    :image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/tabular_classification.svg
-   :tags: Classification
+   :tags: Regression
 
 .. include:: ../links.rst
 
diff --git a/docs/source/segmentation/generalized_dice.rst b/docs/source/segmentation/generalized_dice.rst
index 5c48fc670d1..f0abd2f5353 100644
--- a/docs/source/segmentation/generalized_dice.rst
+++ b/docs/source/segmentation/generalized_dice.rst
@@ -1,7 +1,7 @@
 .. customcarditem::
    :header: Generalized Dice Score
    :image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/tabular_classification.svg
-   :tags: Classification
+   :tags: Segmentation
 
 .. include:: ../links.rst
 
diff --git a/pyproject.toml b/pyproject.toml
index eebf3fb2df9..6585fb9aa8f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -46,6 +46,7 @@ lint.ignore = [
   "D107",   # Missing docstring in `__init__`
   "E731",   # Do not assign a lambda expression, use a def
   "EXE002", # The file is executable but no shebang is present
+  "ISC001", # potehtional comflict, flagged by Ruff itsel
 ]
 lint.per-file-ignores."docs/source/conf.py" = [
   "A001",
diff --git a/requirements/_docs.txt b/requirements/_docs.txt
index f4a791b929a..87b7ac59edc 100644
--- a/requirements/_docs.txt
+++ b/requirements/_docs.txt
@@ -1,7 +1,7 @@
 sphinx ==5.3.0
 myst-parser ==1.0.0
 nbsphinx ==0.9.3
-pandoc ==2.3
+pandoc ==2.4
 docutils ==0.19
 sphinxcontrib-fulltoc >=1.0
 sphinxcontrib-mockautodoc
@@ -11,10 +11,12 @@ sphinx-paramlinks ==0.6.0
 sphinx-togglebutton ==0.3.2
 sphinx-copybutton ==0.5.2
 
-lightning >=1.8.0, <2.4.0
-lightning-utilities ==0.11.6
+lightning >=1.8.0, <2.5.0
+lightning-utilities ==0.11.7
 pydantic > 1.0.0, < 3.0.0
 
+numpy <2.0  # required by pesq package
+
 # integrations
 -r _integrate.txt
 -r visual.txt
diff --git a/requirements/_integrate.txt b/requirements/_integrate.txt
index fb4472a6f92..efc0370237e 100644
--- a/requirements/_integrate.txt
+++ b/requirements/_integrate.txt
@@ -1,4 +1,4 @@
 # contentiously validated integration with these expected ranges
 
 # ToDo: investigate and add validation with 2.0+ on GPU
-pytorch-lightning >=1.9.0, <2.4.0
+pytorch-lightning >=1.9.0, <2.5.0
diff --git a/requirements/multimodal.txt b/requirements/multimodal.txt
index 37c0d169462..bec29c90929 100644
--- a/requirements/multimodal.txt
+++ b/requirements/multimodal.txt
@@ -1,5 +1,5 @@
 # NOTE: the upper bound for the package version is only set for CI stability, and it is dropped while installing this package
 #  in case you want to preserve/enforce restrictions on the latest compatible version, add "strict" as an in-line comment
 
-transformers >=4.42.3, <4.43.0
+transformers >=4.42.3, <4.45.0
 piq <=0.8.0
diff --git a/requirements/text.txt b/requirements/text.txt
index 1ef4fed786d..65396b65451 100644
--- a/requirements/text.txt
+++ b/requirements/text.txt
@@ -1,10 +1,10 @@
 # NOTE: the upper bound for the package version is only set for CI stability, and it is dropped while installing this package
 #  in case you want to preserve/enforce restrictions on the latest compatible version, add "strict" as an in-line comment
 
-nltk >=3.6, <=3.8.1
+nltk >=3.8.2, <=3.9.1
 tqdm >=4.41.0, <4.67.0
-regex >=2021.9.24, <=2024.5.15
-transformers >4.4.0, <4.43.0
+regex >=2021.9.24, <=2024.7.24
+transformers >4.4.0, <4.45.0
 mecab-python3 >=1.0.6, <1.1.0
 ipadic >=1.0.0, <1.1.0
 sentencepiece >=0.2.0, <0.3.0
diff --git a/requirements/typing.txt b/requirements/typing.txt
index 3d45c52e977..2b8cf0b5082 100644
--- a/requirements/typing.txt
+++ b/requirements/typing.txt
@@ -1,5 +1,5 @@
-mypy ==1.11.0
-torch ==2.3.1
+mypy ==1.11.2
+torch ==2.4.1
 
 types-PyYAML
 types-emoji
diff --git a/requirements/visual.txt b/requirements/visual.txt
index 269a45fc7bb..1cdc4060a8b 100644
--- a/requirements/visual.txt
+++ b/requirements/visual.txt
@@ -1,5 +1,5 @@
 # NOTE: the upper bound for the package version is only set for CI stability, and it is dropped while installing this package
 #  in case you want to preserve/enforce restrictions on the latest compatible version, add "strict" as an in-line comment
 
-matplotlib >=3.3.0, <3.10.0
+matplotlib >=3.6.0, <3.10.0
 SciencePlots >= 2.0.0, <2.2.0
diff --git a/src/torchmetrics/__about__.py b/src/torchmetrics/__about__.py
index 64c9c3e48f4..af68edb3072 100644
--- a/src/torchmetrics/__about__.py
+++ b/src/torchmetrics/__about__.py
@@ -1,4 +1,4 @@
-__version__ = "1.4.1"
+__version__ = "1.4.2"
 __author__ = "Lightning-AI et al."
 __author_email__ = "name@pytorchlightning.ai"
 __license__ = "Apache-2.0"
diff --git a/src/torchmetrics/__init__.py b/src/torchmetrics/__init__.py
index b1549dfaf8b..2fa370cb1c9 100644
--- a/src/torchmetrics/__init__.py
+++ b/src/torchmetrics/__init__.py
@@ -20,6 +20,13 @@
     if not hasattr(PIL, "PILLOW_VERSION"):
         PIL.PILLOW_VERSION = PIL.__version__
 
+if package_available("scipy"):
+    import scipy.signal
+
+    # back compatibility patch due to SMRMpy using scipy.signal.hamming
+    if not hasattr(scipy.signal, "hamming"):
+        scipy.signal.hamming = scipy.signal.windows.hamming
+
 from torchmetrics import functional  # noqa: E402
 from torchmetrics.aggregation import (  # noqa: E402
     CatMetric,
diff --git a/src/torchmetrics/audio/_deprecated.py b/src/torchmetrics/audio/_deprecated.py
index 4721ce1265c..c84604c9a2c 100644
--- a/src/torchmetrics/audio/_deprecated.py
+++ b/src/torchmetrics/audio/_deprecated.py
@@ -13,7 +13,6 @@ class _PermutationInvariantTraining(PermutationInvariantTraining):
 
     >>> import torch
     >>> from torchmetrics.functional import scale_invariant_signal_noise_ratio
-    >>> _ = torch.manual_seed(42)
     >>> preds = torch.randn(3, 2, 5) # [batch, spk, time]
     >>> target = torch.randn(3, 2, 5) # [batch, spk, time]
     >>> pit = _PermutationInvariantTraining(scale_invariant_signal_noise_ratio,
@@ -79,12 +78,11 @@ class _SignalDistortionRatio(SignalDistortionRatio):
     """Wrapper for deprecated import.
 
     >>> import torch
-    >>> g = torch.manual_seed(1)
     >>> preds = torch.randn(8000)
     >>> target = torch.randn(8000)
     >>> sdr = _SignalDistortionRatio()
     >>> sdr(preds, target)
-    tensor(-12.0589)
+    tensor(-11.9930)
     >>> # use with pit
     >>> from torchmetrics.functional import signal_distortion_ratio
     >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
@@ -92,7 +90,7 @@ class _SignalDistortionRatio(SignalDistortionRatio):
     >>> pit = _PermutationInvariantTraining(signal_distortion_ratio,
     ...     mode="speaker-wise", eval_func="max")
     >>> pit(preds, target)
-    tensor(-11.6051)
+    tensor(-11.7277)
 
     """
 
diff --git a/src/torchmetrics/audio/pesq.py b/src/torchmetrics/audio/pesq.py
index bcaf6d08d9c..dfcf623aa25 100644
--- a/src/torchmetrics/audio/pesq.py
+++ b/src/torchmetrics/audio/pesq.py
@@ -71,17 +71,16 @@ class PerceptualEvaluationSpeechQuality(Metric):
             If ``mode`` is not either ``"wb"`` or ``"nb"``
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
-        >>> target = torch.randn(8000)
+        >>> preds = randn(8000)
+        >>> target = randn(8000)
         >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')
         >>> pesq(preds, target)
-        tensor(2.2076)
+        tensor(2.2885)
         >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')
         >>> wb_pesq(preds, target)
-        tensor(1.7359)
+        tensor(1.6805)
 
     """
 
diff --git a/src/torchmetrics/audio/pit.py b/src/torchmetrics/audio/pit.py
index 150b8b6d983..2def91d4d01 100644
--- a/src/torchmetrics/audio/pit.py
+++ b/src/torchmetrics/audio/pit.py
@@ -61,12 +61,11 @@ class PermutationInvariantTraining(Metric):
             see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.audio import PermutationInvariantTraining
         >>> from torchmetrics.functional.audio import scale_invariant_signal_noise_ratio
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randn(3, 2, 5) # [batch, spk, time]
-        >>> target = torch.randn(3, 2, 5) # [batch, spk, time]
+        >>> preds = randn(3, 2, 5) # [batch, spk, time]
+        >>> target = randn(3, 2, 5) # [batch, spk, time]
         >>> pit = PermutationInvariantTraining(scale_invariant_signal_noise_ratio,
         ...     mode="speaker-wise", eval_func="max")
         >>> pit(preds, target)
diff --git a/src/torchmetrics/audio/sdr.py b/src/torchmetrics/audio/sdr.py
index a4af4c13c60..9b8646aaa1f 100644
--- a/src/torchmetrics/audio/sdr.py
+++ b/src/torchmetrics/audio/sdr.py
@@ -70,23 +70,22 @@ class SignalDistortionRatio(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.audio import SignalDistortionRatio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
-        >>> target = torch.randn(8000)
+        >>> preds = randn(8000)
+        >>> target = randn(8000)
         >>> sdr = SignalDistortionRatio()
         >>> sdr(preds, target)
-        tensor(-12.0589)
+        tensor(-11.9930)
         >>> # use with pit
         >>> from torchmetrics.audio import PermutationInvariantTraining
         >>> from torchmetrics.functional.audio import signal_distortion_ratio
-        >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
-        >>> target = torch.randn(4, 2, 8000)
+        >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
+        >>> target = randn(4, 2, 8000)
         >>> pit = PermutationInvariantTraining(signal_distortion_ratio,
         ...     mode="speaker-wise", eval_func="max")
         >>> pit(preds, target)
-        tensor(-11.6051)
+        tensor(-11.7277)
 
     """
 
@@ -302,23 +301,22 @@ class SourceAggregatedSignalDistortionRatio(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.audio import SourceAggregatedSignalDistortionRatio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(2, 8000) # [..., spk, time]
-        >>> target = torch.randn(2, 8000)
+        >>> preds = randn(2, 8000) # [..., spk, time]
+        >>> target = randn(2, 8000)
         >>> sasdr = SourceAggregatedSignalDistortionRatio()
         >>> sasdr(preds, target)
-        tensor(-41.6579)
+        tensor(-50.8171)
         >>> # use with pit
         >>> from torchmetrics.audio import PermutationInvariantTraining
         >>> from torchmetrics.functional.audio import source_aggregated_signal_distortion_ratio
-        >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
-        >>> target = torch.randn(4, 2, 8000)
+        >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
+        >>> target = randn(4, 2, 8000)
         >>> pit = PermutationInvariantTraining(source_aggregated_signal_distortion_ratio,
         ...     mode="permutation-wise", eval_func="max")
         >>> pit(preds, target)
-        tensor(-41.2790)
+        tensor(-43.9780)
 
     """
 
diff --git a/src/torchmetrics/audio/snr.py b/src/torchmetrics/audio/snr.py
index bbbe059c8e4..d8b9fd4c173 100644
--- a/src/torchmetrics/audio/snr.py
+++ b/src/torchmetrics/audio/snr.py
@@ -268,15 +268,13 @@ class ComplexScaleInvariantSignalNoiseRatio(Metric):
             If ``preds`` and ``target`` does not have the same shape.
 
     Example:
-        >>> import torch
-        >>> from torch import tensor
+        >>> from torch import randn
         >>> from torchmetrics.audio import ComplexScaleInvariantSignalNoiseRatio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn((1,257,100,2))
-        >>> target = torch.randn((1,257,100,2))
+        >>> preds = randn((1,257,100,2))
+        >>> target = randn((1,257,100,2))
         >>> c_si_snr = ComplexScaleInvariantSignalNoiseRatio()
         >>> c_si_snr(preds, target)
-        tensor(-63.4849)
+        tensor(-38.8832)
 
     """
 
diff --git a/src/torchmetrics/audio/srmr.py b/src/torchmetrics/audio/srmr.py
index 620e8743fd2..62a882e7ccc 100644
--- a/src/torchmetrics/audio/srmr.py
+++ b/src/torchmetrics/audio/srmr.py
@@ -76,13 +76,12 @@ class SpeechReverberationModulationEnergyRatio(Metric):
             If ``gammatone`` or ``torchaudio`` package is not installed
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.audio import SpeechReverberationModulationEnergyRatio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
+        >>> preds = randn(8000)
         >>> srmr = SpeechReverberationModulationEnergyRatio(8000)
         >>> srmr(preds)
-        tensor(0.3354)
+        tensor(0.3191)
 
     """
 
diff --git a/src/torchmetrics/audio/stoi.py b/src/torchmetrics/audio/stoi.py
index c1f14ac2c7e..cf5d5204f77 100644
--- a/src/torchmetrics/audio/stoi.py
+++ b/src/torchmetrics/audio/stoi.py
@@ -63,14 +63,13 @@ class ShortTimeObjectiveIntelligibility(Metric):
             If ``pystoi`` package is not installed
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.audio import ShortTimeObjectiveIntelligibility
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
-        >>> target = torch.randn(8000)
+        >>> preds = randn(8000)
+        >>> target = randn(8000)
         >>> stoi = ShortTimeObjectiveIntelligibility(8000, False)
         >>> stoi(preds, target)
-        tensor(-0.0100)
+        tensor(-0.0842)
 
     """
 
@@ -132,11 +131,10 @@ def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_
             :scale: 75
 
             >>> # Example plotting a single value
-            >>> import torch
+            >>> from torch import randn
             >>> from torchmetrics.audio import ShortTimeObjectiveIntelligibility
-            >>> g = torch.manual_seed(1)
-            >>> preds = torch.randn(8000)
-            >>> target = torch.randn(8000)
+            >>> preds = randn(8000)
+            >>> target = randn(8000)
             >>> metric = ShortTimeObjectiveIntelligibility(8000, False)
             >>> metric.update(preds, target)
             >>> fig_, ax_ = metric.plot()
@@ -145,12 +143,11 @@ def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
+            >>> from torch import randn
             >>> from torchmetrics.audio import ShortTimeObjectiveIntelligibility
             >>> metric = ShortTimeObjectiveIntelligibility(8000, False)
-            >>> g = torch.manual_seed(1)
-            >>> preds = torch.randn(8000)
-            >>> target = torch.randn(8000)
+            >>> preds = randn(8000)
+            >>> target = randn(8000)
             >>> values = [ ]
             >>> for _ in range(10):
             ...     values.append(metric(preds, target))
diff --git a/src/torchmetrics/classification/group_fairness.py b/src/torchmetrics/classification/group_fairness.py
index 4d6735901bb..8575d4d464b 100644
--- a/src/torchmetrics/classification/group_fairness.py
+++ b/src/torchmetrics/classification/group_fairness.py
@@ -302,25 +302,23 @@ def plot(
         .. plot::
             :scale: 75
 
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand, randint
             >>> # Example plotting a single value
             >>> from torchmetrics.classification import BinaryFairness
             >>> metric = BinaryFairness(2)
-            >>> metric.update(torch.rand(20), torch.randint(2,(20,)), torch.randint(2,(20,)))
+            >>> metric.update(rand(20), randint(2, (20,)), randint(2, (20,)))
             >>> fig_, ax_ = metric.plot()
 
         .. plot::
             :scale: 75
 
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import ones, rand, randint
             >>> # Example plotting multiple values
             >>> from torchmetrics.classification import BinaryFairness
             >>> metric = BinaryFairness(2)
             >>> values = [ ]
             >>> for _ in range(10):
-            ...     values.append(metric(torch.rand(20), torch.randint(2,(20,)), torch.ones(20).long()))
+            ...     values.append(metric(rand(20), randint(2, (20,) ), ones(20).long()))
             >>> fig_, ax_ = metric.plot(values)
 
         """
diff --git a/src/torchmetrics/classification/ranking.py b/src/torchmetrics/classification/ranking.py
index dd58022197b..4d2df8a9151 100644
--- a/src/torchmetrics/classification/ranking.py
+++ b/src/torchmetrics/classification/ranking.py
@@ -66,10 +66,10 @@ class MultilabelCoverageError(Metric):
             Set to ``False`` for faster computations.
 
     Example:
+        >>> from torch import rand, randint
         >>> from torchmetrics.classification import MultilabelCoverageError
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(10, 5)
-        >>> target = torch.randint(2, (10, 5))
+        >>> preds = rand(10, 5)
+        >>> target = randint(2, (10, 5))
         >>> mlce = MultilabelCoverageError(num_labels=5)
         >>> mlce(preds, target)
         tensor(3.9000)
@@ -186,10 +186,10 @@ class MultilabelRankingAveragePrecision(Metric):
             Set to ``False`` for faster computations.
 
     Example:
+        >>> from torch import rand, randint
         >>> from torchmetrics.classification import MultilabelRankingAveragePrecision
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(10, 5)
-        >>> target = torch.randint(2, (10, 5))
+        >>> preds = rand(10, 5)
+        >>> target = randint(2, (10, 5))
         >>> mlrap = MultilabelRankingAveragePrecision(num_labels=5)
         >>> mlrap(preds, target)
         tensor(0.7744)
@@ -308,10 +308,10 @@ class MultilabelRankingLoss(Metric):
             Set to ``False`` for faster computations.
 
     Example:
+        >>> from torch import rand, randint
         >>> from torchmetrics.classification import MultilabelRankingLoss
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(10, 5)
-        >>> target = torch.randint(2, (10, 5))
+        >>> preds = rand(10, 5)
+        >>> target = randint(2, (10, 5))
         >>> mlrl = MultilabelRankingLoss(num_labels=5)
         >>> mlrl(preds, target)
         tensor(0.4167)
diff --git a/src/torchmetrics/clustering/calinski_harabasz_score.py b/src/torchmetrics/clustering/calinski_harabasz_score.py
index 5d15a33b0e5..a9cb9df1c01 100644
--- a/src/torchmetrics/clustering/calinski_harabasz_score.py
+++ b/src/torchmetrics/clustering/calinski_harabasz_score.py
@@ -54,11 +54,10 @@ class CalinskiHarabaszScore(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example::
-        >>> import torch
+        >>> from torch import randn, randint
         >>> from torchmetrics.clustering import CalinskiHarabaszScore
-        >>> _ = torch.manual_seed(42)
-        >>> data = torch.randn(10, 3)
-        >>> labels = torch.randint(3, (10,))
+        >>> data = randn(10, 3)
+        >>> labels = randint(3, (10,))
         >>> metric = CalinskiHarabaszScore()
         >>> metric(data, labels)
         tensor(3.0053)
diff --git a/src/torchmetrics/clustering/davies_bouldin_score.py b/src/torchmetrics/clustering/davies_bouldin_score.py
index c856be3ae59..40827b568cb 100644
--- a/src/torchmetrics/clustering/davies_bouldin_score.py
+++ b/src/torchmetrics/clustering/davies_bouldin_score.py
@@ -64,11 +64,10 @@ class DaviesBouldinScore(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example::
-        >>> import torch
+        >>> from torch import randn, randint
         >>> from torchmetrics.clustering import DaviesBouldinScore
-        >>> _ = torch.manual_seed(42)
-        >>> data = torch.randn(10, 3)
-        >>> labels = torch.randint(3, (10,))
+        >>> data = randn(10, 3)
+        >>> labels = randint(3, (10,))
         >>> metric = DaviesBouldinScore()
         >>> metric(data, labels)
         tensor(1.2540)
diff --git a/src/torchmetrics/functional/audio/_deprecated.py b/src/torchmetrics/functional/audio/_deprecated.py
index ebeff731f9d..8b337318f7a 100644
--- a/src/torchmetrics/functional/audio/_deprecated.py
+++ b/src/torchmetrics/functional/audio/_deprecated.py
@@ -69,21 +69,20 @@ def _signal_distortion_ratio(
 ) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> g = torch.manual_seed(1)
-    >>> preds = torch.randn(8000)
-    >>> target = torch.randn(8000)
+    >>> from torch import randn
+    >>> preds = randn(8000)
+    >>> target = randn(8000)
     >>> _signal_distortion_ratio(preds, target)
-    tensor(-12.0589)
+    tensor(-11.9930)
     >>> # use with permutation_invariant_training
-    >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
-    >>> target = torch.randn(4, 2, 8000)
+    >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
+    >>> target = randn(4, 2, 8000)
     >>> best_metric, best_perm = _permutation_invariant_training(preds, target, _signal_distortion_ratio)
     >>> best_metric
-    tensor([-11.6375, -11.4358, -11.7148, -11.6325])
+    tensor([-11.7748, -11.7948, -11.7160, -11.6254])
     >>> best_perm
     tensor([[1, 0],
-            [0, 1],
+            [1, 0],
             [1, 0],
             [0, 1]])
 
diff --git a/src/torchmetrics/functional/audio/pesq.py b/src/torchmetrics/functional/audio/pesq.py
index c865ac80d26..ad1d9506f08 100644
--- a/src/torchmetrics/functional/audio/pesq.py
+++ b/src/torchmetrics/functional/audio/pesq.py
@@ -68,13 +68,12 @@ def perceptual_evaluation_speech_quality(
     Example:
         >>> from torch import randn
         >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality
-        >>> g = torch.manual_seed(1)
         >>> preds = randn(8000)
         >>> target = randn(8000)
         >>> perceptual_evaluation_speech_quality(preds, target, 8000, 'nb')
-        tensor(2.2076)
+        tensor(2.2885)
         >>> perceptual_evaluation_speech_quality(preds, target, 16000, 'wb')
-        tensor(1.7359)
+        tensor(1.6805)
 
     """
     if not _PESQ_AVAILABLE:
diff --git a/src/torchmetrics/functional/audio/sdr.py b/src/torchmetrics/functional/audio/sdr.py
index d549a9c96ed..f6cb0bf2a2e 100644
--- a/src/torchmetrics/functional/audio/sdr.py
+++ b/src/torchmetrics/functional/audio/sdr.py
@@ -124,23 +124,22 @@ def signal_distortion_ratio(
             If ``preds`` and ``target`` does not have the same shape
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.audio import signal_distortion_ratio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
-        >>> target = torch.randn(8000)
+        >>> preds = randn(8000)
+        >>> target = randn(8000)
         >>> signal_distortion_ratio(preds, target)
-        tensor(-12.0589)
+        tensor(-11.9930)
         >>> # use with permutation_invariant_training
         >>> from torchmetrics.functional.audio import permutation_invariant_training
-        >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
-        >>> target = torch.randn(4, 2, 8000)
+        >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
+        >>> target = randn(4, 2, 8000)
         >>> best_metric, best_perm = permutation_invariant_training(preds, target, signal_distortion_ratio)
         >>> best_metric
-        tensor([-11.6375, -11.4358, -11.7148, -11.6325])
+        tensor([-11.7748, -11.7948, -11.7160, -11.6254])
         >>> best_perm
         tensor([[1, 0],
-                [0, 1],
+                [1, 0],
                 [1, 0],
                 [0, 1]])
 
@@ -260,23 +259,22 @@ def source_aggregated_signal_distortion_ratio(
         SA-SDR with shape ``(...)``
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.audio import source_aggregated_signal_distortion_ratio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(2, 8000)  # [..., spk, time]
-        >>> target = torch.randn(2, 8000)
+        >>> preds = randn(2, 8000)  # [..., spk, time]
+        >>> target = randn(2, 8000)
         >>> source_aggregated_signal_distortion_ratio(preds, target)
-        tensor(-41.6579)
+        tensor(-50.8171)
         >>> # use with permutation_invariant_training
         >>> from torchmetrics.functional.audio import permutation_invariant_training
-        >>> preds = torch.randn(4, 2, 8000)  # [batch, spk, time]
-        >>> target = torch.randn(4, 2, 8000)
+        >>> preds = randn(4, 2, 8000)  # [batch, spk, time]
+        >>> target = randn(4, 2, 8000)
         >>> best_metric, best_perm = permutation_invariant_training(preds, target,
         ...     source_aggregated_signal_distortion_ratio, mode="permutation-wise")
         >>> best_metric
-        tensor([-37.9511, -41.9124, -42.7369, -42.5155])
+        tensor([-42.6290, -44.3500, -34.7503, -54.1828])
         >>> best_perm
-        tensor([[1, 0],
+        tensor([[0, 1],
                 [1, 0],
                 [0, 1],
                 [1, 0]])
diff --git a/src/torchmetrics/functional/audio/snr.py b/src/torchmetrics/functional/audio/snr.py
index a157061f832..0adc53dff30 100644
--- a/src/torchmetrics/functional/audio/snr.py
+++ b/src/torchmetrics/functional/audio/snr.py
@@ -106,13 +106,12 @@ def complex_scale_invariant_signal_noise_ratio(preds: Tensor, target: Tensor, ze
             If ``preds`` and ``target`` does not have the same shape.
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.audio import complex_scale_invariant_signal_noise_ratio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn((1,257,100,2))
-        >>> target = torch.randn((1,257,100,2))
+        >>> preds = randn((1,257,100,2))
+        >>> target = randn((1,257,100,2))
         >>> complex_scale_invariant_signal_noise_ratio(preds, target)
-        tensor([-63.4849])
+        tensor([-38.8832])
 
     """
     if preds.is_complex():
diff --git a/src/torchmetrics/functional/audio/srmr.py b/src/torchmetrics/functional/audio/srmr.py
index 03f4f764d8c..79f710a6a31 100644
--- a/src/torchmetrics/functional/audio/srmr.py
+++ b/src/torchmetrics/functional/audio/srmr.py
@@ -221,12 +221,11 @@ def speech_reverberation_modulation_energy_ratio(
             If ``gammatone`` or ``torchaudio`` package is not installed
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.audio import speech_reverberation_modulation_energy_ratio
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
+        >>> preds = randn(8000)
         >>> speech_reverberation_modulation_energy_ratio(preds, 8000)
-        tensor([0.3354], dtype=torch.float64)
+        tensor([0.3191], dtype=torch.float64)
 
     """
     if not _TORCHAUDIO_AVAILABLE or not _TORCHAUDIO_GREATER_EQUAL_0_10 or not _GAMMATONE_AVAILABLE:
diff --git a/src/torchmetrics/functional/audio/stoi.py b/src/torchmetrics/functional/audio/stoi.py
index 79736956c9a..91d09cc64c3 100644
--- a/src/torchmetrics/functional/audio/stoi.py
+++ b/src/torchmetrics/functional/audio/stoi.py
@@ -59,13 +59,12 @@ def short_time_objective_intelligibility(
             If ``preds`` and ``target`` does not have the same shape
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.audio.stoi import short_time_objective_intelligibility
-        >>> g = torch.manual_seed(1)
-        >>> preds = torch.randn(8000)
-        >>> target = torch.randn(8000)
+        >>> preds = randn(8000)
+        >>> target = randn(8000)
         >>> short_time_objective_intelligibility(preds, target, 8000).float()
-        tensor(-0.0100)
+        tensor(-0.0842)
 
     """
     if not _PYSTOI_AVAILABLE:
diff --git a/src/torchmetrics/functional/classification/confusion_matrix.py b/src/torchmetrics/functional/classification/confusion_matrix.py
index b668c152e5b..1b93450ab69 100644
--- a/src/torchmetrics/functional/classification/confusion_matrix.py
+++ b/src/torchmetrics/functional/classification/confusion_matrix.py
@@ -94,7 +94,7 @@ def _binary_confusion_matrix_tensor_validation(
     _check_same_shape(preds, target)
 
     # Check that target only contains {0,1} values or value in ignore_index
-    unique_values = torch.unique(target)
+    unique_values = torch.unique(target, dim=None)
     if ignore_index is None:
         check = torch.any((unique_values != 0) & (unique_values != 1))
     else:
@@ -107,7 +107,7 @@ def _binary_confusion_matrix_tensor_validation(
 
     # If preds is label tensor, also check that it only contains {0,1} values
     if not preds.is_floating_point():
-        unique_values = torch.unique(preds)
+        unique_values = torch.unique(preds, dim=None)
         if torch.any((unique_values != 0) & (unique_values != 1)):
             raise RuntimeError(
                 f"Detected the following values in `preds`: {unique_values} but expected only"
@@ -287,7 +287,7 @@ def _multiclass_confusion_matrix_tensor_validation(
 
     check_value = num_classes if ignore_index is None else num_classes + 1
     for t, name in ((target, "target"),) + ((preds, "preds"),) if not preds.is_floating_point() else ():  # noqa: RUF005
-        num_unique_values = len(torch.unique(t))
+        num_unique_values = len(torch.unique(t, dim=None))
         if num_unique_values > check_value:
             raise RuntimeError(
                 f"Detected more unique values in `{name}` than expected. Expected only {check_value} but found"
@@ -454,7 +454,7 @@ def _multilabel_confusion_matrix_tensor_validation(
         )
 
     # Check that target only contains [0,1] values or value in ignore_index
-    unique_values = torch.unique(target)
+    unique_values = torch.unique(target, dim=None)
     if ignore_index is None:
         check = torch.any((unique_values != 0) & (unique_values != 1))
     else:
@@ -467,7 +467,7 @@ def _multilabel_confusion_matrix_tensor_validation(
 
     # If preds is label tensor, also check that it only contains [0,1] values
     if not preds.is_floating_point():
-        unique_values = torch.unique(preds)
+        unique_values = torch.unique(preds, dim=None)
         if torch.any((unique_values != 0) & (unique_values != 1)):
             raise RuntimeError(
                 f"Detected the following values in `preds`: {unique_values} but expected only"
diff --git a/src/torchmetrics/functional/classification/jaccard.py b/src/torchmetrics/functional/classification/jaccard.py
index 1d240df68af..dfddd68255f 100644
--- a/src/torchmetrics/functional/classification/jaccard.py
+++ b/src/torchmetrics/functional/classification/jaccard.py
@@ -67,7 +67,7 @@ def _jaccard_index_reduce(
         raise ValueError(f"The `average` has to be one of {allowed_average}, got {average}.")
     confmat = confmat.float()
     if average == "binary":
-        return confmat[1, 1] / (confmat[0, 1] + confmat[1, 0] + confmat[1, 1])
+        return _safe_divide(confmat[1, 1], (confmat[0, 1] + confmat[1, 0] + confmat[1, 1]), zero_division=zero_division)
 
     ignore_index_cond = ignore_index is not None and 0 <= ignore_index < confmat.shape[0]
     multilabel = confmat.ndim == 3
diff --git a/src/torchmetrics/functional/classification/precision_recall_curve.py b/src/torchmetrics/functional/classification/precision_recall_curve.py
index da12db561a1..c4607fd9489 100644
--- a/src/torchmetrics/functional/classification/precision_recall_curve.py
+++ b/src/torchmetrics/functional/classification/precision_recall_curve.py
@@ -148,7 +148,7 @@ def _binary_precision_recall_curve_tensor_validation(
         )
 
     # Check that target only contains {0,1} values or value in ignore_index
-    unique_values = torch.unique(target)
+    unique_values = torch.unique(target, dim=None)
     if ignore_index is None:
         check = torch.any((unique_values != 0) & (unique_values != 1))
     else:
@@ -417,7 +417,7 @@ def _multiclass_precision_recall_curve_tensor_validation(
             f" but got {preds.shape} and {target.shape}"
         )
 
-    num_unique_values = len(torch.unique(target))
+    num_unique_values = len(torch.unique(target, dim=None))
     check = num_unique_values > num_classes if ignore_index is None else num_unique_values > num_classes + 1
     if check:
         raise RuntimeError(
diff --git a/src/torchmetrics/functional/classification/ranking.py b/src/torchmetrics/functional/classification/ranking.py
index d6130979cd2..87bade5e88d 100644
--- a/src/torchmetrics/functional/classification/ranking.py
+++ b/src/torchmetrics/functional/classification/ranking.py
@@ -87,10 +87,10 @@ def multilabel_coverage_error(
             Set to ``False`` for faster computations.
 
     Example:
+        >>> from torch import rand, randint
         >>> from torchmetrics.functional.classification import multilabel_coverage_error
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(10, 5)
-        >>> target = torch.randint(2, (10, 5))
+        >>> preds = rand(10, 5)
+        >>> target = randint(2, (10, 5))
         >>> multilabel_coverage_error(preds, target, num_labels=5)
         tensor(3.9000)
 
@@ -160,10 +160,10 @@ def multilabel_ranking_average_precision(
             Set to ``False`` for faster computations.
 
     Example:
+        >>> from torch import rand, randint
         >>> from torchmetrics.functional.classification import multilabel_ranking_average_precision
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(10, 5)
-        >>> target = torch.randint(2, (10, 5))
+        >>> preds = rand(10, 5)
+        >>> target = randint(2, (10, 5))
         >>> multilabel_ranking_average_precision(preds, target, num_labels=5)
         tensor(0.7744)
 
@@ -245,10 +245,10 @@ def multilabel_ranking_loss(
             Set to ``False`` for faster computations.
 
     Example:
+        >>> from torch import rand, randint
         >>> from torchmetrics.functional.classification import multilabel_ranking_loss
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(10, 5)
-        >>> target = torch.randint(2, (10, 5))
+        >>> preds = rand(10, 5)
+        >>> target = randint(2, (10, 5))
         >>> multilabel_ranking_loss(preds, target, num_labels=5)
         tensor(0.4167)
 
diff --git a/src/torchmetrics/functional/classification/stat_scores.py b/src/torchmetrics/functional/classification/stat_scores.py
index 47c38ff72e1..565c212f9bd 100644
--- a/src/torchmetrics/functional/classification/stat_scores.py
+++ b/src/torchmetrics/functional/classification/stat_scores.py
@@ -67,7 +67,7 @@ def _binary_stat_scores_tensor_validation(
     _check_same_shape(preds, target)
 
     # Check that target only contains [0,1] values or value in ignore_index
-    unique_values = torch.unique(target)
+    unique_values = torch.unique(target, dim=None)
     if ignore_index is None:
         check = torch.any((unique_values != 0) & (unique_values != 1))
     else:
@@ -80,7 +80,7 @@ def _binary_stat_scores_tensor_validation(
 
     # If preds is label tensor, also check that it only contains [0,1] values
     if not preds.is_floating_point():
-        unique_values = torch.unique(preds)
+        unique_values = torch.unique(preds, dim=None)
         if torch.any((unique_values != 0) & (unique_values != 1)):
             raise RuntimeError(
                 f"Detected the following values in `preds`: {unique_values} but expected only"
@@ -314,11 +314,11 @@ def _multiclass_stat_scores_tensor_validation(
 
     check_value = num_classes if ignore_index is None else num_classes + 1
     for t, name in ((target, "target"),) + ((preds, "preds"),) if not preds.is_floating_point() else ():  # noqa: RUF005
-        num_unique_values = len(torch.unique(t))
+        num_unique_values = len(torch.unique(t, dim=None))
         if num_unique_values > check_value:
             raise RuntimeError(
                 f"Detected more unique values in `{name}` than expected. Expected only {check_value} but found"
-                f" {num_unique_values} in `target`."
+                f" {num_unique_values} in `{name}`. Found values: {torch.unique(t, dim=None)}."
             )
 
 
@@ -624,7 +624,7 @@ def _multilabel_stat_scores_tensor_validation(
         )
 
     # Check that target only contains [0,1] values or value in ignore_index
-    unique_values = torch.unique(target)
+    unique_values = torch.unique(target, dim=None)
     if ignore_index is None:
         check = torch.any((unique_values != 0) & (unique_values != 1))
     else:
@@ -637,7 +637,7 @@ def _multilabel_stat_scores_tensor_validation(
 
     # If preds is label tensor, also check that it only contains [0,1] values
     if not preds.is_floating_point():
-        unique_values = torch.unique(preds)
+        unique_values = torch.unique(preds, dim=None)
         if torch.any((unique_values != 0) & (unique_values != 1)):
             raise RuntimeError(
                 f"Detected the following values in `preds`: {unique_values} but expected only"
diff --git a/src/torchmetrics/functional/clustering/calinski_harabasz_score.py b/src/torchmetrics/functional/clustering/calinski_harabasz_score.py
index 2c934dfd44d..e28e7f9a9c3 100644
--- a/src/torchmetrics/functional/clustering/calinski_harabasz_score.py
+++ b/src/torchmetrics/functional/clustering/calinski_harabasz_score.py
@@ -31,11 +31,10 @@ def calinski_harabasz_score(data: Tensor, labels: Tensor) -> Tensor:
         Scalar tensor with the Calinski Harabasz Score
 
     Example:
-        >>> import torch
+        >>> from torch import randn, randint
         >>> from torchmetrics.functional.clustering import calinski_harabasz_score
-        >>> _ = torch.manual_seed(42)
-        >>> data = torch.randn(10, 3)
-        >>> labels = torch.randint(0, 2, (10,))
+        >>> data = randn(10, 3)
+        >>> labels = randint(0, 2, (10,))
         >>> calinski_harabasz_score(data, labels)
         tensor(3.4998)
 
diff --git a/src/torchmetrics/functional/clustering/davies_bouldin_score.py b/src/torchmetrics/functional/clustering/davies_bouldin_score.py
index cc3e530d7d9..89ee1bb5d19 100644
--- a/src/torchmetrics/functional/clustering/davies_bouldin_score.py
+++ b/src/torchmetrics/functional/clustering/davies_bouldin_score.py
@@ -31,11 +31,10 @@ def davies_bouldin_score(data: Tensor, labels: Tensor) -> Tensor:
         Scalar tensor with the Davies bouldin score
 
     Example:
-        >>> import torch
+        >>> from torch import randn, randint
         >>> from torchmetrics.functional.clustering import davies_bouldin_score
-        >>> _ = torch.manual_seed(42)
-        >>> data = torch.randn(10, 3)
-        >>> labels = torch.randint(0, 2, (10,))
+        >>> data = randn(10, 3)
+        >>> labels = randint(0, 2, (10,))
         >>> davies_bouldin_score(data, labels)
         tensor(1.3249)
 
diff --git a/src/torchmetrics/functional/image/_deprecated.py b/src/torchmetrics/functional/image/_deprecated.py
index 6fc768ce58e..892d07afaa6 100644
--- a/src/torchmetrics/functional/image/_deprecated.py
+++ b/src/torchmetrics/functional/image/_deprecated.py
@@ -27,10 +27,9 @@ def _spectral_distortion_index(
 ) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> _ = torch.manual_seed(42)
-    >>> preds = torch.rand([16, 3, 16, 16])
-    >>> target = torch.rand([16, 3, 16, 16])
+    >>> from torch import rand
+    >>> preds = rand([16, 3, 16, 16])
+    >>> target = rand([16, 3, 16, 16])
     >>> _spectral_distortion_index(preds, target)
     tensor(0.0234)
 
@@ -47,12 +46,10 @@ def _error_relative_global_dimensionless_synthesis(
 ) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(42)
-    >>> preds = torch.rand([16, 1, 16, 16], generator=gen)
+    >>> from torch import rand
+    >>> preds = rand([16, 1, 16, 16])
     >>> target = preds * 0.75
-    >>> ergds = _error_relative_global_dimensionless_synthesis(preds, target)
-    >>> torch.round(ergds)
+    >>> _error_relative_global_dimensionless_synthesis(preds, target).round()
     tensor(10.)
 
     """
@@ -105,12 +102,11 @@ def _peak_signal_noise_ratio(
 def _relative_average_spectral_error(preds: Tensor, target: Tensor, window_size: int = 8) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(22)
-    >>> preds = torch.rand(4, 3, 16, 16, generator=gen)
-    >>> target = torch.rand(4, 3, 16, 16, generator=gen)
+    >>> from torch import rand
+    >>> preds = rand(4, 3, 16, 16)
+    >>> target = rand(4, 3, 16, 16)
     >>> _relative_average_spectral_error(preds, target)
-    tensor(5114.66...)
+    tensor(5326.40...)
 
     """
     _deprecated_root_import_func("relative_average_spectral_error", "image")
@@ -122,12 +118,11 @@ def _root_mean_squared_error_using_sliding_window(
 ) -> Union[Optional[Tensor], Tuple[Optional[Tensor], Tensor]]:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(22)
-    >>> preds = torch.rand(4, 3, 16, 16, generator=gen)
-    >>> target = torch.rand(4, 3, 16, 16, generator=gen)
+    >>> from torch import rand
+    >>> preds = rand(4, 3, 16, 16)
+    >>> target = rand(4, 3, 16, 16)
     >>> _root_mean_squared_error_using_sliding_window(preds, target)
-    tensor(0.3999)
+    tensor(0.4158)
 
     """
     _deprecated_root_import_func("root_mean_squared_error_using_sliding_window", "image")
@@ -143,10 +138,9 @@ def _spectral_angle_mapper(
 ) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(42)
-    >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-    >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+    >>> from torch import rand
+    >>> preds = rand([16, 3, 16, 16])
+    >>> target = rand([16, 3, 16, 16])
     >>> _spectral_angle_mapper(preds, target)
     tensor(0.5914)
 
@@ -170,12 +164,11 @@ def _multiscale_structural_similarity_index_measure(
 ) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(42)
-    >>> preds = torch.rand([3, 3, 256, 256], generator=gen)
+    >>> from torch import rand
+    >>> preds = rand([3, 3, 256, 256])
     >>> target = preds * 0.75
     >>> _multiscale_structural_similarity_index_measure(preds, target, data_range=1.0)
-    tensor(0.9627)
+    tensor(0.9628)
 
     """
     _deprecated_root_import_func("multiscale_structural_similarity_index_measure", "image")
@@ -235,9 +228,8 @@ def _structural_similarity_index_measure(
 def _total_variation(img: Tensor, reduction: Literal["mean", "sum", "none", None] = "sum") -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> _ = torch.manual_seed(42)
-    >>> img = torch.rand(5, 3, 28, 28)
+    >>> from torch import rand
+    >>> img = rand(5, 3, 28, 28)
     >>> _total_variation(img)
     tensor(7546.8018)
 
diff --git a/src/torchmetrics/functional/image/d_lambda.py b/src/torchmetrics/functional/image/d_lambda.py
index e5ffa25b5cb..5921f51d32d 100644
--- a/src/torchmetrics/functional/image/d_lambda.py
+++ b/src/torchmetrics/functional/image/d_lambda.py
@@ -65,9 +65,9 @@ def _spectral_distortion_index_compute(
             - ``'none'``: no reduction will be applied
 
     Example:
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 16, 16])
-        >>> target = torch.rand([16, 3, 16, 16])
+        >>> from torch import rand
+        >>> preds = rand([16, 3, 16, 16])
+        >>> target = rand([16, 3, 16, 16])
         >>> preds, target = _spectral_distortion_index_update(preds, target)
         >>> _spectral_distortion_index_compute(preds, target)
         tensor(0.0234)
@@ -139,10 +139,10 @@ def spectral_distortion_index(
             If ``p`` is not a positive integer.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import spectral_distortion_index
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 16, 16])
-        >>> target = torch.rand([16, 3, 16, 16])
+        >>> preds = rand([16, 3, 16, 16])
+        >>> target = rand([16, 3, 16, 16])
         >>> spectral_distortion_index(preds, target)
         tensor(0.0234)
 
diff --git a/src/torchmetrics/functional/image/d_s.py b/src/torchmetrics/functional/image/d_s.py
index e2190cb08a8..824cd3bfa8b 100644
--- a/src/torchmetrics/functional/image/d_s.py
+++ b/src/torchmetrics/functional/image/d_s.py
@@ -160,10 +160,10 @@ def _spatial_distortion_index_compute(
             If ``window_size`` is smaller than dimension of ``ms``.
 
     Example:
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 32, 32])
-        >>> ms = torch.rand([16, 3, 16, 16])
-        >>> pan = torch.rand([16, 3, 32, 32])
+        >>> from torch import rand
+        >>> preds = rand([16, 3, 32, 32])
+        >>> ms = rand([16, 3, 16, 16])
+        >>> pan = rand([16, 3, 32, 32])
         >>> preds, ms, pan, pan_lr = _spatial_distortion_index_update(preds, ms, pan)
         >>> _spatial_distortion_index_compute(preds, ms, pan, pan_lr)
         tensor(0.0090)
@@ -250,11 +250,11 @@ def spatial_distortion_index(
             If ``window_size`` is not a positive integer.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import spatial_distortion_index
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 32, 32])
-        >>> ms = torch.rand([16, 3, 16, 16])
-        >>> pan = torch.rand([16, 3, 32, 32])
+        >>> preds = rand([16, 3, 32, 32])
+        >>> ms = rand([16, 3, 16, 16])
+        >>> pan = rand([16, 3, 32, 32])
         >>> spatial_distortion_index(preds, ms, pan)
         tensor(0.0090)
 
diff --git a/src/torchmetrics/functional/image/ergas.py b/src/torchmetrics/functional/image/ergas.py
index 9d3032de9f1..41500c552e0 100644
--- a/src/torchmetrics/functional/image/ergas.py
+++ b/src/torchmetrics/functional/image/ergas.py
@@ -62,8 +62,8 @@ def _ergas_compute(
             - ``'none'`` or ``None``: no reduction will be applied
 
     Example:
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 1, 16, 16], generator=gen)
+        >>> from torch import rand
+        >>> preds = rand([16, 1, 16, 16])
         >>> target = preds * 0.75
         >>> preds, target = _ergas_update(preds, target)
         >>> torch.round(_ergas_compute(preds, target))
@@ -111,9 +111,9 @@ def error_relative_global_dimensionless_synthesis(
             If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import error_relative_global_dimensionless_synthesis
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 1, 16, 16], generator=gen)
+        >>> preds = rand([16, 1, 16, 16])
         >>> target = preds * 0.75
         >>> error_relative_global_dimensionless_synthesis(preds, target)
         tensor(9.6193)
diff --git a/src/torchmetrics/functional/image/lpips.py b/src/torchmetrics/functional/image/lpips.py
index 64c237b087e..0ab3a84ced0 100644
--- a/src/torchmetrics/functional/image/lpips.py
+++ b/src/torchmetrics/functional/image/lpips.py
@@ -421,13 +421,12 @@ def learned_perceptual_image_patch_similarity(
             to ``True`` will instead expect input to be in the ``[0,1]`` range.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(123)
+        >>> from torch import rand
         >>> from torchmetrics.functional.image.lpips import learned_perceptual_image_patch_similarity
-        >>> img1 = (torch.rand(10, 3, 100, 100) * 2) - 1
-        >>> img2 = (torch.rand(10, 3, 100, 100) * 2) - 1
+        >>> img1 = (rand(10, 3, 100, 100) * 2) - 1
+        >>> img2 = (rand(10, 3, 100, 100) * 2) - 1
         >>> learned_perceptual_image_patch_similarity(img1, img2, net_type='squeeze')
-        tensor(0.1008)
+        tensor(0.1005)
 
     """
     net = _NoTrainLpips(net=net_type).to(device=img1.device, dtype=img1.dtype)
diff --git a/src/torchmetrics/functional/image/perceptual_path_length.py b/src/torchmetrics/functional/image/perceptual_path_length.py
index 4b675ae9c54..58b0a7bae05 100644
--- a/src/torchmetrics/functional/image/perceptual_path_length.py
+++ b/src/torchmetrics/functional/image/perceptual_path_length.py
@@ -202,9 +202,8 @@ def perceptual_path_length(
         A tuple containing the mean, standard deviation and all distances.
 
     Example::
-        >>> from torchmetrics.functional.image import perceptual_path_length
         >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torchmetrics.functional.image import perceptual_path_length
         >>> class DummyGenerator(torch.nn.Module):
         ...    def __init__(self, z_size) -> None:
         ...       super().__init__()
diff --git a/src/torchmetrics/functional/image/psnrb.py b/src/torchmetrics/functional/image/psnrb.py
index 8e190d9f563..f725ea4bd80 100644
--- a/src/torchmetrics/functional/image/psnrb.py
+++ b/src/torchmetrics/functional/image/psnrb.py
@@ -122,11 +122,10 @@ def peak_signal_noise_ratio_with_blocked_effect(
         Tensor with PSNRB score
 
     Example:
-        >>> import torch
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import peak_signal_noise_ratio_with_blocked_effect
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(1, 1, 28, 28)
-        >>> target = torch.rand(1, 1, 28, 28)
+        >>> preds = rand(1, 1, 28, 28)
+        >>> target = rand(1, 1, 28, 28)
         >>> peak_signal_noise_ratio_with_blocked_effect(preds, target)
         tensor(7.8402)
 
diff --git a/src/torchmetrics/functional/image/qnr.py b/src/torchmetrics/functional/image/qnr.py
index 2e963345634..e34e6bc2473 100644
--- a/src/torchmetrics/functional/image/qnr.py
+++ b/src/torchmetrics/functional/image/qnr.py
@@ -63,12 +63,11 @@ def quality_with_no_reference(
             If ``alpha`` or ``beta`` is not a non-negative real number.
 
     Example:
-        >>> import torch
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import quality_with_no_reference
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 32, 32])
-        >>> ms = torch.rand([16, 3, 16, 16])
-        >>> pan = torch.rand([16, 3, 32, 32])
+        >>> preds = rand([16, 3, 32, 32])
+        >>> ms = rand([16, 3, 16, 16])
+        >>> pan = rand([16, 3, 32, 32])
         >>> quality_with_no_reference(preds, ms, pan)
         tensor(0.9694)
 
diff --git a/src/torchmetrics/functional/image/rase.py b/src/torchmetrics/functional/image/rase.py
index 54d20c6eee0..388f2c237a3 100644
--- a/src/torchmetrics/functional/image/rase.py
+++ b/src/torchmetrics/functional/image/rase.py
@@ -80,12 +80,12 @@ def relative_average_spectral_error(preds: Tensor, target: Tensor, window_size:
         Relative Average Spectral Error (RASE)
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import relative_average_spectral_error
-        >>> g = torch.manual_seed(22)
-        >>> preds = torch.rand(4, 3, 16, 16)
-        >>> target = torch.rand(4, 3, 16, 16)
+        >>> preds = rand(4, 3, 16, 16)
+        >>> target = rand(4, 3, 16, 16)
         >>> relative_average_spectral_error(preds, target)
-        tensor(5114.66...)
+        tensor(5326.40...)
 
     Raises:
         ValueError: If ``window_size`` is not a positive integer.
diff --git a/src/torchmetrics/functional/image/rmse_sw.py b/src/torchmetrics/functional/image/rmse_sw.py
index 9ef9fa773de..16f1a0af80a 100644
--- a/src/torchmetrics/functional/image/rmse_sw.py
+++ b/src/torchmetrics/functional/image/rmse_sw.py
@@ -124,12 +124,12 @@ def root_mean_squared_error_using_sliding_window(
         (Optionally) RMSE map
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import root_mean_squared_error_using_sliding_window
-        >>> g = torch.manual_seed(22)
-        >>> preds = torch.rand(4, 3, 16, 16)
-        >>> target = torch.rand(4, 3, 16, 16)
+        >>> preds = rand(4, 3, 16, 16)
+        >>> target = rand(4, 3, 16, 16)
         >>> root_mean_squared_error_using_sliding_window(preds, target)
-        tensor(0.3999)
+        tensor(0.4158)
 
     Raises:
         ValueError: If ``window_size`` is not a positive integer.
diff --git a/src/torchmetrics/functional/image/sam.py b/src/torchmetrics/functional/image/sam.py
index 9bfd58cfc8c..71927ff6b42 100644
--- a/src/torchmetrics/functional/image/sam.py
+++ b/src/torchmetrics/functional/image/sam.py
@@ -65,9 +65,9 @@ def _sam_compute(
             - ``'none'`` or ``None``: no reduction will be applied
 
     Example:
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-        >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+        >>> from torch import rand
+        >>> preds = rand([16, 3, 16, 16])
+        >>> target = rand([16, 3, 16, 16])
         >>> preds, target = _sam_update(preds, target)
         >>> _sam_compute(preds, target)
         tensor(0.5914)
@@ -106,10 +106,10 @@ def spectral_angle_mapper(
             If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import spectral_angle_mapper
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-        >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+        >>> preds = rand([16, 3, 16, 16],)
+        >>> target = rand([16, 3, 16, 16])
         >>> spectral_angle_mapper(preds, target)
         tensor(0.5914)
 
diff --git a/src/torchmetrics/functional/image/scc.py b/src/torchmetrics/functional/image/scc.py
index 167ddbd37b5..a4b7bd85725 100644
--- a/src/torchmetrics/functional/image/scc.py
+++ b/src/torchmetrics/functional/image/scc.py
@@ -185,17 +185,16 @@ def spatial_correlation_coefficient(
         Tensor with scc score
 
     Example:
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.image import spatial_correlation_coefficient as scc
-        >>> _ = torch.manual_seed(42)
-        >>> x = torch.randn(5, 3, 16, 16)
+        >>> x = randn(5, 3, 16, 16)
         >>> scc(x, x)
         tensor(1.)
-        >>> x = torch.randn(5, 16, 16)
+        >>> x = randn(5, 16, 16)
         >>> scc(x, x)
         tensor(1.)
-        >>> x = torch.randn(5, 3, 16, 16)
-        >>> y = torch.randn(5, 3, 16, 16)
+        >>> x = randn(5, 3, 16, 16)
+        >>> y = randn(5, 3, 16, 16)
         >>> scc(x, y, reduction="none")
         tensor([0.0223, 0.0256, 0.0616, 0.0159, 0.0170])
 
diff --git a/src/torchmetrics/functional/image/ssim.py b/src/torchmetrics/functional/image/ssim.py
index e33e3943fab..c61ef833fe3 100644
--- a/src/torchmetrics/functional/image/ssim.py
+++ b/src/torchmetrics/functional/image/ssim.py
@@ -124,11 +124,15 @@ def _ssim_update(
     dtype = preds.dtype
     gauss_kernel_size = [int(3.5 * s + 0.5) * 2 + 1 for s in sigma]
 
-    pad_h = (gauss_kernel_size[0] - 1) // 2
-    pad_w = (gauss_kernel_size[1] - 1) // 2
+    if gaussian_kernel:
+        pad_h = (gauss_kernel_size[0] - 1) // 2
+        pad_w = (gauss_kernel_size[1] - 1) // 2
+    else:
+        pad_h = (kernel_size[0] - 1) // 2
+        pad_w = (kernel_size[1] - 1) // 2
 
     if is_3d:
-        pad_d = (gauss_kernel_size[2] - 1) // 2
+        pad_d = (kernel_size[2] - 1) // 2
         preds = _reflection_pad_3d(preds, pad_d, pad_w, pad_h)
         target = _reflection_pad_3d(target, pad_d, pad_w, pad_h)
         if gaussian_kernel:
@@ -164,25 +168,21 @@ def _ssim_update(
 
     ssim_idx_full_image = ((2 * mu_pred_target + c1) * upper) / ((mu_pred_sq + mu_target_sq + c1) * lower)
 
-    if is_3d:
-        ssim_idx = ssim_idx_full_image[..., pad_h:-pad_h, pad_w:-pad_w, pad_d:-pad_d]
-    else:
-        ssim_idx = ssim_idx_full_image[..., pad_h:-pad_h, pad_w:-pad_w]
-
     if return_contrast_sensitivity:
         contrast_sensitivity = upper / lower
         if is_3d:
             contrast_sensitivity = contrast_sensitivity[..., pad_h:-pad_h, pad_w:-pad_w, pad_d:-pad_d]
         else:
             contrast_sensitivity = contrast_sensitivity[..., pad_h:-pad_h, pad_w:-pad_w]
-        return ssim_idx.reshape(ssim_idx.shape[0], -1).mean(-1), contrast_sensitivity.reshape(
+
+        return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1), contrast_sensitivity.reshape(
             contrast_sensitivity.shape[0], -1
         ).mean(-1)
 
     if return_full_image:
-        return ssim_idx.reshape(ssim_idx.shape[0], -1).mean(-1), ssim_idx_full_image
+        return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1), ssim_idx_full_image
 
-    return ssim_idx.reshape(ssim_idx.shape[0], -1).mean(-1)
+    return ssim_idx_full_image.reshape(ssim_idx_full_image.shape[0], -1).mean(-1)
 
 
 def _ssim_compute(
@@ -502,12 +502,12 @@ def multiscale_structural_similarity_index_measure(
             If one of the elements of ``sigma`` is not a ``positive number``.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import multiscale_structural_similarity_index_measure
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([3, 3, 256, 256], generator=gen)
+        >>> preds = rand([3, 3, 256, 256])
         >>> target = preds * 0.75
         >>> multiscale_structural_similarity_index_measure(preds, target, data_range=1.0)
-        tensor(0.9627)
+        tensor(0.9628)
 
     References:
         [1] Multi-Scale Structural Similarity For Image Quality Assessment by Zhou Wang, Eero P. Simoncelli and Alan C.
diff --git a/src/torchmetrics/functional/image/tv.py b/src/torchmetrics/functional/image/tv.py
index da888b97379..be8e3366caa 100644
--- a/src/torchmetrics/functional/image/tv.py
+++ b/src/torchmetrics/functional/image/tv.py
@@ -64,10 +64,9 @@ def total_variation(img: Tensor, reduction: Optional[Literal["mean", "sum", "non
             If ``img`` is not 4D tensor
 
     Example:
-        >>> import torch
+        >>> from torch import rand
         >>> from torchmetrics.functional.image import total_variation
-        >>> _ = torch.manual_seed(42)
-        >>> img = torch.rand(5, 3, 28, 28)
+        >>> img = rand(5, 3, 28, 28)
         >>> total_variation(img)
         tensor(7546.8018)
 
diff --git a/src/torchmetrics/functional/multimodal/clip_iqa.py b/src/torchmetrics/functional/multimodal/clip_iqa.py
index 1c60bf12877..49e710e248a 100644
--- a/src/torchmetrics/functional/multimodal/clip_iqa.py
+++ b/src/torchmetrics/functional/multimodal/clip_iqa.py
@@ -293,32 +293,29 @@ def clip_image_quality_assessment(
     Example::
         Single prompt:
 
+        >>> from torch import randint
         >>> from torchmetrics.functional.multimodal import clip_image_quality_assessment
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> imgs = torch.randint(255, (2, 3, 224, 224)).float()
+        >>> imgs = randint(255, (2, 3, 224, 224)).float()
         >>> clip_image_quality_assessment(imgs, prompts=("quality",))
         tensor([0.8894, 0.8902])
 
     Example::
         Multiple prompts:
 
+        >>> from torch import randint
         >>> from torchmetrics.functional.multimodal import clip_image_quality_assessment
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> imgs = torch.randint(255, (2, 3, 224, 224)).float()
+        >>> imgs = randint(255, (2, 3, 224, 224)).float()
         >>> clip_image_quality_assessment(imgs, prompts=("quality", "brightness"))
-        {'quality': tensor([0.8894, 0.8902]), 'brightness': tensor([0.5507, 0.5208])}
+        {'quality': tensor([0.8693, 0.8705]), 'brightness': tensor([0.5722, 0.4762])}
 
     Example::
         Custom prompts. Must always be a tuple of length 2, with a positive and negative prompt.
 
+        >>> from torch import rand
         >>> from torchmetrics.functional.multimodal import clip_image_quality_assessment
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> imgs = torch.randint(255, (2, 3, 224, 224)).float()
+        >>> imgs = randint(255, (2, 3, 224, 224)).float()
         >>> clip_image_quality_assessment(imgs, prompts=(("Super good photo.", "Super bad photo."), "brightness"))
-        {'user_defined_0': tensor([0.9652, 0.9629]), 'brightness': tensor([0.5507, 0.5208])}
+        {'user_defined_0': tensor([0.9578, 0.9654]), 'brightness': tensor([0.5495, 0.5764])}
 
     """
     prompts_list, prompts_names = _clip_iqa_format_prompts(prompts)
diff --git a/src/torchmetrics/functional/multimodal/clip_score.py b/src/torchmetrics/functional/multimodal/clip_score.py
index bc0df92bd63..920eb6972e6 100644
--- a/src/torchmetrics/functional/multimodal/clip_score.py
+++ b/src/torchmetrics/functional/multimodal/clip_score.py
@@ -153,8 +153,6 @@ def clip_score(
             If the number of images and captions do not match
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
         >>> from torchmetrics.functional.multimodal import clip_score
         >>> score = clip_score(torch.randint(255, (3, 224, 224)), "a photo of a cat", "openai/clip-vit-base-patch16")
         >>> score.detach()
diff --git a/src/torchmetrics/functional/nominal/__init__.py b/src/torchmetrics/functional/nominal/__init__.py
index f29dd9302f0..772cb395895 100644
--- a/src/torchmetrics/functional/nominal/__init__.py
+++ b/src/torchmetrics/functional/nominal/__init__.py
@@ -11,6 +11,7 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+
 from torchmetrics.functional.nominal.cramers import cramers_v, cramers_v_matrix
 from torchmetrics.functional.nominal.fleiss_kappa import fleiss_kappa
 from torchmetrics.functional.nominal.pearson import (
diff --git a/src/torchmetrics/functional/nominal/cramers.py b/src/torchmetrics/functional/nominal/cramers.py
index 75a606f6c19..33b89b92014 100644
--- a/src/torchmetrics/functional/nominal/cramers.py
+++ b/src/torchmetrics/functional/nominal/cramers.py
@@ -124,10 +124,10 @@ def cramers_v(
         Cramer's V statistic
 
     Example:
+        >>> from torch import randint, round
         >>> from torchmetrics.functional.nominal import cramers_v
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(0, 4, (100,))
-        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
+        >>> preds = randint(0, 4, (100,))
+        >>> target = round(preds + torch.randn(100)).clamp(0, 4)
         >>> cramers_v(preds, target)
         tensor(0.5284)
 
@@ -161,9 +161,9 @@ def cramers_v_matrix(
         Cramer's V statistic for a dataset of categorical variables
 
     Example:
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal import cramers_v_matrix
-        >>> _ = torch.manual_seed(42)
-        >>> matrix = torch.randint(0, 4, (200, 5))
+        >>> matrix = randint(0, 4, (200, 5))
         >>> cramers_v_matrix(matrix)
         tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337],
                 [0.0637, 1.0000, 0.0000, 0.0000, 0.0000],
diff --git a/src/torchmetrics/functional/nominal/fleiss_kappa.py b/src/torchmetrics/functional/nominal/fleiss_kappa.py
index f33e11d07ef..69990f552d8 100644
--- a/src/torchmetrics/functional/nominal/fleiss_kappa.py
+++ b/src/torchmetrics/functional/nominal/fleiss_kappa.py
@@ -78,21 +78,19 @@ def fleiss_kappa(ratings: Tensor, mode: Literal["counts", "probs"] = "counts") -
 
     Example:
         >>> # Ratings are provided as counts
-        >>> import torch
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal import fleiss_kappa
-        >>> _ = torch.manual_seed(42)
-        >>> ratings = torch.randint(0, 10, size=(100, 5)).long()  # 100 samples, 5 categories, 10 raters
+        >>> ratings = randint(0, 10, size=(100, 5)).long()  # 100 samples, 5 categories, 10 raters
         >>> fleiss_kappa(ratings)
         tensor(0.0089)
 
     Example:
         >>> # Ratings are provided as probabilities
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.functional.nominal import fleiss_kappa
-        >>> _ = torch.manual_seed(42)
-        >>> ratings = torch.randn(100, 5, 10).softmax(dim=1)  # 100 samples, 5 categories, 10 raters
+        >>> ratings = randn(100, 5, 10).softmax(dim=1)  # 100 samples, 5 categories, 10 raters
         >>> fleiss_kappa(ratings, mode='probs')
-        tensor(-0.0105)
+        tensor(-0.0075)
 
     """
     if mode not in ["counts", "probs"]:
diff --git a/src/torchmetrics/functional/nominal/pearson.py b/src/torchmetrics/functional/nominal/pearson.py
index bd25c701fe4..55fe1681bf7 100644
--- a/src/torchmetrics/functional/nominal/pearson.py
+++ b/src/torchmetrics/functional/nominal/pearson.py
@@ -114,10 +114,10 @@ def pearsons_contingency_coefficient(
         Pearson's Contingency Coefficient
 
     Example:
+        >>> from torch import randint, round
         >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(0, 4, (100,))
-        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
+        >>> preds = randint(0, 4, (100,))
+        >>> target = round(preds + torch.randn(100)).clamp(0, 4)
         >>> pearsons_contingency_coefficient(preds, target)
         tensor(0.6948)
 
@@ -151,9 +151,9 @@ def pearsons_contingency_coefficient_matrix(
         Pearson's Contingency Coefficient statistic for a dataset of categorical variables
 
     Example:
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal import pearsons_contingency_coefficient_matrix
-        >>> _ = torch.manual_seed(42)
-        >>> matrix = torch.randint(0, 4, (200, 5))
+        >>> matrix = randint(0, 4, (200, 5))
         >>> pearsons_contingency_coefficient_matrix(matrix)
         tensor([[1.0000, 0.2326, 0.1959, 0.2262, 0.2989],
                 [0.2326, 1.0000, 0.1386, 0.1895, 0.1329],
diff --git a/src/torchmetrics/functional/nominal/theils_u.py b/src/torchmetrics/functional/nominal/theils_u.py
index 8bdaf38aa8a..f356dbfd03d 100644
--- a/src/torchmetrics/functional/nominal/theils_u.py
+++ b/src/torchmetrics/functional/nominal/theils_u.py
@@ -138,10 +138,10 @@ def theils_u(
         Tensor containing Theil's U statistic
 
     Example:
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal import theils_u
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(10, (10,))
-        >>> target = torch.randint(10, (10,))
+        >>> preds = randint(10, (10,))
+        >>> target = randint(10, (10,))
         >>> theils_u(preds, target)
         tensor(0.8530)
 
@@ -172,9 +172,9 @@ def theils_u_matrix(
         Theil's U statistic for a dataset of categorical variables
 
     Example:
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal import theils_u_matrix
-        >>> _ = torch.manual_seed(42)
-        >>> matrix = torch.randint(0, 4, (200, 5))
+        >>> matrix = randint(0, 4, (200, 5))
         >>> theils_u_matrix(matrix)
         tensor([[1.0000, 0.0202, 0.0142, 0.0196, 0.0353],
                 [0.0202, 1.0000, 0.0070, 0.0136, 0.0065],
diff --git a/src/torchmetrics/functional/nominal/tschuprows.py b/src/torchmetrics/functional/nominal/tschuprows.py
index 2ea20d57f19..22d256d33d1 100644
--- a/src/torchmetrics/functional/nominal/tschuprows.py
+++ b/src/torchmetrics/functional/nominal/tschuprows.py
@@ -130,10 +130,10 @@ def tschuprows_t(
         Tschuprow's T statistic
 
     Example:
+        >>> from torch import randint, round
         >>> from torchmetrics.functional.nominal import tschuprows_t
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(0, 4, (100,))
-        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
+        >>> preds = randint(0, 4, (100,))
+        >>> target = round(preds + torch.randn(100)).clamp(0, 4)
         >>> tschuprows_t(preds, target)
         tensor(0.4930)
 
@@ -169,9 +169,9 @@ def tschuprows_t_matrix(
         Tschuprow's T statistic for a dataset of categorical variables
 
     Example:
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal import tschuprows_t_matrix
-        >>> _ = torch.manual_seed(42)
-        >>> matrix = torch.randint(0, 4, (200, 5))
+        >>> matrix = randint(0, 4, (200, 5))
         >>> tschuprows_t_matrix(matrix)
         tensor([[1.0000, 0.0637, 0.0000, 0.0542, 0.1337],
                 [0.0637, 1.0000, 0.0000, 0.0000, 0.0000],
diff --git a/src/torchmetrics/functional/nominal/utils.py b/src/torchmetrics/functional/nominal/utils.py
index 258209326da..8c8cc166778 100644
--- a/src/torchmetrics/functional/nominal/utils.py
+++ b/src/torchmetrics/functional/nominal/utils.py
@@ -62,18 +62,18 @@ def _drop_empty_rows_and_cols(confmat: Tensor) -> Tensor:
     """Drop all rows and columns containing only zeros.
 
     Example:
-        >>> import torch
+        >>> from torch import randint
         >>> from torchmetrics.functional.nominal.utils import _drop_empty_rows_and_cols
-        >>> _ = torch.manual_seed(22)
-        >>> matrix = torch.randint(10, size=(3, 3))
+        >>> matrix = randint(10, size=(4, 3))
         >>> matrix[1, :] = matrix[:, 1] = 0
         >>> matrix
-        tensor([[9, 0, 6],
+        tensor([[2, 0, 6],
                 [0, 0, 0],
-                [2, 0, 8]])
+                [0, 0, 0],
+                [3, 0, 4]])
         >>> _drop_empty_rows_and_cols(matrix)
-        tensor([[9, 6],
-                [2, 8]])
+        tensor([[2, 6],
+                [3, 4]])
 
     """
     confmat = confmat[confmat.sum(1) != 0]
diff --git a/src/torchmetrics/functional/regression/wmape.py b/src/torchmetrics/functional/regression/wmape.py
index e461951c695..443badba325 100644
--- a/src/torchmetrics/functional/regression/wmape.py
+++ b/src/torchmetrics/functional/regression/wmape.py
@@ -74,10 +74,9 @@ def weighted_mean_absolute_percentage_error(preds: Tensor, target: Tensor) -> Te
         Tensor with WMAPE.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randn(20,)
-        >>> target = torch.randn(20,)
+        >>> from torch import randn
+        >>> preds = randn(20,)
+        >>> target = randn(20,)
         >>> weighted_mean_absolute_percentage_error(preds, target)
         tensor(1.3967)
 
diff --git a/src/torchmetrics/functional/segmentation/generalized_dice.py b/src/torchmetrics/functional/segmentation/generalized_dice.py
index 6b740bcea53..b362ace5393 100644
--- a/src/torchmetrics/functional/segmentation/generalized_dice.py
+++ b/src/torchmetrics/functional/segmentation/generalized_dice.py
@@ -119,11 +119,10 @@ def generalized_dice_score(
         The Generalized Dice Score
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randint
         >>> from torchmetrics.functional.segmentation import generalized_dice_score
-        >>> preds = torch.randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
-        >>> target = torch.randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
+        >>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
+        >>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
         >>> generalized_dice_score(preds, target, num_classes=5)
         tensor([0.4830, 0.4935, 0.5044, 0.4880])
         >>> generalized_dice_score(preds, target, num_classes=5, per_class=True)
diff --git a/src/torchmetrics/functional/segmentation/mean_iou.py b/src/torchmetrics/functional/segmentation/mean_iou.py
index 0a4e24da6e1..df51b9e8b47 100644
--- a/src/torchmetrics/functional/segmentation/mean_iou.py
+++ b/src/torchmetrics/functional/segmentation/mean_iou.py
@@ -90,11 +90,10 @@ def mean_iou(
         The mean IoU score
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randint
         >>> from torchmetrics.functional.segmentation import mean_iou
-        >>> preds = torch.randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
-        >>> target = torch.randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
+        >>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
+        >>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
         >>> mean_iou(preds, target, num_classes=5)
         tensor([0.3193, 0.3305, 0.3382, 0.3246])
         >>> mean_iou(preds, target, num_classes=5, per_class=True)
diff --git a/src/torchmetrics/functional/text/_deprecated.py b/src/torchmetrics/functional/text/_deprecated.py
index 62ea5645048..169c3d5357b 100644
--- a/src/torchmetrics/functional/text/_deprecated.py
+++ b/src/torchmetrics/functional/text/_deprecated.py
@@ -134,7 +134,14 @@ def _chrf_score(
     whitespace: bool = False,
     return_sentence_level_score: bool = False,
 ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
-    """Wrapper for deprecated import."""
+    """Wrapper for deprecated import.
+
+    >>> preds = ['the cat is on the mat']
+    >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
+    >>> _chrf_score(preds, target)
+    tensor(0.8640)
+
+    """
     _deprecated_root_import_func("chrf_score", "text")
     return chrf_score(
         preds=preds,
@@ -238,10 +245,9 @@ def _match_error_rate(preds: Union[str, List[str]], target: Union[str, List[str]
 def _perplexity(preds: Tensor, target: Tensor, ignore_index: Optional[int] = None) -> Tensor:
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(42)
-    >>> preds = torch.rand(2, 8, 5, generator=gen)
-    >>> target = torch.randint(5, (2, 8), generator=gen)
+    >>> from torch import rand, randint
+    >>> preds = rand(2, 8, 5)
+    >>> target = randint(5, (2, 8))
     >>> target[0, 6:] = -100
     >>> _perplexity(preds, target, ignore_index=-100)
     tensor(5.8540)
diff --git a/src/torchmetrics/functional/text/chrf.py b/src/torchmetrics/functional/text/chrf.py
index 397777f7310..ca98778fade 100644
--- a/src/torchmetrics/functional/text/chrf.py
+++ b/src/torchmetrics/functional/text/chrf.py
@@ -11,9 +11,513 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
-from typing import Sequence, Tuple, Union
 
-from torch import Tensor
+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+# Copyright 2017 Maja Popovic
+# The code is derived from https://github.com/m-popovic/chrF/blob/6d3c384/chrF%2B%2B.py
+# The original author and copyright holder have agreed to relicense the derived code under the Apache License,
+# Version 2.0 (the "License")
+# Reference to the approval: https://github.com/Lightning-AI/torchmetrics/pull/2701#issuecomment-2316891785
+
+from collections import defaultdict
+from itertools import chain
+from typing import Dict, List, Optional, Sequence, Tuple, Union
+
+import torch
+from torch import Tensor, tensor
+
+from torchmetrics.functional.text.helper import _validate_inputs
+
+_EPS_SMOOTHING = tensor(1e-16)
+# Taken from https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py
+_PUNCTUATIONS = set("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~")
+
+
+def _prepare_n_grams_dicts(
+    n_char_order: int, n_word_order: int
+) -> Tuple[
+    Dict[int, Tensor], Dict[int, Tensor], Dict[int, Tensor], Dict[int, Tensor], Dict[int, Tensor], Dict[int, Tensor]
+]:
+    """Prepare dictionaries with default zero values for total ref, hypothesis and matching character and word n-grams.
+
+    Args:
+        n_char_order: A character n-gram order.
+        n_word_order: A word n-gram order.
+
+    Return:
+        Dictionaries with default zero values for total reference, hypothesis and matching character and word
+        n-grams.
+
+    """
+    total_preds_char_n_grams: Dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_char_order)}
+    total_preds_word_n_grams: Dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_word_order)}
+    total_target_char_n_grams: Dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_char_order)}
+    total_target_word_n_grams: Dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_word_order)}
+    total_matching_char_n_grams: Dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_char_order)}
+    total_matching_word_n_grams: Dict[int, Tensor] = {n + 1: tensor(0.0) for n in range(n_word_order)}
+
+    return (
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+    )
+
+
+def _get_characters(sentence: str, whitespace: bool) -> List[str]:
+    """Split sentence into individual characters.
+
+    Args:
+        sentence: An input sentence to split.
+        whitespace: An indication whether to keep whitespaces during character n-gram extraction.
+
+    Return:
+        A list of separated characters.
+
+    """
+    if whitespace:
+        return list(sentence)
+    return list(sentence.strip().replace(" ", ""))
+
+
+def _separate_word_and_punctuation(word: str) -> List[str]:
+    """Separates out punctuations from beginning and end of words for chrF.
+
+    Adapted from https://github.com/m-popovic/chrF and
+    https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py.
+
+    Args:
+        word: An input word to be separated from a punctuation if present.
+
+    Return:
+        A list of a single word or a separated word and punctuation.
+
+    """
+    if len(word) == 1:
+        return [word]
+
+    if word[-1] in _PUNCTUATIONS:
+        return [word[:-1], word[-1]]
+    if word[0] in _PUNCTUATIONS:
+        return [word[0], word[1:]]
+    return [word]
+
+
+def _get_words_and_punctuation(sentence: str) -> List[str]:
+    """Separates out punctuations from beginning and end of words for chrF for all words in the sentence.
+
+    Args:
+        sentence: An input sentence to split
+
+    Return:
+        An aggregated list of separated words and punctuations.
+
+    """
+    return list(chain.from_iterable(_separate_word_and_punctuation(word) for word in sentence.strip().split()))
+
+
+def _ngram_counts(char_or_word_list: List[str], n_gram_order: int) -> Dict[int, Dict[Tuple[str, ...], Tensor]]:
+    """Calculate n-gram counts.
+
+    Args:
+        char_or_word_list: A list of characters of words
+        n_gram_order: The largest number of n-gram.
+
+    Return:
+        A dictionary of dictionaries with a counts of given n-grams.
+
+    """
+    ngrams: Dict[int, Dict[Tuple[str, ...], Tensor]] = defaultdict(lambda: defaultdict(lambda: tensor(0.0)))
+    for n in range(1, n_gram_order + 1):
+        for ngram in (tuple(char_or_word_list[i : i + n]) for i in range(len(char_or_word_list) - n + 1)):
+            ngrams[n][ngram] += tensor(1)
+    return ngrams
+
+
+def _get_n_grams_counts_and_total_ngrams(
+    sentence: str, n_char_order: int, n_word_order: int, lowercase: bool, whitespace: bool
+) -> Tuple[
+    Dict[int, Dict[Tuple[str, ...], Tensor]],
+    Dict[int, Dict[Tuple[str, ...], Tensor]],
+    Dict[int, Tensor],
+    Dict[int, Tensor],
+]:
+    """Get n-grams and total n-grams.
+
+    Args:
+        sentence: An input sentence
+        n_char_order: A character n-gram order.
+        n_word_order: A word n-gram order.
+        lowercase: An indication whether to enable case-insensitivity.
+        whitespace: An indication whether to keep whitespaces during character n-gram extraction.
+
+    Return:
+        char_n_grams_counts: A dictionary of dictionaries with sentence character n-grams.
+        word_n_grams_counts: A dictionary of dictionaries with sentence word n-grams.
+        total_char_n_grams: A dictionary containing a total number of sentence character n-grams.
+        total_word_n_grams: A dictionary containing a total number of sentence word n-grams.
+
+    """
+
+    def _char_and_word_ngrams_counts(
+        sentence: str, n_char_order: int, n_word_order: int, lowercase: bool
+    ) -> Tuple[Dict[int, Dict[Tuple[str, ...], Tensor]], Dict[int, Dict[Tuple[str, ...], Tensor]]]:
+        """Get a dictionary of dictionaries with a counts of given n-grams."""
+        if lowercase:
+            sentence = sentence.lower()
+        char_n_grams_counts = _ngram_counts(_get_characters(sentence, whitespace), n_char_order)
+        word_n_grams_counts = _ngram_counts(_get_words_and_punctuation(sentence), n_word_order)
+        return char_n_grams_counts, word_n_grams_counts
+
+    def _get_total_ngrams(n_grams_counts: Dict[int, Dict[Tuple[str, ...], Tensor]]) -> Dict[int, Tensor]:
+        """Get total sum of n-grams over n-grams w.r.t n."""
+        total_n_grams: Dict[int, Tensor] = defaultdict(lambda: tensor(0.0))
+        for n in n_grams_counts:
+            total_n_grams[n] = sum(n_grams_counts[n].values()).detach().clone()  # type: ignore
+        return total_n_grams
+
+    char_n_grams_counts, word_n_grams_counts = _char_and_word_ngrams_counts(
+        sentence, n_char_order, n_word_order, lowercase
+    )
+    total_char_n_grams = _get_total_ngrams(char_n_grams_counts)
+    total_word_n_grams = _get_total_ngrams(word_n_grams_counts)
+
+    return char_n_grams_counts, word_n_grams_counts, total_char_n_grams, total_word_n_grams
+
+
+def _get_ngram_matches(
+    hyp_n_grams_counts: Dict[int, Dict[Tuple[str, ...], Tensor]],
+    ref_n_grams_counts: Dict[int, Dict[Tuple[str, ...], Tensor]],
+) -> Dict[int, Tensor]:
+    """Get a number of n-gram matches between reference and hypothesis n-grams.
+
+    Args:
+        hyp_n_grams_counts: n-grams counts for hypothesis
+        ref_n_grams_counts: n-grams counts for reference
+
+    Return:
+        matching_n_grams
+
+    """
+    matching_n_grams: Dict[int, Tensor] = defaultdict(lambda: tensor(0.0))
+    for n in hyp_n_grams_counts:
+        min_n_grams = [
+            torch.min(ref_n_grams_counts[n][n_gram], hyp_n_grams_counts[n][n_gram]) for n_gram in hyp_n_grams_counts[n]
+        ]
+        matching_n_grams[n] = sum(min_n_grams).detach().clone()  # type: ignore
+    return matching_n_grams
+
+
+def _sum_over_dicts(total_n_grams: Dict[int, Tensor], n_grams: Dict[int, Tensor]) -> Dict[int, Tensor]:
+    """Aggregate total n-grams to keep corpus-level statistics.
+
+    Args:
+        total_n_grams: A dictionary containing a total corpus-level number of n-grams.
+        n_grams: A dictionary containing a sentence-level number of n-grams.
+
+    Return:
+        A dictionary containing a total corpus-level number of n-grams.
+
+    """
+    for n in n_grams:
+        total_n_grams[n] += n_grams[n]
+    return total_n_grams
+
+
+def _calculate_fscore(
+    matching_char_n_grams: Dict[int, Tensor],
+    matching_word_n_grams: Dict[int, Tensor],
+    hyp_char_n_grams: Dict[int, Tensor],
+    hyp_word_n_grams: Dict[int, Tensor],
+    ref_char_n_grams: Dict[int, Tensor],
+    ref_word_n_grams: Dict[int, Tensor],
+    n_order: float,
+    beta: float,
+) -> Tensor:
+    """Calculate sentence-level chrF/chrF++ score.
+
+    For given hypothesis and reference statistics (either sentence-level or corpus-level)
+    the chrF/chrF++ score is returned.
+
+    Args:
+        matching_char_n_grams:
+            A total number of matching character n-grams between the best matching reference and hypothesis.
+        matching_word_n_grams:
+            A total number of matching word n-grams between the best matching reference and hypothesis.
+        hyp_char_n_grams: A total number of hypothesis character n-grams.
+        hyp_word_n_grams: A total number of hypothesis word n-grams.
+        ref_char_n_grams: A total number of reference character n-grams.
+        ref_word_n_grams: A total number of reference word n-grams.
+        n_order: A sum of character and word n-gram order.
+        beta: A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal.
+
+    Return:
+        A chrF/chrF++ score. This function is universal both for sentence-level and corpus-level calculation.
+
+    """
+
+    def _get_n_gram_fscore(
+        matching_n_grams: Dict[int, Tensor], ref_n_grams: Dict[int, Tensor], hyp_n_grams: Dict[int, Tensor], beta: float
+    ) -> Dict[int, Tensor]:
+        """Get n-gram level f-score."""
+        precision: Dict[int, Tensor] = {
+            n: matching_n_grams[n] / hyp_n_grams[n] if hyp_n_grams[n] > 0 else tensor(0.0) for n in matching_n_grams
+        }
+        recall: Dict[int, Tensor] = {
+            n: matching_n_grams[n] / ref_n_grams[n] if ref_n_grams[n] > 0 else tensor(0.0) for n in matching_n_grams
+        }
+        denominator: Dict[int, Tensor] = {
+            n: torch.max(beta**2 * precision[n] + recall[n], _EPS_SMOOTHING) for n in matching_n_grams
+        }
+        f_score: Dict[int, Tensor] = {
+            n: (1 + beta**2) * precision[n] * recall[n] / denominator[n] for n in matching_n_grams
+        }
+
+        return f_score
+
+    char_n_gram_f_score = _get_n_gram_fscore(matching_char_n_grams, ref_char_n_grams, hyp_char_n_grams, beta)
+    word_n_gram_f_score = _get_n_gram_fscore(matching_word_n_grams, ref_word_n_grams, hyp_word_n_grams, beta)
+
+    return (sum(char_n_gram_f_score.values()) + sum(word_n_gram_f_score.values())) / tensor(n_order)
+
+
+def _calculate_sentence_level_chrf_score(
+    targets: List[str],
+    pred_char_n_grams_counts: Dict[int, Dict[Tuple[str, ...], Tensor]],
+    pred_word_n_grams_counts: Dict[int, Dict[Tuple[str, ...], Tensor]],
+    pred_char_n_grams: Dict[int, Tensor],
+    pred_word_n_grams: Dict[int, Tensor],
+    n_char_order: int,
+    n_word_order: int,
+    n_order: float,
+    beta: float,
+    lowercase: bool,
+    whitespace: bool,
+) -> Tuple[Tensor, Dict[int, Tensor], Dict[int, Tensor], Dict[int, Tensor], Dict[int, Tensor]]:
+    """Calculate the best sentence-level chrF/chrF++ score.
+
+    For a given pre-processed hypothesis, all references are evaluated and score and statistics
+    for the best matching reference is returned.
+
+    Args:
+        targets: An iterable of references.
+        pred_char_n_grams_counts: A dictionary of dictionaries with hypothesis character n-grams.
+        pred_word_n_grams_counts: A dictionary of dictionaries with hypothesis word n-grams.
+        pred_char_n_grams: A total number of hypothesis character n-grams.
+        pred_word_n_grams: A total number of hypothesis word n-grams.
+        n_char_order: A character n-gram order.
+        n_word_order: A word n-gram order.
+        n_order: A sum of character and word n-gram order.
+        beta: A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal.
+        lowercase: An indication whether to enable case-insensitivity.
+        whitespace: An indication whether to keep whitespaces during character n-gram extraction.
+
+    Return:
+        Return chrF/chrF++ score and statistics for the best matching hypothesis and reference.
+
+        f_score: A sentence-level chrF/chrF++ score.
+        matching_char_n_grams:
+            A total number of matching character n-grams between the best matching reference and hypothesis.
+        matching_word_n_grams:
+            A total number of matching word n-grams between the best matching reference and hypothesis.
+        target_char_n_grams: A total number of reference character n-grams.
+        target_word_n_grams: A total number of reference word n-grams.
+
+    """
+    best_f_score = tensor(0.0)
+    best_matching_char_n_grams: Dict[int, Tensor] = defaultdict(lambda: tensor(0.0))
+    best_matching_word_n_grams: Dict[int, Tensor] = defaultdict(lambda: tensor(0.0))
+    best_target_char_n_grams: Dict[int, Tensor] = defaultdict(lambda: tensor(0.0))
+    best_target_word_n_grams: Dict[int, Tensor] = defaultdict(lambda: tensor(0.0))
+
+    for target in targets:
+        (
+            target_char_n_grams_counts,
+            target_word_n_grams_counts,
+            target_char_n_grams,
+            target_word_n_grams,
+        ) = _get_n_grams_counts_and_total_ngrams(target, n_char_order, n_word_order, lowercase, whitespace)
+        matching_char_n_grams = _get_ngram_matches(target_char_n_grams_counts, pred_char_n_grams_counts)
+        matching_word_n_grams = _get_ngram_matches(target_word_n_grams_counts, pred_word_n_grams_counts)
+
+        f_score = _calculate_fscore(
+            matching_char_n_grams,
+            matching_word_n_grams,
+            pred_char_n_grams,
+            pred_word_n_grams,
+            target_char_n_grams,
+            target_word_n_grams,
+            n_order,
+            beta,
+        )
+
+        if f_score > best_f_score:
+            best_f_score = f_score
+            best_matching_char_n_grams = matching_char_n_grams
+            best_matching_word_n_grams = matching_word_n_grams
+            best_target_char_n_grams = target_char_n_grams
+            best_target_word_n_grams = target_word_n_grams
+
+    return (
+        best_f_score,
+        best_matching_char_n_grams,
+        best_matching_word_n_grams,
+        best_target_char_n_grams,
+        best_target_word_n_grams,
+    )
+
+
+def _chrf_score_update(
+    preds: Union[str, Sequence[str]],
+    target: Union[Sequence[str], Sequence[Sequence[str]]],
+    total_preds_char_n_grams: Dict[int, Tensor],
+    total_preds_word_n_grams: Dict[int, Tensor],
+    total_target_char_n_grams: Dict[int, Tensor],
+    total_target_word_n_grams: Dict[int, Tensor],
+    total_matching_char_n_grams: Dict[int, Tensor],
+    total_matching_word_n_grams: Dict[int, Tensor],
+    n_char_order: int,
+    n_word_order: int,
+    n_order: float,
+    beta: float,
+    lowercase: bool,
+    whitespace: bool,
+    sentence_chrf_score: Optional[List[Tensor]] = None,
+) -> Tuple[
+    Dict[int, Tensor],
+    Dict[int, Tensor],
+    Dict[int, Tensor],
+    Dict[int, Tensor],
+    Dict[int, Tensor],
+    Dict[int, Tensor],
+    Optional[List[Tensor]],
+]:
+    """Update function for chrf score.
+
+    Args:
+        preds: An iterable of hypothesis corpus.
+        target: An iterable of iterables of reference corpus.
+        total_preds_char_n_grams: A dictionary containing a total number of hypothesis character n-grams.
+        total_preds_word_n_grams: A dictionary containing a total number of hypothesis word n-grams.
+        total_target_char_n_grams: A dictionary containing a total number of reference character n-grams.
+        total_target_word_n_grams: A dictionary containing a total number of reference word n-grams.
+        total_matching_char_n_grams:
+            A dictionary containing a total number of matching character n-grams between references and hypotheses.
+        total_matching_word_n_grams:
+            A dictionary containing a total number of total matching word n-grams between references and hypotheses.
+        n_char_order: A character n-gram order.
+        n_word_order: A word n-gram order.
+        n_order: Sum of character and word n-gram order.
+        beta: A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal.
+        lowercase: An indication whether to enable case-insensitivity.
+        whitespace: An indication whether to keep whitespaces during character n-gram extraction.
+        sentence_chrf_score: A list of sentence-level chrF/chrF++ scores.
+
+    Return:
+        total_target_char_n_grams: number of reference character n-grams.
+        total_target_word_n_grams: number of reference word n-grams.
+        total_preds_char_n_grams: number of hypothesis character n-grams.
+        total_preds_word_n_grams: number of hypothesis word n-grams.
+        total_matching_char_n_grams: number of matching character n-grams between references and hypotheses.
+        total_matching_word_n_grams: number of total matching word n-grams between references and hypotheses.
+        sentence_chrf_score: A list of sentence-level chrF/chrF++ scores.
+
+    Raises:
+        ValueError:
+            If length of ``preds`` and ``target`` differs.
+
+    """
+    target_corpus, preds = _validate_inputs(target, preds)
+
+    for pred, targets in zip(preds, target_corpus):
+        (
+            pred_char_n_grams_counts,
+            pred_word_n_grams_counts,
+            pred_char_n_grams,
+            pred_word_n_grams,
+        ) = _get_n_grams_counts_and_total_ngrams(pred, n_char_order, n_word_order, lowercase, whitespace)
+        total_preds_char_n_grams = _sum_over_dicts(total_preds_char_n_grams, pred_char_n_grams)
+        total_preds_word_n_grams = _sum_over_dicts(total_preds_word_n_grams, pred_word_n_grams)
+
+        (
+            sentence_level_f_score,
+            matching_char_n_grams,
+            matching_word_n_grams,
+            target_char_n_grams,
+            target_word_n_grams,
+        ) = _calculate_sentence_level_chrf_score(
+            targets,  # type: ignore
+            pred_char_n_grams_counts,
+            pred_word_n_grams_counts,
+            pred_char_n_grams,
+            pred_word_n_grams,
+            n_char_order,
+            n_word_order,
+            n_order,
+            beta,
+            lowercase,
+            whitespace,
+        )
+
+        if sentence_chrf_score is not None:
+            sentence_chrf_score.append(sentence_level_f_score.unsqueeze(0))
+
+        total_target_char_n_grams = _sum_over_dicts(total_target_char_n_grams, target_char_n_grams)
+        total_target_word_n_grams = _sum_over_dicts(total_target_word_n_grams, target_word_n_grams)
+        total_matching_char_n_grams = _sum_over_dicts(total_matching_char_n_grams, matching_char_n_grams)
+        total_matching_word_n_grams = _sum_over_dicts(total_matching_word_n_grams, matching_word_n_grams)
+
+    return (
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+        sentence_chrf_score,
+    )
+
+
+def _chrf_score_compute(
+    total_preds_char_n_grams: Dict[int, Tensor],
+    total_preds_word_n_grams: Dict[int, Tensor],
+    total_target_char_n_grams: Dict[int, Tensor],
+    total_target_word_n_grams: Dict[int, Tensor],
+    total_matching_char_n_grams: Dict[int, Tensor],
+    total_matching_word_n_grams: Dict[int, Tensor],
+    n_order: float,
+    beta: float,
+) -> Tensor:
+    """Compute chrF/chrF++ score based on pre-computed target, prediction and matching character and word n-grams.
+
+    Args:
+        total_preds_char_n_grams: number of hypothesis character n-grams.
+        total_preds_word_n_grams: number of hypothesis word n-grams.
+        total_target_char_n_grams: number of reference character n-grams.
+        total_target_word_n_grams: number of reference word n-grams.
+        total_matching_char_n_grams: number of matching character n-grams between references and hypotheses.
+        total_matching_word_n_grams: number of total matching word n-grams between references and hypotheses.
+        n_order: A sum of character and word n-gram order.
+        beta:
+            A parameter determining an importance of recall w.r.t. precision. If `beta=1`, their importance is equal.
+
+    Return:
+        A corpus-level chrF/chrF++ score.
+
+    """
+    return _calculate_fscore(
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        n_order,
+        beta,
+    )
 
 
 def chrf_score(
@@ -32,10 +536,6 @@ def chrf_score(
     `chrF++ score`_. This implementation follows the implementations from https://github.com/m-popovic/chrF and
     https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py.
 
-    .. attention::
-        ChrF has been temporarily removed from the TorchMetrics package
-        due to licensing issues with the upstream package.
-
     Args:
         preds: An iterable of hypothesis corpus.
         target: An iterable of iterables of reference corpus.
@@ -50,13 +550,88 @@ def chrf_score(
         whitespace: An indication whether to keep whitespaces during character n-gram extraction.
         return_sentence_level_score: An indication whether a sentence-level chrF/chrF++ score to be returned.
 
+    Return:
+        A corpus-level chrF/chrF++ score.
+        (Optionally) A list of sentence-level chrF/chrF++ scores if `return_sentence_level_score=True`.
+
+    Raises:
+        ValueError:
+            If ``n_char_order`` is not an integer greater than or equal to 1.
+        ValueError:
+            If ``n_word_order`` is not an integer greater than or equal to 0.
+        ValueError:
+            If ``beta`` is smaller than 0.
+
+    Example:
+        >>> from torchmetrics.functional.text import chrf_score
+        >>> preds = ['the cat is on the mat']
+        >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
+        >>> chrf_score(preds, target)
+        tensor(0.8640)
+
     References:
         [1] chrF: character n-gram F-score for automatic MT evaluation by Maja Popović `chrF score`_
 
         [2] chrF++: words helping character n-grams by Maja Popović `chrF++ score`_
 
     """
-    raise NotImplementedError(
-        "ChrF has been temporarily removed from the TorchMetrics package"
-        " due to licensing issues with the upstream package."
+    if not isinstance(n_char_order, int) or n_char_order < 1:
+        raise ValueError("Expected argument `n_char_order` to be an integer greater than or equal to 1.")
+    if not isinstance(n_word_order, int) or n_word_order < 0:
+        raise ValueError("Expected argument `n_word_order` to be an integer greater than or equal to 0.")
+    if beta < 0:
+        raise ValueError("Expected argument `beta` to be greater than 0.")
+
+    n_order = float(n_char_order + n_word_order)
+
+    (
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+    ) = _prepare_n_grams_dicts(n_char_order, n_word_order)
+
+    sentence_chrf_score: Optional[List[Tensor]] = [] if return_sentence_level_score else None
+
+    (
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+        sentence_chrf_score,
+    ) = _chrf_score_update(
+        preds,
+        target,
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+        n_char_order,
+        n_word_order,
+        n_order,
+        beta,
+        lowercase,
+        whitespace,
+        sentence_chrf_score,
+    )
+
+    chrf_f_score = _chrf_score_compute(
+        total_preds_char_n_grams,
+        total_preds_word_n_grams,
+        total_target_char_n_grams,
+        total_target_word_n_grams,
+        total_matching_char_n_grams,
+        total_matching_word_n_grams,
+        n_order,
+        beta,
     )
+
+    if sentence_chrf_score:
+        return chrf_f_score, torch.cat(sentence_chrf_score)
+    return chrf_f_score
diff --git a/src/torchmetrics/functional/text/perplexity.py b/src/torchmetrics/functional/text/perplexity.py
index 39f832905cf..1561ffa412a 100644
--- a/src/torchmetrics/functional/text/perplexity.py
+++ b/src/torchmetrics/functional/text/perplexity.py
@@ -130,10 +130,9 @@ def perplexity(preds: Tensor, target: Tensor, ignore_index: Optional[int] = None
         Perplexity value
 
     Examples:
-        >>> import torch
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand(2, 8, 5, generator=gen)
-        >>> target = torch.randint(5, (2, 8), generator=gen)
+        >>> from torch import rand, randint
+        >>> preds = rand(2, 8, 5)
+        >>> target = randint(5, (2, 8))
         >>> target[0, 6:] = -100
         >>> perplexity(preds, target, ignore_index=-100)
         tensor(5.8540)
diff --git a/src/torchmetrics/functional/text/rouge.py b/src/torchmetrics/functional/text/rouge.py
index baa0b6a018c..58c9a05fecf 100644
--- a/src/torchmetrics/functional/text/rouge.py
+++ b/src/torchmetrics/functional/text/rouge.py
@@ -48,10 +48,10 @@ def _ensure_nltk_punkt_is_downloaded() -> None:
     import nltk
 
     try:
-        nltk.data.find("tokenizers/punkt")
+        nltk.data.find("tokenizers/punkt_tab")
     except LookupError:
         try:
-            nltk.download("punkt", quiet=True, force=False, halt_on_error=False, raise_on_error=True)
+            nltk.download("punkt_tab", quiet=True, force=False, halt_on_error=False, raise_on_error=True)
         except ValueError as err:
             raise OSError(
                 "`nltk` resource `punkt` is not available on a disk and cannot be downloaded as a machine is not "
diff --git a/src/torchmetrics/image/_deprecated.py b/src/torchmetrics/image/_deprecated.py
index 597f0a0c636..8b382b89cf7 100644
--- a/src/torchmetrics/image/_deprecated.py
+++ b/src/torchmetrics/image/_deprecated.py
@@ -17,11 +17,11 @@
 class _ErrorRelativeGlobalDimensionlessSynthesis(ErrorRelativeGlobalDimensionlessSynthesis):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
+    >>> from torch import rand
+    >>> preds = rand([16, 1, 16, 16])
     >>> target = preds * 0.75
     >>> ergas = _ErrorRelativeGlobalDimensionlessSynthesis()
-    >>> torch.round(ergas(preds, target))
+    >>> ergas(preds, target).round()
     tensor(10.)
 
     """
@@ -39,12 +39,12 @@ def __init__(
 class _MultiScaleStructuralSimilarityIndexMeasure(MultiScaleStructuralSimilarityIndexMeasure):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> preds = torch.rand([3, 3, 256, 256], generator=torch.manual_seed(42))
+    >>> from torch import rand
+    >>> preds = rand([3, 3, 256, 256])
     >>> target = preds * 0.75
     >>> ms_ssim = _MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0)
     >>> ms_ssim(preds, target)
-    tensor(0.9627)
+    tensor(0.9628)
 
     """
 
@@ -103,13 +103,12 @@ def __init__(
 class _RelativeAverageSpectralError(RelativeAverageSpectralError):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> g = torch.manual_seed(22)
-    >>> preds = torch.rand(4, 3, 16, 16)
-    >>> target = torch.rand(4, 3, 16, 16)
+    >>> from torch import rand
+    >>> preds = rand(4, 3, 16, 16)
+    >>> target = rand(4, 3, 16, 16)
     >>> rase = _RelativeAverageSpectralError()
     >>> rase(preds, target)
-    tensor(5114.66...)
+    tensor(5326.40...)
 
     """
 
@@ -125,13 +124,12 @@ def __init__(
 class _RootMeanSquaredErrorUsingSlidingWindow(RootMeanSquaredErrorUsingSlidingWindow):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> g = torch.manual_seed(22)
-    >>> preds = torch.rand(4, 3, 16, 16)
-    >>> target = torch.rand(4, 3, 16, 16)
+    >>> from torch import rand
+    >>> preds = rand(4, 3, 16, 16)
+    >>> target = rand(4, 3, 16, 16)
     >>> rmse_sw = RootMeanSquaredErrorUsingSlidingWindow()
     >>> rmse_sw(preds, target)
-    tensor(0.3999)
+    tensor(0.4158)
 
     """
 
@@ -147,10 +145,9 @@ def __init__(
 class _SpectralAngleMapper(SpectralAngleMapper):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(42)
-    >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-    >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+    >>> from torch import rand
+    >>> preds = rand([16, 3, 16, 16])
+    >>> target = rand([16, 3, 16, 16])
     >>> sam = _SpectralAngleMapper()
     >>> sam(preds, target)
     tensor(0.5914)
@@ -169,10 +166,9 @@ def __init__(
 class _SpectralDistortionIndex(SpectralDistortionIndex):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> _ = torch.manual_seed(42)
-    >>> preds = torch.rand([16, 3, 16, 16])
-    >>> target = torch.rand([16, 3, 16, 16])
+    >>> from torch import rand
+    >>> preds = rand([16, 3, 16, 16])
+    >>> target = rand([16, 3, 16, 16])
     >>> sdi = _SpectralDistortionIndex()
     >>> sdi(preds, target)
     tensor(0.0234)
@@ -229,10 +225,9 @@ def __init__(
 class _TotalVariation(TotalVariation):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> _ = torch.manual_seed(42)
+    >>> from torch import rand
     >>> tv = _TotalVariation()
-    >>> img = torch.rand(5, 3, 28, 28)
+    >>> img = rand(5, 3, 28, 28)
     >>> tv(img)
     tensor(7546.8018)
 
diff --git a/src/torchmetrics/image/d_lambda.py b/src/torchmetrics/image/d_lambda.py
index ff232569748..5b1e58de0dd 100644
--- a/src/torchmetrics/image/d_lambda.py
+++ b/src/torchmetrics/image/d_lambda.py
@@ -53,11 +53,10 @@ class SpectralDistortionIndex(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import rand
         >>> from torchmetrics.image import SpectralDistortionIndex
-        >>> preds = torch.rand([16, 3, 16, 16])
-        >>> target = torch.rand([16, 3, 16, 16])
+        >>> preds = rand([16, 3, 16, 16])
+        >>> target = rand([16, 3, 16, 16])
         >>> sdi = SpectralDistortionIndex()
         >>> sdi(preds, target)
         tensor(0.0234)
@@ -126,11 +125,10 @@ def plot(
             :scale: 75
 
             >>> # Example plotting a single value
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import SpectralDistortionIndex
-            >>> preds = torch.rand([16, 3, 16, 16])
-            >>> target = torch.rand([16, 3, 16, 16])
+            >>> preds = rand([16, 3, 16, 16])
+            >>> target = rand([16, 3, 16, 16])
             >>> metric = SpectralDistortionIndex()
             >>> metric.update(preds, target)
             >>> fig_, ax_ = metric.plot()
@@ -139,11 +137,10 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import SpectralDistortionIndex
-            >>> preds = torch.rand([16, 3, 16, 16])
-            >>> target = torch.rand([16, 3, 16, 16])
+            >>> preds = rand([16, 3, 16, 16])
+            >>> target = rand([16, 3, 16, 16])
             >>> metric = SpectralDistortionIndex()
             >>> values = [ ]
             >>> for _ in range(10):
diff --git a/src/torchmetrics/image/d_s.py b/src/torchmetrics/image/d_s.py
index 434561c558a..a8dacbaf447 100644
--- a/src/torchmetrics/image/d_s.py
+++ b/src/torchmetrics/image/d_s.py
@@ -74,13 +74,12 @@ class SpatialDistortionIndex(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import rand
         >>> from torchmetrics.image import SpatialDistortionIndex
-        >>> preds = torch.rand([16, 3, 32, 32])
+        >>> preds = rand([16, 3, 32, 32])
         >>> target = {
-        ...     'ms': torch.rand([16, 3, 16, 16]),
-        ...     'pan': torch.rand([16, 3, 32, 32]),
+        ...     'ms': rand([16, 3, 16, 16]),
+        ...     'pan': rand([16, 3, 32, 32]),
         ... }
         >>> sdi = SpatialDistortionIndex()
         >>> sdi(preds, target)
@@ -191,13 +190,12 @@ def plot(
             :scale: 75
 
             >>> # Example plotting a single value
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import SpatialDistortionIndex
-            >>> preds = torch.rand([16, 3, 32, 32])
+            >>> preds = rand([16, 3, 32, 32])
             >>> target = {
-            ...     'ms': torch.rand([16, 3, 16, 16]),
-            ...     'pan': torch.rand([16, 3, 32, 32]),
+            ...     'ms': rand([16, 3, 16, 16]),
+            ...     'pan': rand([16, 3, 32, 32]),
             ... }
             >>> metric = SpatialDistortionIndex()
             >>> metric.update(preds, target)
@@ -207,13 +205,12 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import SpatialDistortionIndex
-            >>> preds = torch.rand([16, 3, 32, 32])
+            >>> preds = rand([16, 3, 32, 32])
             >>> target = {
-            ...     'ms': torch.rand([16, 3, 16, 16]),
-            ...     'pan': torch.rand([16, 3, 32, 32]),
+            ...     'ms': rand([16, 3, 16, 16]),
+            ...     'pan': rand([16, 3, 32, 32]),
             ... }
             >>> metric = SpatialDistortionIndex()
             >>> values = [ ]
diff --git a/src/torchmetrics/image/ergas.py b/src/torchmetrics/image/ergas.py
index f1d8da2073e..bf6b1c99a10 100644
--- a/src/torchmetrics/image/ergas.py
+++ b/src/torchmetrics/image/ergas.py
@@ -62,12 +62,12 @@ class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
+        >>> from torch import rand
         >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
-        >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
+        >>> preds = rand([16, 1, 16, 16])
         >>> target = preds * 0.75
         >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis()
-        >>> torch.round(ergas(preds, target))
+        >>> ergas(preds, target).round()
         tensor(10.)
 
     """
@@ -131,9 +131,9 @@ def plot(
             :scale: 75
 
             >>> # Example plotting a single value
-            >>> import torch
+            >>> from torch import rand
             >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
-            >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
+            >>> preds = rand([16, 1, 16, 16])
             >>> target = preds * 0.75
             >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
             >>> metric.update(preds, target)
@@ -143,9 +143,9 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
+            >>> from torch import rand
             >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
-            >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
+            >>> preds = rand([16, 1, 16, 16])
             >>> target = preds * 0.75
             >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
             >>> values = [ ]
diff --git a/src/torchmetrics/image/fid.py b/src/torchmetrics/image/fid.py
index af4b93d7ad5..8c2e5d3cf76 100644
--- a/src/torchmetrics/image/fid.py
+++ b/src/torchmetrics/image/fid.py
@@ -265,8 +265,7 @@ class FrechetInceptionDistance(Metric):
             If ``reset_real_features`` is not an ``bool``
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(123)
+        >>> from torch import rand
         >>> from torchmetrics.image.fid import FrechetInceptionDistance
         >>> fid = FrechetInceptionDistance(feature=64)
         >>> # generate two slightly overlapping image intensity distributions
@@ -275,7 +274,7 @@ class FrechetInceptionDistance(Metric):
         >>> fid.update(imgs_dist1, real=True)
         >>> fid.update(imgs_dist2, real=False)
         >>> fid.compute()
-        tensor(12.7202)
+        tensor(12.6388)
 
     """
 
diff --git a/src/torchmetrics/image/inception.py b/src/torchmetrics/image/inception.py
index 4913a5fe50b..2b125542a17 100644
--- a/src/torchmetrics/image/inception.py
+++ b/src/torchmetrics/image/inception.py
@@ -84,15 +84,14 @@ class InceptionScore(Metric):
             If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(123)
+        >>> from torch import rand
         >>> from torchmetrics.image.inception import InceptionScore
         >>> inception = InceptionScore()
         >>> # generate some images
         >>> imgs = torch.randint(0, 255, (100, 3, 299, 299), dtype=torch.uint8)
         >>> inception.update(imgs)
         >>> inception.compute()
-        (tensor(1.0544), tensor(0.0117))
+        (tensor(1.0549), tensor(0.0121))
 
     """
 
diff --git a/src/torchmetrics/image/kid.py b/src/torchmetrics/image/kid.py
index e080116a33f..975edf800eb 100644
--- a/src/torchmetrics/image/kid.py
+++ b/src/torchmetrics/image/kid.py
@@ -148,17 +148,16 @@ class KernelInceptionDistance(Metric):
             If ``reset_real_features`` is not an ``bool``
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(123)
+        >>> from torch import randint
         >>> from torchmetrics.image.kid import KernelInceptionDistance
         >>> kid = KernelInceptionDistance(subset_size=50)
         >>> # generate two slightly overlapping image intensity distributions
-        >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
-        >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
+        >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
+        >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
         >>> kid.update(imgs_dist1, real=True)
         >>> kid.update(imgs_dist2, real=False)
         >>> kid.compute()
-        (tensor(0.0337), tensor(0.0023))
+        (tensor(0.0312), tensor(0.0025))
 
     """
 
diff --git a/src/torchmetrics/image/lpip.py b/src/torchmetrics/image/lpip.py
index c094003fa4f..f1adb73648a 100644
--- a/src/torchmetrics/image/lpip.py
+++ b/src/torchmetrics/image/lpip.py
@@ -78,15 +78,14 @@ class LearnedPerceptualImagePatchSimilarity(Metric):
             If ``reduction`` is not one of ``"mean"`` or ``"sum"``
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(123)
+        >>> from torch import rand
         >>> from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
         >>> lpips = LearnedPerceptualImagePatchSimilarity(net_type='squeeze')
         >>> # LPIPS needs the images to be in the [-1, 1] range.
-        >>> img1 = (torch.rand(10, 3, 100, 100) * 2) - 1
-        >>> img2 = (torch.rand(10, 3, 100, 100) * 2) - 1
+        >>> img1 = (rand(10, 3, 100, 100) * 2) - 1
+        >>> img2 = (rand(10, 3, 100, 100) * 2) - 1
         >>> lpips(img1, img2)
-        tensor(0.1046)
+        tensor(0.1024)
 
     """
 
diff --git a/src/torchmetrics/image/mifid.py b/src/torchmetrics/image/mifid.py
index 8c1084e6458..7d7237b7416 100644
--- a/src/torchmetrics/image/mifid.py
+++ b/src/torchmetrics/image/mifid.py
@@ -129,13 +129,12 @@ class MemorizationInformedFrechetInceptionDistance(Metric):
             If ``reset_real_features`` is not an ``bool``
 
     Example::
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randint
         >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
         >>> mifid = MemorizationInformedFrechetInceptionDistance(feature=64)
         >>> # generate two slightly overlapping image intensity distributions
-        >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
-        >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
+        >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
+        >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
         >>> mifid.update(imgs_dist1, real=True)
         >>> mifid.update(imgs_dist2, real=False)
         >>> mifid.compute()
diff --git a/src/torchmetrics/image/perceptual_path_length.py b/src/torchmetrics/image/perceptual_path_length.py
index 6b89b36b1c1..b2255941250 100644
--- a/src/torchmetrics/image/perceptual_path_length.py
+++ b/src/torchmetrics/image/perceptual_path_length.py
@@ -23,9 +23,9 @@
     perceptual_path_length,
 )
 from torchmetrics.metric import Metric
-from torchmetrics.utilities.imports import _TORCHVISION_AVAILABLE
+from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_2_0, _TORCHVISION_AVAILABLE
 
-if not _TORCHVISION_AVAILABLE:
+if not _TORCHVISION_AVAILABLE or not _TORCH_GREATER_EQUAL_2_0:
     __doctest_skip__ = ["PerceptualPathLength"]
 
 
@@ -98,9 +98,7 @@ class PerceptualPathLength(Metric):
             If ``upper_discard`` is not a float between 0 and 1 or None.
 
     Example::
-        >>> from torchmetrics.image import PerceptualPathLength
         >>> import torch
-        >>> _ = torch.manual_seed(42)
         >>> class DummyGenerator(torch.nn.Module):
         ...    def __init__(self, z_size) -> None:
         ...       super().__init__()
@@ -112,10 +110,8 @@ class PerceptualPathLength(Metric):
         ...      return torch.randn(num_samples, self.z_size)
         >>> generator = DummyGenerator(2)
         >>> ppl = PerceptualPathLength(num_samples=10)
-        >>> ppl(generator)  # doctest: +SKIP
-        (tensor(0.2371),
-        tensor(0.1763),
-        tensor([0.3502, 0.1362, 0.2535, 0.0902, 0.1784, 0.0769, 0.5871, 0.0691, 0.3921]))
+        >>> ppl(generator)
+        (tensor(...), tensor(...), tensor([...]))
 
     """
 
diff --git a/src/torchmetrics/image/psnrb.py b/src/torchmetrics/image/psnrb.py
index dc050e81fb8..bac58b84e46 100644
--- a/src/torchmetrics/image/psnrb.py
+++ b/src/torchmetrics/image/psnrb.py
@@ -51,12 +51,10 @@ class PeakSignalNoiseRatioWithBlockedEffect(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> from torchmetrics.image import PeakSignalNoiseRatioWithBlockedEffect
+        >>> from torch import rand
         >>> metric = PeakSignalNoiseRatioWithBlockedEffect()
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.rand(2, 1, 10, 10)
-        >>> target = torch.rand(2, 1, 10, 10)
+        >>> preds = rand(2, 1, 10, 10)
+        >>> target = rand(2, 1, 10, 10)
         >>> metric(preds, target)
         tensor(7.2893)
 
diff --git a/src/torchmetrics/image/qnr.py b/src/torchmetrics/image/qnr.py
index 96023db8aab..b226a6b19fd 100644
--- a/src/torchmetrics/image/qnr.py
+++ b/src/torchmetrics/image/qnr.py
@@ -70,13 +70,12 @@ class QualityWithNoReference(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import rand
         >>> from torchmetrics.image import QualityWithNoReference
-        >>> preds = torch.rand([16, 3, 32, 32])
+        >>> preds = rand([16, 3, 32, 32])
         >>> target = {
-        ...     'ms': torch.rand([16, 3, 16, 16]),
-        ...     'pan': torch.rand([16, 3, 32, 32]),
+        ...     'ms': rand([16, 3, 16, 16]),
+        ...     'pan': rand([16, 3, 32, 32]),
         ... }
         >>> qnr = QualityWithNoReference()
         >>> qnr(preds, target)
@@ -195,13 +194,12 @@ def plot(
             :scale: 75
 
             >>> # Example plotting a single value
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import QualityWithNoReference
-            >>> preds = torch.rand([16, 3, 32, 32])
+            >>> preds = rand([16, 3, 32, 32])
             >>> target = {
-            ...     'ms': torch.rand([16, 3, 16, 16]),
-            ...     'pan': torch.rand([16, 3, 32, 32]),
+            ...     'ms': rand([16, 3, 16, 16]),
+            ...     'pan': rand([16, 3, 32, 32]),
             ... }
             >>> metric = QualityWithNoReference()
             >>> metric.update(preds, target)
@@ -211,13 +209,12 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import QualityWithNoReference
-            >>> preds = torch.rand([16, 3, 32, 32])
+            >>> preds = rand([16, 3, 32, 32])
             >>> target = {
-            ...     'ms': torch.rand([16, 3, 16, 16]),
-            ...     'pan': torch.rand([16, 3, 32, 32]),
+            ...     'ms': rand([16, 3, 16, 16]),
+            ...     'pan': rand([16, 3, 32, 32]),
             ... }
             >>> metric = QualityWithNoReference()
             >>> values = [ ]
diff --git a/src/torchmetrics/image/rase.py b/src/torchmetrics/image/rase.py
index c422762eb68..b1eb32141a6 100644
--- a/src/torchmetrics/image/rase.py
+++ b/src/torchmetrics/image/rase.py
@@ -46,14 +46,12 @@ class RelativeAverageSpectralError(Metric):
         Relative Average Spectral Error (RASE)
 
     Example:
-        >>> import torch
-        >>> from torchmetrics.image import RelativeAverageSpectralError
-        >>> g = torch.manual_seed(22)
-        >>> preds = torch.rand(4, 3, 16, 16)
-        >>> target = torch.rand(4, 3, 16, 16)
+        >>> from torch import rand
+        >>> preds = rand(4, 3, 16, 16)
+        >>> target = rand(4, 3, 16, 16)
         >>> rase = RelativeAverageSpectralError()
         >>> rase(preds, target)
-        tensor(5114.66...)
+        tensor(5326.40...)
 
     Raises:
         ValueError: If ``window_size`` is not a positive integer.
@@ -124,13 +122,12 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
-            >>> _ = torch.manual_seed(42)
+            >>> from torch import rand
             >>> from torchmetrics.image import RelativeAverageSpectralError
             >>> metric = RelativeAverageSpectralError()
             >>> values = [ ]
             >>> for _ in range(10):
-            ...     values.append(metric(torch.rand(4, 3, 16, 16), torch.rand(4, 3, 16, 16)))
+            ...     values.append(metric(rand(4, 3, 16, 16), rand(4, 3, 16, 16)))
             >>> fig_, ax_ = metric.plot(values)
 
         """
diff --git a/src/torchmetrics/image/rmse_sw.py b/src/torchmetrics/image/rmse_sw.py
index e0838ec760d..c1f7c652879 100644
--- a/src/torchmetrics/image/rmse_sw.py
+++ b/src/torchmetrics/image/rmse_sw.py
@@ -43,13 +43,13 @@ class RootMeanSquaredErrorUsingSlidingWindow(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.image import RootMeanSquaredErrorUsingSlidingWindow
-        >>> g = torch.manual_seed(22)
-        >>> preds = torch.rand(4, 3, 16, 16)
-        >>> target = torch.rand(4, 3, 16, 16)
+        >>> preds = rand(4, 3, 16, 16)
+        >>> target = rand(4, 3, 16, 16)
         >>> rmse_sw = RootMeanSquaredErrorUsingSlidingWindow()
         >>> rmse_sw(preds, target)
-        tensor(0.3999)
+        tensor(0.4158)
 
     Raises:
         ValueError: If ``window_size`` is not a positive integer.
diff --git a/src/torchmetrics/image/sam.py b/src/torchmetrics/image/sam.py
index 47d4839c5e2..7aad1782852 100644
--- a/src/torchmetrics/image/sam.py
+++ b/src/torchmetrics/image/sam.py
@@ -56,11 +56,10 @@ class SpectralAngleMapper(Metric):
         Tensor with SpectralAngleMapper score
 
     Example:
-        >>> import torch
+        >>> from torch import rand
         >>> from torchmetrics.image import SpectralAngleMapper
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-        >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+        >>> preds = rand([16, 3, 16, 16])
+        >>> target = rand([16, 3, 16, 16])
         >>> sam = SpectralAngleMapper()
         >>> sam(preds, target)
         tensor(0.5914)
@@ -141,11 +140,10 @@ def plot(
             :scale: 75
 
             >>> # Example plotting single value
-            >>> import torch
+            >>> from torch import rand
             >>> from torchmetrics.image import SpectralAngleMapper
-            >>> gen = torch.manual_seed(42)
-            >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-            >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+            >>> preds = rand([16, 3, 16, 16])
+            >>> target = rand([16, 3, 16, 16])
             >>> metric = SpectralAngleMapper()
             >>> metric.update(preds, target)
             >>> fig_, ax_ = metric.plot()
@@ -154,11 +152,10 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
-            >>> import torch
+            >>> from torch import rand
             >>> from torchmetrics.image import SpectralAngleMapper
-            >>> gen = torch.manual_seed(42)
-            >>> preds = torch.rand([16, 3, 16, 16], generator=gen)
-            >>> target = torch.rand([16, 3, 16, 16], generator=gen)
+            >>> preds = rand([16, 3, 16, 16])
+            >>> target = rand([16, 3, 16, 16])
             >>> metric = SpectralAngleMapper()
             >>> values = [ ]
             >>> for _ in range(10):
diff --git a/src/torchmetrics/image/scc.py b/src/torchmetrics/image/scc.py
index 15ea2b96ecf..fac28658f63 100644
--- a/src/torchmetrics/image/scc.py
+++ b/src/torchmetrics/image/scc.py
@@ -39,11 +39,10 @@ class SpatialCorrelationCoefficient(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randn
         >>> from torchmetrics.image import SpatialCorrelationCoefficient as SCC
-        >>> preds = torch.randn([32, 3, 64, 64])
-        >>> target = torch.randn([32, 3, 64, 64])
+        >>> preds = randn([32, 3, 64, 64])
+        >>> target = randn([32, 3, 64, 64])
         >>> scc = SCC()
         >>> scc(preds, target)
         tensor(0.0023)
diff --git a/src/torchmetrics/image/ssim.py b/src/torchmetrics/image/ssim.py
index 5056589fd14..648f9c26029 100644
--- a/src/torchmetrics/image/ssim.py
+++ b/src/torchmetrics/image/ssim.py
@@ -268,14 +268,13 @@ class MultiScaleStructuralSimilarityIndexMeasure(Metric):
             If ``normalize`` is neither `None`, `ReLU` nor `simple`.
 
     Example:
+        >>> from torch import rand
         >>> from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure
-        >>> import torch
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand([3, 3, 256, 256], generator=torch.manual_seed(42))
+        >>> preds = torch.rand([3, 3, 256, 256])
         >>> target = preds * 0.75
         >>> ms_ssim = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0)
         >>> ms_ssim(preds, target)
-        tensor(0.9627)
+        tensor(0.9628)
 
     """
 
@@ -394,9 +393,9 @@ def plot(
             :scale: 75
 
             >>> # Example plotting a single value
+            >>> from torch import rand
             >>> from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure
-            >>> import torch
-            >>> preds = torch.rand([3, 3, 256, 256], generator=torch.manual_seed(42))
+            >>> preds = rand([3, 3, 256, 256])
             >>> target = preds * 0.75
             >>> metric = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0)
             >>> metric.update(preds, target)
@@ -406,9 +405,9 @@ def plot(
             :scale: 75
 
             >>> # Example plotting multiple values
+            >>> from torch import rand
             >>> from torchmetrics.image import MultiScaleStructuralSimilarityIndexMeasure
-            >>> import torch
-            >>> preds = torch.rand([3, 3, 256, 256], generator=torch.manual_seed(42))
+            >>> preds = rand([3, 3, 256, 256])
             >>> target = preds * 0.75
             >>> metric = MultiScaleStructuralSimilarityIndexMeasure(data_range=1.0)
             >>> values = [ ]
diff --git a/src/torchmetrics/image/tv.py b/src/torchmetrics/image/tv.py
index 972a07b745d..ca6276b7e86 100644
--- a/src/torchmetrics/image/tv.py
+++ b/src/torchmetrics/image/tv.py
@@ -53,9 +53,8 @@ class TotalVariation(Metric):
             If ``reduction`` is not one of ``'sum'``, ``'mean'``, ``'none'`` or ``None``
 
     Example:
-        >>> import torch
+        >>> from torch import rand
         >>> from torchmetrics.image import TotalVariation
-        >>> _ = torch.manual_seed(42)
         >>> tv = TotalVariation()
         >>> img = torch.rand(5, 3, 28, 28)
         >>> tv(img)
diff --git a/src/torchmetrics/image/vif.py b/src/torchmetrics/image/vif.py
index 3e844932399..0358cb80e66 100644
--- a/src/torchmetrics/image/vif.py
+++ b/src/torchmetrics/image/vif.py
@@ -37,11 +37,10 @@ class VisualInformationFidelity(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randn
         >>> from torchmetrics.image import VisualInformationFidelity
-        >>> preds = torch.randn([32, 3, 41, 41])
-        >>> target = torch.randn([32, 3, 41, 41])
+        >>> preds = randn([32, 3, 41, 41])
+        >>> target = randn([32, 3, 41, 41])
         >>> vif = VisualInformationFidelity()
         >>> vif(preds, target)
         tensor(0.0032)
diff --git a/src/torchmetrics/metric.py b/src/torchmetrics/metric.py
index ef9055ed560..940e393c6d1 100644
--- a/src/torchmetrics/metric.py
+++ b/src/torchmetrics/metric.py
@@ -284,7 +284,7 @@ def forward(self, *args: Any, **kwargs: Any) -> Any:
         """Aggregate and evaluate batch input directly.
 
         Serves the dual purpose of both computing the metric on the current batch of inputs but also add the batch
-        statistics to the overall accumululating metric state. Input arguments are the exact same as corresponding
+        statistics to the overall accumulating metric state. Input arguments are the exact same as corresponding
         ``update`` method. The returned output is the exact same as the output of ``compute``.
 
         Args:
@@ -361,7 +361,7 @@ def _forward_full_state_update(self, *args: Any, **kwargs: Any) -> Any:
     def _forward_reduce_state_update(self, *args: Any, **kwargs: Any) -> Any:
         """Forward computation using single call to `update`.
 
-        This can be done when the global metric state is a sinple reduction of batch states. This can be unsafe for
+        This can be done when the global metric state is a simple reduction of batch states. This can be unsafe for
         certain metric cases but is also the fastest way to both accumulate globally and compute locally.
 
         """
@@ -802,7 +802,7 @@ def _apply(self, fn: Callable, exclude_state: Sequence[str] = "") -> Module:
         """Overwrite `_apply` function such that we can also move metric states to the correct device.
 
         This method is called by the base ``nn.Module`` class whenever `.to`, `.cuda`, `.float`, `.half` etc. methods
-        are called. Dtype conversion is garded and will only happen through the special `set_dtype` method.
+        are called. Dtype conversion is guarded and will only happen through the special `set_dtype` method.
 
         Args:
             fn: the function to apply
@@ -1166,7 +1166,7 @@ def _sync_dist(self, dist_sync_fn: Optional[Callable] = None, process_group: Opt
         """
 
     def update(self, *args: Any, **kwargs: Any) -> None:
-        """Redirect the call to the input which the conposition was formed from."""
+        """Redirect the call to the input which the composition was formed from."""
         if isinstance(self.metric_a, Metric):
             self.metric_a.update(*args, **self.metric_a._filter_kwargs(**kwargs))
 
@@ -1174,7 +1174,7 @@ def update(self, *args: Any, **kwargs: Any) -> None:
             self.metric_b.update(*args, **self.metric_b._filter_kwargs(**kwargs))
 
     def compute(self) -> Any:
-        """Redirect the call to the input which the conposition was formed from."""
+        """Redirect the call to the input which the composition was formed from."""
         # also some parsing for kwargs?
         val_a = self.metric_a.compute() if isinstance(self.metric_a, Metric) else self.metric_a
         val_b = self.metric_b.compute() if isinstance(self.metric_b, Metric) else self.metric_b
@@ -1216,7 +1216,7 @@ def forward(self, *args: Any, **kwargs: Any) -> Any:
         return self._forward_cache
 
     def reset(self) -> None:
-        """Redirect the call to the input which the conposition was formed from."""
+        """Redirect the call to the input which the composition was formed from."""
         if isinstance(self.metric_a, Metric):
             self.metric_a.reset()
 
diff --git a/src/torchmetrics/multimodal/clip_iqa.py b/src/torchmetrics/multimodal/clip_iqa.py
index b3f934fee33..7a66de4ae3e 100644
--- a/src/torchmetrics/multimodal/clip_iqa.py
+++ b/src/torchmetrics/multimodal/clip_iqa.py
@@ -128,10 +128,9 @@ class CLIPImageQualityAssessment(Metric):
     Example::
         Single prompt:
 
+        >>> from torch import randint
         >>> from torchmetrics.multimodal import CLIPImageQualityAssessment
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> imgs = torch.randint(255, (2, 3, 224, 224)).float()
+        >>> imgs = randint(255, (2, 3, 224, 224)).float()
         >>> metric = CLIPImageQualityAssessment()
         >>> metric(imgs)
         tensor([0.8894, 0.8902])
@@ -139,24 +138,22 @@ class CLIPImageQualityAssessment(Metric):
     Example::
         Multiple prompts:
 
+        >>> from torch import randint
         >>> from torchmetrics.multimodal import CLIPImageQualityAssessment
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> imgs = torch.randint(255, (2, 3, 224, 224)).float()
+        >>> imgs = randint(255, (2, 3, 224, 224)).float()
         >>> metric = CLIPImageQualityAssessment(prompts=("quality", "brightness"))
         >>> metric(imgs)
-        {'quality': tensor([0.8894, 0.8902]), 'brightness': tensor([0.5507, 0.5208])}
+        {'quality': tensor([0.8693, 0.8705]), 'brightness': tensor([0.5722, 0.4762])}
 
     Example::
         Custom prompts. Must always be a tuple of length 2, with a positive and negative prompt.
 
+        >>> from torch import randint
         >>> from torchmetrics.multimodal import CLIPImageQualityAssessment
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> imgs = torch.randint(255, (2, 3, 224, 224)).float()
+        >>> imgs = randint(255, (2, 3, 224, 224)).float()
         >>> metric = CLIPImageQualityAssessment(prompts=(("Super good photo.", "Super bad photo."), "brightness"))
         >>> metric(imgs)
-        {'user_defined_0': tensor([0.9652, 0.9629]), 'brightness': tensor([0.5507, 0.5208])}
+        {'user_defined_0': tensor([0.9578, 0.9654]), 'brightness': tensor([0.5495, 0.5764])}
 
     """
 
diff --git a/src/torchmetrics/multimodal/clip_score.py b/src/torchmetrics/multimodal/clip_score.py
index eb432e0be16..f385fbc145d 100644
--- a/src/torchmetrics/multimodal/clip_score.py
+++ b/src/torchmetrics/multimodal/clip_score.py
@@ -82,12 +82,12 @@ class CLIPScore(Metric):
             If transformers package is not installed or version is lower than 4.10.0
 
     Example:
-        >>> import torch
+        >>> from torch import randint
         >>> from torchmetrics.multimodal.clip_score import CLIPScore
         >>> metric = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16")
-        >>> score = metric(torch.randint(255, (3, 224, 224), generator=torch.manual_seed(42)), "a photo of a cat")
-        >>> score.detach()
-        tensor(24.4255)
+        >>> score = metric(randint(255, (3, 224, 224)), "a photo of a cat")
+        >>> score.detach().round()
+        tensor(25.)
 
     """
 
diff --git a/src/torchmetrics/nominal/__init__.py b/src/torchmetrics/nominal/__init__.py
index f23a7eb8c6b..e36da870308 100644
--- a/src/torchmetrics/nominal/__init__.py
+++ b/src/torchmetrics/nominal/__init__.py
@@ -11,6 +11,7 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+
 from torchmetrics.nominal.cramers import CramersV
 from torchmetrics.nominal.fleiss_kappa import FleissKappa
 from torchmetrics.nominal.pearson import PearsonsContingencyCoefficient
diff --git a/src/torchmetrics/nominal/cramers.py b/src/torchmetrics/nominal/cramers.py
index 2d780e7e379..df47cc079d1 100644
--- a/src/torchmetrics/nominal/cramers.py
+++ b/src/torchmetrics/nominal/cramers.py
@@ -69,10 +69,10 @@ class CramersV(Metric):
 
     Example::
 
+        >>> from torch import randint, randn
         >>> from torchmetrics.nominal import CramersV
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(0, 4, (100,))
-        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
+        >>> preds = randint(0, 4, (100,))
+        >>> target = (preds + randn(100)).round().clamp(0, 4)
         >>> cramers_v = CramersV(num_classes=5)
         >>> cramers_v(preds, target)
         tensor(0.5284)
diff --git a/src/torchmetrics/nominal/fleiss_kappa.py b/src/torchmetrics/nominal/fleiss_kappa.py
index 9518302cdac..619e8196d4c 100644
--- a/src/torchmetrics/nominal/fleiss_kappa.py
+++ b/src/torchmetrics/nominal/fleiss_kappa.py
@@ -54,23 +54,21 @@ class FleissKappa(Metric):
 
     Example:
         >>> # Ratings are provided as counts
-        >>> import torch
+        >>> from torch import randint
         >>> from torchmetrics.nominal import FleissKappa
-        >>> _ = torch.manual_seed(42)
-        >>> ratings = torch.randint(0, 10, size=(100, 5)).long()  # 100 samples, 5 categories, 10 raters
+        >>> ratings = randint(0, 10, size=(100, 5)).long()  # 100 samples, 5 categories, 10 raters
         >>> metric = FleissKappa(mode='counts')
         >>> metric(ratings)
         tensor(0.0089)
 
     Example:
         >>> # Ratings are provided as probabilities
-        >>> import torch
+        >>> from torch import randn
         >>> from torchmetrics.nominal import FleissKappa
-        >>> _ = torch.manual_seed(42)
-        >>> ratings = torch.randn(100, 5, 10).softmax(dim=1)  # 100 samples, 5 categories, 10 raters
+        >>> ratings = randn(100, 5, 10).softmax(dim=1)  # 100 samples, 5 categories, 10 raters
         >>> metric = FleissKappa(mode='probs')
         >>> metric(ratings)
-        tensor(-0.0105)
+        tensor(-0.0075)
 
     """
 
diff --git a/src/torchmetrics/nominal/pearson.py b/src/torchmetrics/nominal/pearson.py
index 2fc88c8e851..a43cd548792 100644
--- a/src/torchmetrics/nominal/pearson.py
+++ b/src/torchmetrics/nominal/pearson.py
@@ -73,10 +73,10 @@ class PearsonsContingencyCoefficient(Metric):
 
     Example::
 
+        >>> from torch import randint, randn
         >>> from torchmetrics.nominal import PearsonsContingencyCoefficient
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(0, 4, (100,))
-        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
+        >>> preds = randint(0, 4, (100,))
+        >>> target = (preds + randn(100)).round().clamp(0, 4)
         >>> pearsons_contingency_coefficient = PearsonsContingencyCoefficient(num_classes=5)
         >>> pearsons_contingency_coefficient(preds, target)
         tensor(0.6948)
diff --git a/src/torchmetrics/nominal/theils_u.py b/src/torchmetrics/nominal/theils_u.py
index f82c7658b1f..7f7f22ecb1b 100644
--- a/src/torchmetrics/nominal/theils_u.py
+++ b/src/torchmetrics/nominal/theils_u.py
@@ -59,10 +59,10 @@ class TheilsU(Metric):
 
     Example::
 
+        >>> from torch import randint
         >>> from torchmetrics.nominal import TheilsU
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(10, (10,))
-        >>> target = torch.randint(10, (10,))
+        >>> preds = randint(10, (10,))
+        >>> target = randint(10, (10,))
         >>> metric = TheilsU(num_classes=10)
         >>> metric(preds, target)
         tensor(0.8530)
diff --git a/src/torchmetrics/nominal/tschuprows.py b/src/torchmetrics/nominal/tschuprows.py
index a14832b4121..9986fa2ec6f 100644
--- a/src/torchmetrics/nominal/tschuprows.py
+++ b/src/torchmetrics/nominal/tschuprows.py
@@ -69,10 +69,10 @@ class TschuprowsT(Metric):
 
     Example::
 
+        >>> from torch import randint
         >>> from torchmetrics.nominal import TschuprowsT
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randint(0, 4, (100,))
-        >>> target = torch.round(preds + torch.randn(100)).clamp(0, 4)
+        >>> preds = randint(0, 4, (100,))
+        >>> target = (preds + torch.randn(100)).round().clamp(0, 4)
         >>> tschuprows_t = TschuprowsT(num_classes=5)
         >>> tschuprows_t(preds, target)
         tensor(0.4930)
diff --git a/src/torchmetrics/regression/wmape.py b/src/torchmetrics/regression/wmape.py
index 067c995bfb2..42fadb906ef 100644
--- a/src/torchmetrics/regression/wmape.py
+++ b/src/torchmetrics/regression/wmape.py
@@ -51,10 +51,9 @@ class WeightedMeanAbsolutePercentageError(Metric):
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
-        >>> preds = torch.randn(20,)
-        >>> target = torch.randn(20,)
+        >>> from torch import randn
+        >>> preds = randn(20,)
+        >>> target = randn(20,)
         >>> wmape = WeightedMeanAbsolutePercentageError()
         >>> wmape(preds, target)
         tensor(1.3967)
diff --git a/src/torchmetrics/segmentation/generalized_dice.py b/src/torchmetrics/segmentation/generalized_dice.py
index 646ba63fbcf..855cc8015cb 100644
--- a/src/torchmetrics/segmentation/generalized_dice.py
+++ b/src/torchmetrics/segmentation/generalized_dice.py
@@ -85,20 +85,19 @@ class GeneralizedDiceScore(Metric):
             If ``weight_type`` is not one of ``"square"``, ``"simple"``, or ``"linear"``
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(0)
+        >>> from torch import randint
         >>> from torchmetrics.segmentation import GeneralizedDiceScore
         >>> gds = GeneralizedDiceScore(num_classes=3)
-        >>> preds = torch.randint(0, 2, (10, 3, 128, 128))
-        >>> target = torch.randint(0, 2, (10, 3, 128, 128))
+        >>> preds = randint(0, 2, (10, 3, 128, 128))
+        >>> target = randint(0, 2, (10, 3, 128, 128))
         >>> gds(preds, target)
-        tensor(0.4983)
+        tensor(0.4992)
         >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True)
         >>> gds(preds, target)
-        tensor([0.4987, 0.4966, 0.4995])
+        tensor([0.5001, 0.4993, 0.4982])
         >>> gds = GeneralizedDiceScore(num_classes=3, per_class=True, include_background=False)
         >>> gds(preds, target)
-        tensor([0.4966, 0.4995])
+        tensor([0.4993, 0.4982])
 
     """
 
diff --git a/src/torchmetrics/segmentation/mean_iou.py b/src/torchmetrics/segmentation/mean_iou.py
index f36f7fc3bc0..5e271f64827 100644
--- a/src/torchmetrics/segmentation/mean_iou.py
+++ b/src/torchmetrics/segmentation/mean_iou.py
@@ -65,20 +65,19 @@ class MeanIoU(Metric):
             If ``per_class`` is not a boolean
 
     Example:
-        >>> import torch
-        >>> _ = torch.manual_seed(0)
+        >>> from torch import randint
         >>> from torchmetrics.segmentation import MeanIoU
         >>> miou = MeanIoU(num_classes=3)
-        >>> preds = torch.randint(0, 2, (10, 3, 128, 128))
-        >>> target = torch.randint(0, 2, (10, 3, 128, 128))
+        >>> preds = randint(0, 2, (10, 3, 128, 128))
+        >>> target = randint(0, 2, (10, 3, 128, 128))
         >>> miou(preds, target)
-        tensor(0.3318)
+        tensor(0.3326)
         >>> miou = MeanIoU(num_classes=3, per_class=True)
         >>> miou(preds, target)
-        tensor([0.3322, 0.3303, 0.3329])
+        tensor([0.3334, 0.3327, 0.3318])
         >>> miou = MeanIoU(num_classes=3, per_class=True, include_background=False)
         >>> miou(preds, target)
-        tensor([0.3303, 0.3329])
+        tensor([0.3327, 0.3318])
 
     """
 
@@ -104,17 +103,19 @@ def __init__(
         self.per_class = per_class
 
         num_classes = num_classes - 1 if not include_background else num_classes
-        self.add_state("score", default=torch.zeros(num_classes if per_class else 1), dist_reduce_fx="mean")
+        self.add_state("score", default=torch.zeros(num_classes if per_class else 1), dist_reduce_fx="sum")
+        self.add_state("num_batches", default=torch.tensor(0), dist_reduce_fx="sum")
 
     def update(self, preds: Tensor, target: Tensor) -> None:
         """Update the state with the new data."""
         intersection, union = _mean_iou_update(preds, target, self.num_classes, self.include_background)
         score = _mean_iou_compute(intersection, union, per_class=self.per_class)
         self.score += score.mean(0) if self.per_class else score.mean()
+        self.num_batches += 1
 
     def compute(self) -> Tensor:
-        """Update the state with the new data."""
-        return self.score  # / self.num_batches
+        """Compute the final Mean Intersection over Union (mIoU)."""
+        return self.score / self.num_batches
 
     def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
         """Plot a single or multiple values from the metric.
diff --git a/src/torchmetrics/text/_deprecated.py b/src/torchmetrics/text/_deprecated.py
index 77e32730711..0c7ffef29af 100644
--- a/src/torchmetrics/text/_deprecated.py
+++ b/src/torchmetrics/text/_deprecated.py
@@ -57,7 +57,15 @@ def __init__(
 
 
 class _CHRFScore(CHRFScore):
-    """Wrapper for deprecated import."""
+    """Wrapper for deprecated import.
+
+    >>> preds = ['the cat is on the mat']
+    >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
+    >>> chrf = _CHRFScore()
+    >>> chrf(preds, target)
+    tensor(0.8640)
+
+    """
 
     def __init__(
         self,
@@ -136,10 +144,9 @@ def __init__(
 class _Perplexity(Perplexity):
     """Wrapper for deprecated import.
 
-    >>> import torch
-    >>> gen = torch.manual_seed(42)
-    >>> preds = torch.rand(2, 8, 5, generator=gen)
-    >>> target = torch.randint(5, (2, 8), generator=gen)
+    >>> from torch import rand, randint
+    >>> preds = rand(2, 8, 5)
+    >>> target = randint(5, (2, 8))
     >>> target[0, 6:] = -100
     >>> perp = _Perplexity(ignore_index=-100)
     >>> perp(preds, target)
diff --git a/src/torchmetrics/text/chrf.py b/src/torchmetrics/text/chrf.py
index 742388d06ff..1ff412ab1a4 100644
--- a/src/torchmetrics/text/chrf.py
+++ b/src/torchmetrics/text/chrf.py
@@ -11,13 +11,20 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+# referenced from
+# Library Name: torchtext
+# Authors: torchtext authors and @sluks
+# Date: 2021-11-25
+# Link:
 
 import itertools
 from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union
 
-from torch import Tensor
+import torch
+from torch import Tensor, tensor
 
 from torchmetrics import Metric
+from torchmetrics.functional.text.chrf import _chrf_score_compute, _chrf_score_update, _prepare_n_grams_dicts
 from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
 from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
 
@@ -49,10 +56,6 @@ class CHRFScore(Metric):
     in `chrF++ score`_. This implementation follows the implementations from https://github.com/m-popovic/chrF and
     https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py.
 
-    .. attention::
-        ChrF has been temporarily removed from the TorchMetrics package
-        due to licensing issues with the upstream package.
-
     As input to ``forward`` and ``update`` the metric accepts the following input:
 
     - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus
@@ -73,6 +76,22 @@ class CHRFScore(Metric):
         return_sentence_level_score: An indication whether a sentence-level chrF/chrF++ score to be returned.
         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
+    Raises:
+        ValueError:
+            If ``n_char_order`` is not an integer greater than or equal to 1.
+        ValueError:
+            If ``n_word_order`` is not an integer greater than or equal to 0.
+        ValueError:
+            If ``beta`` is smaller than 0.
+
+    Example:
+        >>> from torchmetrics.text import CHRFScore
+        >>> preds = ['the cat is on the mat']
+        >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
+        >>> chrf = CHRFScore()
+        >>> chrf(preds, target)
+        tensor(0.8640)
+
     """
 
     is_differentiable: bool = False
@@ -93,77 +112,73 @@ def __init__(
         return_sentence_level_score: bool = False,
         **kwargs: Any,
     ) -> None:
-        # super().__init__(**kwargs)
-        #
-        # if not isinstance(n_char_order, int) or n_char_order < 1:
-        #     raise ValueError("Expected argument `n_char_order` to be an integer greater than or equal to 1.")
-        # self.n_char_order = n_char_order
-        # if not isinstance(n_word_order, int) or n_word_order < 0:
-        #     raise ValueError("Expected argument `n_word_order` to be an integer greater than or equal to 0.")
-        # self.n_word_order = n_word_order
-        # if beta < 0:
-        #     raise ValueError("Expected argument `beta` to be greater than 0.")
-        # self.beta = beta
-        # self.lowercase = lowercase
-        # self.whitespace = whitespace
-        # self.return_sentence_level_score = return_sentence_level_score
-        #
-        # self.n_order = float(n_char_order + n_word_order)
-        #
-        # # Adding state dynamically
-        # for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
-        #     for n in range(1, n_gram_order + 1):
-        #         state_name = self._get_state_name(text, n_gram_level, n)
-        #         self.add_state(state_name, tensor(0.0), dist_reduce_fx="sum")
-        #
-        # if self.return_sentence_level_score:
-        #     self.add_state("sentence_chrf_score", [], dist_reduce_fx="cat")
-        raise NotImplementedError(
-            "ChrF has been temporarily removed from the TorchMetrics package"
-            " due to licensing issues with the upstream package."
-        )
+        super().__init__(**kwargs)
+
+        if not isinstance(n_char_order, int) or n_char_order < 1:
+            raise ValueError("Expected argument `n_char_order` to be an integer greater than or equal to 1.")
+        self.n_char_order = n_char_order
+        if not isinstance(n_word_order, int) or n_word_order < 0:
+            raise ValueError("Expected argument `n_word_order` to be an integer greater than or equal to 0.")
+        self.n_word_order = n_word_order
+        if beta < 0:
+            raise ValueError("Expected argument `beta` to be greater than 0.")
+        self.beta = beta
+        self.lowercase = lowercase
+        self.whitespace = whitespace
+        self.return_sentence_level_score = return_sentence_level_score
+
+        self.n_order = float(n_char_order + n_word_order)
+
+        # Adding state dynamically
+        for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
+            for n in range(1, n_gram_order + 1):
+                state_name = self._get_state_name(text, n_gram_level, n)
+                self.add_state(state_name, tensor(0.0), dist_reduce_fx="sum")
+
+        if self.return_sentence_level_score:
+            self.add_state("sentence_chrf_score", [], dist_reduce_fx="cat")
 
     def update(self, preds: Sequence[str], target: Sequence[Sequence[str]]) -> None:
         """Update state with predictions and targets."""
-        # n_grams_dicts_tuple = _chrf_score_update(
-        #     preds,
-        #     target,
-        #     *self._convert_states_to_dicts(),
-        #     self.n_char_order,
-        #     self.n_word_order,
-        #     self.n_order,
-        #     self.beta,
-        #     self.lowercase,
-        #     self.whitespace,
-        #     self.sentence_chrf_score if self.return_sentence_level_score else None,
-        # )
-        # self._update_states_from_dicts(n_grams_dicts_tuple[:-1])
-        # if self.sentence_chrf_score is not None:
-        #     self.sentence_chrf_score = n_grams_dicts_tuple[-1]
-
-    def compute(self) -> Union[Tensor, Tuple[Tensor, Tensor]]:  # type: ignore[empty-body]
+        n_grams_dicts_tuple = _chrf_score_update(
+            preds,
+            target,
+            *self._convert_states_to_dicts(),
+            self.n_char_order,
+            self.n_word_order,
+            self.n_order,
+            self.beta,
+            self.lowercase,
+            self.whitespace,
+            self.sentence_chrf_score if self.return_sentence_level_score else None,
+        )
+        self._update_states_from_dicts(n_grams_dicts_tuple[:-1])
+        if self.sentence_chrf_score is not None:
+            self.sentence_chrf_score = n_grams_dicts_tuple[-1]
+
+    def compute(self) -> Union[Tensor, Tuple[Tensor, Tensor]]:
         """Calculate chrF/chrF++ score."""
-        # if self.sentence_chrf_score is not None:
-        #     return (
-        #         _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta),
-        #         torch.cat(self.sentence_chrf_score),
-        #     )
-        # return _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta)
-
-    def _convert_states_to_dicts(self) -> _DICT_STATES_TYPES:  # type: ignore[empty-body]
+        if self.sentence_chrf_score is not None:
+            return (
+                _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta),
+                torch.cat(self.sentence_chrf_score),
+            )
+        return _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta)
+
+    def _convert_states_to_dicts(self) -> _DICT_STATES_TYPES:
         """Convert global metric states to the n-gram dictionaries to be passed in ``_chrf_score_update``."""
-        # n_grams_dicts: Dict[str, Dict[int, Tensor]] = dict(
-        #     zip(_DICT_STATES_NAMES, _prepare_n_grams_dicts(self.n_char_order, self.n_word_order))
-        # )
-        #
-        # for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
-        #     for n in range(1, n_gram_order + 1):
-        #         dict_name = self._get_dict_name(text, n_gram_level)
-        #         state_name = self._get_state_name(text, n_gram_level, n)
-        #
-        #         n_grams_dicts[dict_name][n] = getattr(self, state_name)
-        #
-        # return tuple(n_grams_dicts.values())  # type: ignore
+        n_grams_dicts: Dict[str, Dict[int, Tensor]] = dict(
+            zip(_DICT_STATES_NAMES, _prepare_n_grams_dicts(self.n_char_order, self.n_word_order))
+        )
+
+        for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
+            for n in range(1, n_gram_order + 1):
+                dict_name = self._get_dict_name(text, n_gram_level)
+                state_name = self._get_state_name(text, n_gram_level, n)
+
+                n_grams_dicts[dict_name][n] = getattr(self, state_name)
+
+        return tuple(n_grams_dicts.values())  # type: ignore
 
     def _update_states_from_dicts(self, n_grams_dicts_tuple: _DICT_STATES_TYPES) -> None:
         """Update global metric states based on the n-gram dictionaries calculated on the current batch."""
@@ -206,5 +221,29 @@ def plot(
             ModuleNotFoundError:
                 If `matplotlib` is not installed
 
+        .. plot::
+            :scale: 75
+
+            >>> # Example plotting a single value
+            >>> from torchmetrics.text import CHRFScore
+            >>> metric = CHRFScore()
+            >>> preds = ['the cat is on the mat']
+            >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
+            >>> metric.update(preds, target)
+            >>> fig_, ax_ = metric.plot()
+
+        .. plot::
+            :scale: 75
+
+            >>> # Example plotting multiple values
+            >>> from torchmetrics.text import CHRFScore
+            >>> metric = CHRFScore()
+            >>> preds = ['the cat is on the mat']
+            >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
+            >>> values = [ ]
+            >>> for _ in range(10):
+            ...     values.append(metric(preds, target))
+            >>> fig_, ax_ = metric.plot(values)
+
         """
         return self._plot(val, ax)
diff --git a/src/torchmetrics/text/perplexity.py b/src/torchmetrics/text/perplexity.py
index 51804881df8..d13eac2f402 100644
--- a/src/torchmetrics/text/perplexity.py
+++ b/src/torchmetrics/text/perplexity.py
@@ -48,11 +48,10 @@ class Perplexity(Metric):
             Additional keyword arguments, see :ref:`Metric kwargs` for more info.
 
     Examples:
+        >>> from torch import rand, randint
         >>> from torchmetrics.text import Perplexity
-        >>> import torch
-        >>> gen = torch.manual_seed(42)
-        >>> preds = torch.rand(2, 8, 5, generator=gen)
-        >>> target = torch.randint(5, (2, 8), generator=gen)
+        >>> preds = rand(2, 8, 5)
+        >>> target = randint(5, (2, 8))
         >>> target[0, 6:] = -100
         >>> perp = Perplexity(ignore_index=-100)
         >>> perp(preds, target)
diff --git a/src/torchmetrics/utilities/imports.py b/src/torchmetrics/utilities/imports.py
index f21f29f8152..e7228d77454 100644
--- a/src/torchmetrics/utilities/imports.py
+++ b/src/torchmetrics/utilities/imports.py
@@ -60,6 +60,7 @@
 _MECAB_KO_DIC_AVAILABLE = RequirementCache("mecab_ko_dic")
 _IPADIC_AVAILABLE = RequirementCache("ipadic")
 _SENTENCEPIECE_AVAILABLE = RequirementCache("sentencepiece")
+_SCIPI_AVAILABLE = RequirementCache("scipy")
 _SKLEARN_GREATER_EQUAL_1_3 = RequirementCache("scikit-learn>=1.3.0")
 
 _LATEX_AVAILABLE: bool = shutil.which("latex") is not None
diff --git a/src/torchmetrics/wrappers/bootstrapping.py b/src/torchmetrics/wrappers/bootstrapping.py
index 9b904568b65..d59f7724c2a 100644
--- a/src/torchmetrics/wrappers/bootstrapping.py
+++ b/src/torchmetrics/wrappers/bootstrapping.py
@@ -75,15 +75,15 @@ class basically keeps multiple copies of the same base metric in memory and when
 
     Example::
         >>> from pprint import pprint
+        >>> from torch import randint
         >>> from torchmetrics.wrappers import BootStrapper
         >>> from torchmetrics.classification import MulticlassAccuracy
-        >>> _ = torch.manual_seed(123)
         >>> base_metric = MulticlassAccuracy(num_classes=5, average='micro')
         >>> bootstrap = BootStrapper(base_metric, num_bootstraps=20)
-        >>> bootstrap.update(torch.randint(5, (20,)), torch.randint(5, (20,)))
+        >>> bootstrap.update(randint(5, (20,)), randint(5, (20,)))
         >>> output = bootstrap.compute()
         >>> pprint(output)
-        {'mean': tensor(0.2205), 'std': tensor(0.0859)}
+        {'mean': tensor(0.2089), 'std': tensor(0.0772)}
 
     """
 
diff --git a/src/torchmetrics/wrappers/classwise.py b/src/torchmetrics/wrappers/classwise.py
index 78cb27ae46c..217c94d6bc0 100644
--- a/src/torchmetrics/wrappers/classwise.py
+++ b/src/torchmetrics/wrappers/classwise.py
@@ -44,58 +44,54 @@ class ClasswiseWrapper(WrapperMetric):
     Example::
         Basic example where the output of a metric is unwrapped into a dictionary with the class index as keys:
 
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randint, randn
         >>> from torchmetrics.wrappers import ClasswiseWrapper
         >>> from torchmetrics.classification import MulticlassAccuracy
         >>> metric = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None))
-        >>> preds = torch.randn(10, 3).softmax(dim=-1)
-        >>> target = torch.randint(3, (10,))
+        >>> preds = randn(10, 3).softmax(dim=-1)
+        >>> target = randint(3, (10,))
         >>> metric(preds, target)  # doctest: +NORMALIZE_WHITESPACE
         {'multiclassaccuracy_0': tensor(0.5000),
-        'multiclassaccuracy_1': tensor(0.7500),
-        'multiclassaccuracy_2': tensor(0.)}
+         'multiclassaccuracy_1': tensor(0.7500),
+         'multiclassaccuracy_2': tensor(0.)}
 
     Example::
         Using custom name via prefix and postfix:
 
-        >>> import torch
-        >>> _ = torch.manual_seed(42)
+        >>> from torch import randint, randn
         >>> from torchmetrics.wrappers import ClasswiseWrapper
         >>> from torchmetrics.classification import MulticlassAccuracy
         >>> metric_pre = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), prefix="acc-")
         >>> metric_post = ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), postfix="-acc")
-        >>> preds = torch.randn(10, 3).softmax(dim=-1)
-        >>> target = torch.randint(3, (10,))
+        >>> preds = randn(10, 3).softmax(dim=-1)
+        >>> target = randint(3, (10,))
         >>> metric_pre(preds, target)  # doctest: +NORMALIZE_WHITESPACE
-        {'acc-0': tensor(0.5000),
-         'acc-1': tensor(0.7500),
-         'acc-2': tensor(0.)}
+        {'acc-0': tensor(0.3333), 'acc-1': tensor(0.6667), 'acc-2': tensor(0.)}
         >>> metric_post(preds, target)  # doctest: +NORMALIZE_WHITESPACE
-        {'0-acc': tensor(0.5000),
-         '1-acc': tensor(0.7500),
-         '2-acc': tensor(0.)}
+        {'0-acc': tensor(0.3333), '1-acc': tensor(0.6667), '2-acc': tensor(0.)}
 
     Example::
         Providing labels as a list of strings:
 
+        >>> from torch import randint, randn
         >>> from torchmetrics.wrappers import ClasswiseWrapper
         >>> from torchmetrics.classification import MulticlassAccuracy
         >>> metric = ClasswiseWrapper(
         ...    MulticlassAccuracy(num_classes=3, average=None),
         ...    labels=["horse", "fish", "dog"]
         ... )
-        >>> preds = torch.randn(10, 3).softmax(dim=-1)
-        >>> target = torch.randint(3, (10,))
+        >>> preds = randn(10, 3).softmax(dim=-1)
+        >>> target = randint(3, (10,))
         >>> metric(preds, target)  # doctest: +NORMALIZE_WHITESPACE
-        {'multiclassaccuracy_horse': tensor(0.3333),
-        'multiclassaccuracy_fish': tensor(0.6667),
-        'multiclassaccuracy_dog': tensor(0.)}
+        {'multiclassaccuracy_horse': tensor(0.),
+         'multiclassaccuracy_fish': tensor(0.3333),
+         'multiclassaccuracy_dog': tensor(0.4000)}
 
     Example::
         Classwise can also be used in combination with :class:`~torchmetrics.MetricCollection`. In this case, everything
         will be flattened into a single dictionary:
 
+        >>> from torch import randint, randn
         >>> from torchmetrics import MetricCollection
         >>> from torchmetrics.wrappers import ClasswiseWrapper
         >>> from torchmetrics.classification import MulticlassAccuracy, MulticlassRecall
@@ -104,15 +100,15 @@ class ClasswiseWrapper(WrapperMetric):
         ...     {'multiclassaccuracy': ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), labels),
         ...     'multiclassrecall': ClasswiseWrapper(MulticlassRecall(num_classes=3, average=None), labels)}
         ... )
-        >>> preds = torch.randn(10, 3).softmax(dim=-1)
-        >>> target = torch.randint(3, (10,))
+        >>> preds = randn(10, 3).softmax(dim=-1)
+        >>> target = randint(3, (10,))
         >>> metric(preds, target)  # doctest: +NORMALIZE_WHITESPACE
-        {'multiclassaccuracy_horse': tensor(0.),
+        {'multiclassaccuracy_horse': tensor(0.6667),
          'multiclassaccuracy_fish': tensor(0.3333),
-         'multiclassaccuracy_dog': tensor(0.4000),
-         'multiclassrecall_horse': tensor(0.),
+         'multiclassaccuracy_dog': tensor(0.5000),
+         'multiclassrecall_horse': tensor(0.6667),
          'multiclassrecall_fish': tensor(0.3333),
-         'multiclassrecall_dog': tensor(0.4000)}
+         'multiclassrecall_dog': tensor(0.5000)}
 
     """
 
diff --git a/src/torchmetrics/wrappers/feature_share.py b/src/torchmetrics/wrappers/feature_share.py
index b1fe0451534..1bd1b81783b 100644
--- a/src/torchmetrics/wrappers/feature_share.py
+++ b/src/torchmetrics/wrappers/feature_share.py
@@ -68,7 +68,6 @@ class FeatureShare(MetricCollection):
 
     Example::
         >>> import torch
-        >>> _ = torch.manual_seed(42)
         >>> from torchmetrics.wrappers import FeatureShare
         >>> from torchmetrics.image import FrechetInceptionDistance, KernelInceptionDistance
         >>> # initialize the metrics
diff --git a/src/torchmetrics/wrappers/multitask.py b/src/torchmetrics/wrappers/multitask.py
index 556a7183638..fa2f04db97d 100644
--- a/src/torchmetrics/wrappers/multitask.py
+++ b/src/torchmetrics/wrappers/multitask.py
@@ -38,12 +38,27 @@ class MultitaskWrapper(WrapperMetric):
         task_metrics:
             Dictionary associating each task to a Metric or a MetricCollection. The keys of the dictionary represent the
             names of the tasks, and the values represent the metrics to use for each task.
+        prefix:
+            A string to append in front of the metric keys. If not provided, will default to an empty string.
+        postfix:
+            A string to append after the keys of the output dict. If not provided, will default to an empty string.
+
+    .. note::
+        The use pre prefix and postfix allows for easily creating task wrappers for training, validation and test.
+        The arguments are only changing the output keys of the computed metrics and not the input keys. This means
+        that a ``MultitaskWrapper`` initialized as ``MultitaskWrapper({"task": Metric()}, prefix="train_")`` will
+        still expect the input to be a dictionary with the key "task", but the output will be a dictionary with the key
+        "train_task".
 
     Raises:
         TypeError:
             If argument `task_metrics` is not an dictionary
         TypeError:
             If not all values in the `task_metrics` dictionary is instances of `Metric` or `MetricCollection`
+        ValueError:
+            If `prefix` is not a string
+        ValueError:
+            If `postfix` is not a string
 
     Example (with a single metric per class):
          >>> import torch
@@ -91,18 +106,59 @@ class MultitaskWrapper(WrapperMetric):
          {'Classification': {'BinaryAccuracy': tensor(0.3333), 'BinaryF1Score': tensor(0.)},
           'Regression': {'MeanSquaredError': tensor(0.8333), 'MeanAbsoluteError': tensor(0.6667)}}
 
+    Example (with a prefix and postfix):
+        >>> import torch
+        >>> from torchmetrics.wrappers import MultitaskWrapper
+        >>> from torchmetrics.regression import MeanSquaredError
+        >>> from torchmetrics.classification import BinaryAccuracy
+        >>>
+        >>> classification_target = torch.tensor([0, 1, 0])
+        >>> regression_target = torch.tensor([2.5, 5.0, 4.0])
+        >>> targets = {"Classification": classification_target, "Regression": regression_target}
+        >>> classification_preds = torch.tensor([0, 0, 1])
+        >>> regression_preds = torch.tensor([3.0, 5.0, 2.5])
+        >>> preds = {"Classification": classification_preds, "Regression": regression_preds}
+        >>>
+        >>> metrics = MultitaskWrapper({
+        ...     "Classification": BinaryAccuracy(),
+        ...     "Regression": MeanSquaredError()
+        ... }, prefix="train_")
+        >>> metrics.update(preds, targets)
+        >>> metrics.compute()
+        {'train_Classification': tensor(0.3333), 'train_Regression': tensor(0.8333)}
+
     """
 
-    is_differentiable = False
+    is_differentiable: bool = False
 
     def __init__(
         self,
         task_metrics: Dict[str, Union[Metric, MetricCollection]],
+        prefix: Optional[str] = None,
+        postfix: Optional[str] = None,
     ) -> None:
-        self._check_task_metrics_type(task_metrics)
         super().__init__()
+
+        if not isinstance(task_metrics, dict):
+            raise TypeError(f"Expected argument `task_metrics` to be a dict. Found task_metrics = {task_metrics}")
+
+        for metric in task_metrics.values():
+            if not (isinstance(metric, (Metric, MetricCollection))):
+                raise TypeError(
+                    "Expected each task's metric to be a Metric or a MetricCollection. "
+                    f"Found a metric of type {type(metric)}"
+                )
+
         self.task_metrics = nn.ModuleDict(task_metrics)
 
+        if prefix is not None and not isinstance(prefix, str):
+            raise ValueError(f"Expected argument `prefix` to either be `None` or a string but got {prefix}")
+        self._prefix = prefix or ""
+
+        if postfix is not None and not isinstance(postfix, str):
+            raise ValueError(f"Expected argument `postfix` to either be `None` or a string but got {postfix}")
+        self._postfix = postfix or ""
+
     def items(self, flatten: bool = True) -> Iterable[Tuple[str, nn.Module]]:
         """Iterate over task and task metrics.
 
@@ -114,9 +170,9 @@ def items(self, flatten: bool = True) -> Iterable[Tuple[str, nn.Module]]:
         for task_name, metric in self.task_metrics.items():
             if flatten and isinstance(metric, MetricCollection):
                 for sub_metric_name, sub_metric in metric.items():
-                    yield f"{task_name}_{sub_metric_name}", sub_metric
+                    yield f"{self._prefix}{task_name}_{sub_metric_name}{self._postfix}", sub_metric
             else:
-                yield task_name, metric
+                yield f"{self._prefix}{task_name}{self._postfix}", metric
 
     def keys(self, flatten: bool = True) -> Iterable[str]:
         """Iterate over task names.
@@ -129,9 +185,9 @@ def keys(self, flatten: bool = True) -> Iterable[str]:
         for task_name, metric in self.task_metrics.items():
             if flatten and isinstance(metric, MetricCollection):
                 for sub_metric_name in metric:
-                    yield f"{task_name}_{sub_metric_name}"
+                    yield f"{self._prefix}{task_name}_{sub_metric_name}{self._postfix}"
             else:
-                yield task_name
+                yield f"{self._prefix}{task_name}{self._postfix}"
 
     def values(self, flatten: bool = True) -> Iterable[nn.Module]:
         """Iterate over task metrics.
@@ -147,18 +203,6 @@ def values(self, flatten: bool = True) -> Iterable[nn.Module]:
             else:
                 yield metric
 
-    @staticmethod
-    def _check_task_metrics_type(task_metrics: Dict[str, Union[Metric, MetricCollection]]) -> None:
-        if not isinstance(task_metrics, dict):
-            raise TypeError(f"Expected argument `task_metrics` to be a dict. Found task_metrics = {task_metrics}")
-
-        for metric in task_metrics.values():
-            if not (isinstance(metric, (Metric, MetricCollection))):
-                raise TypeError(
-                    "Expected each task's metric to be a Metric or a MetricCollection. "
-                    f"Found a metric of type {type(metric)}"
-                )
-
     def update(self, task_preds: Dict[str, Any], task_targets: Dict[str, Any]) -> None:
         """Update each task's metric with its corresponding pred and target.
 
@@ -179,9 +223,13 @@ def update(self, task_preds: Dict[str, Any], task_targets: Dict[str, Any]) -> No
             target = task_targets[task_name]
             metric.update(pred, target)
 
+    def _convert_output(self, output: Dict[str, Any]) -> Dict[str, Any]:
+        """Convert the output of the underlying metrics to a dictionary with the task names as keys."""
+        return {f"{self._prefix}{task_name}{self._postfix}": task_output for task_name, task_output in output.items()}
+
     def compute(self) -> Dict[str, Any]:
         """Compute metrics for all tasks."""
-        return {task_name: metric.compute() for task_name, metric in self.task_metrics.items()}
+        return self._convert_output({task_name: metric.compute() for task_name, metric in self.task_metrics.items()})
 
     def forward(self, task_preds: Dict[str, Tensor], task_targets: Dict[str, Tensor]) -> Dict[str, Any]:
         """Call underlying forward methods for all tasks and return the result as a dictionary."""
@@ -189,10 +237,10 @@ def forward(self, task_preds: Dict[str, Tensor], task_targets: Dict[str, Tensor]
         # value of full_state_update, and that also accumulates the results. Here, all computations are handled by the
         # underlying metrics, which all have their own value of full_state_update, and which all accumulate the results
         # by themselves.
-        return {
+        return self._convert_output({
             task_name: metric(task_preds[task_name], task_targets[task_name])
             for task_name, metric in self.task_metrics.items()
-        }
+        })
 
     def reset(self) -> None:
         """Reset all underlying metrics."""
@@ -215,16 +263,8 @@ def clone(self, prefix: Optional[str] = None, postfix: Optional[str] = None) ->
 
         """
         multitask_copy = deepcopy(self)
-        if prefix is not None:
-            prefix = self._check_arg(prefix, "prefix")
-            multitask_copy.task_metrics = nn.ModuleDict({
-                prefix + key: value for key, value in multitask_copy.task_metrics.items()
-            })
-        if postfix is not None:
-            postfix = self._check_arg(postfix, "postfix")
-            multitask_copy.task_metrics = nn.ModuleDict({
-                key + postfix: value for key, value in multitask_copy.task_metrics.items()
-            })
+        multitask_copy._prefix = self._check_arg(prefix, "prefix") or ""
+        multitask_copy._postfix = self._check_arg(postfix, "prefix") or ""
         return multitask_copy
 
     def plot(
diff --git a/src/torchmetrics/wrappers/tracker.py b/src/torchmetrics/wrappers/tracker.py
index e898813f7b4..bf0b8c032be 100644
--- a/src/torchmetrics/wrappers/tracker.py
+++ b/src/torchmetrics/wrappers/tracker.py
@@ -52,15 +52,14 @@ class MetricTracker(ModuleList):
             better (``True``) or lower is better (``False``).
 
     Example (single metric):
+        >>> from torch import randint
         >>> from torchmetrics.wrappers import MetricTracker
         >>> from torchmetrics.classification import MulticlassAccuracy
-        >>> _ = torch.manual_seed(42)
         >>> tracker = MetricTracker(MulticlassAccuracy(num_classes=10, average='micro'))
         >>> for epoch in range(5):
         ...     tracker.increment()
         ...     for batch_idx in range(5):
-        ...         preds, target = torch.randint(10, (100,)), torch.randint(10, (100,))
-        ...         tracker.update(preds, target)
+        ...         tracker.update(randint(10, (100,)), randint(10, (100,)))
         ...     print(f"current acc={tracker.compute()}")
         current acc=0.1120000034570694
         current acc=0.08799999952316284
@@ -76,32 +75,31 @@ class MetricTracker(ModuleList):
         tensor([0.1120, 0.0880, 0.1260, 0.0800, 0.1020])
 
     Example (multiple metrics using MetricCollection):
+        >>> from torch import randn
         >>> from torchmetrics.wrappers import MetricTracker
         >>> from torchmetrics import MetricCollection
         >>> from torchmetrics.regression import MeanSquaredError, ExplainedVariance
-        >>> _ = torch.manual_seed(42)
         >>> tracker = MetricTracker(MetricCollection([MeanSquaredError(), ExplainedVariance()]), maximize=[False, True])
         >>> for epoch in range(5):
         ...     tracker.increment()
         ...     for batch_idx in range(5):
-        ...         preds, target = torch.randn(100), torch.randn(100)
-        ...         tracker.update(preds, target)
+        ...         tracker.update(randn(100), randn(100))
         ...     print(f"current stats={tracker.compute()}")  # doctest: +NORMALIZE_WHITESPACE
-        current stats={'MeanSquaredError': tensor(1.8218), 'ExplainedVariance': tensor(-0.8969)}
-        current stats={'MeanSquaredError': tensor(2.0268), 'ExplainedVariance': tensor(-1.0206)}
-        current stats={'MeanSquaredError': tensor(1.9491), 'ExplainedVariance': tensor(-0.8298)}
-        current stats={'MeanSquaredError': tensor(1.9800), 'ExplainedVariance': tensor(-0.9199)}
-        current stats={'MeanSquaredError': tensor(2.2481), 'ExplainedVariance': tensor(-1.1622)}
+        current stats={'MeanSquaredError': tensor(2.3292), 'ExplainedVariance': tensor(-0.9516)}
+        current stats={'MeanSquaredError': tensor(2.1370), 'ExplainedVariance': tensor(-1.0775)}
+        current stats={'MeanSquaredError': tensor(2.1695), 'ExplainedVariance': tensor(-0.9945)}
+        current stats={'MeanSquaredError': tensor(2.1072), 'ExplainedVariance': tensor(-1.1878)}
+        current stats={'MeanSquaredError': tensor(2.0562), 'ExplainedVariance': tensor(-1.0754)}
         >>> from pprint import pprint
         >>> best_res, which_epoch = tracker.best_metric(return_step=True)
         >>> pprint(best_res)  # doctest: +ELLIPSIS
-        {'ExplainedVariance': -0.829...,
-         'MeanSquaredError': 1.821...}
+        {'ExplainedVariance': -0.951...,
+         'MeanSquaredError': 2.056...}
         >>> which_epoch
-        {'MeanSquaredError': 0, 'ExplainedVariance': 2}
+        {'MeanSquaredError': 4, 'ExplainedVariance': 0}
         >>> pprint(tracker.compute_all())
-        {'ExplainedVariance': tensor([-0.8969, -1.0206, -0.8298, -0.9199, -1.1622]),
-         'MeanSquaredError': tensor([1.8218, 2.0268, 1.9491, 1.9800, 2.2481])}
+        {'ExplainedVariance': tensor([-0.9516, -1.0775, -0.9945, -1.1878, -1.0754]),
+         'MeanSquaredError': tensor([2.3292, 2.1370, 2.1695, 2.1072, 2.0562])}
 
     """
 


Test patch:
diff --git a/.azure/gpu-unittests.yml b/.azure/gpu-unittests.yml
index e592ae93b47..0b8ead7ad70 100644
--- a/.azure/gpu-unittests.yml
+++ b/.azure/gpu-unittests.yml
@@ -25,9 +25,6 @@ jobs:
           docker-image: "ubuntu22.04-cuda11.8.0-py3.9-torch1.13"
           torch-ver: "1.13"
         "PyTorch | 2.X stable":
-          docker-image: "ubuntu22.04-cuda12.1.1-py3.11-torch2.3"
-          torch-ver: "2.3"
-        "PyTorch | 2.X future":
           docker-image: "ubuntu22.04-cuda12.1.1-py3.11-torch2.4"
           torch-ver: "2.4"
     # how long to run the job before automatically cancelling
diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.yml
index d53b101acc9..0647a865ebb 100644
--- a/.github/workflows/ci-tests.yml
+++ b/.github/workflows/ci-tests.yml
@@ -41,28 +41,28 @@ jobs:
           - "2.0.1"
           - "2.1.2"
           - "2.2.2"
-          - "2.3.0"
+          - "2.3.1"
+          - "2.4.0"
         include:
-          # cover additional python nad PR combinations
+          # cover additional python and PT combinations
           - { os: "ubuntu-22.04", python-version: "3.8", pytorch-version: "1.13.1" }
           - { os: "ubuntu-22.04", python-version: "3.10", pytorch-version: "2.0.1" }
           - { os: "ubuntu-22.04", python-version: "3.10", pytorch-version: "2.2.2" }
-          - { os: "ubuntu-22.04", python-version: "3.11", pytorch-version: "2.3.0" }
+          - { os: "ubuntu-22.04", python-version: "3.11", pytorch-version: "2.3.1" }
           # standard mac machine, not the M1
           - { os: "macOS-13", python-version: "3.8", pytorch-version: "1.13.1" }
           - { os: "macOS-13", python-version: "3.10", pytorch-version: "2.0.1" }
-          - { os: "macOS-13", python-version: "3.11", pytorch-version: "2.2.2" }
           # using the ARM based M1 machine
           - { os: "macOS-14", python-version: "3.10", pytorch-version: "2.0.1" }
-          - { os: "macOS-14", python-version: "3.11", pytorch-version: "2.3.0" }
+          - { os: "macOS-14", python-version: "3.11", pytorch-version: "2.4.0" }
           # some windows
           - { os: "windows-2022", python-version: "3.8", pytorch-version: "1.13.1" }
           - { os: "windows-2022", python-version: "3.10", pytorch-version: "2.0.1" }
-          - { os: "windows-2022", python-version: "3.11", pytorch-version: "2.3.0" }
-          # Future released version
-          - { os: "ubuntu-22.04", python-version: "3.11", pytorch-version: "2.4.0" }
-          - { os: "macOS-14", python-version: "3.11", pytorch-version: "2.4.0" }
           - { os: "windows-2022", python-version: "3.11", pytorch-version: "2.4.0" }
+          # Future released version
+          #- { os: "ubuntu-22.04", python-version: "3.11", pytorch-version: "2.5.0" }
+          #- { os: "macOS-14", python-version: "3.11", pytorch-version: "2.5.0" }
+          #- { os: "windows-2022", python-version: "3.11", pytorch-version: "2.5.0" }
     env:
       FREEZE_REQUIREMENTS: ${{ ! (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/heads/release/')) }}
       PYPI_CACHE_DIR: "_ci-cache_PyPI"
@@ -105,9 +105,9 @@ jobs:
           pytorch-version: ${{ matrix.pytorch-version }}
           pypi-dir: ${{ env.PYPI_CACHE_DIR }}
 
-      - name: Switch to PT test URL
-        if: ${{ matrix.pytorch-version == '2.4.0' }}
-        run: echo 'PIP_EXTRA_INDEX_URL=--extra-index-url https://download.pytorch.org/whl/test/cpu/' >> $GITHUB_ENV
+      #- name: Switch to PT test URL
+      #  if: ${{ matrix.pytorch-version == '2.X.0' }}
+      #  run: echo 'PIP_EXTRA_INDEX_URL=--extra-index-url https://download.pytorch.org/whl/test/cpu/' >> $GITHUB_ENV
       - name: Install pkg
         timeout-minutes: 25
         run: |
diff --git a/requirements/_tests.txt b/requirements/_tests.txt
index 657f61b2074..1aeb982ee9e 100644
--- a/requirements/_tests.txt
+++ b/requirements/_tests.txt
@@ -11,10 +11,10 @@ pytest-xdist ==3.6.1
 phmdoctest ==1.4.0
 
 psutil <6.1.0
-pyGithub ==2.3.0
+pyGithub ==2.4.0
 fire <=0.6.0
 
 cloudpickle >1.3, <=3.0.0
 scikit-learn >=1.1.1, <1.3.0; python_version < "3.9"
 scikit-learn >=1.4.0, <1.6.0; python_version >= "3.9"
-cachier ==3.0.0
+cachier ==3.0.1
diff --git a/requirements/classification_test.txt b/requirements/classification_test.txt
index 6dd76f35957..8cadb2b3e3e 100644
--- a/requirements/classification_test.txt
+++ b/requirements/classification_test.txt
@@ -1,7 +1,7 @@
 # NOTE: the upper bound for the package version is only set for CI stability, and it is dropped while installing this package
 #  in case you want to preserve/enforce restrictions on the latest compatible version, add "strict" as an in-line comment
 
-pandas >=1.4.0, <=2.2.2
-netcal >1.0.0, <=1.3.5  # calibration_error
-numpy <2.1.0
+pandas >1.4.0, <=2.2.2
+netcal >1.0.0, <1.4.0 # calibration_error
+numpy <2.2.0
 fairlearn # group_fairness
diff --git a/requirements/image_test.txt b/requirements/image_test.txt
index 692f5953431..956a370fa0e 100644
--- a/requirements/image_test.txt
+++ b/requirements/image_test.txt
@@ -5,6 +5,6 @@ scikit-image >=0.19.0, <0.25.0
 kornia >=0.6.7, <0.8.0
 pytorch-msssim ==1.0.0
 sewar >=0.4.4, <=0.4.6
-numpy <2.1.0
+numpy <2.2.0
 torch-fidelity @ git+https://github.com/toshas/torch-fidelity@master
 lpips <=0.1.4
diff --git a/requirements/nominal_test.txt b/requirements/nominal_test.txt
index ca2f21fcc9a..7ee5809af6f 100644
--- a/requirements/nominal_test.txt
+++ b/requirements/nominal_test.txt
@@ -1,7 +1,7 @@
 # NOTE: the upper bound for the package version is only set for CI stability, and it is dropped while installing this package
 #  in case you want to preserve/enforce restrictions on the latest compatible version, add "strict" as an in-line comment
 
-pandas >1.0.0, <=2.2.2 # cannot pin version due to numpy version incompatibility
-dython <=0.7.6
+pandas >1.4.0, <=2.2.2 # cannot pin version due to numpy version incompatibility
+dython ~=0.7.6
 scipy >1.0.0, <1.15.0 # cannot pin version due to some version conflicts with `oldest` CI configuration
 statsmodels >0.13.5, <0.15.0
diff --git a/src/conftest.py b/src/conftest.py
new file mode 100644
index 00000000000..c988c1784c5
--- /dev/null
+++ b/src/conftest.py
@@ -0,0 +1,40 @@
+from pathlib import Path
+from typing import Optional
+
+from lightning_utilities.core.imports import package_available
+
+if package_available("pytest") and package_available("doctest"):
+    import doctest
+
+    import pytest
+
+    MANUAL_SEED = doctest.register_optionflag("MANUAL_SEED")
+
+    @pytest.fixture(autouse=True)
+    def reset_random_seed(seed: int = 42) -> None:  # noqa: PT004
+        """Reset the random seed before running each doctest."""
+        import random
+
+        import numpy as np
+        import torch
+
+        random.seed(seed)
+        np.random.seed(seed)
+        torch.manual_seed(seed)
+        torch.cuda.manual_seed_all(seed)
+
+    class DoctestModule(pytest.Module):
+        """A custom module class that augments collected doctests with the reset_random_seed fixture."""
+
+        def collect(self) -> GeneratorExit:
+            """Augment collected doctests with the reset_random_seed fixture."""
+            for item in super().collect():
+                if isinstance(item, pytest.DoctestItem):
+                    item.add_marker(pytest.mark.usefixtures("reset_random_seed"))
+                yield item
+
+    def pytest_collect_file(parent: Path, path: Path) -> Optional[DoctestModule]:
+        """Collect doctests and add the reset_random_seed fixture."""
+        if path.ext == ".py":
+            return DoctestModule.from_parent(parent, fspath=path)
+        return None
diff --git a/tests/integrations/test_lightning.py b/tests/integrations/test_lightning.py
index fec59ea22b0..513c351e2a0 100644
--- a/tests/integrations/test_lightning.py
+++ b/tests/integrations/test_lightning.py
@@ -27,10 +27,10 @@
 
 from torchmetrics import MetricCollection
 from torchmetrics.aggregation import SumMetric
-from torchmetrics.classification import BinaryAccuracy, BinaryAveragePrecision
+from torchmetrics.classification import BinaryAccuracy, BinaryAveragePrecision, MulticlassAccuracy
 from torchmetrics.regression import MeanAbsoluteError, MeanSquaredError
 from torchmetrics.utilities.prints import rank_zero_only
-from torchmetrics.wrappers import MultitaskWrapper
+from torchmetrics.wrappers import ClasswiseWrapper, MultitaskWrapper
 
 from integrations.lightning.boring_model import BoringModel
 
@@ -504,3 +504,71 @@ def configure_optimizers(self):
 
     model = model.type(torch.half)
     assert model.metric.sum_value.dtype == torch.float32
+
+
+def test_collection_classwise_lightning_integration(tmpdir):
+    """Check the integration of ClasswiseWrapper, MetricCollection and LightningModule.
+
+    See issue: https://github.com/Lightning-AI/torchmetrics/issues/2683
+
+    """
+
+    class TestModel(BoringModel):
+        def __init__(self) -> None:
+            super().__init__()
+            self.train_metrics = MetricCollection(
+                {
+                    "macro_accuracy": MulticlassAccuracy(num_classes=5, average="macro"),
+                    "classwise_accuracy": ClasswiseWrapper(MulticlassAccuracy(num_classes=5, average=None)),
+                },
+                prefix="train_",
+            )
+
+            self.val_metrics = MetricCollection(
+                {
+                    "macro_accuracy": MulticlassAccuracy(num_classes=5, average="macro"),
+                    "classwise_accuracy": ClasswiseWrapper(MulticlassAccuracy(num_classes=5, average=None)),
+                },
+                prefix="val_",
+            )
+
+        def training_step(self, batch, batch_idx):
+            loss = self(batch).sum()
+
+            preds = torch.randint(0, 5, (100,), device=batch.device)
+            target = torch.randint(0, 5, (100,), device=batch.device)
+
+            self.train_metrics.update(preds, target)
+            batch_values = self.train_metrics.compute()
+            self.log_dict(batch_values, on_step=True, on_epoch=False)
+
+            return {"loss": loss}
+
+        def validation_step(self, batch, batch_idx):
+            preds = torch.randint(0, 5, (100,), device=batch.device)
+            target = torch.randint(0, 5, (100,), device=batch.device)
+
+            self.val_metrics.update(preds, target)
+
+        def on_validation_epoch_end(self):
+            self.log_dict(self.val_metrics.compute(), on_step=False, on_epoch=True)
+
+    model = TestModel()
+
+    trainer = Trainer(
+        default_root_dir=tmpdir,
+        limit_train_batches=2,
+        limit_val_batches=2,
+        max_epochs=1,
+        log_every_n_steps=1,
+    )
+    trainer.fit(model)
+
+    logged = trainer.logged_metrics
+
+    # check that all metrics are logged
+    assert "train_macro_accuracy" in logged
+    assert "val_macro_accuracy" in logged
+    for i in range(5):
+        assert f"train_multiclassaccuracy_{i}" in logged
+        assert f"val_multiclassaccuracy_{i}" in logged
diff --git a/tests/unittests/_helpers/testers.py b/tests/unittests/_helpers/testers.py
index deb4c12324e..c5a69077f3c 100644
--- a/tests/unittests/_helpers/testers.py
+++ b/tests/unittests/_helpers/testers.py
@@ -32,7 +32,12 @@ def _assert_allclose(tm_result: Any, ref_result: Any, atol: float = 1e-8, key: O
     """Recursively assert that two results are within a certain tolerance."""
     # single output compare
     if isinstance(tm_result, Tensor):
-        assert np.allclose(tm_result.detach().cpu().numpy(), ref_result, atol=atol, equal_nan=True)
+        assert np.allclose(
+            tm_result.detach().cpu().numpy() if isinstance(tm_result, Tensor) else tm_result,
+            ref_result.detach().cpu().numpy() if isinstance(ref_result, Tensor) else ref_result,
+            atol=atol,
+            equal_nan=True,
+        )
     # multi output compare
     elif isinstance(tm_result, Sequence):
         for pl_res, ref_res in zip(tm_result, ref_result):
@@ -40,7 +45,12 @@ def _assert_allclose(tm_result: Any, ref_result: Any, atol: float = 1e-8, key: O
     elif isinstance(tm_result, Dict):
         if key is None:
             raise KeyError("Provide Key for Dict based metric results.")
-        assert np.allclose(tm_result[key].detach().cpu().numpy(), ref_result, atol=atol, equal_nan=True)
+        assert np.allclose(
+            tm_result[key].detach().cpu().numpy() if isinstance(tm_result[key], Tensor) else tm_result[key],
+            ref_result.detach().cpu().numpy() if isinstance(ref_result, Tensor) else ref_result,
+            atol=atol,
+            equal_nan=True,
+        )
     else:
         raise ValueError("Unknown format for comparison")
 
@@ -147,6 +157,7 @@ def _class_test(
     # verify metrics work after being loaded from pickled state
     pickled_metric = pickle.dumps(metric)
     metric = pickle.loads(pickled_metric)
+    metric_clone = deepcopy(metric)
 
     for i in range(rank, num_batches, world_size):
         batch_kwargs_update = {k: v[i] if isinstance(v, Tensor) else v for k, v in kwargs_update.items()}
@@ -154,6 +165,16 @@ def _class_test(
         # compute batch stats and aggregate for global stats
         batch_result = metric(preds[i], target[i], **batch_kwargs_update)
 
+        if rank == 0 and world_size == 1 and i == 0:  # check only in non-ddp mode and first batch
+            # dummy check to make sure that forward/update works as expected
+            metric_clone.update(preds[i], target[i], **batch_kwargs_update)
+            update_result = metric_clone.compute()
+            if isinstance(batch_result, dict):
+                for key in batch_result:
+                    _assert_allclose(batch_result, update_result[key], key=key)
+            else:
+                _assert_allclose(batch_result, update_result)
+
         if metric.dist_sync_on_step and check_dist_sync_on_step and rank == 0:
             if isinstance(preds, Tensor):
                 ddp_preds = torch.cat([preds[i + r] for r in range(world_size)]).cpu()
diff --git a/tests/unittests/classification/test_jaccard.py b/tests/unittests/classification/test_jaccard.py
index 6901868eac9..e7afdb557a6 100644
--- a/tests/unittests/classification/test_jaccard.py
+++ b/tests/unittests/classification/test_jaccard.py
@@ -26,6 +26,7 @@
     MultilabelJaccardIndex,
 )
 from torchmetrics.functional.classification.jaccard import (
+    _jaccard_index_reduce,
     binary_jaccard_index,
     multiclass_jaccard_index,
     multilabel_jaccard_index,
@@ -403,6 +404,26 @@ def test_corner_case():
     assert torch.allclose(res, out)
 
 
+def test_jaccard_index_zero_division():
+    """Issue: https://github.com/Lightning-AI/torchmetrics/issues/2658."""
+    # Test case where all pixels are background (zeros)
+    confmat = torch.tensor([[4, 0], [0, 0]])
+
+    # Test with zero_division=0.0
+    result = _jaccard_index_reduce(confmat, average="binary", zero_division=0.0)
+    assert result == 0.0, f"Expected 0.0, but got {result}"
+
+    # Test with zero_division=1.0
+    result = _jaccard_index_reduce(confmat, average="binary", zero_division=1.0)
+    assert result == 1.0, f"Expected 1.0, but got {result}"
+
+    # Test case with some foreground pixels
+    confmat = torch.tensor([[2, 1], [1, 1]])
+    result = _jaccard_index_reduce(confmat, average="binary", zero_division=0.0)
+    expected = 1 / 3
+    assert torch.isclose(result, torch.tensor(expected)), f"Expected {expected}, but got {result}"
+
+
 @pytest.mark.parametrize(
     ("metric", "kwargs"),
     [
diff --git a/tests/unittests/classification/test_stat_scores.py b/tests/unittests/classification/test_stat_scores.py
index 3cf7090a632..5ea4c206bc0 100644
--- a/tests/unittests/classification/test_stat_scores.py
+++ b/tests/unittests/classification/test_stat_scores.py
@@ -11,6 +11,7 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+
 from functools import partial
 
 import numpy as np
@@ -581,8 +582,8 @@ def test_support_for_int():
     """See issue: https://github.com/Lightning-AI/torchmetrics/issues/1970."""
     seed_all(42)
     metric = MulticlassStatScores(num_classes=4, average="none", multidim_average="samplewise", ignore_index=0)
-    prediction = torch.randint(low=0, high=4, size=(1, 224, 224)).to(torch.uint8)
-    label = torch.randint(low=0, high=4, size=(1, 224, 224)).to(torch.uint8)
+    prediction = torch.randint(low=0, high=4, size=(1, 50, 50)).to(torch.uint8)
+    label = torch.randint(low=0, high=4, size=(1, 50, 50)).to(torch.uint8)
     score = metric(preds=prediction, target=label)
     assert score.shape == (1, 4, 5)
 
diff --git a/tests/unittests/image/test_ssim.py b/tests/unittests/image/test_ssim.py
index 6b464f2a97b..49954f45cd7 100644
--- a/tests/unittests/image/test_ssim.py
+++ b/tests/unittests/image/test_ssim.py
@@ -278,7 +278,16 @@ def test_ssim_invalid_inputs(pred, target, kernel, sigma, match):
         structural_similarity_index_measure(pred, target, kernel_size=kernel, sigma=sigma)
 
 
-def test_ssim_unequal_kernel_size():
+@pytest.mark.parametrize(
+    ("sigma", "kernel_size", "result"),
+    [
+        ((0.25, 0.5), None, torch.tensor(0.20977394)),
+        ((0.5, 0.25), None, torch.tensor(0.13884821)),
+        (None, (3, 5), torch.tensor(0.05032664)),
+        (None, (5, 3), torch.tensor(0.03472072)),
+    ],
+)
+def test_ssim_unequal_kernel_size(sigma, kernel_size, result):
     """Test the case where kernel_size[0] != kernel_size[1]."""
     preds = torch.tensor([
         [
@@ -306,24 +315,18 @@ def test_ssim_unequal_kernel_size():
             ]
         ]
     ])
-    # kernel order matters
-    assert torch.isclose(
-        structural_similarity_index_measure(preds, target, gaussian_kernel=True, sigma=(0.25, 0.5)),
-        torch.tensor(0.08869550),
-    )
-    assert not torch.isclose(
-        structural_similarity_index_measure(preds, target, gaussian_kernel=True, sigma=(0.5, 0.25)),
-        torch.tensor(0.08869550),
-    )
-
-    assert torch.isclose(
-        structural_similarity_index_measure(preds, target, gaussian_kernel=False, kernel_size=(3, 5)),
-        torch.tensor(0.05131844),
-    )
-    assert not torch.isclose(
-        structural_similarity_index_measure(preds, target, gaussian_kernel=False, kernel_size=(5, 3)),
-        torch.tensor(0.05131844),
-    )
+    if sigma is not None:
+        assert torch.isclose(
+            structural_similarity_index_measure(preds, target, gaussian_kernel=True, sigma=sigma),
+            result,
+            atol=1e-04,
+        )
+    else:
+        assert torch.isclose(
+            structural_similarity_index_measure(preds, target, gaussian_kernel=False, kernel_size=kernel_size),
+            result,
+            atol=1e-04,
+        )
 
 
 @pytest.mark.parametrize(
@@ -341,3 +344,19 @@ def test_full_image_output(preds, target):
     assert len(out) == 2
     assert out[0].numel() == 1
     assert out[1].shape == preds[0].shape
+
+
+def test_ssim_for_correct_padding():
+    """Check that padding is correctly added and removed for SSIM.
+
+    See issue: https://github.com/Lightning-AI/torchmetrics/issues/2718
+
+    """
+    preds = torch.rand([3, 3, 256, 256])
+    # let the edge of the image be 0
+    target = preds.clone()
+    target[:, :, 0, :] = 0
+    target[:, :, -1, :] = 0
+    target[:, :, :, 0] = 0
+    target[:, :, :, -1] = 0
+    assert structural_similarity_index_measure(preds, target) < 1.0
diff --git a/tests/unittests/segmentation/test_generalized_dice_score.py b/tests/unittests/segmentation/test_generalized_dice_score.py
index ed80e6fd6d7..5086a533d0c 100644
--- a/tests/unittests/segmentation/test_generalized_dice_score.py
+++ b/tests/unittests/segmentation/test_generalized_dice_score.py
@@ -21,8 +21,11 @@
 from torchmetrics.segmentation.generalized_dice import GeneralizedDiceScore
 
 from unittests import BATCH_SIZE, NUM_BATCHES, NUM_CLASSES, _Input
+from unittests._helpers import seed_all
 from unittests._helpers.testers import MetricTester
 
+seed_all(42)
+
 _inputs1 = _Input(
     preds=torch.randint(0, 2, (NUM_BATCHES, BATCH_SIZE, NUM_CLASSES, 16)),
     target=torch.randint(0, 2, (NUM_BATCHES, BATCH_SIZE, NUM_CLASSES, 16)),
@@ -63,7 +66,7 @@ def _reference_generalized_dice(
     ],
 )
 @pytest.mark.parametrize("include_background", [True, False])
-class TestMeanIoU(MetricTester):
+class TestMeanDiceScore(MetricTester):
     """Test class for `MeanIoU` metric."""
 
     @pytest.mark.parametrize("ddp", [pytest.param(True, marks=pytest.mark.DDP), False])
diff --git a/tests/unittests/text/test_chrf.py b/tests/unittests/text/test_chrf.py
new file mode 100644
index 00000000000..233c9451381
--- /dev/null
+++ b/tests/unittests/text/test_chrf.py
@@ -0,0 +1,163 @@
+# Copyright The Lightning team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from functools import partial
+from typing import Sequence
+
+import pytest
+from torch import Tensor, tensor
+from torchmetrics.functional.text.chrf import chrf_score
+from torchmetrics.text.chrf import CHRFScore
+
+from unittests.text._helpers import TextTester
+from unittests.text._inputs import _inputs_multiple_references, _inputs_single_sentence_multiple_references
+
+
+def _reference_sacrebleu_chrf(
+    preds: Sequence[str],
+    targets: Sequence[Sequence[str]],
+    char_order: int,
+    word_order: int,
+    lowercase: bool,
+    whitespace: bool,
+) -> Tensor:
+    try:
+        from sacrebleu import CHRF
+    except ImportError:
+        pytest.skip("test requires sacrebleu package to be installed")
+
+    sacrebleu_chrf = CHRF(
+        char_order=char_order, word_order=word_order, lowercase=lowercase, whitespace=whitespace, eps_smoothing=True
+    )
+    # Sacrebleu CHRF expects different format of input
+    targets = [[target[i] for target in targets] for i in range(len(targets[0]))]
+    sacrebleu_chrf = sacrebleu_chrf.corpus_score(preds, targets).score / 100
+    return tensor(sacrebleu_chrf)
+
+
+@pytest.mark.parametrize(
+    ["char_order", "word_order", "lowercase", "whitespace"],
+    [
+        (6, 2, False, False),
+        (6, 2, False, True),
+        (4, 2, True, False),
+        (6, 0, True, False),
+        (6, 0, True, True),
+        (4, 0, False, True),
+    ],
+)
+@pytest.mark.parametrize(
+    ["preds", "targets"],
+    [(_inputs_multiple_references.preds, _inputs_multiple_references.target)],
+)
+class TestCHRFScore(TextTester):
+    """Test class for `CHRFScore` metric."""
+
+    @pytest.mark.parametrize("ddp", [pytest.param(True, marks=pytest.mark.DDP), False])
+    def test_chrf_score_class(self, ddp, preds, targets, char_order, word_order, lowercase, whitespace):
+        """Test class implementation of metric."""
+        metric_args = {
+            "n_char_order": char_order,
+            "n_word_order": word_order,
+            "lowercase": lowercase,
+            "whitespace": whitespace,
+        }
+        nltk_metric = partial(
+            _reference_sacrebleu_chrf,
+            char_order=char_order,
+            word_order=word_order,
+            lowercase=lowercase,
+            whitespace=whitespace,
+        )
+
+        self.run_class_metric_test(
+            ddp=ddp,
+            preds=preds,
+            targets=targets,
+            metric_class=CHRFScore,
+            reference_metric=nltk_metric,
+            metric_args=metric_args,
+        )
+
+    def test_chrf_score_functional(self, preds, targets, char_order, word_order, lowercase, whitespace):
+        """Test functional implementation of metric."""
+        metric_args = {
+            "n_char_order": char_order,
+            "n_word_order": word_order,
+            "lowercase": lowercase,
+            "whitespace": whitespace,
+        }
+        nltk_metric = partial(
+            _reference_sacrebleu_chrf,
+            char_order=char_order,
+            word_order=word_order,
+            lowercase=lowercase,
+            whitespace=whitespace,
+        )
+
+        self.run_functional_metric_test(
+            preds,
+            targets,
+            metric_functional=chrf_score,
+            reference_metric=nltk_metric,
+            metric_args=metric_args,
+        )
+
+    def test_chrf_score_differentiability(self, preds, targets, char_order, word_order, lowercase, whitespace):
+        """Test the differentiability of the metric, according to its `is_differentiable` attribute."""
+        metric_args = {
+            "n_char_order": char_order,
+            "n_word_order": word_order,
+            "lowercase": lowercase,
+            "whitespace": whitespace,
+        }
+
+        self.run_differentiability_test(
+            preds=preds,
+            targets=targets,
+            metric_module=CHRFScore,
+            metric_functional=chrf_score,
+            metric_args=metric_args,
+        )
+
+
+def test_chrf_empty_functional():
+    """Test that eed returns 0 when no input is provided."""
+    preds = []
+    targets = [[]]
+    assert chrf_score(preds, targets) == tensor(0.0)
+
+
+def test_chrf_empty_class():
+    """Test that eed returns 0 when no input is provided."""
+    chrf = CHRFScore()
+    preds = []
+    targets = [[]]
+    assert chrf(preds, targets) == tensor(0.0)
+
+
+def test_chrf_return_sentence_level_score_functional():
+    """Test that chrf can return sentence level scores."""
+    preds = _inputs_single_sentence_multiple_references.preds
+    targets = _inputs_single_sentence_multiple_references.target
+    _, chrf_sentence_score = chrf_score(preds, targets, return_sentence_level_score=True)
+    isinstance(chrf_sentence_score, Tensor)
+
+
+def test_chrf_return_sentence_level_class():
+    """Test that chrf can return sentence level scores."""
+    chrf = CHRFScore(return_sentence_level_score=True)
+    preds = _inputs_single_sentence_multiple_references.preds
+    targets = _inputs_single_sentence_multiple_references.target
+    _, chrf_sentence_score = chrf(preds, targets)
+    isinstance(chrf_sentence_score, Tensor)
diff --git a/tests/unittests/text/test_sacre_bleu.py b/tests/unittests/text/test_sacre_bleu.py
index e8b66012011..bf2d45fbd5a 100644
--- a/tests/unittests/text/test_sacre_bleu.py
+++ b/tests/unittests/text/test_sacre_bleu.py
@@ -55,8 +55,8 @@ def test_bleu_score_class(self, ddp, preds, targets, tokenize, lowercase):
         """Test class implementation of metric."""
         if _should_skip_tokenizer(tokenize):
             pytest.skip(reason="`ko-mecab` tokenizer requires  `mecab-ko` package to be installed")
-        if tokenize == "flores200":
-            pytest.skip("flores200 tests are flaky")  # TODO: figure out why
+        if tokenize == "flores200" or tokenize == "flores101":
+            pytest.skip("flores101 and flores200 tests are flaky")  # TODO: figure out why
 
         metric_args = {"tokenize": tokenize, "lowercase": lowercase}
         original_sacrebleu = partial(_reference_sacre_bleu, tokenize=tokenize, lowercase=lowercase)
@@ -75,6 +75,8 @@ def test_bleu_score_functional(self, preds, targets, tokenize, lowercase):
         """Test functional implementation of metric."""
         if _should_skip_tokenizer(tokenize):
             pytest.skip(reason="`ko-mecab` tokenizer requires  `mecab-ko` package to be installed")
+        if tokenize == "flores200" or tokenize == "flores101":
+            pytest.skip("flores101 and flores200 tests are flaky")  # TODO: figure out why
 
         metric_args = {"tokenize": tokenize, "lowercase": lowercase}
         original_sacrebleu = partial(_reference_sacre_bleu, tokenize=tokenize, lowercase=lowercase)
diff --git a/tests/unittests/wrappers/test_multitask.py b/tests/unittests/wrappers/test_multitask.py
index 63af6f31b35..069a4472d64 100644
--- a/tests/unittests/wrappers/test_multitask.py
+++ b/tests/unittests/wrappers/test_multitask.py
@@ -248,14 +248,24 @@ def test_key_value_items_method(method, flatten):
 
 def test_clone_with_prefix_and_postfix():
     """Check that the clone method works with prefix and postfix arguments."""
-    multitask_metrics = MultitaskWrapper({"Classification": BinaryAccuracy(), "Regression": MeanSquaredError()})
-    cloned_metrics_with_prefix = multitask_metrics.clone(prefix="prefix_")
-    cloned_metrics_with_postfix = multitask_metrics.clone(postfix="_postfix")
+    multitask_metrics = MultitaskWrapper(
+        {"Classification": BinaryAccuracy(), "Regression": MeanSquaredError()},
+        prefix="prefix_",
+        postfix="_postfix",
+    )
+    assert set(multitask_metrics.keys()) == {"prefix_Classification_postfix", "prefix_Regression_postfix"}
 
-    # Check if the cloned metrics have the expected keys
-    assert set(cloned_metrics_with_prefix.task_metrics.keys()) == {"prefix_Classification", "prefix_Regression"}
-    assert set(cloned_metrics_with_postfix.task_metrics.keys()) == {"Classification_postfix", "Regression_postfix"}
+    output = multitask_metrics(
+        {"Classification": _classification_preds, "Regression": _regression_preds},
+        {"Classification": _classification_target, "Regression": _regression_target},
+    )
+    assert set(output.keys()) == {"prefix_Classification_postfix", "prefix_Regression_postfix"}
 
-    # Check if the cloned metrics have the expected values
-    assert isinstance(cloned_metrics_with_prefix.task_metrics["prefix_Classification"], BinaryAccuracy)
-    assert isinstance(cloned_metrics_with_prefix.task_metrics["prefix_Regression"], MeanSquaredError)
+    cloned_metrics = multitask_metrics.clone(prefix="new_prefix_", postfix="_new_postfix")
+    assert set(cloned_metrics.keys()) == {"new_prefix_Classification_new_postfix", "new_prefix_Regression_new_postfix"}
+
+    output = cloned_metrics(
+        {"Classification": _classification_preds, "Regression": _regression_preds},
+        {"Classification": _classification_target, "Regression": _regression_target},
+    )
+    assert set(output.keys()) == {"new_prefix_Classification_new_postfix", "new_prefix_Regression_new_postfix"}