mikonvergence commited on
Commit
5107cc3
·
1 Parent(s): dfc9360

triffuser definition

Browse files
Files changed (2) hide show
  1. src/MLP.py +111 -0
  2. src/Triffuser.py +302 -0
src/MLP.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # code from timm 0.3.2
2
+ import torch
3
+ import torch.nn as nn
4
+ import math
5
+ import warnings
6
+
7
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
8
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
9
+ # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
10
+ def norm_cdf(x):
11
+ # Computes standard normal cumulative distribution function
12
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
13
+
14
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
15
+ warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. "
16
+ "The distribution of values may be incorrect.",
17
+ stacklevel=2)
18
+
19
+ with torch.no_grad():
20
+ # Values are generated by using a truncated uniform distribution and
21
+ # then using the inverse CDF for the normal distribution.
22
+ # Get upper and lower cdf values
23
+ l = norm_cdf((a - mean) / std)
24
+ u = norm_cdf((b - mean) / std)
25
+
26
+ # Uniformly fill tensor with values from [l, u], then translate to
27
+ # [2l-1, 2u-1].
28
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
29
+
30
+ # Use inverse cdf transform for normal distribution to get truncated
31
+ # standard normal
32
+ tensor.erfinv_()
33
+
34
+ # Transform to proper mean, std
35
+ tensor.mul_(std * math.sqrt(2.))
36
+ tensor.add_(mean)
37
+
38
+ # Clamp to ensure it's in the proper range
39
+ tensor.clamp_(min=a, max=b)
40
+ return tensor
41
+
42
+
43
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
44
+ # type: (Tensor, float, float, float, float) -> Tensor
45
+ r"""Fills the input Tensor with values drawn from a truncated
46
+ normal distribution. The values are effectively drawn from the
47
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
48
+ with values outside :math:`[a, b]` redrawn until they are within
49
+ the bounds. The method used for generating the random values works
50
+ best when :math:`a \leq \text{mean} \leq b`.
51
+ Args:
52
+ tensor: an n-dimensional `torch.Tensor`
53
+ mean: the mean of the normal distribution
54
+ std: the standard deviation of the normal distribution
55
+ a: the minimum cutoff value
56
+ b: the maximum cutoff value
57
+ Examples:
58
+ >>> w = torch.empty(3, 5)
59
+ >>> nn.init.trunc_normal_(w)
60
+ """
61
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
62
+
63
+
64
+ def drop_path(x, drop_prob: float = 0., training: bool = False):
65
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
66
+
67
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
68
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
69
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
70
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
71
+ 'survival rate' as the argument.
72
+
73
+ """
74
+ if drop_prob == 0. or not training:
75
+ return x
76
+ keep_prob = 1 - drop_prob
77
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
78
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
79
+ random_tensor.floor_() # binarize
80
+ output = x.div(keep_prob) * random_tensor
81
+ return output
82
+
83
+
84
+ class DropPath(nn.Module):
85
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
86
+ """
87
+ def __init__(self, drop_prob=None):
88
+ super(DropPath, self).__init__()
89
+ self.drop_prob = drop_prob
90
+
91
+ def forward(self, x):
92
+ return drop_path(x, self.drop_prob, self.training)
93
+
94
+
95
+ class Mlp(nn.Module):
96
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
97
+ super().__init__()
98
+ out_features = out_features or in_features
99
+ hidden_features = hidden_features or in_features
100
+ self.fc1 = nn.Linear(in_features, hidden_features)
101
+ self.act = act_layer()
102
+ self.fc2 = nn.Linear(hidden_features, out_features)
103
+ self.drop = nn.Dropout(drop)
104
+
105
+ def forward(self, x):
106
+ x = self.fc1(x)
107
+ x = self.act(x)
108
+ x = self.drop(x)
109
+ x = self.fc2(x)
110
+ x = self.drop(x)
111
+ return x
src/Triffuser.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import math
4
+ from .MLP import trunc_normal_, DropPath, Mlp
5
+ import einops
6
+ import torch.utils.checkpoint
7
+ import torch.nn.functional as F
8
+
9
+ if hasattr(torch.nn.functional, 'scaled_dot_product_attention'):
10
+ ATTENTION_MODE = 'flash'
11
+ else:
12
+ try:
13
+ import xformers
14
+ import xformers.ops
15
+ ATTENTION_MODE = 'xformers'
16
+ except:
17
+ ATTENTION_MODE = 'math'
18
+ print(f'attention mode is {ATTENTION_MODE}')
19
+
20
+
21
+ def timestep_embedding(timesteps, dim, max_period=10000):
22
+ """
23
+ Create sinusoidal timestep embeddings.
24
+
25
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
26
+ These may be fractional.
27
+ :param dim: the dimension of the output.
28
+ :param max_period: controls the minimum frequency of the embeddings.
29
+ :return: an [N x dim] Tensor of positional embeddings.
30
+ """
31
+ half = dim // 2
32
+ freqs = torch.exp(
33
+ -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
34
+ ).to(device=timesteps.device)
35
+ args = timesteps[:, None].float() * freqs[None]
36
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
37
+ if dim % 2:
38
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
39
+ return embedding
40
+
41
+
42
+ def patchify(imgs, patch_size):
43
+ x = einops.rearrange(imgs, 'B C (h p1) (w p2) -> B (h w) (p1 p2 C)', p1=patch_size, p2=patch_size)
44
+ return x
45
+
46
+
47
+ def unpatchify(x, in_chans):
48
+ patch_size = int((x.shape[2] // in_chans) ** 0.5)
49
+ h = w = int(x.shape[1] ** .5)
50
+ assert h * w == x.shape[1] and patch_size ** 2 * in_chans == x.shape[2]
51
+ x = einops.rearrange(x, 'B (h w) (p1 p2 C) -> B C (h p1) (w p2)', h=h, p1=patch_size, p2=patch_size)
52
+ return x
53
+
54
+
55
+ def interpolate_pos_emb(pos_emb, old_shape, new_shape):
56
+ pos_emb = einops.rearrange(pos_emb, 'B (H W) C -> B C H W', H=old_shape[0], W=old_shape[1])
57
+ pos_emb = F.interpolate(pos_emb, new_shape, mode='bilinear')
58
+ pos_emb = einops.rearrange(pos_emb, 'B C H W -> B (H W) C')
59
+ return pos_emb
60
+
61
+
62
+ class Attention(nn.Module):
63
+ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):
64
+ super().__init__()
65
+ self.num_heads = num_heads
66
+ head_dim = dim // num_heads
67
+ self.scale = qk_scale or head_dim ** -0.5
68
+
69
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
70
+ self.attn_drop = nn.Dropout(attn_drop)
71
+ self.proj = nn.Linear(dim, dim)
72
+ self.proj_drop = nn.Dropout(proj_drop)
73
+
74
+ def forward(self, x):
75
+ B, L, C = x.shape
76
+
77
+ qkv = self.qkv(x)
78
+ if ATTENTION_MODE == 'flash':
79
+ qkv = einops.rearrange(qkv, 'B L (K H D) -> K B H L D', K=3, H=self.num_heads).float()
80
+ q, k, v = qkv[0], qkv[1], qkv[2] # B H L D
81
+ x = torch.nn.functional.scaled_dot_product_attention(q, k, v)
82
+ x = einops.rearrange(x, 'B H L D -> B L (H D)')
83
+ elif ATTENTION_MODE == 'xformers':
84
+ qkv = einops.rearrange(qkv, 'B L (K H D) -> K B L H D', K=3, H=self.num_heads)
85
+ q, k, v = qkv[0], qkv[1], qkv[2] # B L H D
86
+ x = xformers.ops.memory_efficient_attention(q, k, v)
87
+ x = einops.rearrange(x, 'B L H D -> B L (H D)', H=self.num_heads)
88
+ elif ATTENTION_MODE == 'math':
89
+ with torch.amp.autocast(device_type='cuda', enabled=False):
90
+ qkv = einops.rearrange(qkv, 'B L (K H D) -> K B H L D', K=3, H=self.num_heads).float()
91
+ q, k, v = qkv[0], qkv[1], qkv[2] # B H L D
92
+ attn = (q @ k.transpose(-2, -1)) * self.scale
93
+ attn = attn.softmax(dim=-1)
94
+ attn = self.attn_drop(attn)
95
+ x = (attn @ v).transpose(1, 2).reshape(B, L, C)
96
+ else:
97
+ raise NotImplemented
98
+
99
+ x = self.proj(x)
100
+ x = self.proj_drop(x)
101
+ return x
102
+
103
+
104
+ class Block(nn.Module):
105
+
106
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
107
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, skip=False, use_checkpoint=False):
108
+ super().__init__()
109
+ self.norm1 = norm_layer(dim) if skip else None
110
+ self.norm2 = norm_layer(dim)
111
+
112
+ self.attn = Attention(
113
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
114
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
115
+ self.norm3 = norm_layer(dim)
116
+ mlp_hidden_dim = int(dim * mlp_ratio)
117
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
118
+ self.skip_linear = nn.Linear(2 * dim, dim) if skip else None
119
+ self.use_checkpoint = use_checkpoint
120
+
121
+ def forward(self, x, skip=None):
122
+ if self.use_checkpoint:
123
+ return torch.utils.checkpoint.checkpoint(self._forward, x, skip)
124
+ else:
125
+ return self._forward(x, skip)
126
+
127
+ def _forward(self, x, skip=None):
128
+ if self.skip_linear is not None:
129
+ x = self.skip_linear(torch.cat([x, skip], dim=-1))
130
+ x = self.norm1(x)
131
+ x = x + self.drop_path(self.attn(x))
132
+ x = self.norm2(x)
133
+
134
+ x = x + self.drop_path(self.mlp(x))
135
+ x = self.norm3(x)
136
+
137
+ return x
138
+
139
+
140
+ class PatchEmbed(nn.Module):
141
+ """ Image to Patch Embedding
142
+ """
143
+ def __init__(self, patch_size, in_chans=3, embed_dim=768):
144
+ super().__init__()
145
+ self.patch_size = patch_size
146
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
147
+
148
+ def forward(self, x):
149
+ B, C, H, W = x.shape
150
+ assert H % self.patch_size == 0 and W % self.patch_size == 0
151
+ x = self.proj(x).flatten(2).transpose(1, 2)
152
+ return x
153
+
154
+ class Triffuser(nn.Module):
155
+ def __init__(self,
156
+ img_size=32, # Assuming latent diffusion
157
+ in_chans=4, # Assuming latent diffusion
158
+ num_modalities=4,
159
+ patch_size=2,
160
+ embed_dim=1024,
161
+ depth=20,
162
+ num_heads=16,
163
+ mlp_ratio=4.,
164
+ qkv_bias=False,
165
+ qk_scale=None,
166
+ pos_drop_rate=0.,
167
+ drop_rate=0.,
168
+ attn_drop_rate=0.,
169
+ norm_layer=nn.LayerNorm,
170
+ mlp_time_embed=False,
171
+ use_checkpoint=False,
172
+ # text_dim=None,
173
+ # num_text_tokens=None,
174
+ clip_img_dim=None # All modalities with the same clip dimension
175
+ ):
176
+ super().__init__()
177
+ self.in_chans = in_chans
178
+ self.patch_size = patch_size
179
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
180
+ self.num_modalities = num_modalities
181
+ if num_modalities is None:
182
+ raise ValueError("num_modalities must be provided")
183
+
184
+ self.patch_embeds = nn.ModuleList([PatchEmbed(patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim) for _ in range(num_modalities)])
185
+ self.img_size = (img_size, img_size) if isinstance(img_size, int) else img_size # the default img size
186
+ assert self.img_size[0] % patch_size == 0 and self.img_size[1] % patch_size == 0
187
+ self.num_patches = (self.img_size[0] // patch_size) * (self.img_size[1] // patch_size)
188
+
189
+ self.time_img_embeds = nn.ModuleList([nn.Sequential(
190
+ nn.Linear(embed_dim, 4 * embed_dim),
191
+ nn.SiLU(),
192
+ nn.Linear(4 * embed_dim, embed_dim),
193
+ ) if mlp_time_embed else nn.Identity() for _ in range(num_modalities)])
194
+
195
+ # self.text_embed = nn.Linear(text_dim, embed_dim)
196
+ # self.text_out = nn.Linear(embed_dim, text_dim)
197
+
198
+ # TODO: We skip clip embedding for now
199
+ # self.clip_img_embed = nn.Linear(clip_img_dim, embed_dim)
200
+ # self.clip_img_out = nn.Linear(embed_dim, clip_img_dim)
201
+
202
+ # self.num_text_tokens = num_text_tokens
203
+ # TODO: ATM we assume the same num_patches for all modalities
204
+ # 1 for time embedding token of each modality
205
+ # num_patches for each modality (assuming the same number of patches for all modalities)
206
+ self.num_tokens = 1 * self.num_modalities + self.num_patches * self.num_modalities
207
+
208
+ self.pos_embed = nn.Parameter(torch.zeros(1, self.num_tokens, embed_dim))
209
+ self.pos_drop = nn.Dropout(p=pos_drop_rate)
210
+
211
+ self.in_blocks = nn.ModuleList([
212
+ Block(
213
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
214
+ drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint)
215
+ for _ in range(depth // 2)])
216
+
217
+ self.mid_block = Block(
218
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
219
+ drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, use_checkpoint=use_checkpoint)
220
+
221
+ self.out_blocks = nn.ModuleList([
222
+ Block(
223
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
224
+ drop=drop_rate, attn_drop=attn_drop_rate, norm_layer=norm_layer, skip=True, use_checkpoint=use_checkpoint)
225
+ for _ in range(depth // 2)])
226
+
227
+ self.norm = norm_layer(embed_dim)
228
+ self.patch_dim = patch_size ** 2 * in_chans
229
+ self.decoder_preds = nn.ModuleList([nn.Linear(embed_dim, self.patch_dim, bias=True) for _ in range(num_modalities)])
230
+
231
+ trunc_normal_(self.pos_embed, std=.02)
232
+ self.apply(self._init_weights)
233
+
234
+ def _init_weights(self, m):
235
+ if isinstance(m, nn.Linear):
236
+ trunc_normal_(m.weight, std=.02)
237
+ if isinstance(m, nn.Linear) and m.bias is not None:
238
+ nn.init.constant_(m.bias, 0)
239
+ elif isinstance(m, nn.LayerNorm):
240
+ nn.init.constant_(m.bias, 0)
241
+ nn.init.constant_(m.weight, 1.0)
242
+
243
+ @torch.jit.ignore
244
+ def no_weight_decay(self):
245
+ return {'pos_embed'}
246
+
247
+ def forward(self, imgs, t_imgs):
248
+
249
+ assert len(imgs) == len(t_imgs) == self.num_modalities
250
+
251
+ # TODO: We are still assuming all images have the same shape
252
+ _, _, H, W = imgs[0].shape
253
+
254
+ imgs = [self.patch_embeds[i](img) for i, img in enumerate(imgs)]
255
+
256
+ t_imgs_token = [self.time_img_embeds[i](timestep_embedding(t_img, self.embed_dim)) for i, t_img in enumerate(t_imgs)]
257
+ t_imgs_token = [t_img_token.unsqueeze(dim=1) for t_img_token in t_imgs_token]
258
+
259
+ # text = self.text_embed(text)
260
+ # clip_img = self.clip_img_embed(clip_img)
261
+ x = torch.cat((*t_imgs_token, *imgs), dim=1)
262
+
263
+ num_img_tokens = [img.size(1) for img in imgs] # Each image might have different number of tokens
264
+ num_t_tokens = [1] * self.num_modalities # There is only one time token for each modality
265
+
266
+ # TODO: ATM assume all modality images have the same shape
267
+ if H == self.img_size[0] and W == self.img_size[1]:
268
+ pos_embed = self.pos_embed
269
+ else: # interpolate the positional embedding when the input image is not of the default shape
270
+ raise NotImplementedError("Why are we here? Images are not of the default shape. Interpolate positional embedding.")
271
+ pos_embed_others, pos_embed_patches = torch.split(self.pos_embed, [1 + 1 + num_text_tokens + 1, self.num_patches], dim=1)
272
+ pos_embed_patches = interpolate_pos_emb(pos_embed_patches, (self.img_size[0] // self.patch_size, self.img_size[1] // self.patch_size),
273
+ (H // self.patch_size, W // self.patch_size))
274
+ pos_embed = torch.cat((pos_embed_others, pos_embed_patches), dim=1)
275
+
276
+ x = x + pos_embed
277
+ x = self.pos_drop(x)
278
+
279
+ skips = []
280
+ for blk in self.in_blocks:
281
+ x = blk(x)
282
+ skips.append(x)
283
+
284
+ x = self.mid_block(x)
285
+
286
+ for blk in self.out_blocks:
287
+ x = blk(x, skips.pop())
288
+
289
+ x = self.norm(x)
290
+
291
+ all_t_imgs = x.split((*num_t_tokens, *num_img_tokens), dim=1)
292
+
293
+ t_imgs_token_out = all_t_imgs[:self.num_modalities]
294
+ imgs_out = all_t_imgs[self.num_modalities:]
295
+
296
+ imgs_out = [self.decoder_preds[i](img_out) for i, img_out in enumerate(imgs_out)]
297
+ imgs_out = [unpatchify(img_out, self.in_chans) for img_out in imgs_out]
298
+
299
+ # clip_img_out = self.clip_img_out(clip_img_out)
300
+ # text_out = self.text_out(text_out)
301
+
302
+ return imgs_out