Fill-Mask
Transformers
Safetensors
English
mdlm
custom_code
subbham commited on
Commit
19f029e
1 Parent(s): 72bf2e0

Upload MDLM

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