Repository: Lightning-AI/torchmetrics

Issue:
Adding MiFID (Memorization-Informed Frechet Inception Distance) Metric
## 🚀 Feature

The goal of this feature would be to implement the MiFID metric initially proposed in [On Training Sample Memorization: Lessons from Benchmarking Generative Modeling with a Large-scale Competition](https://arxiv.org/abs/2106.03062#:~:text=To%20detect%20intentional%20memorization%2C%20we%20propose%20the%20%60%60Memorization-Informed,winning%20submissions%20made%20genuine%20improvements%20in%20perceptual%20quality). It is an extension of FID, so it could be implemented similarly.

### Motivation

I found myself needing to use this metric with PyTorch, but didn't find any existing implementations that use PyTorch tensors. I've used torchmetrics (including for FID) in the past, so I thought that this metric could be a good addition to the library. Additionally, since FID is already present then I imagined an MiFID implementation should not be too difficult to write as an extension of the existing FID code.

### Pitch

I would like to add MiFID to the library as an extension of FID. I've already implemented the metric myself as a Metric, and ran some basic tests against the original implementation from the source repo (which uses NumPy for matrix operations, found [here](https://github.com/jybai/generative-memorization-benchmark/blob/main/src/competition_scoring.py)). 

Although I've already got the metric working (and I'll paste my class code below), I would need some help integrating it into the library and adding tests in order to follow the contribution guidelines and the steps given at the bottom of the [Metric page](https://torchmetrics.readthedocs.io/en/stable/pages/implement.html#torchmetrics.Metric).

### Alternatives

The current alternative us just using the NumPy-based solution given in the original source repository.

### Additional context

Here is my current code for this feature:

```python
from numpy.lib.type_check import real
from copy import deepcopy
from typing import Any, List, Optional, Union
from torch import Tensor
from torch.autograd import Function
from torch.nn import Module

from torchmetrics.image.fid import NoTrainInceptionV3, MatrixSquareRoot, sqrtm, _compute_fid
from torchmetrics.metric import Metric
from torchmetrics.utilities import rank_zero_info
from torchmetrics.utilities.imports import _SCIPY_AVAILABLE, _TORCH_FIDELITY_AVAILABLE
import numpy as np
import scipy

if _SCIPY_AVAILABLE:
    import scipy

def _normalize_rows(x: torch.Tensor):
    """
    function that normalizes each row of the matrix x to have unit length.

    Args:
     ``x``: A PyTorch tensor of shape (n, m)

    Returns:
     ``x``: The normalized (by row) PyTorch tensor.
    """
    return x / torch.norm(x, dim=1, keepdim=True)

def _distance_thresholding(d : torch.Tensor, eps=0.1):
    if d < eps:
        return d
    else:
        return 1

def _compute_cosine_distance(features1 : Tensor, features2: Tensor):
    features1_nozero = features1[torch.sum(features1, dim=1) != 0]
    features2_nozero = features2[torch.sum(features2, dim=1) != 0]
    norm_f1 = _normalize_rows(features1_nozero)
    norm_f2 = _normalize_rows(features2_nozero)

    d = 1.0 - torch.abs(torch.matmul(norm_f1, norm_f2.t()))
    mean_min_d = torch.mean(torch.min(d, dim=1).values)
    return mean_min_d

def _compute_mifid(mu1: Tensor, sigma1: Tensor, features1: Tensor, mu2 : Tensor, sigma2: Tensor, features2: Tensor):
    fid_value = _compute_fid(mu1, sigma1, mu2, sigma2)
    distance = _compute_cosine_distance(features1, features2)
    distance_thr = _distance_thresholding(distance, eps=0.1)
    mifid = fid_value / (distance_thr + 10e-15)
    # print("FID_public: ", fid_value, "distance_public: ", distance_thr, "multiplied_public: ", mifid)
    return mifid

class MemorizationInformedFrechetInceptionDistance(Metric):
    higher_is_better: bool = False
    is_differentiable: bool = False
    full_state_update: bool = False

    real_features_sum: Tensor
    real_features_cov_sum: Tensor
    real_features_num_samples: Tensor
    real_features_stacked: Tensor

    fake_features_sum: Tensor
    fake_features_cov_sum: Tensor
    fake_features_num_samples: Tensor
    fake_features_stacked: Tensor

    def __init__(
        self,
        feature: Union[int, Module] = 2048,
        reset_real_features: bool = True,
        normalize: bool = False,
        **kwargs: Any,
    ) -> None:
        super().__init__(**kwargs)

        if isinstance(feature, int):
            num_features = feature
            if not _TORCH_FIDELITY_AVAILABLE:
                raise ModuleNotFoundError(
                    "MemorizationInformedFrechetInceptionDistance metric requires that `Torch-fidelity` is installed."
                    " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
                )
            valid_int_input = [64, 192, 768, 2048]
            if feature not in valid_int_input:
                raise ValueError(
                    f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}."
                )

            self.inception = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)])

        elif isinstance(feature, Module):
            self.inception = feature
            dummy_image = torch.randint(0, 255, (1, 3, 299, 299), dtype=torch.uint8, device=self.inception.device)
            num_features = self.inception(dummy_image).shape[-1]
        else:
            raise TypeError("Got unknown input to argument `feature`")

        if not isinstance(reset_real_features, bool):
            raise ValueError("Argument `reset_real_features` expected to be a bool")
        self.reset_real_features = reset_real_features

        if not isinstance(normalize, bool):
            raise ValueError("Argument `normalize` expected to be a bool")
        self.normalize = normalize

        mx_nb_feets = (num_features, num_features)

        self.add_state("real_features_stacked", torch.zeros((0, num_features)).double(), dist_reduce_fx='cat')
        self.add_state("fake_features_stacked", torch.zeros((0, num_features)).double(), dist_reduce_fx='cat')

    def update(self, imgs: Tensor, real: bool) -> None:  # type: ignore
        """Update the state with extracted features."""
        imgs = (imgs * 255).byte() if self.normalize else imgs
        features = self.inception(imgs)
        self.orig_dtype = features.dtype
        features = features.double()

        if features.dim() == 1:
            features = features.unsqueeze(0)   
        if real:
            self.real_features_stacked = torch.cat((self.real_features_stacked, features), dim=0)
        else:
            self.fake_features_stacked = torch.cat((self.fake_features_stacked, features), dim=0)

    def compute(self) -> Tensor:
        """Calculate MiFID score based on accumulated extracted features from the two distributions."""
 
        mean_real = torch.mean(self.real_features_stacked, dim=0).unsqueeze(0)
        mean_fake = torch.mean(self.fake_features_stacked, dim=0).unsqueeze(0)

        cov_real = torch.cov(self.real_features_stacked.t())
        cov_fake = torch.cov(self.fake_features_stacked.t())

        return _compute_mifid(mean_real.squeeze(0), cov_real, self.real_features_stacked, mean_fake.squeeze(0), cov_fake, self.fake_features_stacked).to(self.orig_dtype)

    def to(self, device):
        self.inception = self.inception.to(device)
        return super().to(device)

    def reset(self) -> None:
        if not self.reset_real_features:
            real_features_stacked = deepcopy(self.real_features_stacked)
            super().reset()
            self.real_features_stacked = real_features_stacked
        else:
            super().reset()
```



A couple of notes about this:

- I added  `device=self.inception.device` to the dummy_image test from the original FID because I found this line gave me errors when my Inception network was already on a CUDA device, but the Metric wasn't yet (as it is just being initialized). This happened with the original FID class as well. I don't know if this works with the broader torchmetrics library but was a workaround for me.
- The MiFID metric utilizes the cosine distance between the two feature vectors. I wasn't sure how to break this down so that all the features don't need to be stacked together and used to calculate the distance under 'compute'. Perhaps there's a way to avoid storing all the stacked features, I am hoping someone here would know if that could be done.
- Additionally, I haven't yet tested this extensively. But I have found that it gives values that are very similar to those from the source NumPy solution. I just found myself implementing this code for my own project that I'm working on, and wanted to contribute it here :). 



