kid.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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
  20. from torchmetrics.metric import Metric
  21. from torchmetrics.utilities import rank_zero_warn
  22. from torchmetrics.utilities.data import dim_zero_cat
  23. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE
  24. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  25. if not _MATPLOTLIB_AVAILABLE:
  26. __doctest_skip__ = ["KernelInceptionDistance.plot"]
  27. __doctest_requires__ = {("KernelInceptionDistance", "KernelInceptionDistance.plot"): ["torch_fidelity"]}
  28. def maximum_mean_discrepancy(k_xx: Tensor, k_xy: Tensor, k_yy: Tensor) -> Tensor:
  29. """Adapted from `KID Score`_."""
  30. m = k_xx.shape[0]
  31. diag_x = torch.diag(k_xx)
  32. diag_y = torch.diag(k_yy)
  33. kt_xx_sums = k_xx.sum(dim=-1) - diag_x
  34. kt_yy_sums = k_yy.sum(dim=-1) - diag_y
  35. k_xy_sums = k_xy.sum(dim=0)
  36. kt_xx_sum = kt_xx_sums.sum()
  37. kt_yy_sum = kt_yy_sums.sum()
  38. k_xy_sum = k_xy_sums.sum()
  39. value = (kt_xx_sum + kt_yy_sum) / (m * (m - 1))
  40. value -= 2 * k_xy_sum / (m**2)
  41. return value
  42. def poly_kernel(f1: Tensor, f2: Tensor, degree: int = 3, gamma: Optional[float] = None, coef: float = 1.0) -> Tensor:
  43. """Adapted from `KID Score`_."""
  44. if gamma is None:
  45. gamma = 1.0 / f1.shape[1]
  46. return (f1 @ f2.T * gamma + coef) ** degree
  47. def poly_mmd(
  48. f_real: Tensor, f_fake: Tensor, degree: int = 3, gamma: Optional[float] = None, coef: float = 1.0
  49. ) -> Tensor:
  50. """Adapted from `KID Score`_."""
  51. k_11 = poly_kernel(f_real, f_real, degree, gamma, coef)
  52. k_22 = poly_kernel(f_fake, f_fake, degree, gamma, coef)
  53. k_12 = poly_kernel(f_real, f_fake, degree, gamma, coef)
  54. return maximum_mean_discrepancy(k_11, k_12, k_22)
  55. class KernelInceptionDistance(Metric):
  56. r"""Calculate Kernel Inception Distance (KID) which is used to access the quality of generated images.
  57. .. math::
  58. KID = MMD(f_{real}, f_{fake})^2
  59. where :math:`MMD` is the maximum mean discrepancy and :math:`I_{real}, I_{fake}` are extracted features
  60. from real and fake images, see `kid ref1`_ for more details. In particular, calculating the MMD requires the
  61. evaluation of a polynomial kernel function :math:`k`
  62. .. math::
  63. k(x,y) = (\gamma * x^T y + coef)^{degree}
  64. which controls the distance between two features. In practise the MMD is calculated over a number of
  65. subsets to be able to both get the mean and standard deviation of KID.
  66. Using the default feature extraction (Inception v3 using the original weights from `kid ref2`_), the input is
  67. expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize``
  68. is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if
  69. ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]``
  70. range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian
  71. flag ``real`` determines if the images should update the statistics of the real distribution or the
  72. fake distribution.
  73. Using custom feature extractor is also possible. One can give a torch.nn.Module as `feature` argument. This
  74. custom feature extractor is expected to have output shape of ``(1, num_features)`` This would change the
  75. used feature extractor from default (Inception v3) to the given network. ``normalize`` argument won't have any
  76. effect and update method expects to have the tensor given to `imgs` argument to be in the correct shape and
  77. type that is compatible to the custom feature extractor.
  78. .. hint::
  79. Using this metric with the default feature extractor requires that ``torch-fidelity``
  80. is installed. Either install as ``pip install torchmetrics[image]`` or
  81. ``pip install torch-fidelity``
  82. As input to ``forward`` and ``update`` the metric accepts the following input
  83. - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor of shape ``(N,C,H,W)``
  84. - ``real`` (`bool`): bool indicating if ``imgs`` belong to the real or the fake distribution
  85. As output of `forward` and `compute` the metric returns the following output
  86. - ``kid_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean value over subsets
  87. - ``kid_std`` (:class:`~torch.Tensor`): float scalar tensor with standard deviation value over subsets
  88. Args:
  89. feature: Either an str, integer or ``nn.Module``:
  90. - an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
  91. 'logits_unbiased', 64, 192, 768, 2048
  92. - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
  93. an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.
  94. subsets: Number of subsets to calculate the mean and standard deviation scores over
  95. subset_size: Number of randomly picked samples in each subset
  96. degree: Degree of the polynomial kernel function
  97. gamma: Scale-length of polynomial kernel. If set to ``None`` will be automatically set to the feature size
  98. coef: Bias term in the polynomial kernel.
  99. reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
  100. change, the features can cached them to avoid recomputing them which is costly. Set this to ``False`` if
  101. your dataset does not change.
  102. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  103. Raises:
  104. ValueError:
  105. If ``feature`` is set to an ``int`` (default settings) and ``torch-fidelity`` is not installed
  106. ValueError:
  107. If ``feature`` is set to an ``int`` not in ``(64, 192, 768, 2048)``
  108. ValueError:
  109. If ``subsets`` is not an integer larger than 0
  110. ValueError:
  111. If ``subset_size`` is not an integer larger than 0
  112. ValueError:
  113. If ``degree`` is not an integer larger than 0
  114. ValueError:
  115. If ``gamma`` is neither ``None`` or a float larger than 0
  116. ValueError:
  117. If ``coef`` is not an float larger than 0
  118. ValueError:
  119. If ``reset_real_features`` is not an ``bool``
  120. Example:
  121. >>> from torch import randint
  122. >>> from torchmetrics.image.kid import KernelInceptionDistance
  123. >>> kid = KernelInceptionDistance(subset_size=50)
  124. >>> # generate two slightly overlapping image intensity distributions
  125. >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  126. >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  127. >>> kid.update(imgs_dist1, real=True)
  128. >>> kid.update(imgs_dist2, real=False)
  129. >>> kid.compute()
  130. (tensor(0.0312), tensor(0.0025))
  131. """
  132. higher_is_better: bool = False
  133. is_differentiable: bool = False
  134. full_state_update: bool = False
  135. plot_lower_bound: float = 0.0
  136. plot_upper_bound: float = 1.0
  137. real_features: List[Tensor]
  138. fake_features: List[Tensor]
  139. inception: Module
  140. feature_network: str = "inception"
  141. def __init__(
  142. self,
  143. feature: Union[str, int, Module] = 2048,
  144. subsets: int = 100,
  145. subset_size: int = 1000,
  146. degree: int = 3,
  147. gamma: Optional[float] = None,
  148. coef: float = 1.0,
  149. reset_real_features: bool = True,
  150. normalize: bool = False,
  151. **kwargs: Any,
  152. ) -> None:
  153. super().__init__(**kwargs)
  154. rank_zero_warn(
  155. "Metric `Kernel Inception Distance` will save all extracted features in buffer."
  156. " For large datasets this may lead to large memory footprint.",
  157. UserWarning,
  158. )
  159. self.used_custom_model = False
  160. if isinstance(feature, (str, int)):
  161. if not _TORCH_FIDELITY_AVAILABLE:
  162. raise ModuleNotFoundError(
  163. "Kernel Inception Distance metric requires that `Torch-fidelity` is installed."
  164. " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
  165. )
  166. valid_int_input = ("logits_unbiased", 64, 192, 768, 2048)
  167. if feature not in valid_int_input:
  168. raise ValueError(
  169. f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}."
  170. )
  171. self.inception: Module = NoTrainInceptionV3(name="inception-v3-compat", features_list=[str(feature)])
  172. elif isinstance(feature, Module):
  173. self.inception = feature
  174. self.used_custom_model = True
  175. else:
  176. raise TypeError("Got unknown input to argument `feature`")
  177. if not (isinstance(subsets, int) and subsets > 0):
  178. raise ValueError("Argument `subsets` expected to be integer larger than 0")
  179. self.subsets = subsets
  180. if not (isinstance(subset_size, int) and subset_size > 0):
  181. raise ValueError("Argument `subset_size` expected to be integer larger than 0")
  182. self.subset_size = subset_size
  183. if not (isinstance(degree, int) and degree > 0):
  184. raise ValueError("Argument `degree` expected to be integer larger than 0")
  185. self.degree = degree
  186. if gamma is not None and not (isinstance(gamma, float) and gamma > 0):
  187. raise ValueError("Argument `gamma` expected to be `None` or float larger than 0")
  188. self.gamma = gamma
  189. if not (isinstance(coef, float) and coef > 0):
  190. raise ValueError("Argument `coef` expected to be float larger than 0")
  191. self.coef = coef
  192. if not isinstance(reset_real_features, bool):
  193. raise ValueError("Argument `reset_real_features` expected to be a bool")
  194. self.reset_real_features = reset_real_features
  195. if not isinstance(normalize, bool):
  196. raise ValueError("Argument `normalize` expected to be a bool")
  197. self.normalize = normalize
  198. # states for extracted features
  199. self.add_state("real_features", [], dist_reduce_fx=None)
  200. self.add_state("fake_features", [], dist_reduce_fx=None)
  201. def update(self, imgs: Tensor, real: bool) -> None:
  202. """Update the state with extracted features.
  203. Args:
  204. imgs: Input img tensors to evaluate. If used custom feature extractor please
  205. make sure dtype and size is correct for the model.
  206. real: Whether given image is real or fake.
  207. """
  208. imgs = (imgs * 255).byte() if self.normalize and (not self.used_custom_model) else imgs
  209. features = self.inception(imgs)
  210. if real:
  211. self.real_features.append(features)
  212. else:
  213. self.fake_features.append(features)
  214. def compute(self) -> tuple[Tensor, Tensor]:
  215. """Calculate KID score based on accumulated extracted features from the two distributions.
  216. Implementation inspired by `Fid Score`_
  217. Returns:
  218. kid_mean (:class:`~torch.Tensor`): float scalar tensor with mean value over subsets
  219. kid_std (:class:`~torch.Tensor`): float scalar tensor with standard deviation value over subsets
  220. """
  221. real_features = dim_zero_cat(self.real_features)
  222. fake_features = dim_zero_cat(self.fake_features)
  223. n_samples_real = real_features.shape[0]
  224. if n_samples_real < self.subset_size:
  225. raise ValueError("Argument `subset_size` should be smaller than the number of samples")
  226. n_samples_fake = fake_features.shape[0]
  227. if n_samples_fake < self.subset_size:
  228. raise ValueError("Argument `subset_size` should be smaller than the number of samples")
  229. kid_scores_ = []
  230. for _ in range(self.subsets):
  231. perm = torch.randperm(n_samples_real)
  232. f_real = real_features[perm[: self.subset_size]]
  233. perm = torch.randperm(n_samples_fake)
  234. f_fake = fake_features[perm[: self.subset_size]]
  235. o = poly_mmd(f_real, f_fake, self.degree, self.gamma, self.coef)
  236. kid_scores_.append(o)
  237. kid_scores = torch.stack(kid_scores_)
  238. return kid_scores.mean(), kid_scores.std(unbiased=False)
  239. def reset(self) -> None:
  240. """Reset metric states."""
  241. if not self.reset_real_features:
  242. # remove temporarily to avoid resetting
  243. value = self._defaults.pop("real_features")
  244. super().reset()
  245. self._defaults["real_features"] = value
  246. else:
  247. super().reset()
  248. def plot(
  249. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  250. ) -> _PLOT_OUT_TYPE:
  251. """Plot a single or multiple values from the metric.
  252. Args:
  253. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  254. If no value is provided, will automatically call `metric.compute` and plot that result.
  255. ax: An matplotlib axis object. If provided will add plot to that axis
  256. Returns:
  257. Figure and Axes object
  258. Raises:
  259. ModuleNotFoundError:
  260. If `matplotlib` is not installed
  261. .. plot::
  262. :scale: 75
  263. >>> # Example plotting a single value
  264. >>> import torch
  265. >>> from torchmetrics.image.kid import KernelInceptionDistance
  266. >>> imgs_dist1 = torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8)
  267. >>> imgs_dist2 = torch.randint(100, 255, (30, 3, 299, 299), dtype=torch.uint8)
  268. >>> metric = KernelInceptionDistance(subsets=3, subset_size=20)
  269. >>> metric.update(imgs_dist1, real=True)
  270. >>> metric.update(imgs_dist2, real=False)
  271. >>> fig_, ax_ = metric.plot()
  272. .. plot::
  273. :scale: 75
  274. >>> # Example plotting multiple values
  275. >>> import torch
  276. >>> from torchmetrics.image.kid import KernelInceptionDistance
  277. >>> imgs_dist1 = lambda: torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8)
  278. >>> imgs_dist2 = lambda: torch.randint(100, 255, (30, 3, 299, 299), dtype=torch.uint8)
  279. >>> metric = KernelInceptionDistance(subsets=3, subset_size=20)
  280. >>> values = [ ]
  281. >>> for _ in range(3):
  282. ... metric.update(imgs_dist1(), real=True)
  283. ... metric.update(imgs_dist2(), real=False)
  284. ... values.append(metric.compute()[0])
  285. ... metric.reset()
  286. >>> fig_, ax_ = metric.plot(values)
  287. """
  288. val = val or self.compute()[0] # by default we select the mean to plot
  289. return self._plot(val, ax)