wpeebles/DiT
68
1# Copyright (c) Meta Platforms, Inc. and affiliates.2# All rights reserved.3 4# This source code is licensed under the license found in the5# LICENSE file in the root directory of this source tree.6 7import torch8import torch.nn as nn9import numpy as np10import math11from timm.models.vision_transformer import PatchEmbed, Attention, Mlp12 13 14def modulate(x, shift, scale):15 return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)16 17 18#################################################################################19# Embedding Layers for Timesteps and Class Labels #20#################################################################################21 22class TimestepEmbedder(nn.Module):23 """24 Embeds scalar timesteps into vector representations.25 """26 def __init__(self, hidden_size, frequency_embedding_size=256):27 super().__init__()28 self.mlp = nn.Sequential(29 nn.Linear(frequency_embedding_size, hidden_size, bias=True),30 nn.SiLU(),31 nn.Linear(hidden_size, hidden_size, bias=True),32 )33 self.frequency_embedding_size = frequency_embedding_size34 35 @staticmethod36 def timestep_embedding(t, dim, max_period=10000):37 """38 Create sinusoidal timestep embeddings.39 :param t: a 1-D Tensor of N indices, one per batch element.40 These may be fractional.41 :param dim: the dimension of the output.42 :param max_period: controls the minimum frequency of the embeddings.43 :return: an (N, D) Tensor of positional embeddings.44 """45 half = dim // 246 freqs = torch.exp(47 -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half48 ).to(device=t.device)49 args = t[:, None].float() * freqs[None]50 embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)51 if dim % 2:52 embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)53 return embedding54 55 def forward(self, t):56 t_freq = self.timestep_embedding(t, self.frequency_embedding_size)57 t_emb = self.mlp(t_freq)58 return t_emb59 60 61class LabelEmbedder(nn.Module):62 """63 Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.64 """65 def __init__(self, num_classes, hidden_size, dropout_prob):66 super().__init__()67 use_cfg_embedding = dropout_prob > 068 self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)69 self.num_classes = num_classes70 self.dropout_prob = dropout_prob71 72 def token_drop(self, labels, force_drop_ids=None):73 """74 Drops labels to enable classifier-free guidance.75 """76 if force_drop_ids is None:77 drop_ids = torch.rand(labels.shape[0]) < self.dropout_prob78 else:79 drop_ids = force_drop_ids == 180 labels = torch.where(drop_ids, self.num_classes, labels)81 return labels82 83 def forward(self, labels, train, force_drop_ids=None):84 use_dropout = self.dropout_prob > 085 if (train and use_dropout) or (force_drop_ids is not None):86 labels = self.token_drop(labels, force_drop_ids)87 embeddings = self.embedding_table(labels)88 return embeddings89 90 91#################################################################################92# Core DiT Model #93#################################################################################94 95class DiTBlock(nn.Module):96 """97 A DiT block with gated adaptive layer norm (adaLN) conditioning.98 """99 def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):100 super().__init__()101 self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)102 self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)103 self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)104 mlp_hidden_dim = int(hidden_size * mlp_ratio)105 approx_gelu = lambda: nn.GELU(approximate="tanh")106 self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)107 self.adaLN_modulation = nn.Sequential(108 nn.SiLU(),109 nn.Linear(hidden_size, 6 * hidden_size, bias=True)110 )111 112 def forward(self, x, c):113 shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)114 x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa))115 x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))116 return x117 118 119class FinalLayer(nn.Module):120 """121 The final layer of DiT.122 """123 def __init__(self, hidden_size, patch_size, out_channels):124 super().__init__()125 self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)126 self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)127 self.adaLN_modulation = nn.Sequential(128 nn.SiLU(),129 nn.Linear(hidden_size, 2 * hidden_size, bias=True)130 )131 132 def forward(self, x, c):133 shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)134 x = modulate(self.norm_final(x), shift, scale)135 x = self.linear(x)136 return x137 138 139class DiT(nn.Module):140 """141 Diffusion model with a Transformer backbone.142 """143 def __init__(144 self,145 input_size=32,146 patch_size=2,147 in_channels=4,148 hidden_size=1152,149 depth=28,150 num_heads=16,151 mlp_ratio=4.0,152 class_dropout_prob=0.1,153 num_classes=1000,154 learn_sigma=True,155 ):156 super().__init__()157 self.learn_sigma = learn_sigma158 self.in_channels = in_channels159 self.out_channels = in_channels * 2 if learn_sigma else in_channels160 self.patch_size = patch_size161 self.num_heads = num_heads162 163 self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)164 self.t_embedder = TimestepEmbedder(hidden_size)165 self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)166 num_patches = self.x_embedder.num_patches167 # Will use fixed sin-cos embedding:168 self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)169 170 self.blocks = nn.ModuleList([171 DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)172 ])173 self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)174 self.initialize_weights()175 176 def initialize_weights(self):177 # Initialize transformer layers:178 def _basic_init(module):179 if isinstance(module, nn.Linear):180 torch.nn.init.xavier_uniform_(module.weight)181 if module.bias is not None:182 nn.init.constant_(module.bias, 0)183 self.apply(_basic_init)184 185 # Initialize (and freeze) pos_embed by sin-cos embedding186 pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))187 self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))188 189 # Initialize patch_embed like nn.Linear (instead of nn.Conv2d)190 w = self.x_embedder.proj.weight.data191 nn.init.xavier_uniform_(w.view([w.shape[0], -1]))192 193 # Initialize label embedding table:194 nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)195 196 # Initialize timestep embedding MLP:197 nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)198 nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)199 200 # Zero-out adaLN modulation layers in DiT blocks:201 for block in self.blocks:202 nn.init.constant_(block.adaLN_modulation[-1].weight, 0)203 nn.init.constant_(block.adaLN_modulation[-1].bias, 0)204 205 # Zero-out output layers:206 nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)207 nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)208 nn.init.constant_(self.final_layer.linear.weight, 0)209 nn.init.constant_(self.final_layer.linear.bias, 0)210 211 def unpatchify(self, x):212 """213 x: (N, T, patch_size**2 * C)214 imgs: (N, H, W, C)215 """216 c = self.out_channels217 p = self.x_embedder.patch_size[0]218 h = w = int(x.shape[1] ** 0.5)219 assert h * w == x.shape[1]220 221 x = x.reshape(shape=(x.shape[0], h, w, p, p, c))222 x = torch.einsum('nhwpqc->nchpwq', x)223 imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))224 return imgs225 226 def forward(self, x, t, y):227 """228 Forward pass of DiT.229 x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)230 t: (N,) tensor of diffusion timesteps231 y: (N,) tensor of class labels232 """233 x = self.x_embedder(x) + self.pos_embed # (N, T, D), where T = H * W / patch_size ** 2234 t = self.t_embedder(t) # (N, D)235 y = self.y_embedder(y, self.training) # (N, D)236 c = t + y # (N, D)237 for block in self.blocks:238 x = block(x, c) # (N, T, D)239 x = self.final_layer(x, c) # (N, T, patch_size ** 2 * out_channels)240 x = self.unpatchify(x) # (N, out_channels, H, W)241 return x242 243 def forward_with_cfg(self, x, t, y, cfg_scale):244 """245 Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance.246 """247 # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb248 half = x[: len(x) // 2]249 combined = torch.cat([half, half], dim=0)250 model_out = self.forward(combined, t, y)251 eps, rest = model_out[:, :3], model_out[:, 3:]252 cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)253 half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)254 eps = torch.cat([half_eps, half_eps], dim=0)255 return torch.cat([eps, rest], dim=1)256 257 258#################################################################################259# Sine/Cosine Positional Embedding Functions #260#################################################################################261 262def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):263 """264 grid_size: int of the grid height and width265 return:266 pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)267 """268 grid_h = np.arange(grid_size, dtype=np.float32)269 grid_w = np.arange(grid_size, dtype=np.float32)270 grid = np.meshgrid(grid_w, grid_h) # here w goes first271 grid = np.stack(grid, axis=0)272 273 grid = grid.reshape([2, 1, grid_size, grid_size])274 pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)275 if cls_token and extra_tokens > 0:276 pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)277 return pos_embed278 279 280def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):281 assert embed_dim % 2 == 0282 283 # use half of dimensions to encode grid_h284 emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)285 emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)286 287 emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)288 return emb289 290 291def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):292 """293 embed_dim: output dimension for each position294 pos: a list of positions to be encoded: size (M,)295 out: (M, D)296 """297 assert embed_dim % 2 == 0298 omega = np.arange(embed_dim // 2, dtype=np.float32)299 omega /= embed_dim / 2.300 omega = 1. / 10000**omega # (D/2,)301 302 pos = pos.reshape(-1) # (M,)303 out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product304 305 emb_sin = np.sin(out) # (M, D/2)306 emb_cos = np.cos(out) # (M, D/2)307 308 emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)309 return emb310 311 312#################################################################################313# DiT Configs #314#################################################################################315 316def DiT_XL_2(**kwargs):317 return DiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)318 319def DiT_XL_4(**kwargs):320 return DiT(depth=28, hidden_size=1152, patch_size=4, num_heads=16, **kwargs)321 322def DiT_XL_8(**kwargs):323 return DiT(depth=28, hidden_size=1152, patch_size=8, num_heads=16, **kwargs)324 325def DiT_L_2(**kwargs):326 return DiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)327 328def DiT_L_4(**kwargs):329 return DiT(depth=24, hidden_size=1024, patch_size=4, num_heads=16, **kwargs)330 331def DiT_L_8(**kwargs):332 return DiT(depth=24, hidden_size=1024, patch_size=8, num_heads=16, **kwargs)333 334def DiT_B_2(**kwargs):335 return DiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)336 337def DiT_B_4(**kwargs):338 return DiT(depth=12, hidden_size=768, patch_size=4, num_heads=12, **kwargs)339 340def DiT_B_8(**kwargs):341 return DiT(depth=12, hidden_size=768, patch_size=8, num_heads=12, **kwargs)342 343def DiT_S_2(**kwargs):344 return DiT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)345 346def DiT_S_4(**kwargs):347 return DiT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)348 349def DiT_S_8(**kwargs):350 return DiT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)351 