Discussion:
Hi! thanks for your contribution!, great first issue!
Hi @Dibz15, thanks for a nice initiative.I think you can try to open a draft PR and we can help you there to finish it! :]

Resolving patch:
diff --git a/src/torchmetrics/image/__init__.py b/src/torchmetrics/image/__init__.py
--- a/src/torchmetrics/image/__init__.py
+++ b/src/torchmetrics/image/__init__.py
@@ -13,6 +13,7 @@
 # limitations under the License.
 from torchmetrics.image.d_lambda import SpectralDistortionIndex
 from torchmetrics.image.ergas import ErrorRelativeGlobalDimensionlessSynthesis
+from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
 from torchmetrics.image.psnr import PeakSignalNoiseRatio
 from torchmetrics.image.psnrb import PeakSignalNoiseRatioWithBlockedEffect
 from torchmetrics.image.rase import RelativeAverageSpectralError
@@ -32,6 +33,7 @@
     "RootMeanSquaredErrorUsingSlidingWindow",
     "SpectralAngleMapper",
     "MultiScaleStructuralSimilarityIndexMeasure",
+    "MemorizationInformedFrechetInceptionDistance",
     "StructuralSimilarityIndexMeasure",
     "UniversalImageQualityIndex",
     "TotalVariation",
diff --git a/src/torchmetrics/image/mifid.py b/src/torchmetrics/image/mifid.py
new file mode 100644
--- /dev/null
+++ b/src/torchmetrics/image/mifid.py
@@ -0,0 +1,297 @@
+# 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 typing import Any, List, Optional, Sequence, Union
+
+import torch
+from torch import Tensor
+from torch.nn import Module
+
+from torchmetrics.image.fid import NoTrainInceptionV3, _compute_fid
+from torchmetrics.metric import Metric
+from torchmetrics.utilities.data import dim_zero_cat
+from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE, _TORCH_GREATER_EQUAL_1_10
+from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
+
+__doctest_requires__ = {
+    ("MemorizationInformedFrechetInceptionDistance", "MemorizationInformedFrechetInceptionDistance.plot"): [
+        "torch_fidelity"
+    ]
+}
+
+if not _TORCH_GREATER_EQUAL_1_10:
+    __doctest_skip__ = [
+        "MemorizationInformedFrechetInceptionDistance",
+        "MemorizationInformedFrechetInceptionDistance.plot",
+    ]
+
+if not _MATPLOTLIB_AVAILABLE:
+    __doctest_skip__ = ["MemorizationInformedFrechetInceptionDistance.plot"]
+
+
+def _compute_cosine_distance(features1: Tensor, features2: Tensor, cosine_distance_eps: float = 0.1) -> Tensor:
+    """Compute the cosine distance between two sets of features."""
+    features1_nozero = features1[torch.sum(features1, dim=1) != 0]
+    features2_nozero = features2[torch.sum(features2, dim=1) != 0]
+
+    # normalize
+    norm_f1 = features1_nozero / torch.norm(features1_nozero, dim=1, keepdim=True)
+    norm_f2 = features2_nozero / torch.norm(features2_nozero, dim=1, keepdim=True)
+
+    d = 1.0 - torch.abs(torch.matmul(norm_f1, norm_f2.t()))
+    mean_min_d = torch.mean(d.min(dim=1).values)
+    return mean_min_d if mean_min_d < cosine_distance_eps else torch.ones_like(mean_min_d)
+
+
+def _mifid_compute(
+    mu1: Tensor,
+    sigma1: Tensor,
+    features1: Tensor,
+    mu2: Tensor,
+    sigma2: Tensor,
+    features2: Tensor,
+    cosine_distance_eps: float = 0.1,
+) -> Tensor:
+    """Compute MIFID score given two sets of features and their statistics."""
+    fid_value = _compute_fid(mu1, sigma1, mu2, sigma2)
+    distance = _compute_cosine_distance(features1, features2, cosine_distance_eps)
+    # secure that very small fid values does not explode the mifid
+    return fid_value / (distance + 10e-15) if fid_value > 1e-8 else torch.zeros_like(fid_value)
+
+
+class MemorizationInformedFrechetInceptionDistance(Metric):
+    r"""Calculate Memorization-Informed Frechet Inception Distance (MIFID_).
+
+    MIFID is a improved variation of the Frechet Inception Distance (FID_) that penalizes memorization of the training
+    set by the generator. It is calculated as
+
+    .. math::
+        MIFID = \frac{FID(F_{real}, F_{fake})}{M(F_{real}, F_{fake})}
+
+    where :math:`FID` is the normal FID score and :math:`M` is the memorization penalty. The memorization penalty
+    essentially corresponds to the average minimum cosine distance between the features of the real and fake
+    distribution.
+
+    Using the default feature extraction (Inception v3 using the original weights from `fid ref2`_), the input is
+    expected to be mini-batches of 3-channel RGB images of shape ``(3 x H x W)``. If argument ``normalize``
+    is ``True`` images are expected to be dtype ``float`` and have values in the ``[0, 1]`` range, else if
+    ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]``
+    range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian
+    flag ``real`` determines if the images should update the statistics of the real distribution or the
+    fake distribution.
+
+    .. note:: using this metrics requires you to have ``scipy`` install. Either install as ``pip install
+        torchmetrics[image]`` or ``pip install scipy``
+
+    .. note:: using this metric with the default feature extractor requires that ``torch-fidelity``
+        is installed. Either install as ``pip install torchmetrics[image]`` or
+        ``pip install torch-fidelity``
+
+    As input to ``forward`` and ``update`` the metric accepts the following input
+
+    - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with
+    - ``real`` (:class:`~bool`): bool indicating if ``imgs`` belong to the real or the fake distribution
+
+    As output of `forward` and `compute` the metric returns the following output
+
+    - ``mifid`` (:class:`~torch.Tensor`): float scalar tensor with mean MIFID value over samples
+
+    Args:
+        feature:
+            Either an integer or ``nn.Module``:
+
+            - an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
+              64, 192, 768, 2048
+            - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
+              an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.
+
+        reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
+            change, the features can be cached them to avoid recomputing them which is costly. Set this to ``False`` if
+            your dataset does not change.
+        cosine_distance_eps: Epsilon value for the cosine distance. If the cosine distance is larger than this value
+            it is set to 1 and thus ignored in the MIFID calculation.
+        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
+
+    Raises:
+        RuntimeError:
+            If ``torch`` is version less than 1.10
+        ValueError:
+            If ``feature`` is set to an ``int`` and ``torch-fidelity`` is not installed
+        ValueError:
+            If ``feature`` is set to an ``int`` not in [64, 192, 768, 2048]
+        TypeError:
+            If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``
+        ValueError:
+            If ``reset_real_features`` is not an ``bool``
+
+    Example::
+        >>> import torch
+        >>> _ = torch.manual_seed(42)
+        >>> 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)
+        >>> mifid.update(imgs_dist1, real=True)
+        >>> mifid.update(imgs_dist2, real=False)
+        >>> mifid.compute()
+        tensor(3003.3691)
+    """
+    higher_is_better: bool = False
+    is_differentiable: bool = False
+    full_state_update: bool = False
+
+    real_features: List[Tensor]
+    fake_features: List[Tensor]
+
+    inception: Module
+
+    def __init__(
+        self,
+        feature: Union[int, Module] = 2048,
+        reset_real_features: bool = True,
+        normalize: bool = False,
+        cosine_distance_eps: float = 0.1,
+        **kwargs: Any,
+    ) -> None:
+        super().__init__(**kwargs)
+        if not _TORCH_GREATER_EQUAL_1_10:
+            raise RuntimeError(
+                "MemorizationInformedFrechetInceptionDistance metric requires PyTorch version greater or equal to 1.10"
+            )
+
+        if isinstance(feature, int):
+            if not _TORCH_FIDELITY_AVAILABLE:
+                raise ModuleNotFoundError(
+                    "MemorizationInformedFrechetInceptionDistance metric requires that `Torch-fidelity` is installed."
+                    " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
+                )
+            valid_int_input = [64, 192, 768, 2048]
+            if feature not in valid_int_input:
+                raise ValueError(
+                    f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}."
+                )
+
+            self.inception = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)])
+
+        elif isinstance(feature, Module):
+            self.inception = feature
+        else:
+            raise TypeError("Got unknown input to argument `feature`")
+
+        if not isinstance(reset_real_features, bool):
+            raise ValueError("Argument `reset_real_features` expected to be a bool")
+        self.reset_real_features = reset_real_features
+
+        if not isinstance(normalize, bool):
+            raise ValueError("Argument `normalize` expected to be a bool")
+        self.normalize = normalize
+
+        if not (isinstance(cosine_distance_eps, float) and 1 >= cosine_distance_eps > 0):
+            raise ValueError("Argument `cosine_distance_eps` expected to be a float greater than 0 and less than 1")
+        self.cosine_distance_eps = cosine_distance_eps
+
+        # states for extracted features
+        self.add_state("real_features", [], dist_reduce_fx=None)
+        self.add_state("fake_features", [], dist_reduce_fx=None)
+
+    def update(self, imgs: Tensor, real: bool) -> None:
+        """Update the state with extracted features."""
+        imgs = (imgs * 255).byte() if self.normalize else imgs
+        features = self.inception(imgs)
+        self.orig_dtype = features.dtype
+        features = features.double()
+
+        if real:
+            self.real_features.append(features)
+        else:
+            self.fake_features.append(features)
+
+    def compute(self) -> Tensor:
+        """Calculate FID score based on accumulated extracted features from the two distributions."""
+        real_features = dim_zero_cat(self.real_features)
+        fake_features = dim_zero_cat(self.fake_features)
+
+        mean_real, mean_fake = torch.mean(real_features, dim=0), torch.mean(fake_features, dim=0)
+        cov_real, cov_fake = torch.cov(real_features.t()), torch.cov(fake_features.t())
+
+        return _mifid_compute(
+            mean_real,
+            cov_real,
+            real_features,
+            mean_fake,
+            cov_fake,
+            fake_features,
+            cosine_distance_eps=self.cosine_distance_eps,
+        ).to(self.orig_dtype)
+
+    def reset(self) -> None:
+        """Reset metric states."""
+        if not self.reset_real_features:
+            # remove temporarily to avoid resetting
+            value = self._defaults.pop("real_features")
+            super().reset()
+            self._defaults["real_features"] = value
+        else:
+            super().reset()
+
+    def plot(
+        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
+    ) -> _PLOT_OUT_TYPE:
+        """Plot a single or multiple values from the metric.
+
+        Args:
+            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
+                If no value is provided, will automatically call `metric.compute` and plot that result.
+            ax: An matplotlib axis object. If provided will add plot to that axis
+
+        Returns:
+            Figure and Axes object
+
+        Raises:
+            ModuleNotFoundError:
+                If `matplotlib` is not installed
+
+        .. plot::
+            :scale: 75
+
+            >>> # Example plotting a single value
+            >>> import torch
+            >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
+            >>> 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)
+            >>> metric = MemorizationInformedFrechetInceptionDistance(feature=64)
+            >>> metric.update(imgs_dist1, real=True)
+            >>> metric.update(imgs_dist2, real=False)
+            >>> fig_, ax_ = metric.plot()
+
+        .. plot::
+            :scale: 75
+
+            >>> # Example plotting multiple values
+            >>> import torch
+            >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
+            >>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
+            >>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
+            >>> metric = MemorizationInformedFrechetInceptionDistance(feature=64)
+            >>> values = [ ]
+            >>> for _ in range(3):
+            ...     metric.update(imgs_dist1(), real=True)
+            ...     metric.update(imgs_dist2(), real=False)
+            ...     values.append(metric.compute())
+            ...     metric.reset()
+            >>> fig_, ax_ = metric.plot(values)
+
+
+        """
+        return self._plot(val, ax)


