|
| 1 | +import copy |
| 2 | +import torch |
| 3 | +from torch import nn |
| 4 | +from torch.cuda import amp |
| 5 | + |
| 6 | +class UNetModel: |
| 7 | + """Core model architecture implementation for diffusion models.""" |
| 8 | + def __init__(self, conf): |
| 9 | + """ |
| 10 | + Initialize the UNet model. |
| 11 | + |
| 12 | + Args: |
| 13 | + conf: Configuration object containing model parameters |
| 14 | + """ |
| 15 | + self.conf = conf |
| 16 | + self.model = conf.make_model_conf().make_model() |
| 17 | + self.ema_model = copy.deepcopy(self.model) |
| 18 | + self.ema_model.requires_grad_(False) |
| 19 | + self.ema_model.eval() |
| 20 | + |
| 21 | + # Calculate model size |
| 22 | + model_size = 0 |
| 23 | + for param in self.model.parameters(): |
| 24 | + model_size += param.data.nelement() |
| 25 | + print('Model params: %.2f M' % (model_size / 1024 / 1024)) |
| 26 | + |
| 27 | + # Initialize samplers |
| 28 | + self.sampler = conf.make_diffusion_conf().make_sampler() |
| 29 | + self.eval_sampler = conf.make_eval_diffusion_conf().make_sampler() |
| 30 | + self.T_sampler = conf.make_T_sampler() |
| 31 | + |
| 32 | + # Initialize latent samplers if needed |
| 33 | + if conf.train_mode.use_latent_net(): |
| 34 | + self.latent_sampler = conf.make_latent_diffusion_conf().make_sampler() |
| 35 | + self.eval_latent_sampler = conf.make_latent_eval_diffusion_conf().make_sampler() |
| 36 | + else: |
| 37 | + self.latent_sampler = None |
| 38 | + self.eval_latent_sampler = None |
| 39 | + |
| 40 | + def update_ema(self, decay): |
| 41 | + """ |
| 42 | + Update the exponential moving average model. |
| 43 | + |
| 44 | + Args: |
| 45 | + decay: EMA decay rate |
| 46 | + """ |
| 47 | + self._ema(self.model, self.ema_model, decay) |
| 48 | + |
| 49 | + def _ema(self, source, target, decay): |
| 50 | + """ |
| 51 | + Apply exponential moving average update. |
| 52 | + |
| 53 | + Args: |
| 54 | + source: Source model |
| 55 | + target: Target model (EMA) |
| 56 | + decay: EMA decay rate |
| 57 | + """ |
| 58 | + source_dict = source.state_dict() |
| 59 | + target_dict = target.state_dict() |
| 60 | + for key in source_dict.keys(): |
| 61 | + target_dict[key].data.copy_(target_dict[key].data * decay + |
| 62 | + source_dict[key].data * (1 - decay)) |
| 63 | + |
| 64 | + def encode(self, x): |
| 65 | + """ |
| 66 | + Encode input using the model's encoder. |
| 67 | + |
| 68 | + Args: |
| 69 | + x: Input tensor |
| 70 | + |
| 71 | + Returns: |
| 72 | + Encoded representation |
| 73 | + """ |
| 74 | + assert self.conf.model_type.has_autoenc() |
| 75 | + cond = self.ema_model.encoder.forward(x) |
| 76 | + return cond |
| 77 | + |
| 78 | + def encode_stochastic(self, x, cond, T=None): |
| 79 | + """ |
| 80 | + Stochastically encode input. |
| 81 | + |
| 82 | + Args: |
| 83 | + x: Input tensor |
| 84 | + cond: Conditioning tensor |
| 85 | + T: Number of diffusion steps |
| 86 | + |
| 87 | + Returns: |
| 88 | + Stochastically encoded sample |
| 89 | + """ |
| 90 | + if T is None: |
| 91 | + sampler = self.eval_sampler |
| 92 | + else: |
| 93 | + sampler = self.conf._make_diffusion_conf(T).make_sampler() |
| 94 | + out = sampler.ddim_reverse_sample_loop(self.ema_model, |
| 95 | + x, |
| 96 | + model_kwargs={'cond': cond}) |
| 97 | + return out['sample'] |
| 98 | + |
| 99 | + def forward(self, noise=None, x_start=None, use_ema=False): |
| 100 | + """ |
| 101 | + Forward pass through the model. |
| 102 | + |
| 103 | + Args: |
| 104 | + noise: Input noise |
| 105 | + x_start: Starting point for diffusion |
| 106 | + use_ema: Whether to use EMA model |
| 107 | + |
| 108 | + Returns: |
| 109 | + Generated sample |
| 110 | + """ |
| 111 | + with amp.autocast(False): |
| 112 | + model = self.ema_model if use_ema else self.model |
| 113 | + gen = self.eval_sampler.sample(model=model, |
| 114 | + noise=noise, |
| 115 | + x_start=x_start) |
| 116 | + return gen |
0 commit comments