BiliSakura commited on
Commit
50b9ee8
·
verified ·
1 Parent(s): ddac775

Update all files for BitDance-ImageNet-diffusers

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