Test patch:
diff --git a/tests/unittests/image/test_fid.py b/tests/unittests/image/test_fid.py
--- a/tests/unittests/image/test_fid.py
+++ b/tests/unittests/image/test_fid.py
@@ -13,6 +13,7 @@
 # limitations under the License.
 import pickle
 from contextlib import nullcontext as does_not_raise
+from functools import partial
 
 import pytest
 import torch
@@ -119,8 +120,7 @@ def test_compare_fid(tmpdir, equal_size, feature=768):
 
     metric = FrechetInceptionDistance(feature=feature).cuda()
 
-    n = 100
-    m = 100 if equal_size else 90
+    n, m = 100, 100 if equal_size else 90
 
     # Generate some synthetic data
     torch.manual_seed(42)
@@ -179,20 +179,21 @@ def test_reset_real_features_arg(reset_real_features):
 
 
 @pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_9, reason="test requires torch>=1.9")
-def test_normalize_arg_true():
+@pytest.mark.parametrize("normalize", [True, False])
+def test_normalize_arg(normalize):
     """Test that normalize argument works as expected."""
     img = torch.rand(2, 3, 299, 299)
-    metric = FrechetInceptionDistance(normalize=True)
-    with does_not_raise():
-        metric.update(img, real=True)
-
+    metric = FrechetInceptionDistance(normalize=normalize)
+
+    context = (
+        partial(
+            pytest.raises, expected_exception=ValueError, match="Expecting image as torch.Tensor with dtype=torch.uint8"
+        )
+        if not normalize
+        else does_not_raise
+    )
 
