Source code for diffusion_models.models.conditioned_simple_unet

  1# Diffusion Model taken from DeepFindr (https://www.youtube.com/@DeepFindr)
  2import math
  3from typing import Optional
  4
  5import torch
  6from torch import nn
  7
  8from diffusion_models.gaussian_diffusion.base_diffuser import BaseDiffuser
  9from diffusion_models.gaussian_diffusion.gaussian_diffuser import (
 10  GaussianDiffuser,
 11)
 12from diffusion_models.models.SimpleUnet import (
 13  SinusoidalPositionEmbeddings,
 14  Block,
 15)
 16from diffusion_models.models.base_diffusion_model import BaseDiffusionModel
 17
 18
[docs] 19class ConditionedSimpleUnet(BaseDiffusionModel): 20 def __init__( 21 self, 22 diffuser: BaseDiffuser, 23 image_channels: int, 24 text_embedding_size: int, 25 ): 26 """A Simplified variant of the Unet architecture used in DDPM. 27 28 Args: 29 diffuser: A gaussian diffuser. 30 image_channels: The number of image channels. 31 """ 32 super().__init__(diffuser=diffuser) 33 image_channels = image_channels 34 down_channels = (64, 128, 256, 512, 1024) 35 up_channels = (1024, 512, 256, 128, 64) 36 out_dim = image_channels 37 time_emb_dim = 32 38 39 # Text embeddings
[docs] 40 self.text_embedding_mlp = nn.Sequential( 41 nn.Linear(text_embedding_size, time_emb_dim), 42 nn.ReLU(), 43 )
44 45 # Time embedding
[docs] 46 self.time_mlp = nn.Sequential( 47 SinusoidalPositionEmbeddings(time_emb_dim), 48 nn.Linear(time_emb_dim, time_emb_dim), 49 nn.ReLU(), 50 )
51 52 # Initial projection
[docs] 53 self.conv0 = nn.Conv2d(image_channels, down_channels[0], 3, padding=1)
54 55 # Downsample
[docs] 56 self.downs = nn.ModuleList( 57 [ 58 Block(down_channels[i], down_channels[i + 1], time_emb_dim) 59 for i in range(len(down_channels) - 1) 60 ] 61 )
62 # Upsample
[docs] 63 self.ups = nn.ModuleList( 64 [ 65 Block(up_channels[i], up_channels[i + 1], time_emb_dim, up=True) 66 for i in range(len(up_channels) - 1) 67 ] 68 )
69 70 # Edit: Corrected a bug found by Jakub C (see YouTube comment)
[docs] 71 self.output = nn.Conv2d(up_channels[-1], out_dim, 1)
72
[docs] 73 def forward( 74 self, 75 x: torch.Tensor, 76 timestep: torch.Tensor, 77 labels: Optional[torch.Tensor] = None, 78 ): 79 # if self.training: 80 # x = self.augmentations(x) 81 82 # Embed time 83 t = self.time_mlp(timestep) 84 85 # Embed time 86 if labels is not None: 87 text_embedding = self.text_embedding_mlp(labels) 88 else: 89 text_embedding = torch.zeros_like(t) 90 91 h = t + text_embedding 92 93 # Initial conv 94 x = self.conv0(x) 95 # Unet 96 residual_inputs = [] 97 for down in self.downs: 98 x = down(x, h) 99 residual_inputs.append(x) 100 for up in self.ups: 101 residual_x = residual_inputs.pop() 102 # Add residual x as additional channels 103 x = torch.cat((x, residual_x), dim=1) 104 x = up(x, h) 105 return self.output(x)