Upload BD3LM
Browse files- config.json +5 -5
- configuration_bd3lm.py +43 -0
- modeling_bd3lm.py +560 -0
config.json
CHANGED
@@ -1,12 +1,12 @@
|
|
1 |
{
|
2 |
-
"_name_or_path": "kuleshov-group/
|
3 |
"architectures": [
|
4 |
-
"
|
5 |
],
|
6 |
"attn_backend": "sdpa",
|
7 |
"auto_map": {
|
8 |
-
"AutoConfig": "
|
9 |
-
"AutoModelForMaskedLM": "
|
10 |
},
|
11 |
"block_size": 16,
|
12 |
"cond_dim": 128,
|
@@ -14,7 +14,7 @@
|
|
14 |
"dropout": 0.1,
|
15 |
"hidden_dim": 768,
|
16 |
"model_length": 1024,
|
17 |
-
"model_type": "
|
18 |
"n_blocks": 12,
|
19 |
"n_heads": 12,
|
20 |
"return_dict": false,
|
|
|
1 |
{
|
2 |
+
"_name_or_path": "kuleshov-group/bd3lm-owt-block_size16",
|
3 |
"architectures": [
|
4 |
+
"BD3LM"
|
5 |
],
|
6 |
"attn_backend": "sdpa",
|
7 |
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_bd3lm.BD3LMConfig",
|
9 |
+
"AutoModelForMaskedLM": "modeling_bd3lm.BD3LM"
|
10 |
},
|
11 |
"block_size": 16,
|
12 |
"cond_dim": 128,
|
|
|
14 |
"dropout": 0.1,
|
15 |
"hidden_dim": 768,
|
16 |
"model_length": 1024,
|
17 |
+
"model_type": "bd3lm",
|
18 |
"n_blocks": 12,
|
19 |
"n_heads": 12,
|
20 |
"return_dict": false,
|
configuration_bd3lm.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""BD3LM config for Hugging Face.
|
2 |
+
|
3 |
+
"""
|
4 |
+
|
5 |
+
import transformers
|
6 |
+
|
7 |
+
|
8 |
+
class BD3LMConfig(transformers.PretrainedConfig):
|
9 |
+
"""Hugging Face configuration class for BD3LM."""
|
10 |
+
model_type = "bd3lm"
|
11 |
+
|
12 |
+
def __init__(
|
13 |
+
self,
|
14 |
+
block_size: int = 1,
|
15 |
+
vocab_size: int = 50258,
|
16 |
+
model_length: int = 1024,
|
17 |
+
cross_attn: bool = True,
|
18 |
+
attn_backend: str = 'sdpa',
|
19 |
+
hidden_dim: int = 768,
|
20 |
+
cond_dim: int = 129,
|
21 |
+
n_blocks: int = 12,
|
22 |
+
n_heads: int = 12,
|
23 |
+
dropout: float = 0.1,
|
24 |
+
time_conditioning: bool = False,
|
25 |
+
var_min: bool = True,
|
26 |
+
sampling_eps_min: float = 1e-3,
|
27 |
+
sampling_eps_max: float = 0.999,
|
28 |
+
** kwargs):
|
29 |
+
super().__init__(**kwargs)
|
30 |
+
self.block_size = block_size
|
31 |
+
self.cross_attn = cross_attn
|
32 |
+
self.attn_backend = attn_backend
|
33 |
+
self.vocab_size = vocab_size
|
34 |
+
self.model_length = model_length
|
35 |
+
self.hidden_dim = hidden_dim
|
36 |
+
self.cond_dim = cond_dim
|
37 |
+
self.n_blocks = n_blocks
|
38 |
+
self.n_heads = n_heads
|
39 |
+
self.dropout = dropout
|
40 |
+
self.time_conditioning = time_conditioning
|
41 |
+
self.var_min = var_min
|
42 |
+
self.sampling_eps_min = sampling_eps_min
|
43 |
+
self.sampling_eps_max = sampling_eps_max
|
modeling_bd3lm.py
ADDED
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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D3LM model for Hugging Face.
|
2 |
+
|
3 |
+
"""
|
4 |
+
import math
|
5 |
+
import typing
|
6 |
+
|
7 |
+
import einops
|
8 |
+
import flash_attn
|
9 |
+
import flash_attn.layers.rotary
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
import torch.nn.functional as F
|
13 |
+
import transformers
|
14 |
+
from transformers import modeling_outputs
|
15 |
+
|
16 |
+
from .configuration_bd3lm import BD3LMConfig
|
17 |
+
|
18 |
+
# Flags required to enable jit fusion kernels
|
19 |
+
torch._C._jit_set_profiling_mode(False)
|
20 |
+
torch._C._jit_set_profiling_executor(False)
|
21 |
+
torch._C._jit_override_can_fuse_on_cpu(True)
|
22 |
+
torch._C._jit_override_can_fuse_on_gpu(True)
|
23 |
+
|
24 |
+
def block_causal_mask(num_rows, block_size, mode='full', offset=0):
|
25 |
+
mask = block_size * torch.arange(
|
26 |
+
1, num_rows // block_size + 1).unsqueeze(1).tile(block_size).flatten().unsqueeze(1)
|
27 |
+
if mode == 'full':
|
28 |
+
mask = (mask >= mask.T + offset)
|
29 |
+
elif mode == 'diag':
|
30 |
+
mask = (mask + offset == mask.T)
|
31 |
+
elif mode == 'triu_diag':
|
32 |
+
mask = torch.zeros(num_rows, num_rows)
|
33 |
+
rows = torch.arange(0, num_rows)
|
34 |
+
group_indices = rows // (block_size)
|
35 |
+
column_indices = group_indices * (block_size) + block_size + offset
|
36 |
+
valid_rows = column_indices < num_rows
|
37 |
+
mask[rows[valid_rows].unsqueeze(1), column_indices[valid_rows].unsqueeze(1)] = 1
|
38 |
+
return mask.int()
|
39 |
+
|
40 |
+
def bias_dropout_add_scale(
|
41 |
+
x: torch.Tensor,
|
42 |
+
bias: typing.Optional[torch.Tensor],
|
43 |
+
scale: torch.Tensor,
|
44 |
+
residual: typing.Optional[torch.Tensor],
|
45 |
+
prob: float,
|
46 |
+
training: bool) -> torch.Tensor:
|
47 |
+
if bias is not None:
|
48 |
+
out = scale * F.dropout(x + bias, p=prob, training=training)
|
49 |
+
else:
|
50 |
+
out = scale * F.dropout(x, p=prob, training=training)
|
51 |
+
|
52 |
+
if residual is not None:
|
53 |
+
out = residual + out
|
54 |
+
return out
|
55 |
+
|
56 |
+
|
57 |
+
def get_bias_dropout_add_scale(training):
|
58 |
+
def _bias_dropout_add(x, bias, scale, residual, prob):
|
59 |
+
return bias_dropout_add_scale(
|
60 |
+
x, bias, scale, residual, prob, training)
|
61 |
+
|
62 |
+
return _bias_dropout_add
|
63 |
+
|
64 |
+
|
65 |
+
# function overload
|
66 |
+
def modulate(x: torch.Tensor,
|
67 |
+
shift: torch.Tensor,
|
68 |
+
scale: torch.Tensor) -> torch.Tensor:
|
69 |
+
return x * (1 + scale) + shift
|
70 |
+
|
71 |
+
|
72 |
+
@torch.jit.script
|
73 |
+
def bias_dropout_add_scale_fused_train(
|
74 |
+
x: torch.Tensor,
|
75 |
+
bias: typing.Optional[torch.Tensor],
|
76 |
+
scale: torch.Tensor,
|
77 |
+
residual: typing.Optional[torch.Tensor],
|
78 |
+
prob: float) -> torch.Tensor:
|
79 |
+
return bias_dropout_add_scale(
|
80 |
+
x, bias, scale, residual, prob, True)
|
81 |
+
|
82 |
+
|
83 |
+
@torch.jit.script
|
84 |
+
def bias_dropout_add_scale_fused_inference(
|
85 |
+
x: torch.Tensor,
|
86 |
+
bias: typing.Optional[torch.Tensor],
|
87 |
+
scale: torch.Tensor,
|
88 |
+
residual: typing.Optional[torch.Tensor],
|
89 |
+
prob: float) -> torch.Tensor:
|
90 |
+
return bias_dropout_add_scale(
|
91 |
+
x, bias, scale, residual, prob, False)
|
92 |
+
|
93 |
+
|
94 |
+
@torch.jit.script
|
95 |
+
def modulate_fused(x: torch.Tensor,
|
96 |
+
shift: torch.Tensor,
|
97 |
+
scale: torch.Tensor) -> torch.Tensor:
|
98 |
+
return modulate(x, shift, scale)
|
99 |
+
|
100 |
+
|
101 |
+
class Rotary(torch.nn.Module):
|
102 |
+
def __init__(self, dim, base=10_000):
|
103 |
+
super().__init__()
|
104 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
|
105 |
+
self.register_buffer('inv_freq', inv_freq)
|
106 |
+
self.seq_len_cached = None
|
107 |
+
self.cos_cached = None
|
108 |
+
self.sin_cached = None
|
109 |
+
|
110 |
+
def forward(self, x, seq_dim=1):
|
111 |
+
seq_len = x.shape[seq_dim]
|
112 |
+
if seq_len != self.seq_len_cached:
|
113 |
+
self.seq_len_cached = seq_len
|
114 |
+
t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
|
115 |
+
freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
|
116 |
+
emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
117 |
+
# dims are: batch, seq_len, qkv, head, dim
|
118 |
+
self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1,1,3,1,1)
|
119 |
+
self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1,1,3,1,1)
|
120 |
+
# This makes the transformation on v an identity.
|
121 |
+
self.cos_cached[:,:,2,:,:].fill_(1.)
|
122 |
+
self.sin_cached[:,:,2,:,:].fill_(0.)
|
123 |
+
|
124 |
+
return self.cos_cached, self.sin_cached
|
125 |
+
|
126 |
+
|
127 |
+
def rotate_half(x):
|
128 |
+
x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
|
129 |
+
return torch.cat((-x2, x1), dim=-1)
|
130 |
+
|
131 |
+
|
132 |
+
def apply_rotary_pos_emb_torchscript(qkv, cos, sin):
|
133 |
+
return (qkv * cos) + (rotate_half(qkv) * sin)
|
134 |
+
|
135 |
+
def apply_rotary_pos_emb(qkv, cos, sin):
|
136 |
+
cos = cos[0,:,0,0,:cos.shape[-1]//2]
|
137 |
+
sin = sin[0,:,0,0,:sin.shape[-1]//2]
|
138 |
+
return flash_attn.layers.rotary.apply_rotary_emb_qkv_(qkv, cos, sin)
|
139 |
+
|
140 |
+
|
141 |
+
# function overload
|
142 |
+
def modulate(x, shift, scale):
|
143 |
+
return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
|
144 |
+
|
145 |
+
|
146 |
+
#################################################################################
|
147 |
+
# Layers #
|
148 |
+
#################################################################################
|
149 |
+
class LayerNorm(nn.Module):
|
150 |
+
def __init__(self, dim):
|
151 |
+
super().__init__()
|
152 |
+
self.weight = nn.Parameter(torch.ones([dim]))
|
153 |
+
self.dim = dim
|
154 |
+
def forward(self, x):
|
155 |
+
with torch.cuda.amp.autocast(enabled=False):
|
156 |
+
x = F.layer_norm(x.float(), [self.dim])
|
157 |
+
return x * self.weight[None,None,:]
|
158 |
+
|
159 |
+
|
160 |
+
def residual_linear(x, W, x_skip, residual_scale):
|
161 |
+
"""x_skip + residual_scale * W @ x"""
|
162 |
+
dim_out, dim_in = W.shape[0], W.shape[1]
|
163 |
+
return torch.addmm(
|
164 |
+
x_skip.view(-1, dim_out),
|
165 |
+
x.view(-1, dim_in),
|
166 |
+
W.T,
|
167 |
+
alpha=residual_scale).view(*x.shape[:-1], dim_out)
|
168 |
+
|
169 |
+
|
170 |
+
#################################################################################
|
171 |
+
# Embedding Layers for Timesteps and Class Labels #
|
172 |
+
#################################################################################
|
173 |
+
class TimestepEmbedder(nn.Module):
|
174 |
+
"""
|
175 |
+
Embeds scalar timesteps into vector representations.
|
176 |
+
"""
|
177 |
+
def __init__(self, hidden_size, frequency_embedding_size=256):
|
178 |
+
super().__init__()
|
179 |
+
self.mlp = nn.Sequential(
|
180 |
+
nn.Linear(frequency_embedding_size, hidden_size, bias=True),
|
181 |
+
nn.SiLU(),
|
182 |
+
nn.Linear(hidden_size, hidden_size, bias=True))
|
183 |
+
self.frequency_embedding_size = frequency_embedding_size
|
184 |
+
|
185 |
+
@staticmethod
|
186 |
+
def timestep_embedding(t, dim, max_period=10000):
|
187 |
+
"""
|
188 |
+
Create sinusoidal timestep embeddings.
|
189 |
+
:param t: a 1-D Tensor of N indices, one per batch element.
|
190 |
+
These may be fractional.
|
191 |
+
:param dim: the dimension of the output.
|
192 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
193 |
+
:return: an (N, D) Tensor of positional embeddings.
|
194 |
+
"""
|
195 |
+
# https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
|
196 |
+
half = dim // 2
|
197 |
+
freqs = torch.exp(
|
198 |
+
- math.log(max_period)
|
199 |
+
* torch.arange(start=0, end=half, dtype=torch.float32)
|
200 |
+
/ half).to(device=t.device)
|
201 |
+
args = t[:, None].float() * freqs[None]
|
202 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
203 |
+
if dim % 2:
|
204 |
+
embedding = torch.cat(
|
205 |
+
[embedding,
|
206 |
+
torch.zeros_like(embedding[:, :1])], dim=-1)
|
207 |
+
return embedding
|
208 |
+
|
209 |
+
def forward(self, t):
|
210 |
+
t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
|
211 |
+
t_emb = self.mlp(t_freq)
|
212 |
+
return t_emb
|
213 |
+
|
214 |
+
|
215 |
+
class LabelEmbedder(nn.Module):
|
216 |
+
"""Embeds class labels into vector representations.
|
217 |
+
|
218 |
+
Also handles label dropout for classifier-free guidance.
|
219 |
+
"""
|
220 |
+
def __init__(self, num_classes, cond_size):
|
221 |
+
super().__init__()
|
222 |
+
self.embedding_table = nn.Embedding(num_classes + 1, cond_size)
|
223 |
+
self.num_classes = num_classes
|
224 |
+
|
225 |
+
# TODO think of initializing with 0.02 std deviation like in original DiT paper
|
226 |
+
|
227 |
+
def forward(self, labels):
|
228 |
+
embeddings = self.embedding_table(labels)
|
229 |
+
return embeddings
|
230 |
+
|
231 |
+
|
232 |
+
#################################################################################
|
233 |
+
# Core Model #
|
234 |
+
#################################################################################
|
235 |
+
|
236 |
+
def regular_attention_multi_headed(qkv):
|
237 |
+
# Assuming qkv is a tensor with shape [batch, seq_len, 3, num_heads, head_dim]
|
238 |
+
# where the 3 represents Q, K, V packed in that order
|
239 |
+
batch_size, seq_len, _, num_heads, head_dim = qkv.shape
|
240 |
+
# Separate Q, K, V from the packed qkv tensor
|
241 |
+
# [batch_size, seq_len, num_heads, head_dim]
|
242 |
+
q = qkv[:, :, 0, :, :]
|
243 |
+
k = qkv[:, :, 1, :, :]
|
244 |
+
v = qkv[:, :, 2, :, :]
|
245 |
+
|
246 |
+
# Transpose and reshape Q and K for batched matrix multiplication:
|
247 |
+
# [batch_size, num_heads, seq_len, head_dim]
|
248 |
+
q = q.transpose(1, 2)
|
249 |
+
k = k.transpose(1, 2)
|
250 |
+
v = v.transpose(1, 2)
|
251 |
+
|
252 |
+
# Compute scaled dot-product attention
|
253 |
+
# [batch_size, num_heads, seq_len, seq_len]
|
254 |
+
attention_scores = torch.matmul(
|
255 |
+
q, k.transpose(-2, -1)) / math.sqrt(head_dim)
|
256 |
+
|
257 |
+
# Apply softmax to calculate the attention weights
|
258 |
+
attention_probs = F.softmax(attention_scores, dim=-1)
|
259 |
+
|
260 |
+
# [batch_size, num_heads, seq_len, head_dim]
|
261 |
+
attention_output = torch.matmul(attention_probs, v)
|
262 |
+
|
263 |
+
# [batch_size, seq_len, num_heads, head_dim]
|
264 |
+
attention_output = attention_output.transpose(1, 2)
|
265 |
+
return einops.rearrange(attention_output,
|
266 |
+
'b s h d -> b s (h d)')
|
267 |
+
|
268 |
+
|
269 |
+
class DDiTBlock(nn.Module):
|
270 |
+
def __init__(self, n, dim, n_heads, cond_dim, mlp_ratio=4,
|
271 |
+
dropout=0.1, attn_backend='flash_attn'):
|
272 |
+
super().__init__()
|
273 |
+
self.n = n
|
274 |
+
self.n_heads = n_heads
|
275 |
+
self.attn_backend = attn_backend
|
276 |
+
self.kv_cache = None
|
277 |
+
|
278 |
+
self.norm1 = LayerNorm(dim)
|
279 |
+
self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
|
280 |
+
self.attn_out = nn.Linear(dim, dim, bias=False)
|
281 |
+
self.dropout1 = nn.Dropout(dropout)
|
282 |
+
|
283 |
+
self.norm2 = LayerNorm(dim)
|
284 |
+
self.mlp = nn.Sequential(
|
285 |
+
nn.Linear(dim, mlp_ratio * dim, bias=True),
|
286 |
+
nn.GELU(approximate='tanh'),
|
287 |
+
nn.Linear(mlp_ratio * dim, dim, bias=True))
|
288 |
+
self.dropout2 = nn.Dropout(dropout)
|
289 |
+
self.dropout = dropout
|
290 |
+
|
291 |
+
self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim, bias=True)
|
292 |
+
self.adaLN_modulation.weight.data.zero_()
|
293 |
+
self.adaLN_modulation.bias.data.zero_()
|
294 |
+
|
295 |
+
def _get_bias_dropout_scale(self):
|
296 |
+
if self.training:
|
297 |
+
return bias_dropout_add_scale_fused_train
|
298 |
+
else:
|
299 |
+
return bias_dropout_add_scale_fused_inference
|
300 |
+
|
301 |
+
|
302 |
+
def get_qkv(self, x, rotary_cos_sin, save_kv=False):
|
303 |
+
# compute qkv (potentially use cache)
|
304 |
+
if self.kv_cache is not None:
|
305 |
+
block_len = x.shape[1] - self.kv_cache.shape[1]
|
306 |
+
new_qkv = self.attn_qkv(x[:, -block_len:])
|
307 |
+
qkv = torch.cat((self.kv_cache, new_qkv), dim=1)
|
308 |
+
else:
|
309 |
+
qkv = self.attn_qkv(x)
|
310 |
+
|
311 |
+
# save kv cache in a sliding window (can't exceed context len)
|
312 |
+
if save_kv:
|
313 |
+
if self.kv_cache is not None:
|
314 |
+
cache_len = min(x.shape[1], self.n - block_len)
|
315 |
+
self.kv_cache = qkv[:, -cache_len:]
|
316 |
+
else:
|
317 |
+
self.kv_cache = qkv
|
318 |
+
qkv = einops.rearrange(
|
319 |
+
qkv,
|
320 |
+
'b s (three h d) -> b s three h d',
|
321 |
+
three=3,
|
322 |
+
h=self.n_heads)
|
323 |
+
with torch.cuda.amp.autocast(enabled=False):
|
324 |
+
cos, sin = rotary_cos_sin
|
325 |
+
if self.attn_backend == 'flash_attn':
|
326 |
+
qkv = apply_rotary_pos_emb(
|
327 |
+
qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
|
328 |
+
else:
|
329 |
+
qkv = apply_rotary_pos_emb_torchscript(
|
330 |
+
qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
|
331 |
+
return qkv
|
332 |
+
|
333 |
+
def cross_attn(self, x, qkv, cross_attn_mask=None):
|
334 |
+
scale = qkv.shape[-1]
|
335 |
+
qkv = qkv.transpose(1, 3)
|
336 |
+
attn_dropout = self.attn_dropout if self.training else 0.0
|
337 |
+
cross_attn_mask = cross_attn_mask.bool() if cross_attn_mask is not None else None
|
338 |
+
x = F.scaled_dot_product_attention(
|
339 |
+
query=qkv[:, :, 0],
|
340 |
+
key=qkv[:, :, 1],
|
341 |
+
value=qkv[:, :, 2],
|
342 |
+
attn_mask=cross_attn_mask,
|
343 |
+
dropout_p=attn_dropout,
|
344 |
+
is_causal=False,
|
345 |
+
scale=1 / math.sqrt(scale))
|
346 |
+
x = x.transpose(1, 2)
|
347 |
+
x = einops.rearrange(x, 'b s h d -> b s (h d)')
|
348 |
+
return x
|
349 |
+
|
350 |
+
def forward(self, x, rotary_cos_sin, c, cross_attn_mask=None, save_kv=False):
|
351 |
+
bias_dropout_scale_fn = self._get_bias_dropout_scale()
|
352 |
+
|
353 |
+
(shift_msa, scale_msa, gate_msa, shift_mlp,
|
354 |
+
scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
|
355 |
+
|
356 |
+
# attention operation
|
357 |
+
x_skip = x
|
358 |
+
x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
|
359 |
+
|
360 |
+
# get qkvs
|
361 |
+
if cross_attn_mask is not None and not save_kv:
|
362 |
+
qkv_x = self.get_qkv(x[:,:self.n], rotary_cos_sin)
|
363 |
+
qkv_x0 = self.get_qkv(x[:,self.n:], rotary_cos_sin)
|
364 |
+
qkv = torch.cat((qkv_x, qkv_x0), dim=1)
|
365 |
+
else:
|
366 |
+
qkv = self.get_qkv(x, rotary_cos_sin, save_kv=save_kv)
|
367 |
+
|
368 |
+
if cross_attn_mask is None and self.attn_backend == 'flash_attn':
|
369 |
+
x = regular_attention_multi_headed(qkv)
|
370 |
+
else:
|
371 |
+
x = self.cross_attn(x, qkv, cross_attn_mask=cross_attn_mask)
|
372 |
+
|
373 |
+
x = bias_dropout_scale_fn(self.attn_out(x),
|
374 |
+
None,
|
375 |
+
gate_msa,
|
376 |
+
x_skip,
|
377 |
+
self.dropout)
|
378 |
+
|
379 |
+
# mlp operation
|
380 |
+
x = bias_dropout_scale_fn(
|
381 |
+
self.mlp(modulate_fused(
|
382 |
+
self.norm2(x), shift_mlp, scale_mlp)),
|
383 |
+
None, gate_mlp, x, self.dropout)
|
384 |
+
return x
|
385 |
+
|
386 |
+
|
387 |
+
class EmbeddingLayer(nn.Module):
|
388 |
+
def __init__(self, dim, vocab_dim):
|
389 |
+
super().__init__()
|
390 |
+
self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
|
391 |
+
torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
|
392 |
+
|
393 |
+
def forward(self, x):
|
394 |
+
return self.embedding[x]
|
395 |
+
|
396 |
+
|
397 |
+
class DDitFinalLayer(nn.Module):
|
398 |
+
def __init__(self, hidden_size, out_channels, cond_dim):
|
399 |
+
super().__init__()
|
400 |
+
self.norm_final = LayerNorm(hidden_size)
|
401 |
+
self.linear = nn.Linear(hidden_size, out_channels)
|
402 |
+
self.linear.weight.data.zero_()
|
403 |
+
self.linear.bias.data.zero_()
|
404 |
+
|
405 |
+
self.adaLN_modulation = nn.Linear(cond_dim,
|
406 |
+
2 * hidden_size,
|
407 |
+
bias=True)
|
408 |
+
self.adaLN_modulation.weight.data.zero_()
|
409 |
+
self.adaLN_modulation.bias.data.zero_()
|
410 |
+
|
411 |
+
|
412 |
+
def forward(self, x, c):
|
413 |
+
shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
|
414 |
+
x = modulate_fused(self.norm_final(x), shift, scale)
|
415 |
+
x = self.linear(x)
|
416 |
+
return x
|
417 |
+
|
418 |
+
|
419 |
+
class DITBackbone(nn.Module):
|
420 |
+
def __init__(
|
421 |
+
self,
|
422 |
+
config: BD3LMConfig):
|
423 |
+
super().__init__()
|
424 |
+
|
425 |
+
self.config = config
|
426 |
+
self.cross_attn = config.cross_attn
|
427 |
+
self.block_size = config.block_size
|
428 |
+
self.vocab_size = config.vocab_size
|
429 |
+
self.n = config.model_length
|
430 |
+
|
431 |
+
self.vocab_embed = EmbeddingLayer(
|
432 |
+
config.hidden_dim,
|
433 |
+
config.vocab_size)
|
434 |
+
self.sigma_map = TimestepEmbedder(
|
435 |
+
config.cond_dim)
|
436 |
+
self.rotary_emb = Rotary(
|
437 |
+
config.hidden_dim // config.n_heads)
|
438 |
+
|
439 |
+
blocks = []
|
440 |
+
for _ in range(config.n_blocks):
|
441 |
+
blocks.append(DDiTBlock(self.n,
|
442 |
+
config.hidden_dim,
|
443 |
+
config.n_heads,
|
444 |
+
config.cond_dim,
|
445 |
+
dropout=config.dropout,
|
446 |
+
attn_backend=config.attn_backend,))
|
447 |
+
self.blocks = nn.ModuleList(blocks)
|
448 |
+
|
449 |
+
self.output_layer = DDitFinalLayer(
|
450 |
+
config.hidden_dim,
|
451 |
+
config.vocab_size,
|
452 |
+
config.cond_dim)
|
453 |
+
if self.cross_attn:
|
454 |
+
self.gen_mask(config.model_length, self.block_size)
|
455 |
+
self.precision = torch.float32
|
456 |
+
|
457 |
+
def _get_bias_dropout_scale(self):
|
458 |
+
if self.training:
|
459 |
+
return bias_dropout_add_scale_fused_train
|
460 |
+
else:
|
461 |
+
return bias_dropout_add_scale_fused_inference
|
462 |
+
|
463 |
+
def gen_mask(self, seqlen, block_size):
|
464 |
+
self_attn_mask = block_causal_mask(seqlen, block_size, mode='diag')
|
465 |
+
x0_attn_mask = block_causal_mask(seqlen, block_size, mode='full')
|
466 |
+
cross_attn_mask = x0_attn_mask.clone()
|
467 |
+
cross_attn_mask.masked_fill_(self_attn_mask == 1, 0)
|
468 |
+
|
469 |
+
cross_attn_mask = torch.cat((self_attn_mask, cross_attn_mask), dim=1)
|
470 |
+
x0_attn_mask = torch.cat((torch.zeros_like(self_attn_mask), x0_attn_mask), dim=1)
|
471 |
+
self.cross_attn_mask = torch.cat((cross_attn_mask, x0_attn_mask), dim=0)
|
472 |
+
|
473 |
+
def forward(self, indices, sigma, disable_cross_attn=False,
|
474 |
+
output_hidden_states=False, save_kv=False):
|
475 |
+
cross_attn = self.cross_attn and not disable_cross_attn
|
476 |
+
if not self.config.time_conditioning:
|
477 |
+
sigma = torch.zeros_like(sigma)
|
478 |
+
all_hidden_states = []
|
479 |
+
x = self.vocab_embed(indices)
|
480 |
+
if output_hidden_states:
|
481 |
+
all_hidden_states.append(x)
|
482 |
+
c = F.silu(self.sigma_map(sigma))
|
483 |
+
if cross_attn:
|
484 |
+
cross_attn_mask = self.cross_attn_mask.to(x.device)
|
485 |
+
if save_kv:
|
486 |
+
cross_attn_mask = cross_attn_mask[:x.shape[1], :x.shape[1]]
|
487 |
+
rotary_cos_sin = self.rotary_emb(x[:, :self.n])
|
488 |
+
else:
|
489 |
+
cross_attn_mask = None
|
490 |
+
rotary_cos_sin = self.rotary_emb(x)
|
491 |
+
|
492 |
+
with torch.cuda.amp.autocast(dtype=self.precision):
|
493 |
+
for i in range(len(self.blocks)):
|
494 |
+
x = self.blocks[i](x,
|
495 |
+
rotary_cos_sin,
|
496 |
+
c,
|
497 |
+
cross_attn_mask=cross_attn_mask,
|
498 |
+
save_kv=save_kv)
|
499 |
+
if output_hidden_states:
|
500 |
+
all_hidden_states.append(x)
|
501 |
+
logits = self.output_layer(x, c)
|
502 |
+
if cross_attn and not save_kv:
|
503 |
+
logits = logits[:, :self.n]
|
504 |
+
all_hidden_states = [hidden_states[:, :self.n] for hidden_states in all_hidden_states]
|
505 |
+
return logits, all_hidden_states
|
506 |
+
|
507 |
+
class BD3LM(transformers.PreTrainedModel):
|
508 |
+
"""HF-compatible model."""
|
509 |
+
config_class = BD3LMConfig
|
510 |
+
base_model_prefix = "bd3lm"
|
511 |
+
|
512 |
+
def __init__(
|
513 |
+
self,
|
514 |
+
config: BD3LMConfig):
|
515 |
+
super().__init__(config)
|
516 |
+
self.backbone = DITBackbone(config)
|
517 |
+
if config.var_min:
|
518 |
+
self.register_buffer(
|
519 |
+
'sampling_eps_min',
|
520 |
+
torch.tensor(config.sampling_eps_min))
|
521 |
+
self.register_buffer(
|
522 |
+
'sampling_eps_max',
|
523 |
+
torch.tensor(config.sampling_eps_max))
|
524 |
+
|
525 |
+
def forward(
|
526 |
+
self,
|
527 |
+
input_ids: torch.LongTensor = None,
|
528 |
+
timesteps: torch.FloatTensor = None,
|
529 |
+
disable_cross_attn: typing.Optional[bool] = None,
|
530 |
+
output_hidden_states: typing.Optional[bool] = None,
|
531 |
+
return_dict: typing.Optional[bool] = None,
|
532 |
+
) -> typing.Union[
|
533 |
+
torch.Tensor, typing.Tuple,
|
534 |
+
modeling_outputs.MaskedLMOutput]:
|
535 |
+
"""HF-compatible forward method."""
|
536 |
+
output_hidden_states = (
|
537 |
+
output_hidden_states
|
538 |
+
if output_hidden_states is not None
|
539 |
+
else self.config.output_hidden_states
|
540 |
+
)
|
541 |
+
return_dict = return_dict \
|
542 |
+
if return_dict is not None \
|
543 |
+
else self.config.use_return_dict
|
544 |
+
|
545 |
+
logits, all_hidden_states = self.backbone(
|
546 |
+
indices=input_ids,
|
547 |
+
sigma=timesteps,
|
548 |
+
disable_cross_attn=disable_cross_attn,
|
549 |
+
output_hidden_states=output_hidden_states
|
550 |
+
)
|
551 |
+
if return_dict:
|
552 |
+
return modeling_outputs.MaskedLMOutput(
|
553 |
+
logits=logits,
|
554 |
+
hidden_states=all_hidden_states if output_hidden_states else None,
|
555 |
+
loss=None
|
556 |
+
)
|
557 |
+
elif output_hidden_states:
|
558 |
+
return logits, all_hidden_states
|
559 |
+
else:
|
560 |
+
return logits
|