1import contextlib
2import logging
3import pathlib
4import signal
5from typing import Callable, Dict, Optional, Union
6
7import torch
8from torch.nn import functional as F
9from torch.utils.data import DataLoader, Dataset
10from tqdm import tqdm
11
12from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
13from diffusion_models.utils.ema import ExponentialMovingAverage
14from diffusion_models.utils.ema import unwrap_model
15from diffusion_models.utils.schemas import (
16 BetaSchedulerConfiguration,
17 Checkpoint,
18 EvaluationConfiguration,
19 LogConfiguration,
20 PredictionType,
21 TrainingConfiguration,
22)
23from diffusion_models.utils.tensorboard import TensorboardManager
24
25
[docs]
26class DiffusionTrainer:
27 def __init__(
28 self,
29 model: BaseDiffusionModel,
30 dataset: Dataset,
31 optimizer: torch.optim.Optimizer,
32 training_configuration: TrainingConfiguration,
33 loss_function: Callable = F.l1_loss,
34 # scheduler: Optional[torch.optim.lr_scheduler.StepLR] = None,
35 log_configuration: LogConfiguration = LogConfiguration(),
36 reverse_transforms: Callable = lambda x: x,
37 device: str = "cuda",
38 output_directory: Optional[Union[str, pathlib.Path]] = None,
39 run_config: Optional[str] = None,
40 resume_from: Optional[Union[str, pathlib.Path]] = None,
41 evaluation_configuration: Optional[EvaluationConfiguration] = None,
42 evaluation_dataset: Optional[Dataset] = None,
43 ):
44 """A diffusion trainer framework.
45
46 This is a simplified framework for training a diffusion models.
47
48 Args:
49 model: A diffusion model.
50 dataset: A dataset to train on.
51 optimizer: The optimizer to use.
52 training_configuration: The training configuration to use.
53 loss_function: The loss function to use.
54 log_configuration: The logging configuration to use.
55 reverse_transforms: The reverse transforms to use.
56 device: The device to use.
57 output_directory: Where to write this run's artifacts. When provided,
58 checkpoints go to ``<output_directory>/checkpoints`` and tensorboard
59 logs to ``<output_directory>/tensorboard``. Otherwise the legacy
60 ``../checkpoints/<name>`` and ``../runs/<name>`` locations are used.
61 run_config: The resolved configuration (YAML) of the run. It is logged
62 to tensorboard and stored in every checkpoint for reproducibility.
63 resume_from: A checkpoint to resume training from. The model, optimizer,
64 grad scaler and EMA are restored and training continues from the
65 epoch after the last completed one. Resuming happens at an epoch
66 boundary; progress within an interrupted epoch is lost.
67 evaluation_configuration: When ``fid_rate`` is set, FID (and KID) of
68 samples from the EMA model (or the raw model without EMA) is computed
69 every that many epochs, and after the last epoch, then logged to
70 tensorboard. Needs the ``evaluation`` extra.
71 evaluation_dataset: The real reference images for the evaluation,
72 ideally a held-out split.
73 """
[docs]
74 self.model = model.to(device)
75 """The diffusion model to use."""
[docs]
76 self.optimizer = optimizer
77 """The optimizer to use."""
[docs]
78 self.loss_function = loss_function
79 """The loss function to use."""
[docs]
80 self.training_configuration = training_configuration
81 """The training configuration to use."""
82 # self.scheduler = scheduler
[docs]
83 self.device = device
84 """The device to use."""
85
86 num_workers = training_configuration.num_workers
[docs]
87 self.dataloader = DataLoader(
88 dataset=dataset,
89 batch_size=training_configuration.batch_size,
90 shuffle=True,
91 drop_last=True,
92 num_workers=num_workers,
93 # Pinned memory only helps host-to-CUDA copies.
94 pin_memory=training_configuration.pin_memory
95 and torch.device(device).type == "cuda",
96 persistent_workers=training_configuration.persistent_workers
97 and num_workers > 0,
98 prefetch_factor=training_configuration.prefetch_factor
99 if num_workers > 0
100 else None,
101 )
102 """A torch dataloader."""
103
104 self._image_shape = dataset[0][0].shape
105
106 dtypes = {"float16": torch.float16, "bfloat16": torch.bfloat16}
107 if training_configuration.mixed_precision_dtype not in dtypes:
108 raise ValueError(
109 "mixed_precision_dtype must be one of "
110 f"{sorted(dtypes)}, got {training_configuration.mixed_precision_dtype!r}."
111 )
112 self._autocast_dtype = dtypes[training_configuration.mixed_precision_dtype]
113 """The dtype used by autocast when mixed precision is on."""
114
[docs]
115 self.scaler = torch.amp.GradScaler(
116 device=torch.device(device).type,
117 # bfloat16 has the range of fp32, so only fp16 needs loss scaling.
118 enabled=training_configuration.mixed_precision_training
119 and self._autocast_dtype == torch.float16,
120 )
121 """A torch GradScaler object (a no-op unless training in float16)."""
122
123 if training_configuration.channels_last:
124 if not training_configuration.mixed_precision_training:
125 logging.warning(
126 "channels_last is very slow without mixed precision training."
127 )
128 # ``BaseDiffusionModel.to`` does not accept ``memory_format``.
129 torch.nn.Module.to( # ty: ignore[no-matching-overload]
130 self.model, memory_format=torch.channels_last)
131
[docs]
132 self.log_configuration = log_configuration
133 """A LogConfiguration object."""
134
135 if output_directory is not None:
136 output_directory = pathlib.Path(output_directory)
137 self.checkpoint_path = output_directory / "checkpoints"
138 log_directory = output_directory / "tensorboard"
139 else:
140 self.checkpoint_path = (
141 pathlib.Path("../checkpoints")
142 / self.training_configuration.training_name
143 )
144 log_directory = None
145 """The path to save checkpoints."""
146
147 self.checkpoint_path.mkdir(parents=True, exist_ok=True)
[docs]
148 self.tensorboard_manager = TensorboardManager(
149 log_name=self.training_configuration.training_name,
150 log_directory=log_directory,
151 )
152 """A tensorboard manager instance."""
153
[docs]
154 self.run_config = run_config
155 """The resolved run configuration (YAML), if any."""
156 if run_config is not None:
157 self.tensorboard_manager.log_text(
158 "config", f"```yaml\n{run_config}\n```"
159 )
160
162 """A set of reverse transforms."""
163
[docs]
164 self.ema: Optional[ExponentialMovingAverage] = None
165 """The EMA of the model weights, when ``ema_decay`` is configured."""
166 if training_configuration.ema_decay is not None:
167 self.ema = ExponentialMovingAverage(
168 self.model,
169 decay=training_configuration.ema_decay,
170 warmup_steps=training_configuration.ema_warmup_steps,
171 )
172
[docs]
173 self.evaluation_configuration = evaluation_configuration
174 """The FID/KID evaluation settings."""
[docs]
175 self.evaluator = None
176 """The FID/KID evaluator, when ``fid_rate`` is configured."""
177 if (
178 evaluation_configuration is not None
179 and evaluation_configuration.fid_rate is not None
180 ):
181 if evaluation_dataset is None:
182 raise ValueError("FID evaluation needs an evaluation_dataset.")
183 # Imported lazily: torchmetrics is an optional dependency.
184 from diffusion_models.evaluation.fid import ImageQualityEvaluator
185
186 self.evaluator = ImageQualityEvaluator(
187 real_dataset=evaluation_dataset,
188 number_of_samples=evaluation_configuration.number_of_samples,
189 batch_size=evaluation_configuration.batch_size,
190 device=device,
191 compute_kid=evaluation_configuration.compute_kid,
192 kid_subset_size=evaluation_configuration.kid_subset_size,
193 seed=evaluation_configuration.seed,
194 num_workers=evaluation_configuration.num_workers,
195 )
196
197 self._completed_epochs = 0
198 """The number of fully completed epochs."""
199
200 self._train_model: Callable = self.model
201 """The callable used for the training forward pass (possibly compiled)."""
202 if training_configuration.compile:
203 # ``self.model`` stays the plain module: the optimizer, EMA and
204 # checkpoints keep unprefixed state dict keys. The compiled wrapper
205 # shares its parameters, so updating one updates the other.
206 self._train_model = torch.compile(self.model)
207
208 if resume_from is not None:
209 self.load_checkpoint(resume_from)
210
211 torch.backends.cudnn.benchmark = True
212
[docs]
213 def load_checkpoint(self, file_path: Union[str, pathlib.Path]) -> None:
214 """Restore the training state from a checkpoint.
215
216 Args:
217 file_path: The checkpoint to restore (e.g. ``latest.pt`` or
218 ``interrupted.pt``).
219 """
220 checkpoint = Checkpoint.from_file(str(file_path), map_location=self.device)
221 expected = PredictionType(self.model.diffuser.prediction_type).value
222 if checkpoint.prediction_type != expected:
223 raise ValueError(
224 f"Checkpoint was trained to predict {checkpoint.prediction_type!r} "
225 f"but the diffuser predicts {expected!r}; refusing to resume."
226 )
227 unwrap_model(self.model).load_state_dict(checkpoint.model_state_dict)
228 self.optimizer.load_state_dict(checkpoint.optimizer_state_dict)
229 if checkpoint.scaler is not None and self.scaler.is_enabled():
230 self.scaler.load_state_dict(checkpoint.scaler)
231 if self.ema is not None:
232 if checkpoint.ema_model_state_dict is not None:
233 self.ema.load_state_dict(
234 checkpoint.ema_model_state_dict,
235 num_updates=checkpoint.ema_num_updates,
236 )
237 else:
238 logging.warning(
239 "Checkpoint has no EMA weights; the EMA restarts from the raw weights."
240 )
241 self.ema.load_state_dict(checkpoint.model_state_dict)
242 self._completed_epochs = (
243 checkpoint.completed_epochs
244 if checkpoint.completed_epochs is not None
245 else checkpoint.epoch
246 )
247 logging.info(
248 f"Resumed from {file_path} after {self._completed_epochs} epochs."
249 )
250
[docs]
251 def save_checkpoint(self, epoch: int, checkpoint_name: str):
252 """Save a checkpoint (atomically).
253
254 Args:
255 epoch: The current epoch. ``final.pt``, ``latest.pt`` and
256 ``interrupted.pt`` store the number of completed epochs.
257 checkpoint_name: The name of the checkpoint.
258 """
259 checkpoint = Checkpoint(
260 epoch=epoch,
261 completed_epochs=self._completed_epochs,
262 model_state_dict=self.model.state_dict(),
263 ema_model_state_dict=self.ema.state_dict()
264 if self.ema is not None
265 else None,
266 ema_num_updates=self.ema.num_updates if self.ema is not None else None,
267 optimizer_state_dict=self.optimizer.state_dict(),
268 scaler=self.scaler.state_dict() if self.scaler.is_enabled() else None,
269 image_channels=self._image_shape[0],
270 prediction_type=PredictionType(
271 self.model.diffuser.prediction_type
272 ).value,
273 beta_scheduler_config=BetaSchedulerConfiguration(
274 steps=self.model.diffuser.beta_scheduler.steps,
275 betas=self.model.diffuser.beta_scheduler.betas,
276 alpha_bars=self.model.diffuser.beta_scheduler.alpha_bars,
277 ),
278 tensorboard_run_name=self.tensorboard_manager.summary_writer.log_dir,
279 config_yaml=self.run_config,
280 )
281 checkpoint.to_file(self.checkpoint_path / checkpoint_name)
282
283 @contextlib.contextmanager
284 def _sigterm_as_interrupt(self):
285 """Treat SIGTERM like Ctrl-C so an interrupted checkpoint gets saved."""
286
287 def handler(signum, frame):
288 raise KeyboardInterrupt
289
290 try:
291 previous = signal.signal(signal.SIGTERM, handler)
292 except ValueError: # Not in the main thread.
293 yield
294 return
295 try:
296 yield
297 finally:
298 signal.signal(signal.SIGTERM, previous)
299
[docs]
300 def train(self):
301 """Start the diffusion training.
302
303 If the run is interrupted (``KeyboardInterrupt`` or SIGTERM), an
304 ``interrupted.pt`` checkpoint is saved before the interruption is
305 re-raised. When ``latest_checkpoint_rate`` is set, ``latest.pt`` is
306 overwritten every that many epochs.
307 """
308 try:
309 with self._sigterm_as_interrupt():
310 self._train()
311 except KeyboardInterrupt:
312 self.save_checkpoint(
313 epoch=self._completed_epochs, checkpoint_name="interrupted.pt"
314 )
315 logging.warning(
316 f"Interrupted after {self._completed_epochs} completed epochs; "
317 f"saved {self.checkpoint_path / 'interrupted.pt'}"
318 )
319 raise
320
321 def _train(self):
322 self.model.train()
323 configuration = self.training_configuration
324 for epoch in range(self._completed_epochs, configuration.number_of_epochs):
325 for step, batch in enumerate(
326 tqdm(self.dataloader, desc=f"Epoch={epoch}")
327 ):
328 global_step = epoch * len(self.dataloader) + step
329
330 images, _ = batch
331 images = images.to(self.device)
332
333 noisy_images, noise, timesteps = self.model.diffuse(images=images)
334 if configuration.channels_last:
335 noisy_images = noisy_images.contiguous(
336 memory_format=torch.channels_last
337 )
338
339 self.optimizer.zero_grad(set_to_none=True)
340
341 with torch.autocast(
342 device_type=torch.device(self.device).type,
343 dtype=self._autocast_dtype,
344 enabled=configuration.mixed_precision_training,
345 ):
346 prediction = self._train_model(noisy_images, timesteps)
347 target = self.model.diffuser.get_target(images, noise, timesteps)
348 loss = self.loss_function(target, prediction)
349
350 self.scaler.scale(loss).backward()
351
352 if configuration.gradient_clip is not None:
353 # Unscales the gradients of optimizer's assigned params in-place
354 self.scaler.unscale_(self.optimizer)
355
356 # Since the gradients of optimizer's assigned params are unscaled, clips as usual:
357 torch.nn.utils.clip_grad_norm_(
358 self.model.parameters(),
359 max_norm=configuration.gradient_clip,
360 )
361
362 self.scaler.step(self.optimizer)
363 self.scaler.update()
364
365 if self.ema is not None:
366 self.ema.update(self.model)
367
368 self.log_to_tensorboard(
369 metrics={
370 "Loss": loss,
371 },
372 global_step=global_step,
373 )
374 self._completed_epochs = epoch + 1
375 if epoch % configuration.checkpoint_rate == 0:
376 self.save_checkpoint(epoch=epoch, checkpoint_name=f"epoch_{epoch}.pt")
377 if (
378 configuration.latest_checkpoint_rate is not None
379 and self._completed_epochs % configuration.latest_checkpoint_rate == 0
380 ):
381 self.save_checkpoint(
382 epoch=self._completed_epochs, checkpoint_name="latest.pt"
383 )
384 self._maybe_evaluate()
385 self.save_checkpoint(
386 epoch=configuration.number_of_epochs,
387 checkpoint_name="final.pt",
388 )
389
390 def _maybe_evaluate(self) -> None:
391 """Compute and log FID/KID when due (after checkpoints are saved)."""
392 if self.evaluator is None or self.evaluation_configuration is None:
393 return
394 rate = self.evaluation_configuration.fid_rate
395 is_last = (
396 self._completed_epochs == self.training_configuration.number_of_epochs
397 )
398 if rate is None or self._completed_epochs % rate != 0 and not is_last:
399 return
400 # Evaluate the EMA weights when available: they are what you would ship.
401 model = self.ema.model if self.ema is not None else self.model
402 metrics = self.evaluator.evaluate(model) # ty: ignore[invalid-argument-type]
403 # ``evaluate`` restores the model's training mode.
404 global_step = self._completed_epochs * len(self.dataloader)
405 self.tensorboard_manager.log_metrics(
406 metrics={f"Eval/{name}": value for name, value in metrics.items()},
407 global_step=global_step,
408 )
409 logging.info(f"Epoch {self._completed_epochs}: {metrics}")
410
411 @torch.no_grad()
[docs]
412 def log_to_tensorboard(self, metrics: Dict[str, float], global_step: int):
413 """Log to tensorboard.
414
415 This method logs some useful metrics and visualizations to tensorboard.
416
417 Args:
418 metrics: A dictionary mapping metric names to values.
419 global_step: The current global step.
420 """
421 was_training = self.model.training
422 self.model.eval()
423 try:
424 self._log_to_tensorboard(metrics=metrics, global_step=global_step)
425 finally:
426 # Logging switches to eval mode (BatchNorm, etc.); always restore.
427 self.model.train(was_training)
428
429 @torch.no_grad()
430 def _log_to_tensorboard(self, metrics: Dict[str, float], global_step: int):
431 if global_step % self.log_configuration.log_rate == 0:
432 self.tensorboard_manager.log_metrics(
433 metrics=metrics, global_step=global_step
434 )
435
436 if (
437 self.log_configuration.weight_rate is not None
438 and global_step % self.log_configuration.weight_rate == 0
439 ):
440 self.tensorboard_manager.log_weights(
441 model=self.model, global_step=global_step
442 )
443
444 if (global_step % self.log_configuration.image_rate == 0) and (
445 self.log_configuration.number_of_images > 0
446 ):
447 image_channels, image_height, image_width = self._image_shape
448 images = torch.randn(
449 (
450 self.log_configuration.number_of_images,
451 image_channels,
452 image_height,
453 image_width,
454 ),
455 device=self.device,
456 )
457 # Sample from the EMA weights when available; they are far less noisy.
458 images = (
459 self.ema.model if self.ema is not None else self.model
460 ).denoise(images)
461 for step, images in enumerate(images[::-1]):
462 self.tensorboard_manager.log_images(
463 tag=f"Images at timestep {global_step}",
464 images=self.reverse_transforms(images),
465 timestep=step,
466 )