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