1"""Score a saved training checkpoint with FID / KID."""
2
3import pathlib
4from typing import Dict
5from typing import Optional
6from typing import Union
7
8import torch
9from hydra_zen import instantiate
10from omegaconf import OmegaConf
11
12from diffusion_models.evaluation.fid import ImageQualityEvaluator
13from diffusion_models.utils.schemas import Checkpoint
14
15
[docs]
16def evaluate_checkpoint(
17 checkpoint_path: Union[str, pathlib.Path],
18 number_of_samples: int = 10000,
19 batch_size: int = 100,
20 device: str = "cuda",
21 use_ema: bool = True,
22 compute_kid: bool = True,
23 kid_subset_size: int = 1000,
24 steps: Optional[int] = None,
25 seed: int = 0,
26 num_workers: int = 4,
27) -> Dict[str, float]:
28 """Compute FID/KID of a checkpoint produced by ``diffusion-models train``.
29
30 The model and the reference dataset are rebuilt from the resolved config
31 stored in the checkpoint. The reference images are the config's
32 ``eval_dataset`` when it has one, otherwise its ``dataset`` with
33 ``split="valid"`` when that dataset has a ``split`` option.
34
35 Args:
36 checkpoint_path: The checkpoint to evaluate.
37 number_of_samples: The number of real and generated images compared.
38 batch_size: The batch size used for sampling and feature extraction.
39 device: The device to use.
40 use_ema: Prefer the EMA weights when the checkpoint has them.
41 compute_kid: Whether to also compute KID.
42 kid_subset_size: The KID subset size.
43 steps: Overrides the number of DDIM sampling steps, when the diffuser has
44 that option.
45 seed: The seed of the sampling noise.
46 num_workers: Dataloader workers used to read the real images.
47
48 Returns:
49 The ``FID`` (and ``KID``) scores.
50 """
51 checkpoint = Checkpoint.from_file(str(checkpoint_path), map_location=device)
52 if checkpoint.config_yaml is None:
53 raise ValueError(
54 "The checkpoint has no embedded config, so the model cannot be rebuilt."
55 )
56 configuration = OmegaConf.create(checkpoint.config_yaml)
57
58 model = instantiate(configuration.model)
59 model.load_state_dict(checkpoint.get_model_state_dict(use_ema=use_ema))
60 model = model.to(device).eval()
61 if steps is not None:
62 if not hasattr(model.diffuser, "number_of_steps"):
63 raise ValueError("This diffuser has no configurable number of steps.")
64 model.diffuser.number_of_steps = steps
65
66 if configuration.get("eval_dataset") is not None: # ty: ignore[invalid-argument-type]
67 real_configuration = configuration.eval_dataset
68 else:
69 real_configuration = OmegaConf.create(
70 OmegaConf.to_container(configuration.dataset)
71 )
72 if "split" in real_configuration:
73 real_configuration.split = "valid"
74 real_dataset = instantiate(real_configuration)
75
76 evaluator = ImageQualityEvaluator(
77 real_dataset=real_dataset,
78 number_of_samples=number_of_samples,
79 batch_size=batch_size,
80 device=device,
81 compute_kid=compute_kid,
82 kid_subset_size=kid_subset_size,
83 seed=seed,
84 num_workers=num_workers,
85 )
86 with torch.no_grad():
87 return evaluator.evaluate(model)