fid.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 copy import deepcopy
  16. from typing import Any, Optional, Union
  17. import torch
  18. from torch import Tensor
  19. from torch.nn import Module
  20. from torch.nn.functional import adaptive_avg_pool2d
  21. from torchmetrics.metric import Metric
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCH_FIDELITY_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["FrechetInceptionDistance.plot"]
  26. if _TORCH_FIDELITY_AVAILABLE:
  27. from torch_fidelity.feature_extractor_inceptionv3 import FeatureExtractorInceptionV3 as _FeatureExtractorInceptionV3
  28. from torch_fidelity.helpers import vassert
  29. from torch_fidelity.interpolate_compat_tensorflow import interpolate_bilinear_2d_like_tensorflow1x
  30. else:
  31. class _FeatureExtractorInceptionV3(Module): # type: ignore[no-redef]
  32. pass
  33. vassert = None
  34. interpolate_bilinear_2d_like_tensorflow1x = None
  35. __doctest_skip__ = ["FrechetInceptionDistance", "FrechetInceptionDistance.plot"]
  36. class NoTrainInceptionV3(_FeatureExtractorInceptionV3):
  37. """Module that never leaves evaluation mode."""
  38. INPUT_IMAGE_SIZE: int
  39. def __init__(
  40. self,
  41. name: str,
  42. features_list: list[str],
  43. feature_extractor_weights_path: Optional[str] = None,
  44. antialias: bool = True,
  45. ) -> None:
  46. if not _TORCH_FIDELITY_AVAILABLE:
  47. raise ModuleNotFoundError(
  48. "NoTrainInceptionV3 module requires that `Torch-fidelity` is installed."
  49. " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
  50. )
  51. super().__init__(name, features_list, feature_extractor_weights_path)
  52. self.use_antialias = antialias
  53. # put into evaluation mode
  54. self.eval()
  55. def train(self, mode: bool) -> "NoTrainInceptionV3":
  56. """Force network to always be in evaluation mode."""
  57. return super().train(False)
  58. def _torch_fidelity_forward(self, x: Tensor) -> tuple[Tensor, ...]:
  59. """Forward method of inception net.
  60. Copy of the forward method from this file:
  61. https://github.com/toshas/torch-fidelity/blob/master/torch_fidelity/feature_extractor_inceptionv3.py
  62. with a single line change regarding the casting of `x` in the beginning.
  63. Corresponding license file (Apache License, Version 2.0):
  64. https://github.com/toshas/torch-fidelity/blob/master/LICENSE.md
  65. """
  66. vassert(torch.is_tensor(x) and x.dtype == torch.uint8, "Expecting image as torch.Tensor with dtype=torch.uint8")
  67. features = {}
  68. remaining_features = self.features_list.copy()
  69. x = x.to(self._dtype) if hasattr(self, "_dtype") else x.to(torch.float)
  70. if self.use_antialias:
  71. x = torch.nn.functional.interpolate(
  72. x,
  73. size=(self.INPUT_IMAGE_SIZE, self.INPUT_IMAGE_SIZE),
  74. mode="bilinear",
  75. align_corners=False,
  76. antialias=True,
  77. )
  78. else:
  79. x = interpolate_bilinear_2d_like_tensorflow1x(
  80. x,
  81. size=(self.INPUT_IMAGE_SIZE, self.INPUT_IMAGE_SIZE),
  82. align_corners=False,
  83. )
  84. x = (x - 128) / 128
  85. x = self.Conv2d_1a_3x3(x)
  86. x = self.Conv2d_2a_3x3(x)
  87. x = self.Conv2d_2b_3x3(x)
  88. x = self.MaxPool_1(x)
  89. if "64" in remaining_features:
  90. features["64"] = adaptive_avg_pool2d(x, output_size=(1, 1)).squeeze(-1).squeeze(-1)
  91. remaining_features.remove("64")
  92. if len(remaining_features) == 0:
  93. return tuple(features[a] for a in self.features_list)
  94. x = self.Conv2d_3b_1x1(x)
  95. x = self.Conv2d_4a_3x3(x)
  96. x = self.MaxPool_2(x)
  97. if "192" in remaining_features:
  98. features["192"] = adaptive_avg_pool2d(x, output_size=(1, 1)).squeeze(-1).squeeze(-1)
  99. remaining_features.remove("192")
  100. if len(remaining_features) == 0:
  101. return tuple(features[a] for a in self.features_list)
  102. x = self.Mixed_5b(x)
  103. x = self.Mixed_5c(x)
  104. x = self.Mixed_5d(x)
  105. x = self.Mixed_6a(x)
  106. x = self.Mixed_6b(x)
  107. x = self.Mixed_6c(x)
  108. x = self.Mixed_6d(x)
  109. x = self.Mixed_6e(x)
  110. if "768" in remaining_features:
  111. features["768"] = adaptive_avg_pool2d(x, output_size=(1, 1)).squeeze(-1).squeeze(-1)
  112. remaining_features.remove("768")
  113. if len(remaining_features) == 0:
  114. return tuple(features[a] for a in self.features_list)
  115. x = self.Mixed_7a(x)
  116. x = self.Mixed_7b(x)
  117. x = self.Mixed_7c(x)
  118. x = self.AvgPool(x)
  119. x = torch.flatten(x, 1)
  120. if "2048" in remaining_features:
  121. features["2048"] = x
  122. remaining_features.remove("2048")
  123. if len(remaining_features) == 0:
  124. return tuple(features[a] for a in self.features_list)
  125. if "logits_unbiased" in remaining_features:
  126. x = x.mm(self.fc.weight.T)
  127. # N x 1008 (num_classes)
  128. features["logits_unbiased"] = x
  129. remaining_features.remove("logits_unbiased")
  130. if len(remaining_features) == 0:
  131. return tuple(features[a] for a in self.features_list)
  132. x = x + self.fc.bias.unsqueeze(0)
  133. else:
  134. x = self.fc(x)
  135. features["logits"] = x
  136. return tuple(features[a] for a in self.features_list)
  137. def forward(self, x: Tensor) -> Tensor:
  138. """Forward pass of neural network with reshaping of output."""
  139. out = self._torch_fidelity_forward(x)
  140. return out[0].reshape(x.shape[0], -1)
  141. def _compute_fid(mu1: Tensor, sigma1: Tensor, mu2: Tensor, sigma2: Tensor) -> Tensor:
  142. r"""Compute adjusted version of `Fid Score`_.
  143. The Frechet Inception Distance between two multivariate Gaussians X_x ~ N(mu_1, sigm_1)
  144. and X_y ~ N(mu_2, sigm_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(sigm_1 + sigm_2 - 2*sqrt(sigm_1*sigm_2)).
  145. Args:
  146. mu1: mean of activations calculated on predicted (x) samples
  147. sigma1: covariance matrix over activations calculated on predicted (x) samples
  148. mu2: mean of activations calculated on target (y) samples
  149. sigma2: covariance matrix over activations calculated on target (y) samples
  150. Returns:
  151. Scalar value of the distance between sets.
  152. """
  153. a = (mu1 - mu2).square().sum(dim=-1)
  154. b = sigma1.trace() + sigma2.trace()
  155. c = torch.linalg.eigvals(sigma1 @ sigma2).sqrt().real.sum(dim=-1)
  156. return a + b - 2 * c
  157. class FrechetInceptionDistance(Metric):
  158. r"""Calculate Fréchet inception distance (FID_) which is used to assess the quality of generated images.
  159. .. math::
  160. FID = \|\mu - \mu_w\|^2 + tr(\Sigma + \Sigma_w - 2(\Sigma \Sigma_w)^{\frac{1}{2}})
  161. where :math:`\mathcal{N}(\mu, \Sigma)` is the multivariate normal distribution estimated from Inception v3
  162. (`fid ref1`_) features calculated on real life images and :math:`\mathcal{N}(\mu_w, \Sigma_w)` is the
  163. multivariate normal distribution estimated from Inception v3 features calculated on generated (fake) images.
  164. The metric was originally proposed in `fid ref1`_.
  165. Using the default feature extraction (Inception v3 using the original weights from `fid ref2`_), the input is
  166. expected to be mini-batches of 3-channel RGB images of shape ``(3xHxW)``. If argument ``normalize``
  167. is ``True`` images are expected to be dtype ``float`` and have values in the ``[0,1]`` range, else if
  168. ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]``
  169. range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian
  170. flag ``real`` determines if the images should update the statistics of the real distribution or the
  171. fake distribution.
  172. Using custom feature extractor is also possible. One can give a torch.nn.Module as `feature` argument. This
  173. custom feature extractor is expected to have output shape of ``(1, num_features)``. This would change the
  174. used feature extractor from default (Inception v3) to the given network. In case network doesn't have
  175. ``num_features`` attribute, a random tensor will be given to the network to infer feature dimensionality.
  176. Size of this tensor can be controlled by ``input_img_size`` argument and type of the tensor can be controlled
  177. with ``normalize`` argument (``True`` uses float32 tensors and ``False`` uses int8 tensors). In this case, update
  178. method expects to have the tensor given to `imgs` argument to be in the correct shape and type that is compatible
  179. to the custom feature extractor.
  180. This metric is known to be unstable in its calculatations, and we recommend for the best results using this metric
  181. that you calculate using `torch.float64` (default is `torch.float32`) which can be set using the `.set_dtype`
  182. method of the metric.
  183. .. hint::
  184. Using this metric with the default feature extractor requires that ``torch-fidelity``
  185. is installed. Either install as ``pip install torchmetrics[image]`` or ``pip install torch-fidelity``
  186. As input to ``forward`` and ``update`` the metric accepts the following input
  187. - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with
  188. - ``real`` (:class:`~bool`): bool indicating if ``imgs`` belong to the real or the fake distribution
  189. As output of `forward` and `compute` the metric returns the following output
  190. - ``fid`` (:class:`~torch.Tensor`): float scalar tensor with mean FID value over samples
  191. Args:
  192. feature:
  193. Either an integer or ``nn.Module``:
  194. - an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
  195. 64, 192, 768, 2048
  196. - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
  197. an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.
  198. reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
  199. change, the features can be cached them to avoid recomputing them which is costly. Set this to ``False`` if
  200. your dataset does not change.
  201. normalize:
  202. Argument for controlling the input image dtype normalization:
  203. - If default feature extractor is used, controls whether input imgs have values in range [0, 1] or not:
  204. - True: if input imgs have values ranged in [0, 1]. They are cast to int8/byte tensors.
  205. - False: if input imgs have values ranged in [0, 255]. No casting is done.
  206. - If custom feature extractor module is used, controls type of the input img tensors:
  207. - True: if input imgs are expected to be in the data type of torch.float32.
  208. - False: if input imgs are expected to be in the data type of torch.int8.
  209. input_img_size: tuple of integers. Indicates input img size to the custom feature extractor network if provided.
  210. use_antialias: boolian flag to indicate whether to use antialiasing when resizing images. This will change the
  211. resize function to use bilinear interpolation with antialiasing, which is different from the original
  212. Inception v3 implementation. Does not apply to custom feature extractor networks.
  213. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  214. Raises:
  215. ValueError:
  216. If torch version is lower than 1.9
  217. ModuleNotFoundError:
  218. If ``feature`` is set to an ``int`` (default settings) and ``torch-fidelity`` is not installed
  219. ValueError:
  220. If ``feature`` is set to an ``int`` not in [64, 192, 768, 2048]
  221. TypeError:
  222. If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``
  223. ValueError:
  224. If ``reset_real_features`` is not an ``bool``
  225. Example:
  226. >>> from torch import rand
  227. >>> from torchmetrics.image.fid import FrechetInceptionDistance
  228. >>> fid = FrechetInceptionDistance(feature=64)
  229. >>> # generate two slightly overlapping image intensity distributions
  230. >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  231. >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  232. >>> fid.update(imgs_dist1, real=True)
  233. >>> fid.update(imgs_dist2, real=False)
  234. >>> fid.compute()
  235. tensor(12.6388)
  236. """
  237. higher_is_better: bool = False
  238. is_differentiable: bool = False
  239. full_state_update: bool = False
  240. plot_lower_bound: float = 0.0
  241. real_features_sum: Tensor
  242. real_features_cov_sum: Tensor
  243. real_features_num_samples: Tensor
  244. fake_features_sum: Tensor
  245. fake_features_cov_sum: Tensor
  246. fake_features_num_samples: Tensor
  247. inception: Module
  248. feature_network: str = "inception"
  249. def __init__(
  250. self,
  251. feature: Union[int, Module] = 2048,
  252. reset_real_features: bool = True,
  253. normalize: bool = False,
  254. input_img_size: tuple[int, int, int] = (3, 299, 299),
  255. feature_extractor_weights_path: Optional[str] = None,
  256. antialias: bool = True,
  257. **kwargs: Any,
  258. ) -> None:
  259. super().__init__(**kwargs)
  260. if not isinstance(normalize, bool):
  261. raise ValueError("Argument `normalize` expected to be a bool")
  262. self.normalize = normalize
  263. self.used_custom_model = False
  264. antialias = antialias
  265. if isinstance(feature, int):
  266. num_features = feature
  267. if not _TORCH_FIDELITY_AVAILABLE:
  268. raise ModuleNotFoundError(
  269. "FrechetInceptionDistance metric requires that `Torch-fidelity` is installed."
  270. " Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`."
  271. )
  272. valid_int_input = (64, 192, 768, 2048)
  273. if feature not in valid_int_input:
  274. raise ValueError(
  275. f"Integer input to argument `feature` must be one of {valid_int_input}, but got {feature}."
  276. )
  277. self.inception = NoTrainInceptionV3(
  278. name="inception-v3-compat",
  279. features_list=[str(feature)],
  280. feature_extractor_weights_path=feature_extractor_weights_path,
  281. antialias=antialias,
  282. )
  283. elif isinstance(feature, Module):
  284. self.inception = feature
  285. self.used_custom_model = True
  286. if hasattr(self.inception, "num_features"):
  287. if isinstance(self.inception.num_features, int):
  288. num_features = self.inception.num_features
  289. elif isinstance(self.inception.num_features, Tensor):
  290. num_features = int(self.inception.num_features.item())
  291. else:
  292. raise TypeError("Expected `self.inception.num_features` to be of type int or Tensor.")
  293. else:
  294. if self.normalize:
  295. dummy_image = torch.rand(1, *input_img_size, dtype=torch.float32)
  296. else:
  297. dummy_image = torch.randint(0, 255, (1, *input_img_size), dtype=torch.uint8)
  298. num_features = self.inception(dummy_image).shape[-1]
  299. else:
  300. raise TypeError("Got unknown input to argument `feature`")
  301. if not isinstance(reset_real_features, bool):
  302. raise ValueError("Argument `reset_real_features` expected to be a bool")
  303. self.reset_real_features = reset_real_features
  304. mx_num_feats = (num_features, num_features)
  305. self.add_state("real_features_sum", torch.zeros(num_features).double(), dist_reduce_fx="sum")
  306. self.add_state("real_features_cov_sum", torch.zeros(mx_num_feats).double(), dist_reduce_fx="sum")
  307. self.add_state("real_features_num_samples", torch.tensor(0).long(), dist_reduce_fx="sum")
  308. self.add_state("fake_features_sum", torch.zeros(num_features).double(), dist_reduce_fx="sum")
  309. self.add_state("fake_features_cov_sum", torch.zeros(mx_num_feats).double(), dist_reduce_fx="sum")
  310. self.add_state("fake_features_num_samples", torch.tensor(0).long(), dist_reduce_fx="sum")
  311. def update(self, imgs: Tensor, real: bool) -> None:
  312. """Update the state with extracted features.
  313. Args:
  314. imgs: Input img tensors to evaluate. If used custom feature extractor please
  315. make sure dtype and size is correct for the model.
  316. real: Whether given image is real or fake.
  317. """
  318. imgs = (imgs * 255).byte() if self.normalize and (not self.used_custom_model) else imgs
  319. features = self.inception(imgs)
  320. self.orig_dtype = features.dtype
  321. features = features.double()
  322. if features.dim() == 1:
  323. features = features.unsqueeze(0)
  324. if real:
  325. self.real_features_sum += features.sum(dim=0)
  326. self.real_features_cov_sum += features.t().mm(features)
  327. self.real_features_num_samples += imgs.shape[0]
  328. else:
  329. self.fake_features_sum += features.sum(dim=0)
  330. self.fake_features_cov_sum += features.t().mm(features)
  331. self.fake_features_num_samples += imgs.shape[0]
  332. def compute(self) -> Tensor:
  333. """Calculate FID score based on accumulated extracted features from the two distributions."""
  334. if self.real_features_num_samples < 2 or self.fake_features_num_samples < 2:
  335. raise RuntimeError("More than one sample is required for both the real and fake distributed to compute FID")
  336. mean_real = (self.real_features_sum / self.real_features_num_samples).unsqueeze(0)
  337. mean_fake = (self.fake_features_sum / self.fake_features_num_samples).unsqueeze(0)
  338. cov_real_num = self.real_features_cov_sum - self.real_features_num_samples * mean_real.t().mm(mean_real)
  339. cov_real = cov_real_num / (self.real_features_num_samples - 1)
  340. cov_fake_num = self.fake_features_cov_sum - self.fake_features_num_samples * mean_fake.t().mm(mean_fake)
  341. cov_fake = cov_fake_num / (self.fake_features_num_samples - 1)
  342. return _compute_fid(mean_real.squeeze(0), cov_real, mean_fake.squeeze(0), cov_fake).to(self.orig_dtype)
  343. def reset(self) -> None:
  344. """Reset metric states."""
  345. if not self.reset_real_features:
  346. real_features_sum = deepcopy(self.real_features_sum)
  347. real_features_cov_sum = deepcopy(self.real_features_cov_sum)
  348. real_features_num_samples = deepcopy(self.real_features_num_samples)
  349. super().reset()
  350. self.real_features_sum = real_features_sum
  351. self.real_features_cov_sum = real_features_cov_sum
  352. self.real_features_num_samples = real_features_num_samples
  353. else:
  354. super().reset()
  355. def set_dtype(self, dst_type: Union[str, torch.dtype]) -> "Metric":
  356. """Transfer all metric state to specific dtype. Special version of standard `type` method.
  357. Arguments:
  358. dst_type: the desired type as ``torch.dtype`` or string
  359. """
  360. out = super().set_dtype(dst_type)
  361. if isinstance(out.inception, NoTrainInceptionV3):
  362. out.inception._dtype = dst_type
  363. return out
  364. def plot(
  365. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  366. ) -> _PLOT_OUT_TYPE:
  367. """Plot a single or multiple values from the metric.
  368. Args:
  369. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  370. If no value is provided, will automatically call `metric.compute` and plot that result.
  371. ax: An matplotlib axis object. If provided will add plot to that axis
  372. Returns:
  373. Figure and Axes object
  374. Raises:
  375. ModuleNotFoundError:
  376. If `matplotlib` is not installed
  377. .. plot::
  378. :scale: 75
  379. >>> # Example plotting a single value
  380. >>> import torch
  381. >>> from torchmetrics.image.fid import FrechetInceptionDistance
  382. >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  383. >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  384. >>> metric = FrechetInceptionDistance(feature=64)
  385. >>> metric.update(imgs_dist1, real=True)
  386. >>> metric.update(imgs_dist2, real=False)
  387. >>> fig_, ax_ = metric.plot()
  388. .. plot::
  389. :scale: 75
  390. >>> # Example plotting multiple values
  391. >>> import torch
  392. >>> from torchmetrics.image.fid import FrechetInceptionDistance
  393. >>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
  394. >>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
  395. >>> metric = FrechetInceptionDistance(feature=64)
  396. >>> values = [ ]
  397. >>> for _ in range(3):
  398. ... metric.update(imgs_dist1(), real=True)
  399. ... metric.update(imgs_dist2(), real=False)
  400. ... values.append(metric.compute())
  401. ... metric.reset()
  402. >>> fig_, ax_ = metric.plot(values)
  403. """
  404. return self._plot(val, ax)