mifid.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections.abc import Sequence
  15. from typing import Any, List, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torch.nn import Module
  19. from torchmetrics.image.fid import NoTrainInceptionV3, _compute_fid
  20. from torchmetrics.metric import Metric
  21. from torchmetrics.utilities.data import dim_zero_cat
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. __doctest_requires__ = {
  25. ("MemorizationInformedFrechetInceptionDistance", "MemorizationInformedFrechetInceptionDistance.plot"): [
  26. "torch_fidelity"
  27. ]
  28. }
  29. if not _MATPLOTLIB_AVAILABLE:
  30. __doctest_skip__ = ["MemorizationInformedFrechetInceptionDistance.plot"]
  31. def _compute_cosine_distance(features1: Tensor, features2: Tensor, cosine_distance_eps: float = 0.1) -> Tensor:
  32. """Compute the cosine distance between two sets of features."""
  33. features1_nozero = features1[torch.sum(features1, dim=1) != 0]
  34. features2_nozero = features2[torch.sum(features2, dim=1) != 0]
  35. # normalize
  36. norm_f1 = features1_nozero / torch.norm(features1_nozero, dim=1, keepdim=True)
  37. norm_f2 = features2_nozero / torch.norm(features2_nozero, dim=1, keepdim=True)
  38. d = 1.0 - torch.abs(torch.matmul(norm_f1, norm_f2.t()))
  39. mean_min_d = torch.mean(d.min(dim=1).values)
  40. return mean_min_d if mean_min_d < cosine_distance_eps else torch.ones_like(mean_min_d)
  41. def _mifid_compute(
  42. mu1: Tensor,
  43. sigma1: Tensor,
  44. features1: Tensor,
  45. mu2: Tensor,
  46. sigma2: Tensor,
  47. features2: Tensor,
  48. cosine_distance_eps: float = 0.1,
  49. ) -> Tensor:
  50. """Compute MIFID score given two sets of features and their statistics."""
  51. fid_value = _compute_fid(mu1, sigma1, mu2, sigma2)
  52. distance = _compute_cosine_distance(features1, features2, cosine_distance_eps)
  53. # secure that very small fid values does not explode the mifid
  54. return fid_value / (distance + 10e-15) if fid_value > 1e-8 else torch.zeros_like(fid_value)
  55. class MemorizationInformedFrechetInceptionDistance(Metric):
  56. r"""Calculate Memorization-Informed Frechet Inception Distance (MIFID_).
  57. MIFID is a improved variation of the Frechet Inception Distance (FID_) that penalizes memorization of the training
  58. set by the generator. It is calculated as
  59. .. math::
  60. MIFID = \frac{FID(F_{real}, F_{fake})}{M(F_{real}, F_{fake})}
  61. where :math:`FID` is the normal FID score and :math:`M` is the memorization penalty. The memorization penalty
  62. essentially corresponds to the average minimum cosine distance between the features of the real and fake
  63. distribution.
  64. Using the default feature extraction (Inception v3 using the original weights from `fid ref2`_), the input is
  65. expected to be mini-batches of 3-channel RGB images of shape ``(3 x H x W)``. If argument ``normalize``
  66. is ``True`` images are expected to be dtype ``float`` and have values in the ``[0, 1]`` range, else if
  67. ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]``
  68. range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian
  69. flag ``real`` determines if the images should update the statistics of the real distribution or the
  70. fake distribution.
  71. .. hint::
  72. Using this metrics requires you to have ``scipy`` install. Either install as ``pip install
  73. torchmetrics[image]`` or ``pip install scipy``
  74. .. hint::
  75. Using this metric with the default feature extractor requires that ``torch-fidelity``
  76. is installed. Either install as ``pip install torchmetrics[image]`` or
  77. ``pip install torch-fidelity``
  78. As input to ``forward`` and ``update`` the metric accepts the following input
  79. - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with
  80. - ``real`` (:class:`~bool`): bool indicating if ``imgs`` belong to the real or the fake distribution
  81. As output of `forward` and `compute` the metric returns the following output
  82. - ``mifid`` (:class:`~torch.Tensor`): float scalar tensor with mean MIFID value over samples
  83. Args:
  84. feature:
  85. Either an integer or ``nn.Module``:
  86. - an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
  87. 64, 192, 768, 2048
  88. - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
  89. an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.
  90. reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
  91. change, the features can be cached them to avoid recomputing them which is costly. Set this to ``False`` if
  92. your dataset does not change.
  93. normalize: Whether to normalize the input images. If ``True`` the input is expected to be in the range [0, 1]
  94. and converted to ``uint8``. If ``False`` the input is expected to already be in the range [0, 255] and of
  95. type ``uint8``. If a custom feature extractor is used, this argument is ignored.
  96. cosine_distance_eps: Epsilon value for the cosine distance. If the cosine distance is larger than this value
  97. it is set to 1 and thus ignored in the MIFID calculation.
  98. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  99. Raises:
  100. RuntimeError:
  101. If ``torch`` is version less than 1.10
  102. ValueError:
  103. If ``feature`` is set to an ``int`` and ``torch-fidelity`` is not installed
  104. ValueError:
  105. If ``feature`` is set to an ``int`` not in [64, 192, 768, 2048]
  106. TypeError:
  107. If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``
  108. ValueError:
  109. If ``reset_real_features`` is not an ``bool``
  110. Example::
  111. >>> from torch import randint
  112. >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
  113. >>> mifid = MemorizationInformedFrechetInceptionDistance(feature=64)
  114. >>> # generate two slightly overlapping image intensity distributions
  115. >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  116. >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  117. >>> mifid.update(imgs_dist1, real=True)
  118. >>> mifid.update(imgs_dist2, real=False)
  119. >>> mifid.compute()
  120. tensor(3003.3691)
  121. """
  122. higher_is_better: bool = False
  123. is_differentiable: bool = False
  124. full_state_update: bool = False
  125. real_features: List[Tensor]
  126. fake_features: List[Tensor]
  127. inception: Module
  128. feature_network: str = "inception"
  129. def __init__(
  130. self,
  131. feature: Union[int, Module] = 2048,
  132. reset_real_features: bool = True,
  133. normalize: bool = False,
  134. cosine_distance_eps: float = 0.1,
  135. **kwargs: Any,
  136. ) -> None:
  137. super().__init__(**kwargs)
  138. self.used_custom_model = False
  139. if isinstance(feature, int):
  140. if not _TORCH_FIDELITY_AVAILABLE:
  141. raise ModuleNotFoundError(
  142. "MemorizationInformedFrechetInceptionDistance metric requires that `Torch-fidelity` is installed."
  143. " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
  144. )
  145. valid_int_input = [64, 192, 768, 2048]
  146. if feature not in valid_int_input:
  147. raise ValueError(
  148. f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}."
  149. )
  150. self.inception = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)])
  151. elif isinstance(feature, Module):
  152. self.inception = feature
  153. self.used_custom_model = True
  154. else:
  155. raise TypeError("Got unknown input to argument `feature`")
  156. if not isinstance(reset_real_features, bool):
  157. raise ValueError("Argument `reset_real_features` expected to be a bool")
  158. self.reset_real_features = reset_real_features
  159. if not isinstance(normalize, bool):
  160. raise ValueError("Argument `normalize` expected to be a bool")
  161. self.normalize = normalize
  162. if not (isinstance(cosine_distance_eps, float) and 1 >= cosine_distance_eps > 0):
  163. raise ValueError("Argument `cosine_distance_eps` expected to be a float greater than 0 and less than 1")
  164. self.cosine_distance_eps = cosine_distance_eps
  165. # states for extracted features
  166. self.add_state("real_features", [], dist_reduce_fx=None)
  167. self.add_state("fake_features", [], dist_reduce_fx=None)
  168. def update(self, imgs: Tensor, real: bool) -> None:
  169. """Update the state with extracted features."""
  170. imgs = (imgs * 255).byte() if self.normalize and not self.used_custom_model else imgs
  171. features = self.inception(imgs)
  172. self.orig_dtype = features.dtype
  173. features = features.double()
  174. if real:
  175. self.real_features.append(features)
  176. else:
  177. self.fake_features.append(features)
  178. def compute(self) -> Tensor:
  179. """Calculate FID score based on accumulated extracted features from the two distributions."""
  180. real_features = dim_zero_cat(self.real_features)
  181. fake_features = dim_zero_cat(self.fake_features)
  182. mean_real, mean_fake = torch.mean(real_features, dim=0), torch.mean(fake_features, dim=0)
  183. cov_real, cov_fake = torch.cov(real_features.t()), torch.cov(fake_features.t())
  184. return _mifid_compute(
  185. mean_real,
  186. cov_real,
  187. real_features,
  188. mean_fake,
  189. cov_fake,
  190. fake_features,
  191. cosine_distance_eps=self.cosine_distance_eps,
  192. ).to(self.orig_dtype)
  193. def reset(self) -> None:
  194. """Reset metric states."""
  195. if not self.reset_real_features:
  196. # remove temporarily to avoid resetting
  197. value = self._defaults.pop("real_features")
  198. super().reset()
  199. self._defaults["real_features"] = value
  200. else:
  201. super().reset()
  202. def plot(
  203. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  204. ) -> _PLOT_OUT_TYPE:
  205. """Plot a single or multiple values from the metric.
  206. Args:
  207. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  208. If no value is provided, will automatically call `metric.compute` and plot that result.
  209. ax: An matplotlib axis object. If provided will add plot to that axis
  210. Returns:
  211. Figure and Axes object
  212. Raises:
  213. ModuleNotFoundError:
  214. If `matplotlib` is not installed
  215. .. plot::
  216. :scale: 75
  217. >>> # Example plotting a single value
  218. >>> import torch
  219. >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
  220. >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  221. >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  222. >>> metric = MemorizationInformedFrechetInceptionDistance(feature=64)
  223. >>> metric.update(imgs_dist1, real=True)
  224. >>> metric.update(imgs_dist2, real=False)
  225. >>> fig_, ax_ = metric.plot()
  226. .. plot::
  227. :scale: 75
  228. >>> # Example plotting multiple values
  229. >>> import torch
  230. >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
  231. >>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  232. >>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  233. >>> metric = MemorizationInformedFrechetInceptionDistance(feature=64)
  234. >>> values = [ ]
  235. >>> for _ in range(3):
  236. ... metric.update(imgs_dist1(), real=True)
  237. ... metric.update(imgs_dist2(), real=False)
  238. ... values.append(metric.compute())
  239. ... metric.reset()
  240. >>> fig_, ax_ = metric.plot(values)
  241. """
  242. return self._plot(val, ax)