Source code for diffusion_models.evaluation.fid

  1"""Frechet / Kernel Inception Distance for diffusion models."""
  2
  3import logging
  4from typing import Dict
  5from typing import Optional
  6
  7import torch
  8from torch.utils.data import DataLoader
  9from torch.utils.data import Dataset
 10from torch.utils.data import Subset
 11from torchmetrics.image.fid import FrechetInceptionDistance
 12from torchmetrics.image.kid import KernelInceptionDistance
 13
 14from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
 15
 16
[docs] 17class ImageQualityEvaluator: 18 def __init__( 19 self, 20 real_dataset: Dataset, 21 number_of_samples: int = 5000, 22 batch_size: int = 100, 23 device: str = "cuda", 24 compute_kid: bool = True, 25 kid_subset_size: int = 1000, 26 seed: int = 0, 27 num_workers: int = 4, 28 ): 29 """Scores generated images against real ones with FID (and KID). 30 31 The Inception statistics of the real images are computed once, on the 32 first call to :meth:`evaluate`, and reused afterwards. FID is biased by the 33 number of samples, so only compare scores that use the same 34 ``number_of_samples``. KID is unbiased, which makes it more reliable for 35 small sample sizes. 36 37 The real dataset must yield ``(image, label)`` pairs whose images are 38 normalized to ``[-1, 1]`` (the same convention as the training data). 39 40 Args: 41 real_dataset: The reference images, ideally a held-out split. 42 number_of_samples: How many real and generated images to compare. 43 batch_size: The batch size used for sampling and feature extraction. 44 device: The device used for sampling and the Inception network. 45 compute_kid: Whether to also compute the Kernel Inception Distance. 46 kid_subset_size: The KID subset size (at most ``number_of_samples``). 47 seed: Seed of the sampling noise, so scores are comparable across runs. 48 num_workers: Dataloader workers used to read the real images. 49 """
[docs] 50 self.real_dataset = real_dataset
51 """The reference images."""
[docs] 52 self.number_of_samples = min(number_of_samples, len(real_dataset)) # ty: ignore[invalid-argument-type]
53 """The number of real and generated images compared."""
[docs] 54 self.batch_size = batch_size
55 """The batch size used for sampling and feature extraction."""
[docs] 56 self.device = device
57 """The device used for sampling and feature extraction."""
[docs] 58 self.seed = seed
59 """The seed of the sampling noise."""
[docs] 60 self.num_workers = num_workers
61 """Dataloader workers used to read the real images.""" 62 63 # ``reset_real_features=False`` keeps the real statistics across resets.
[docs] 64 self.fid = FrechetInceptionDistance( 65 feature=2048, normalize=True, reset_real_features=False 66 ).to(device)
67 """The FID metric."""
[docs] 68 self.kid: Optional[KernelInceptionDistance] = None
69 """The KID metric, when enabled.""" 70 if compute_kid: 71 self.kid = KernelInceptionDistance( 72 feature=2048, 73 subset_size=min(kid_subset_size, self.number_of_samples), 74 normalize=True, 75 reset_real_features=False, 76 ).to(device) 77 self._real_ready = False 78 79 @staticmethod
[docs] 80 def to_unit_range(images: torch.Tensor) -> torch.Tensor: 81 """Map images from ``[-1, 1]`` to ``[0, 1]``.""" 82 return ((images.float() + 1) / 2).clamp(0, 1)
83 84 def _update(self, images: torch.Tensor, real: bool) -> None: 85 images = images.to(self.device) 86 self.fid.update(images, real=real) 87 if self.kid is not None: 88 self.kid.update(images, real=real) 89 90 def _prepare_real(self) -> None: 91 logging.info( 92 f"Computing Inception statistics of {self.number_of_samples} real images." 93 ) 94 loader = DataLoader( 95 Subset(self.real_dataset, range(self.number_of_samples)), 96 batch_size=self.batch_size, 97 shuffle=False, 98 num_workers=self.num_workers, 99 ) 100 for images, _ in loader: 101 self._update(self.to_unit_range(images), real=True) 102 self._real_ready = True 103 104 @torch.no_grad()
[docs] 105 def evaluate(self, model: BaseDiffusionModel) -> Dict[str, float]: 106 """Generate images with the model and score them. 107 108 The model is put in eval mode for sampling and restored afterwards. 109 110 Args: 111 model: The (EMA) model to evaluate, already on ``self.device``. 112 113 Returns: 114 A dictionary with ``"FID"`` and, when enabled, ``"KID"`` and 115 ``"KID_std"``. 116 """ 117 if not self._real_ready: 118 self._prepare_real() 119 120 image_shape = self.real_dataset[0][0].shape 121 generator = torch.Generator(device=self.device).manual_seed(self.seed) 122 was_training = model.training 123 model.eval() 124 try: 125 remaining = self.number_of_samples 126 while remaining > 0: 127 count = min(self.batch_size, remaining) 128 noise = torch.randn( 129 (count, *image_shape), device=self.device, generator=generator 130 ) 131 # ``denoise`` returns every step of the reverse process; the last 132 # entry is the fully denoised image. 133 images = model.denoise(noise)[-1] 134 self._update(self.to_unit_range(images), real=False) 135 remaining -= count 136 finally: 137 model.train(was_training) 138 139 metrics = {"FID": float(self.fid.compute())} 140 self.fid.reset() 141 if self.kid is not None: 142 kid_mean, kid_std = self.kid.compute() 143 metrics["KID"] = float(kid_mean) 144 metrics["KID_std"] = float(kid_std) 145 self.kid.reset() 146 return metrics