BiliSakura commited on
Commit
47de14c
·
verified ·
1 Parent(s): 63683b6

Update all files for BitDance-ImageNet-diffusers

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