Load a trained DDPM model from checkpoint. §4 — "we also report results with an exponential moving average" The EMA parameters typically produce better samples. Args: checkpoint_path: Path to .pt checkpoint file device: Target device use_ema: Whether to load EMA
(
checkpoint_path: str,
device: torch.device,
use_ema: bool = True,
)
| 39 | |
| 40 | |
| 41 | def load_model( |
| 42 | checkpoint_path: str, |
| 43 | device: torch.device, |
| 44 | use_ema: bool = True, |
| 45 | ) -> tuple: |
| 46 | """Load a trained DDPM model from checkpoint. |
| 47 | |
| 48 | §4 — "we also report results with an exponential moving average" |
| 49 | The EMA parameters typically produce better samples. |
| 50 | |
| 51 | Args: |
| 52 | checkpoint_path: Path to .pt checkpoint file |
| 53 | device: Target device |
| 54 | use_ema: Whether to load EMA parameters (recommended) |
| 55 | |
| 56 | Returns: |
| 57 | (model, config_dict) |
| 58 | """ |
| 59 | checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False) |
| 60 | cfg = checkpoint["config"] |
| 61 | model_cfg = cfg["model"] |
| 62 | |
| 63 | unet_config = UNetConfig( |
| 64 | image_channels=model_cfg.get("image_channels", 3), |
| 65 | base_channels=model_cfg.get("base_channels", 128), |
| 66 | channel_mults=tuple(model_cfg.get("channel_mults", [1, 2, 2, 2])), |
| 67 | num_res_blocks=model_cfg.get("num_res_blocks", 2), |
| 68 | attention_resolutions=tuple(model_cfg.get("attention_resolutions", [16])), |
| 69 | dropout=model_cfg.get("dropout", 0.0), |
| 70 | num_groups=model_cfg.get("num_groups", 32), |
| 71 | image_size=cfg["data"].get("image_size", 32), |
| 72 | ) |
| 73 | |
| 74 | model = UNet(unet_config).to(device) |
| 75 | |
| 76 | if use_ema and "ema_state_dict" in checkpoint: |
| 77 | # Load EMA parameters |
| 78 | ema_params = checkpoint["ema_state_dict"] |
| 79 | for name, param in model.named_parameters(): |
| 80 | if name in ema_params: |
| 81 | param.data.copy_(ema_params[name]) |
| 82 | logger.info("Loaded EMA parameters") |
| 83 | else: |
| 84 | model.load_state_dict(checkpoint["model_state_dict"]) |
| 85 | logger.info("Loaded model parameters (no EMA)") |
| 86 | |
| 87 | return model, cfg |
| 88 | |
| 89 | |
| 90 | @torch.no_grad() |
no test coverage detected