BiliSakura commited on
Commit
4b7d7ce
·
verified ·
1 Parent(s): a973809

Update all files for BitDance-ImageNet-diffusers

Browse files
BitDance_L_1x/transformer/src/layers.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from typing import Optional
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from flash_attn import flash_attn_func
8
+
9
+ from torch.nn import RMSNorm
10
+ from torch.nn import functional as F
11
+
12
+
13
+ def drop_path(
14
+ x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True
15
+ ):
16
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
17
+
18
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
19
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
20
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
21
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
22
+ 'survival rate' as the argument.
23
+
24
+ """
25
+ if drop_prob == 0.0 or not training:
26
+ return x
27
+ keep_prob = 1 - drop_prob
28
+ shape = (x.shape[0],) + (1,) * (
29
+ x.ndim - 1
30
+ ) # work with diff dim tensors, not just 2D ConvNets
31
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
32
+ if keep_prob > 0.0 and scale_by_keep:
33
+ random_tensor.div_(keep_prob)
34
+ return x * random_tensor
35
+
36
+
37
+ class DropPath(torch.nn.Module):
38
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
39
+
40
+ def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True):
41
+ super(DropPath, self).__init__()
42
+ self.drop_prob = drop_prob
43
+ self.scale_by_keep = scale_by_keep
44
+
45
+ def forward(self, x):
46
+ return drop_path(x, self.drop_prob, self.training, self.scale_by_keep)
47
+
48
+ def extra_repr(self):
49
+ return f"drop_prob={round(self.drop_prob,3):0.3f}"
50
+
51
+
52
+ def find_multiple(n: int, k: int):
53
+ if n % k == 0:
54
+ return n
55
+ return n + k - (n % k)
56
+
57
+
58
+ @lru_cache(maxsize=16)
59
+ def get_causal_mask(seq_q, seq_k, device):
60
+ offset = seq_k - seq_q
61
+ i = torch.arange(seq_q, device=device).unsqueeze(1)
62
+ j = torch.arange(seq_k, device=device).unsqueeze(0)
63
+ causal_mask = (j > (offset + i)).bool()
64
+ causal_mask = causal_mask.unsqueeze(0).unsqueeze(0)
65
+ return causal_mask
66
+
67
+
68
+ class Attention(nn.Module):
69
+ def __init__(
70
+ self,
71
+ dim,
72
+ n_head,
73
+ attn_dropout_p,
74
+ resid_dropout_p,
75
+ causal: bool = True,
76
+ ):
77
+ super().__init__()
78
+ assert dim % n_head == 0
79
+ self.dim = dim
80
+ self.head_dim = dim // n_head
81
+ self.scale = self.head_dim**-0.5
82
+ self.n_head = n_head
83
+ total_kv_dim = (self.n_head * 3) * self.head_dim
84
+
85
+ self.wqkv = nn.Linear(dim, total_kv_dim, bias=False)
86
+ self.wo = nn.Linear(dim, dim, bias=False)
87
+
88
+ self.attn_dropout_p = attn_dropout_p
89
+ self.resid_dropout = nn.Dropout(resid_dropout_p)
90
+ self.causal = causal
91
+
92
+ self.k_cache = None
93
+ self.v_cache = None
94
+ self.kv_cache_size = None
95
+
96
+ def enable_kv_cache(self, bsz, max_seq_len):
97
+ if self.kv_cache_size != (bsz, max_seq_len):
98
+ device = self.wo.weight.device
99
+ dtype = self.wo.weight.dtype
100
+ self.k_cache = torch.zeros(
101
+ (bsz, self.n_head, max_seq_len, self.head_dim),
102
+ device=device,
103
+ dtype=dtype,
104
+ )
105
+ self.v_cache = torch.zeros(
106
+ (bsz, self.n_head, max_seq_len, self.head_dim),
107
+ device=device,
108
+ dtype=dtype,
109
+ )
110
+ self.kv_cache_size = (bsz, max_seq_len)
111
+
112
+ def update_kv_cache(
113
+ self, start_pos, end_pos, keys: torch.Tensor, values: torch.Tensor
114
+ ):
115
+ self.k_cache[:, :, start_pos:end_pos, :] = keys
116
+ self.v_cache[:, :, start_pos:end_pos, :] = values
117
+ return (
118
+ self.k_cache[:, :, :end_pos, :],
119
+ self.v_cache[:, :, :end_pos, :],
120
+ )
121
+
122
+ def naive_attention(self, xq, keys, values, is_causal):
123
+ xq = xq * self.scale
124
+ # q: [B, H, 1, D], k: [B, H, D, L] -> attn [B, H, 1, L]
125
+ attn = xq @ keys.transpose(-1, -2)
126
+ seq_q, seq_k = attn.shape[-2], attn.shape[-1]
127
+ if is_causal and seq_q > 1:
128
+ causal_mask = get_causal_mask(seq_q, seq_k, attn.device)
129
+ attn.masked_fill_(causal_mask, float("-inf"))
130
+ attn = torch.softmax(attn, dim=-1)
131
+ if self.attn_dropout_p > 0 and self.training:
132
+ attn = F.dropout(attn, p=self.attn_dropout_p, training=self.training)
133
+ # [B, H, 1, L] @ [B, H, L, D] -> [B, H, 1, D]
134
+ return attn @ values
135
+
136
+ def forward(
137
+ self,
138
+ x: torch.Tensor,
139
+ freqs_cis: torch.Tensor = None,
140
+ start_pos: Optional[int] = None,
141
+ end_pos: Optional[int] = None,
142
+ ):
143
+ bsz, seqlen, _ = x.shape
144
+ xq, xk, xv = self.wqkv(x).chunk(3, dim=-1)
145
+
146
+ xq = xq.view(bsz, seqlen, self.n_head, self.head_dim)
147
+ xk = xk.view(bsz, seqlen, self.n_head, self.head_dim)
148
+ xv = xv.view(bsz, seqlen, self.n_head, self.head_dim)
149
+
150
+ if freqs_cis is not None:
151
+ xq = apply_rotary_emb(xq, freqs_cis)
152
+ xk = apply_rotary_emb(xk, freqs_cis)
153
+
154
+ is_causal = self.causal
155
+ if self.k_cache is not None and start_pos is not None:
156
+ xq, xk, xv = map(lambda x: x.transpose(1, 2), (xq, xk, xv))
157
+ keys, values = self.update_kv_cache(start_pos, end_pos, xk, xv)
158
+ output = self.naive_attention(xq, keys, values, is_causal=is_causal)
159
+ output = output.transpose(1, 2).contiguous()
160
+ else:
161
+ output = flash_attn_func(
162
+ xq,
163
+ xk,
164
+ xv,
165
+ causal=is_causal,
166
+ dropout_p=self.attn_dropout_p if self.training else 0,
167
+ )
168
+
169
+ output = output.view(bsz, seqlen, self.dim)
170
+
171
+ output = self.resid_dropout(self.wo(output))
172
+ return output
173
+
174
+
175
+ class FeedForward(nn.Module):
176
+
177
+ def __init__(self, dim, dropout_p=0.1, mlp_ratio=4.0):
178
+ super().__init__()
179
+ hidden_dim = mlp_ratio * dim
180
+ hidden_dim = int(2 * hidden_dim / 3)
181
+ hidden_dim = find_multiple(hidden_dim, 256)
182
+
183
+ self.w1 = nn.Linear(dim, hidden_dim * 2, bias=False)
184
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
185
+ self.ffn_dropout = nn.Dropout(dropout_p)
186
+
187
+ def forward(self, x):
188
+ h1, h2 = self.w1(x).chunk(2, dim=-1)
189
+ return self.ffn_dropout(self.w2(F.silu(h1) * h2))
190
+
191
+
192
+ class TransformerBlock(nn.Module):
193
+ def __init__(
194
+ self,
195
+ dim,
196
+ n_head,
197
+ attn_dropout_p: float = 0.0,
198
+ resid_dropout_p: float = 0.0,
199
+ drop_path: float = 0.0,
200
+ causal: bool = True,
201
+ ):
202
+ super().__init__()
203
+ self.attention = Attention(
204
+ dim=dim,
205
+ n_head=n_head,
206
+ attn_dropout_p=attn_dropout_p,
207
+ resid_dropout_p=resid_dropout_p,
208
+ causal=causal,
209
+ )
210
+ self.feed_forward = FeedForward(
211
+ dim=dim,
212
+ dropout_p=resid_dropout_p,
213
+ )
214
+ self.attention_norm = RMSNorm(dim, eps=1e-6)
215
+ self.ffn_norm = RMSNorm(dim, eps=1e-6)
216
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
217
+
218
+ def forward(
219
+ self,
220
+ x: torch.Tensor,
221
+ freqs_cis: torch.Tensor,
222
+ ):
223
+ h = x + self.drop_path(self.attention(self.attention_norm(x), freqs_cis))
224
+ out = h + self.drop_path(self.feed_forward(self.ffn_norm(h)))
225
+ return out
226
+
227
+ def forward_onestep(
228
+ self,
229
+ x: torch.Tensor,
230
+ freqs_cis: torch.Tensor,
231
+ start_pos: int,
232
+ end_pos: int,
233
+ ):
234
+ h = x + self.drop_path(
235
+ self.attention(self.attention_norm(x), freqs_cis, start_pos, end_pos)
236
+ )
237
+ out = h + self.drop_path(self.feed_forward(self.ffn_norm(h)))
238
+ return out
239
+
240
+
241
+ def get_2d_pos(resolution, patch_size, num_scales=1):
242
+ max_pos = resolution // patch_size
243
+ coords_list = []
244
+
245
+ for i in range(num_scales):
246
+ scale = 2 ** (num_scales - i - 1)
247
+ P = max(resolution // scale // patch_size, 1)
248
+ edge = float(max_pos) / P
249
+ centers = (torch.arange(P, dtype=torch.float32) + 0.5) * edge
250
+ grid_y, grid_x = torch.meshgrid(centers, centers, indexing="ij")
251
+ coords = torch.stack([grid_x.reshape(-1), grid_y.reshape(-1)], dim=1)
252
+ coords_list.append(coords)
253
+
254
+ return torch.cat(coords_list, dim=0)
255
+
256
+
257
+ def precompute_freqs_cis_2d(
258
+ pos_2d, n_elem: int, base: float = 10000, cls_token_num=120
259
+ ):
260
+ # split the dimension into half, one for x and one for y
261
+ half_dim = n_elem // 2
262
+ freqs = 1.0 / (
263
+ base ** (torch.arange(0, half_dim, 2)[: (half_dim // 2)].float() / half_dim)
264
+ )
265
+ t = pos_2d + 1.0
266
+ if cls_token_num > 0:
267
+ t = torch.cat(
268
+ [torch.zeros((cls_token_num, 2), device=freqs.device), t],
269
+ dim=0,
270
+ )
271
+ freqs = torch.outer(t.flatten(), freqs).view(*t.shape[:-1], -1)
272
+ return torch.stack([torch.cos(freqs), torch.sin(freqs)], dim=-1)
273
+
274
+
275
+ def apply_rotary_emb(x: torch.Tensor, freqs_cis: torch.Tensor):
276
+ # x: (bs, seq_len, n_head, head_dim)
277
+ # freqs_cis (seq_len, head_dim // 2, 2)
278
+ xshaped = x.float().reshape(
279
+ *x.shape[:-1], -1, 2
280
+ ) # (bs, seq_len, n_head, head_dim//2, 2)
281
+ freqs_cis = freqs_cis.view(
282
+ 1, xshaped.size(1), 1, xshaped.size(3), 2
283
+ ) # (1, seq_len, 1, head_dim//2, 2)
284
+ x_out2 = torch.stack(
285
+ [
286
+ xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
287
+ xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
288
+ ],
289
+ dim=-1,
290
+ )
291
+ x_out2 = x_out2.flatten(3)
292
+ return x_out2.type_as(x)