Dragunflie-420 commited on
Commit
288a8da
1 Parent(s): 73b4102

Create models.py

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