1"""The ``diffusion-models`` command line interface.
2
3Hydra does the heavy lifting for training and inference, so everything after the
4sub-command is forwarded to it untouched::
5
6 diffusion-models train +config=small_attention_ema training.batch_size=64
7 diffusion-models train --help # hydra's own help, listing the config groups
8 diffusion-models infer checkpoint=<path> +config=small_attention_ema
9"""
10
11import importlib
12import pathlib
13import sys
14from typing import Tuple
15
16import click
17
18
19@click.group(context_settings={"help_option_names": ["-h", "--help"]})
[docs]
20def main() -> None:
21 """Tools for training and running diffusion models."""
22
23
24def _run_hydra(command, module, extra, overrides, config_directories):
25 """Forwards ``overrides`` to the hydra entry point ``module.main``."""
26 try:
27 entry_point = importlib.import_module(module).main
28 except ModuleNotFoundError as error: # pragma: no cover
29 raise click.ClickException(
30 f"Missing {extra} dependency ({error.name}). "
31 "Install them with `uv sync --group training`."
32 ) from error
33
34 arguments = list(overrides)
35 if config_directories:
36 paths = ",".join(f"file://{path.resolve()}" for path in config_directories)
37 arguments.append(f"hydra.searchpath=[{paths}]")
38 # Hydra reads its overrides straight from sys.argv.
39 sys.argv = [f"{sys.argv[0]} {command}", *arguments]
40 entry_point()
41
42
43_HYDRA_COMMAND = dict(
44 context_settings={
45 "ignore_unknown_options": True,
46 "allow_extra_args": True,
47 # Let ``--help`` reach hydra, which knows about the config groups.
48 "help_option_names": [],
49 },
50 add_help_option=False,
51)
52_config_dir_option = click.option(
53 "--config-dir",
54 "config_directories",
55 multiple=True,
56 type=click.Path(exists=True, file_okay=False, path_type=pathlib.Path),
57 help="An extra directory to search for hydra configs and `+config=` presets.",
58)
59
60
61@main.command(**_HYDRA_COMMAND)
62@_config_dir_option
63@click.argument("overrides", nargs=-1, type=click.UNPROCESSED)
[docs]
64def train(config_directories: Tuple[pathlib.Path, ...], overrides) -> None:
65 """Train a diffusion model.
66
67 OVERRIDES are hydra overrides and flags, e.g. `+config=small_attention_ema`,
68 `training.batch_size=64`, `resume_from=<checkpoint>` or `--multirun`.
69 Pass `--help` to list the available config groups.
70 """
71 _run_hydra(
72 "train", "diffusion_models.training", "training", overrides, config_directories
73 )
74
75
76@main.command(**_HYDRA_COMMAND)
77@_config_dir_option
78@click.argument("overrides", nargs=-1, type=click.UNPROCESSED)
[docs]
79def infer(config_directories: Tuple[pathlib.Path, ...], overrides) -> None:
80 """Generate images with a trained checkpoint.
81
82 OVERRIDES are hydra overrides: `checkpoint=<path>` is required and the model
83 config should match the training run, e.g. `+config=small_attention_ema`.
84 Other options: `number_of_images=25`, `save_gif=true`, `steps=50`,
85 `use_ema=false`, `device=cpu`. Pass `--help` to list the config groups.
86 """
87 _run_hydra(
88 "infer", "diffusion_models.inference", "training", overrides, config_directories
89 )
90
91
92@main.command()
93@click.argument(
94 "checkpoint",
95 type=click.Path(exists=True, dir_okay=False, path_type=pathlib.Path),
96)
97@click.option("--samples", default=10000, show_default=True, help="Images.")
98@click.option("--batch-size", default=100, show_default=True)
99@click.option("--steps", type=int, help="Override the DDIM sampling steps.")
100@click.option("--device", default="cuda", show_default=True)
101@click.option("--ema/--no-ema", default=True, show_default=True)
102@click.option("--kid/--no-kid", default=True, show_default=True)
103@click.option("--seed", default=0, show_default=True)
[docs]
104def fid(
105 checkpoint, samples, batch_size, steps, device, ema, kid, seed
106) -> None:
107 """Compute FID (and KID) of a training CHECKPOINT.
108
109 Needs the `evaluation` and `training` dependency groups. Only compare scores
110 that use the same number of samples.
111 """
112 try:
113 from diffusion_models.evaluation.checkpoint import evaluate_checkpoint
114 except ModuleNotFoundError as error: # pragma: no cover
115 raise click.ClickException(
116 f"Missing evaluation dependency ({error.name}). "
117 "Install them with `uv sync --group training --group evaluation`."
118 ) from error
119
120 metrics = evaluate_checkpoint(
121 checkpoint,
122 number_of_samples=samples,
123 batch_size=batch_size,
124 device=device,
125 use_ema=ema,
126 compute_kid=kid,
127 steps=steps,
128 seed=seed,
129 )
130 for name, value in metrics.items():
131 click.echo(f"{name}: {value:.4f}")
132
133
134if __name__ == "__main__":
135 main()