1import dataclasses
2import logging
3import os
4import pathlib
5from dataclasses import dataclass
6from enum import Enum
7from typing import Any
8from typing import Dict
9from typing import Optional
10from typing import Union
11
12import torch
13
14from diffusion_models.gaussian_diffusion.beta_schedulers import (
15 BaseBetaScheduler,
16)
17
18
[docs]
19class PredictionType(str, Enum):
20 """What the model is trained to predict."""
21
22 @classmethod
23 def _missing_(cls, value):
24 # Configs saved in checkpoints spell enums by member name ("V").
25 if isinstance(value, str):
26 for member in cls:
27 if value.lower() in (member.name.lower(), member.value):
28 return member
29 return None
30
32 """The noise added to the image."""
34 """The velocity, :math:`v = \\sqrt{\\bar{\\alpha}}\\epsilon - \\sqrt{1-\\bar{\\alpha}}x_0`."""
35
36
37@dataclass
[docs]
38class TrainingConfiguration:
39 """A training configuration for simple experiment management."""
40
42 """The name of the training."""
44 """The batch size used for training."""
[docs]
45 learning_rate: float
46 """The learning rate of the training."""
[docs]
47 number_of_epochs: int
48 """The number of epoch used for training."""
[docs]
49 checkpoint_rate: int = 100
50 """The rate at which checkpoints are saved.."""
[docs]
51 mixed_precision_training: bool = False
52 """Whether or not to use automatic mixed precision training."""
[docs]
53 mixed_precision_dtype: str = "bfloat16"
54 """The autocast dtype when mixed precision is on: ``bfloat16`` (no gradient
55 scaling needed) or ``float16`` (uses a ``GradScaler``)."""
[docs]
56 channels_last: bool = False
57 """Whether to use the ``channels_last`` memory format for the model and its
58 inputs. This speeds up mixed precision training on tensor cores but is very
59 slow in fp32, so it should be combined with ``mixed_precision_training``."""
[docs]
60 gradient_clip: Optional[float] = None # TODO: This is not complete yet
61 """Whether or not to clip gradients."""
[docs]
62 ema_decay: Optional[float] = None
63 """The decay of the exponential moving average of the weights. Disabled when None."""
[docs]
64 ema_warmup_steps: int = 0
65 """When positive, ramps the EMA decay up as ``(1 + n) / (warmup + n)`` (capped at ``ema_decay``)."""
[docs]
66 latest_checkpoint_rate: Optional[int] = None
67 """The rate (in epochs) at which the rolling ``latest.pt`` is overwritten. Disabled when None."""
[docs]
68 num_workers: int = 4
69 """The number of dataloader worker processes. ``0`` loads data in the main process."""
[docs]
70 pin_memory: bool = True
71 """Whether the dataloader copies batches into pinned memory (only used with CUDA)."""
[docs]
72 persistent_workers: bool = True
73 """Whether dataloader workers are kept alive between epochs (needs ``num_workers > 0``)."""
[docs]
74 prefetch_factor: Optional[int] = None
75 """Batches prefetched per worker. Uses the torch default when None (needs ``num_workers > 0``)."""
[docs]
76 compile: bool = False
77 """Whether to ``torch.compile`` the model's forward pass during training.
78 Checkpoints and the EMA always hold the uncompiled model's weights."""
79
80
81@dataclass
[docs]
82class EvaluationConfiguration:
83 """Settings of the FID / KID evaluation that runs during training."""
84
[docs]
85 fid_rate: Optional[int] = None
86 """The rate (in epochs) at which FID/KID is computed and logged. Also computed after the last epoch. Disabled when None."""
[docs]
87 number_of_samples: int = 5000
88 """The number of generated (and real) images compared. Only compare scores that use the same number."""
[docs]
89 batch_size: int = 100
90 """The batch size used for sampling and feature extraction."""
[docs]
91 compute_kid: bool = True
92 """Whether to also compute the Kernel Inception Distance."""
[docs]
93 kid_subset_size: int = 1000
94 """The KID subset size."""
96 """The seed of the sampling noise, so scores are comparable across runs."""
[docs]
97 num_workers: int = 4
98 """Dataloader workers used to read the real images."""
99
100
101@dataclass
[docs]
102class LogConfiguration:
103 """An object to manage logging configuration."""
104
106 """The rate at which training metrics are logged."""
[docs]
107 image_rate: int = 50
108 """The rate at which images are generated for visualization. This can be used to validate model performance."""
[docs]
109 number_of_images: int = 5
110 """The number of images to generate."""
[docs]
111 weight_rate: Optional[int] = None
112 """The rate (in steps) at which weight histograms are logged. Disabled when None."""
113 # metrics: Dict[str, float] # TODO: consider Dict[str, Callable]
114
115
116@dataclass
[docs]
117class BetaSchedulerConfiguration:
118 """A simplified beta scheduler configuration."""
119
121 """The number of steps in the beta scheduler."""
[docs]
122 betas: torch.Tensor
123 """The beta values."""
[docs]
124 alpha_bars: torch.Tensor
125 """The alpha bar values."""
126
127
128@dataclass
[docs]
129class Checkpoint:
130 """A simplified checkpoint framework for easy saving and loading."""
131
133 """The current epoch."""
[docs]
134 model_state_dict: Dict[str, Any]
135 """The model state dict."""
[docs]
136 optimizer_state_dict: Dict[str, Any]
137 """The optimizer state dict."""
[docs]
138 beta_scheduler_config: BetaSchedulerConfiguration
139 """The beta scheduler configuration."""
[docs]
140 scaler: Optional[Dict[str, Any]] = None
141 """The GradScaler instance."""
[docs]
142 ema_model_state_dict: Optional[Dict[str, Any]] = None
143 """The state dict of the EMA (exponential moving average) weights, if tracked."""
[docs]
144 ema_num_updates: Optional[int] = None
145 """The number of EMA updates performed so far (needed to resume the EMA warmup)."""
[docs]
146 completed_epochs: Optional[int] = None
147 """The number of fully completed epochs. Training resumes from here."""
[docs]
148 tensorboard_run_name: Optional[str] = None
149 """The name of the tensorboard run."""
[docs]
150 image_channels: int = 3
151 """The number of image channels used in the training."""
[docs]
152 prediction_type: str = "epsilon"
153 """What the model predicts (``"epsilon"`` or ``"v"``). Legacy checkpoints are epsilon."""
[docs]
154 config_yaml: Optional[str] = None
155 """The resolved configuration (YAML) of the run that produced this checkpoint."""
[docs]
156 loss: Optional[float] = (
157 None # TODO: remove legacy parameter and resave models
158 )
159 """The final loss value recorded.
160
161 Note:
162 This is a legacy parameter and will be removed in a future release.
163
164 """
165
166 @classmethod
[docs]
167 def from_file(
168 cls, file_path: str, map_location: Optional[str] = None
169 ) -> "Checkpoint":
170 """Load and instantiate a checkpoint from a file.
171
172 Args:
173 file_path: The path to the checkpoint file.
174 map_location: A function, torch. device, string or a dict specifying how to remap storage location.
175
176 Returns:
177 A checkpoint instance.
178 """
179 checkpoint = torch.load(
180 f=file_path, weights_only=True, map_location=map_location
181 )
182 checkpoint = cls(**checkpoint)
183 beta_scheduler_config = BetaSchedulerConfiguration(
184 **checkpoint.beta_scheduler_config # ty: ignore[invalid-argument-type]
185 )
186 checkpoint.beta_scheduler_config = beta_scheduler_config
187 return checkpoint
188
[docs]
189 def get_model_state_dict(self, use_ema: bool = True) -> Dict[str, Any]:
190 """Get the weights to load into a model.
191
192 Args:
193 use_ema: Prefer the EMA weights when the checkpoint has them. Falls back
194 to the raw weights (with a warning) for checkpoints without EMA.
195
196 Returns:
197 A model state dict.
198 """
199 if use_ema:
200 if self.ema_model_state_dict is not None:
201 return self.ema_model_state_dict
202 logging.warning("Checkpoint has no EMA weights; using the raw weights.")
203 return self.model_state_dict
204
[docs]
205 def to_file(self, file_path: Union[str, pathlib.Path]) -> None:
206 """Saves a checkpoint to a file.
207
208 The write is atomic: the checkpoint goes to a temporary file which then
209 replaces the destination, so readers never see a partial file.
210 """
211 file_path = pathlib.Path(file_path)
212 temporary_path = file_path.with_name(file_path.name + ".tmp")
213 try:
214 torch.save(dataclasses.asdict(self), temporary_path)
215 os.replace(temporary_path, file_path)
216 finally:
217 temporary_path.unlink(missing_ok=True)
218
219
220@dataclass
[docs]
221class OldCheckpoint:
[docs]
223 model_state_dict: Dict[str, Any]
[docs]
224 optimizer_state_dict: Dict[str, Any]
[docs]
225 scaler: Optional[Dict[str, Any]]
226 # beta_scheduler_config: BetaSchedulerConfiguration
[docs]
227 tensorboard_run_name: Optional[str] = None
[docs]
228 loss: Optional[float] = (
229 None # TODO: remove legacy parameter and resave models
230 )
231
232 @classmethod
[docs]
233 def from_file(cls, file_path: str) -> "OldCheckpoint":
234 checkpoint = torch.load(f=file_path)
235 return cls(**checkpoint)
236
[docs]
237 def to_file(self, file_path: Union[str, pathlib.Path]) -> None:
238 torch.save(dataclasses.asdict(self), file_path)
239
[docs]
240 def to_new_checkpoint(self, beta_scheduler: BaseBetaScheduler) -> Checkpoint:
241 beta_scheduler_config = BetaSchedulerConfiguration(
242 steps=beta_scheduler.steps,
243 betas=beta_scheduler.betas,
244 alpha_bars=beta_scheduler.alpha_bars,
245 )
246 return Checkpoint(
247 **dataclasses.asdict(self), beta_scheduler_config=beta_scheduler_config
248 )
249
250
251@dataclass
[docs]
252class Timestep:
[docs]
253 current: torch.Tensor
[docs]
254 previous: Optional[torch.Tensor] = None