-@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_9, reason="test requires torch>=1.9")
-def test_normalize_arg_false():
-    """Test that normalize argument works as expected."""
-    img = torch.rand(2, 3, 299, 299)
-    metric = FrechetInceptionDistance(normalize=False)
-    with pytest.raises(ValueError, match="Expecting image as torch.Tensor with dtype=torch.uint8"):
+    with context():
         metric.update(img, real=True)
 
 
diff --git a/tests/unittests/image/test_mifid.py b/tests/unittests/image/test_mifid.py
new file mode 100644
--- /dev/null
+++ b/tests/unittests/image/test_mifid.py
@@ -0,0 +1,202 @@
+# 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 contextlib import nullcontext as does_not_raise
+from functools import partial
+
+import numpy as np
+import pytest
+import torch
+from scipy.linalg import sqrtm
+from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance, NoTrainInceptionV3
+from torchmetrics.utilities.imports import _TORCH_FIDELITY_AVAILABLE, _TORCH_GREATER_EQUAL_1_10
+
+
+def _compare_mifid(preds, target, cosine_distance_eps: float = 0.1):
+    """Reference implementation.
+
+    Implementation taken from:
+    https://github.com/jybai/generative-memorization-benchmark/blob/main/src/competition_scoring.py
+
+    Adjusted slightly to work with our code. We replace the feature extraction with our own, since we already check in
+    FID that we use the correct feature extractor. This saves us from needing to download tensorflow for comparison.
+    """
+
+    def normalize_rows(x: np.ndarray):
+        return np.nan_to_num(x / np.linalg.norm(x, ord=2, axis=1, keepdims=True))
+
+    def cosine_distance(features1, features2):
+        features1_nozero = features1[np.sum(features1, axis=1) != 0]
+        features2_nozero = features2[np.sum(features2, axis=1) != 0]
+        norm_f1 = normalize_rows(features1_nozero)
+        norm_f2 = normalize_rows(features2_nozero)
+
+        d = 1.0 - np.abs(np.matmul(norm_f1, norm_f2.T))
+        return np.mean(np.min(d, axis=1))
+
+    def distance_thresholding(d, eps):
+        return d if d < eps else 1
+
+    def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
+        mu1 = np.atleast_1d(mu1)
+        mu2 = np.atleast_1d(mu2)
+
+        sigma1 = np.atleast_2d(sigma1)
+        sigma2 = np.atleast_2d(sigma2)
+
+        diff = mu1 - mu2
+
+        # product might be almost singular
+        covmean, _ = sqrtm(sigma1.dot(sigma2), disp=False)
+        if not np.isfinite(covmean).all():
+            offset = np.eye(sigma1.shape[0]) * eps
+            covmean = sqrtm((sigma1 + offset).dot(sigma2 + offset))
+
+        # numerical error might give slight imaginary component
+        if np.iscomplexobj(covmean):
+            if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
+                m = np.max(np.abs(covmean.imag))
+                raise Exception(f"Imaginary component {m}")
+            covmean = covmean.real
+
+        tr_covmean = np.trace(covmean)
+        return diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean
+
+    def calculate_activation_statistics(act):
+        mu = np.mean(act, axis=0)
+        sigma = np.cov(act, rowvar=False)
+        return mu, sigma, act
+
+    def calculate_mifid(m1, s1, features1, m2, s2, features2):
+        fid = calculate_frechet_distance(m1, s1, m2, s2)
+        distance = cosine_distance(features1, features2)
+        return fid, distance
+
+    net = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(768)])
+    preds_act = net(preds).numpy()
+    target_act = net(target).numpy()
+
+    m1, s1, features1 = calculate_activation_statistics(preds_act)
+    m2, s2, features2 = calculate_activation_statistics(target_act)
+
+    fid_private, distance_private = calculate_mifid(m1, s1, features1, m2, s2, features2)
+    distance_private_thresholded = distance_thresholding(distance_private, cosine_distance_eps)
+    return fid_private / (distance_private_thresholded + 1e-15)
+
+
+@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_10, reason="test requires torch>=1.10")
+@pytest.mark.skipif(not _TORCH_FIDELITY_AVAILABLE, reason="test requires torch-fidelity")
+def test_no_train():
+    """Assert that metric never leaves evaluation mode."""
+
+    class MyModel(torch.nn.Module):
+        def __init__(self) -> None:
+            super().__init__()
+            self.metric = MemorizationInformedFrechetInceptionDistance()
+
+        def forward(self, x):
+            return x
+
+    model = MyModel()
+    model.train()
+    assert model.training
+    assert not model.metric.inception.training, "MiFID metric was changed to training mode which should not happen"
+
+
+@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_10, reason="test requires torch>=1.10")
+def test_mifid_raises_errors_and_warnings():
+    """Test that expected warnings and errors are raised."""
+    if _TORCH_FIDELITY_AVAILABLE:
+        with pytest.raises(ValueError, match="Integer input to argument `feature` must be one of .*"):
+            _ = MemorizationInformedFrechetInceptionDistance(feature=2)
+    else:
+        with pytest.raises(
+            ModuleNotFoundError,
+            match="FID metric requires that `Torch-fidelity` is installed."
+            " Either install as `pip install torchmetrics[image-quality]` or `pip install torch-fidelity`.",
+        ):
+            _ = MemorizationInformedFrechetInceptionDistance()
+
+    with pytest.raises(TypeError, match="Got unknown input to argument `feature`"):
+        _ = MemorizationInformedFrechetInceptionDistance(feature=[1, 2])
+
+    with pytest.raises(ValueError, match="Argument `cosine_distance_eps` expected to be a float greater than 0"):
+        _ = MemorizationInformedFrechetInceptionDistance(cosine_distance_eps=-1)
+
+    with pytest.raises(ValueError, match="Argument `cosine_distance_eps` expected to be a float greater than 0"):
+        _ = MemorizationInformedFrechetInceptionDistance(cosine_distance_eps=1.1)
+
+
+@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_10, reason="test requires torch>=1.10")
+@pytest.mark.skipif(not _TORCH_FIDELITY_AVAILABLE, reason="test requires torch-fidelity")
+@pytest.mark.parametrize("feature", [64, 192, 768, 2048])
+def test_fid_same_input(feature):
+    """If real and fake are update on the same data the fid score should be 0."""
+    metric = MemorizationInformedFrechetInceptionDistance(feature=feature)
+
+    for _ in range(2):
+        img = torch.randint(0, 255, (10, 3, 299, 299), dtype=torch.uint8)
+        metric.update(img, real=True)
+        metric.update(img, real=False)
+
+    assert torch.allclose(torch.cat(metric.real_features, dim=0), torch.cat(metric.fake_features, dim=0))
+
+    val = metric.compute()
+    assert torch.allclose(val, torch.zeros_like(val), atol=1e-3)
+
+
+@pytest.mark.skipif(not torch.cuda.is_available(), reason="test is too slow without gpu")
+@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_10, reason="test requires torch>=1.10")
+@pytest.mark.skipif(not _TORCH_FIDELITY_AVAILABLE, reason="test requires torch-fidelity")
+@pytest.mark.parametrize("equal_size", [False, True])
+def test_compare_mifid(equal_size):
+    """Check that our implementation of MIFID is correct by comparing it to the original implementation."""
+    metric = MemorizationInformedFrechetInceptionDistance(feature=768).cuda()
+
+    n, m = 100, 100 if equal_size else 90
+
+    # Generate some synthetic data
+    torch.manual_seed(42)
+    img1 = torch.randint(0, 180, (n, 3, 299, 299), dtype=torch.uint8)
+    img2 = torch.randint(100, 255, (m, 3, 299, 299), dtype=torch.uint8)
+
+    batch_size = 10
+    for i in range(n // batch_size):
+        metric.update(img1[batch_size * i : batch_size * (i + 1)].cuda(), real=True)
+
+    for i in range(m // batch_size):
+        metric.update(img2[batch_size * i : batch_size * (i + 1)].cuda(), real=False)
+
+    compare_val = _compare_mifid(img1, img2)
+    tm_res = metric.compute()
+
+    assert torch.allclose(tm_res.cpu(), torch.tensor(compare_val, dtype=tm_res.dtype), atol=1e-3)
+
+
+@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_10, reason="test requires torch>=1.10")
+@pytest.mark.parametrize("normalize", [True, False])
+def test_normalize_arg(normalize):
+    """Test that normalize argument works as expected."""
+    img = torch.rand(2, 3, 299, 299)
+    metric = MemorizationInformedFrechetInceptionDistance(normalize=normalize)
+
+    context = (
+        partial(
+            pytest.raises, expected_exception=ValueError, match="Expecting image as torch.Tensor with dtype=torch.uint8"
+        )
+        if not normalize
+        else does_not_raise
+    )
+
+    with context():
+        metric.update(img, real=True)
diff --git a/tests/unittests/utilities/test_plot.py b/tests/unittests/utilities/test_plot.py
--- a/tests/unittests/utilities/test_plot.py
+++ b/tests/unittests/utilities/test_plot.py
@@ -100,6 +100,7 @@
     InceptionScore,
     KernelInceptionDistance,
     LearnedPerceptualImagePatchSimilarity,
+    MemorizationInformedFrechetInceptionDistance,
     MultiScaleStructuralSimilarityIndexMeasure,
     PeakSignalNoiseRatio,
     RelativeAverageSpectralError,
@@ -160,7 +161,11 @@
     WordInfoLost,
     WordInfoPreserved,
 )
-from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_1_9, _TORCHAUDIO_GREATER_EQUAL_0_10
+from torchmetrics.utilities.imports import (
+    _TORCH_GREATER_EQUAL_1_9,
+    _TORCH_GREATER_EQUAL_1_10,
+    _TORCHAUDIO_GREATER_EQUAL_0_10,
+)
 from torchmetrics.wrappers import (
     BootStrapper,
     ClasswiseWrapper,
@@ -654,6 +659,14 @@ def test_plot_methods(metric_class: object, preds: Callable, target: Callable, n
             True,
             id="inception score",
         ),
+        pytest.param(
+            partial(MemorizationInformedFrechetInceptionDistance, feature=64),
+            lambda: torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8),
+            lambda: torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8),
+            False,
+            id="memorization informed frechet inception distance",
+            marks=pytest.mark.skipif(not _TORCH_GREATER_EQUAL_1_10, reason="test requires torch>=1.9"),
+        ),
     ],
 )
 @pytest.mark.parametrize("num_vals", [1, 2])