marriola commited on
Commit
a61c637
·
verified ·
1 Parent(s): aa9d3f4

Upload BAMDLM

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +28 -0
  3. configuration_bamdlm.py +43 -0
  4. model.safetensors +3 -0
  5. modeling_bamdlm.py +538 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "kuleshov-group/bamdlm-owt-block_size8",
3
+ "architectures": [
4
+ "BAMDLM"
5
+ ],
6
+ "attn_backend": "sdpa",
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_bamdlm.BAMDLMConfig",
9
+ "AutoModelForMaskedLM": "modeling_bamdlm.BAMDLM"
10
+ },
11
+ "block_size": 8,
12
+ "cond_dim": 128,
13
+ "cross_attn": true,
14
+ "dropout": 0.1,
15
+ "hidden_dim": 768,
16
+ "model_length": 1024,
17
+ "model_type": "bamdlm",
18
+ "n_blocks": 12,
19
+ "n_heads": 12,
20
+ "return_dict": false,
21
+ "sampling_eps_max": 0.999,
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": 50258
28
+ }
configuration_bamdlm.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BAMDLM config for Hugging Face.
2
+
3
+ """
4
+
5
+ import transformers
6
+
7
+
8
+ class BAMDLMConfig(transformers.PretrainedConfig):
9
+ """Hugging Face configuration class for BAMDLM."""
10
+ model_type = "bamdlm"
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
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e5ad9cca0e9f1562edcb4db1426d806d83a1faa25945f6e291395e673eca229
3
+ size 678522896
modeling_bamdlm.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BAMDLM 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_bamdlm import BAMDLMConfig
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, dim, n_heads, cond_dim, mlp_ratio=4,
271
+ dropout=0.1, attn_backend='flash_attn'):
272
+ super().__init__()
273
+ self.n_heads = n_heads
274
+ self.attn_backend = attn_backend
275
+
276
+ self.norm1 = LayerNorm(dim)
277
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
278
+ self.attn_out = nn.Linear(dim, dim, bias=False)
279
+ self.dropout1 = nn.Dropout(dropout)
280
+
281
+ self.norm2 = LayerNorm(dim)
282
+ self.mlp = nn.Sequential(
283
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
284
+ nn.GELU(approximate='tanh'),
285
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
286
+ self.dropout2 = nn.Dropout(dropout)
287
+ self.dropout = dropout
288
+
289
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim, bias=True)
290
+ self.adaLN_modulation.weight.data.zero_()
291
+ self.adaLN_modulation.bias.data.zero_()
292
+
293
+ def _get_bias_dropout_scale(self):
294
+ if self.training:
295
+ return bias_dropout_add_scale_fused_train
296
+ else:
297
+ return bias_dropout_add_scale_fused_inference
298
+
299
+
300
+ def get_qkv(self, x, rotary_cos_sin):
301
+ qkv = self.attn_qkv(x)
302
+ qkv = einops.rearrange(
303
+ qkv,
304
+ 'b s (three h d) -> b s three h d',
305
+ three=3,
306
+ h=self.n_heads)
307
+ with torch.cuda.amp.autocast(enabled=False):
308
+ cos, sin = rotary_cos_sin
309
+ if self.attn_backend == 'flash_attn':
310
+ qkv = apply_rotary_pos_emb(
311
+ qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
312
+ else:
313
+ qkv = apply_rotary_pos_emb_torchscript(
314
+ qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
315
+ return qkv
316
+
317
+ def cross_attn(self, x, rotary_cos_sin, cross_attn_mask=None):
318
+ if cross_attn_mask is not None:
319
+ n = x.shape[1] // 2
320
+ qkv_x = self.get_qkv(x[:,:n], rotary_cos_sin)
321
+ qkv_x0 = self.get_qkv(x[:,n:], rotary_cos_sin)
322
+ qkv = torch.cat((qkv_x, qkv_x0), dim=1)
323
+ else:
324
+ qkv = self.get_qkv(x, rotary_cos_sin)
325
+ scale = qkv.shape[-1]
326
+ qkv = qkv.transpose(1, 3)
327
+ attn_dropout = self.attn_dropout if self.training else 0.0
328
+ cross_attn_mask = cross_attn_mask.bool() if cross_attn_mask is not None else None
329
+ x = F.scaled_dot_product_attention(
330
+ query=qkv[:, :, 0],
331
+ key=qkv[:, :, 1],
332
+ value=qkv[:, :, 2],
333
+ attn_mask=cross_attn_mask,
334
+ dropout_p=attn_dropout,
335
+ is_causal=False,
336
+ scale=1 / math.sqrt(scale))
337
+ x = x.transpose(1, 2)
338
+ x = einops.rearrange(x, 'b s h d -> b s (h d)')
339
+ return x
340
+
341
+ def forward(self, x, rotary_cos_sin, c, cross_attn_mask=None):
342
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
343
+
344
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
345
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
346
+
347
+ # attention operation
348
+ x_skip = x
349
+ x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
350
+
351
+ if cross_attn_mask is None and self.attn_backend == 'flash_attn':
352
+ qkv = self.attn_qkv(x)
353
+ x = regular_attention_multi_headed(qkv)
354
+ else:
355
+ x = self.cross_attn(x, rotary_cos_sin, cross_attn_mask=cross_attn_mask)
356
+
357
+ x = bias_dropout_scale_fn(self.attn_out(x),
358
+ None,
359
+ gate_msa,
360
+ x_skip,
361
+ self.dropout)
362
+
363
+ # mlp operation
364
+ x = bias_dropout_scale_fn(
365
+ self.mlp(modulate_fused(
366
+ self.norm2(x), shift_mlp, scale_mlp)),
367
+ None, gate_mlp, x, self.dropout)
368
+ return x
369
+
370
+
371
+ class EmbeddingLayer(nn.Module):
372
+ def __init__(self, dim, vocab_dim):
373
+ super().__init__()
374
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
375
+ torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
376
+
377
+ def forward(self, x):
378
+ return self.embedding[x]
379
+
380
+
381
+ class DDitFinalLayer(nn.Module):
382
+ def __init__(self, hidden_size, out_channels, cond_dim):
383
+ super().__init__()
384
+ self.norm_final = LayerNorm(hidden_size)
385
+ self.linear = nn.Linear(hidden_size, out_channels)
386
+ self.linear.weight.data.zero_()
387
+ self.linear.bias.data.zero_()
388
+
389
+ self.adaLN_modulation = nn.Linear(cond_dim,
390
+ 2 * hidden_size,
391
+ bias=True)
392
+ self.adaLN_modulation.weight.data.zero_()
393
+ self.adaLN_modulation.bias.data.zero_()
394
+
395
+
396
+ def forward(self, x, c):
397
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
398
+ x = modulate_fused(self.norm_final(x), shift, scale)
399
+ x = self.linear(x)
400
+ return x
401
+
402
+
403
+ class DITBackbone(nn.Module):
404
+ def __init__(
405
+ self,
406
+ config: BAMDLMConfig):
407
+ super().__init__()
408
+
409
+ self.config = config
410
+ self.cross_attn = config.cross_attn
411
+ self.block_size = config.block_size
412
+ self.vocab_size = config.vocab_size
413
+
414
+ self.vocab_embed = EmbeddingLayer(
415
+ config.hidden_dim,
416
+ config.vocab_size)
417
+ self.sigma_map = TimestepEmbedder(
418
+ config.cond_dim)
419
+ self.rotary_emb = Rotary(
420
+ config.hidden_dim // config.n_heads)
421
+
422
+ blocks = []
423
+ for _ in range(config.n_blocks):
424
+ blocks.append(DDiTBlock(config.hidden_dim,
425
+ config.n_heads,
426
+ config.cond_dim,
427
+ dropout=config.dropout,
428
+ attn_backend=config.attn_backend,))
429
+ self.blocks = nn.ModuleList(blocks)
430
+
431
+ self.output_layer = DDitFinalLayer(
432
+ config.hidden_dim,
433
+ config.vocab_size,
434
+ config.cond_dim)
435
+ if self.cross_attn:
436
+ self.gen_mask(config.model_length, self.block_size)
437
+ self.precision = torch.float32
438
+
439
+ def _get_bias_dropout_scale(self):
440
+ if self.training:
441
+ return bias_dropout_add_scale_fused_train
442
+ else:
443
+ return bias_dropout_add_scale_fused_inference
444
+
445
+ def gen_mask(self, seqlen, block_size):
446
+ self_attn_mask = block_causal_mask(seqlen, block_size, mode='diag')
447
+ x0_attn_mask = block_causal_mask(seqlen, block_size, mode='full')
448
+ cross_attn_mask = x0_attn_mask.clone()
449
+ cross_attn_mask.masked_fill_(self_attn_mask == 1, 0)
450
+
451
+ cross_attn_mask = torch.cat((self_attn_mask, cross_attn_mask), dim=1)
452
+ x0_attn_mask = torch.cat((torch.zeros_like(self_attn_mask), x0_attn_mask), dim=1)
453
+ self.cross_attn_mask = torch.cat((cross_attn_mask, x0_attn_mask), dim=0)
454
+
455
+ def forward(self, indices, sigma, disable_cross_attn=False,
456
+ output_hidden_states=False):
457
+ cross_attn = self.cross_attn and not disable_cross_attn
458
+ if not self.config.time_conditioning:
459
+ sigma = torch.zeros_like(sigma)
460
+ all_hidden_states = []
461
+ x = self.vocab_embed(indices)
462
+ if output_hidden_states:
463
+ all_hidden_states.append(x)
464
+ c = F.silu(self.sigma_map(sigma))
465
+ if cross_attn:
466
+ cross_attn_mask = self.cross_attn_mask.to(x.device)
467
+ n = x.shape[1] // 2
468
+ rotary_cos_sin = self.rotary_emb(x[:, :n])
469
+ else:
470
+ cross_attn_mask = None
471
+ rotary_cos_sin = self.rotary_emb(x)
472
+
473
+ with torch.cuda.amp.autocast(dtype=self.precision):
474
+ for i in range(len(self.blocks)):
475
+ x = self.blocks[i](x, rotary_cos_sin, c,
476
+ cross_attn_mask=cross_attn_mask,)
477
+ if output_hidden_states:
478
+ all_hidden_states.append(x)
479
+ logits = self.output_layer(x, c)
480
+ if cross_attn:
481
+ logits = logits[:, :n]
482
+ all_hidden_states = [hidden_states[:, :n] for hidden_states in all_hidden_states]
483
+ return logits, all_hidden_states
484
+
485
+ class BAMDLM(transformers.PreTrainedModel):
486
+ """HF-compatible model."""
487
+ config_class = BAMDLMConfig
488
+ base_model_prefix = "bamdlm"
489
+
490
+ def __init__(
491
+ self,
492
+ config: BAMDLMConfig):
493
+ super().__init__(config)
494
+ self.backbone = DITBackbone(config)
495
+ if config.var_min:
496
+ self.register_buffer(
497
+ 'sampling_eps_min',
498
+ torch.tensor(config.sampling_eps_min))
499
+ self.register_buffer(
500
+ 'sampling_eps_max',
501
+ torch.tensor(config.sampling_eps_max))
502
+
503
+ def forward(
504
+ self,
505
+ input_ids: torch.LongTensor = None,
506
+ timesteps: torch.FloatTensor = None,
507
+ disable_cross_attn: typing.Optional[bool] = None,
508
+ output_hidden_states: typing.Optional[bool] = None,
509
+ return_dict: typing.Optional[bool] = None,
510
+ ) -> typing.Union[
511
+ torch.Tensor, typing.Tuple,
512
+ modeling_outputs.MaskedLMOutput]:
513
+ """HF-compatible forward method."""
514
+ output_hidden_states = (
515
+ output_hidden_states
516
+ if output_hidden_states is not None
517
+ else self.config.output_hidden_states
518
+ )
519
+ return_dict = return_dict \
520
+ if return_dict is not None \
521
+ else self.config.use_return_dict
522
+
523
+ logits, all_hidden_states = self.backbone(
524
+ indices=input_ids,
525
+ sigma=timesteps,
526
+ disable_cross_attn=disable_cross_attn,
527
+ output_hidden_states=output_hidden_states
528
+ )
529
+ if return_dict:
530
+ return modeling_outputs.MaskedLMOutput(
531
+ logits=logits,
532
+ hidden_states=all_hidden_states if output_hidden_states else None,
533
+ loss=None
534
+ )
535
+ elif output_hidden_states:
536
+ return logits, all_hidden_states
537
+ else:
538
+ return logits