yairschiff commited on
Commit
25ce5c5
1 Parent(s): 7896a73

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.py +450 -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-owt",
3
+ "architectures": [
4
+ "MDLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_mdlm.MDLMConfig",
8
+ "AutoModelForMaskedLM": "modeling_mdlm.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.py ADDED
@@ -0,0 +1,450 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MDLM model for Hugging Face.
2
+
3
+ """
4
+ import itertools
5
+ import math
6
+ import typing
7
+
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 einops import rearrange
15
+ from transformers import modeling_outputs
16
+
17
+ from .configuration_mdlm import MDLMConfig
18
+
19
+ # Flags required to enable jit fusion kernels
20
+ torch._C._jit_set_profiling_mode(False)
21
+ torch._C._jit_set_profiling_executor(False)
22
+ torch._C._jit_override_can_fuse_on_cpu(True)
23
+ torch._C._jit_override_can_fuse_on_gpu(True)
24
+
25
+
26
+ def bias_dropout_add_scale(
27
+ x: torch.Tensor,
28
+ bias: typing.Optional[torch.Tensor],
29
+ scale: torch.Tensor,
30
+ residual: typing.Optional[torch.Tensor],
31
+ prob: float,
32
+ training: bool) -> torch.Tensor:
33
+ if bias is not None:
34
+ out = scale * F.dropout(x + bias, p=prob,
35
+ 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 / (
92
+ base ** (torch.arange(0, dim, 2).float() / dim))
93
+ self.register_buffer('inv_freq', inv_freq)
94
+ self.seq_len_cached = None
95
+ self.cos_cached = None
96
+ self.sin_cached = None
97
+
98
+ def forward(self, x, seq_dim=1):
99
+ seq_len = x.shape[seq_dim]
100
+ if seq_len != self.seq_len_cached:
101
+ self.seq_len_cached = seq_len
102
+ t = torch.arange(x.shape[seq_dim],
103
+ device=x.device).type_as(
104
+ self.inv_freq)
105
+ freqs = torch.einsum("i,j->ij", t,
106
+ self.inv_freq.clone())
107
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
108
+ # dims are: batch, seq_len, qkv, head, dim
109
+ self.cos_cached = emb.cos()[None, :, None, None,
110
+ :].repeat(1, 1, 3, 1, 1)
111
+ self.sin_cached = emb.sin()[None, :, None, None,
112
+ :].repeat(1, 1, 3, 1, 1)
113
+ # This makes the transformation on v an identity.
114
+ self.cos_cached[:, :, 2, :, :].fill_(1.)
115
+ self.sin_cached[:, :, 2, :, :].fill_(0.)
116
+
117
+ return self.cos_cached, self.sin_cached
118
+
119
+
120
+ def rotate_half(x):
121
+ x1, x2 = x[..., : x.shape[-1] // 2], x[...,
122
+ x.shape[-1] // 2:]
123
+ return torch.cat((-x2, x1), dim=-1)
124
+
125
+
126
+ def apply_rotary_pos_emb(qkv, cos, sin):
127
+ cos = cos[0, :, 0, 0, :cos.shape[-1] // 2]
128
+ sin = sin[0, :, 0, 0, :sin.shape[-1] // 2]
129
+ return flash_attn.layers.rotary.apply_rotary_emb_qkv_(qkv,
130
+ cos,
131
+ sin)
132
+ # function overload
133
+ def modulate(x, shift, scale):
134
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
135
+
136
+
137
+ ############################################################
138
+ # Layers #
139
+ ############################################################
140
+ class LayerNorm(nn.Module):
141
+ def __init__(self, dim):
142
+ super().__init__()
143
+ self.weight = nn.Parameter(torch.ones([dim]))
144
+ self.dim = dim
145
+
146
+ def forward(self, x):
147
+ with torch.cuda.amp.autocast(enabled=False):
148
+ x = F.layer_norm(x.float(), [self.dim])
149
+ return x * self.weight[None, None, :]
150
+
151
+
152
+ def residual_linear(x, W, x_skip, residual_scale):
153
+ """x_skip + residual_scale * W @ x"""
154
+ dim_out, dim_in = W.shape[0], W.shape[1]
155
+ return torch.addmm(
156
+ x_skip.view(-1, dim_out),
157
+ x.view(-1, dim_in),
158
+ W.T,
159
+ alpha=residual_scale).view(*x.shape[:-1], dim_out)
160
+
161
+
162
+ ############################################################
163
+ # Embedding Layers for Timesteps and Class Labels #
164
+ ############################################################
165
+ class TimestepEmbedder(nn.Module):
166
+ """
167
+ Embeds scalar timesteps into vector representations.
168
+ """
169
+
170
+ def __init__(self, hidden_size,
171
+ frequency_embedding_size=256):
172
+ super().__init__()
173
+ self.mlp = nn.Sequential(
174
+ nn.Linear(frequency_embedding_size, hidden_size,
175
+ bias=True),
176
+ nn.SiLU(),
177
+ nn.Linear(hidden_size, hidden_size, bias=True))
178
+ self.frequency_embedding_size = frequency_embedding_size
179
+
180
+ @staticmethod
181
+ def timestep_embedding(t, dim, max_period=10000):
182
+ """
183
+ Create sinusoidal timestep embeddings.
184
+ :param t: a 1-D Tensor of N indices, one per batch
185
+ element. These may be fractional.
186
+ :param dim: the dimension of the output.
187
+ :param max_period: controls the minimum frequency of the
188
+ embeddings.
189
+ :return: an (N, D) Tensor of positional embeddings.
190
+ """
191
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
192
+ half = dim // 2
193
+ freqs = torch.exp(
194
+ - math.log(max_period)
195
+ * torch.arange(start=0, end=half, dtype=torch.float32)
196
+ / half).to(device=t.device)
197
+ args = t[:, None].float() * freqs[None]
198
+ embedding = torch.cat(
199
+ [torch.cos(args), torch.sin(args)], dim=-1)
200
+ if dim % 2:
201
+ embedding = torch.cat(
202
+ [embedding,
203
+ torch.zeros_like(embedding[:, :1])], dim=-1)
204
+ return embedding
205
+
206
+ def forward(self, t):
207
+ t_freq = self.timestep_embedding(t,
208
+ self.frequency_embedding_size)
209
+ t_emb = self.mlp(t_freq)
210
+ return t_emb
211
+
212
+
213
+ class LabelEmbedder(nn.Module):
214
+ """Embeds class labels into vector representations.
215
+
216
+ Also handles label dropout for classifier-free guidance.
217
+ """
218
+
219
+ def __init__(self, num_classes, cond_size):
220
+ super().__init__()
221
+ self.embedding_table = nn.Embedding(num_classes + 1,
222
+ 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
+
237
+ class DDiTBlock(nn.Module):
238
+ def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4,
239
+ dropout=0.1):
240
+ super().__init__()
241
+ self.n_heads = n_heads
242
+
243
+ self.norm1 = LayerNorm(dim)
244
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
245
+ self.attn_out = nn.Linear(dim, dim, bias=False)
246
+ self.dropout1 = nn.Dropout(dropout)
247
+
248
+ self.norm2 = LayerNorm(dim)
249
+ self.mlp = nn.Sequential(
250
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
251
+ nn.GELU(approximate='tanh'),
252
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
253
+ self.dropout2 = nn.Dropout(dropout)
254
+ self.dropout = dropout
255
+
256
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim,
257
+ bias=True)
258
+ self.adaLN_modulation.weight.data.zero_()
259
+ self.adaLN_modulation.bias.data.zero_()
260
+
261
+ def _get_bias_dropout_scale(self):
262
+ if self.training:
263
+ return bias_dropout_add_scale_fused_train
264
+ else:
265
+ return bias_dropout_add_scale_fused_inference
266
+
267
+ def forward(self, x, rotary_cos_sin, c, seqlens=None):
268
+ batch_size, seq_len = x.shape[0], x.shape[1]
269
+
270
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
271
+
272
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
273
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:,
274
+ None].chunk(6, dim=2)
275
+
276
+ # attention operation
277
+ x_skip = x
278
+ x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
279
+
280
+ qkv = self.attn_qkv(x)
281
+ qkv = rearrange(qkv,
282
+ 'b s (three h d) -> b s three h d',
283
+ three=3,
284
+ h=self.n_heads)
285
+ with torch.cuda.amp.autocast(enabled=False):
286
+ cos, sin = rotary_cos_sin
287
+ qkv = apply_rotary_pos_emb(
288
+ qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
289
+ qkv = rearrange(qkv, 'b s ... -> (b s) ...')
290
+ if seqlens is None:
291
+ cu_seqlens = torch.arange(
292
+ 0, (batch_size + 1) * seq_len, step=seq_len,
293
+ dtype=torch.int32, device=qkv.device)
294
+ else:
295
+ cu_seqlens = seqlens.cumsum(-1)
296
+ x = flash_attn.flash_attn_interface.flash_attn_varlen_qkvpacked_func(
297
+ qkv, cu_seqlens, seq_len, 0., causal=False)
298
+
299
+ x = rearrange(x, '(b s) h d -> b s (h d)', b=batch_size)
300
+
301
+ x = bias_dropout_scale_fn(self.attn_out(x),
302
+ None,
303
+ gate_msa,
304
+ x_skip,
305
+ self.dropout)
306
+
307
+ # mlp operation
308
+ x = bias_dropout_scale_fn(
309
+ self.mlp(modulate_fused(
310
+ self.norm2(x), shift_mlp, scale_mlp)),
311
+ None, gate_mlp, x, self.dropout)
312
+ return x
313
+
314
+
315
+ class EmbeddingLayer(nn.Module):
316
+ def __init__(self, dim, vocab_dim):
317
+ super().__init__()
318
+ self.embedding = nn.Parameter(
319
+ torch.empty((vocab_dim, dim)))
320
+ torch.nn.init.kaiming_uniform_(self.embedding,
321
+ a=math.sqrt(5))
322
+
323
+ def forward(self, x):
324
+ return self.embedding[x]
325
+
326
+
327
+ class DDitFinalLayer(nn.Module):
328
+ def __init__(self, hidden_size, out_channels, cond_dim):
329
+ super().__init__()
330
+ self.norm_final = LayerNorm(hidden_size)
331
+ self.linear = nn.Linear(hidden_size, out_channels)
332
+ self.linear.weight.data.zero_()
333
+ self.linear.bias.data.zero_()
334
+
335
+ self.adaLN_modulation = nn.Linear(cond_dim,
336
+ 2 * hidden_size,
337
+ bias=True)
338
+ self.adaLN_modulation.weight.data.zero_()
339
+ self.adaLN_modulation.bias.data.zero_()
340
+
341
+ def forward(self, x, c):
342
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(
343
+ 2, dim=2)
344
+ x = modulate_fused(self.norm_final(x), shift, scale)
345
+ x = self.linear(x)
346
+ return x
347
+
348
+
349
+ class DITBackbone(nn.Module):
350
+ def __init__(
351
+ self,
352
+ config: MDLMConfig):
353
+ super().__init__()
354
+
355
+ self.config = config
356
+ self.vocab_size = config.vocab_size
357
+
358
+ self.vocab_embed = EmbeddingLayer(
359
+ config.hidden_dim,
360
+ config.vocab_size)
361
+ self.sigma_map = TimestepEmbedder(
362
+ config.cond_dim)
363
+ self.rotary_emb = Rotary(
364
+ config.hidden_dim // config.n_heads)
365
+
366
+ blocks = []
367
+ for _ in range(config.n_blocks):
368
+ blocks.append(DDiTBlock(config.hidden_dim,
369
+ config.n_heads,
370
+ config.cond_dim,
371
+ dropout=config.dropout))
372
+ self.blocks = nn.ModuleList(blocks)
373
+
374
+ self.output_layer = DDitFinalLayer(
375
+ config.hidden_dim,
376
+ config.vocab_size,
377
+ config.cond_dim)
378
+
379
+ def _get_bias_dropout_scale(self):
380
+ if self.training:
381
+ return bias_dropout_add_scale_fused_train
382
+ else:
383
+ return bias_dropout_add_scale_fused_inference
384
+
385
+ def forward(self, indices, sigma,
386
+ output_hidden_states=False):
387
+ if not self.config.time_conditioning:
388
+ sigma = torch.zeros_like(sigma)
389
+ all_hidden_states = []
390
+ x = self.vocab_embed(indices)
391
+ if output_hidden_states:
392
+ all_hidden_states.append(x)
393
+ c = F.silu(self.sigma_map(sigma))
394
+
395
+ rotary_cos_sin = self.rotary_emb(x)
396
+
397
+ with torch.cuda.amp.autocast(dtype=torch.bfloat16):
398
+ for i in range(len(self.blocks)):
399
+ x = self.blocks[i](x, rotary_cos_sin, c,
400
+ seqlens=None)
401
+ if output_hidden_states:
402
+ all_hidden_states.append(x)
403
+ logits = self.output_layer(x, c)
404
+ return logits, all_hidden_states
405
+
406
+ class MDLM(transformers.PreTrainedModel):
407
+ """HF-compatible model."""
408
+ config_class = MDLMConfig
409
+ base_model_prefix = "mdlm"
410
+
411
+ def __init__(
412
+ self,
413
+ config: MDLMConfig):
414
+ super().__init__(config)
415
+ self.backbone = DITBackbone(config)
416
+
417
+ def forward(
418
+ self,
419
+ input_ids: torch.LongTensor = None,
420
+ timesteps: torch.FloatTensor = None,
421
+ output_hidden_states: typing.Optional[bool] = None,
422
+ return_dict: typing.Optional[bool] = None,
423
+ ) -> typing.Union[
424
+ torch.Tensor, typing.Tuple,
425
+ modeling_outputs.MaskedLMOutput]:
426
+ """HF-compatible forward method."""
427
+ output_hidden_states = (
428
+ output_hidden_states
429
+ if output_hidden_states is not None
430
+ else self.config.output_hidden_states
431
+ )
432
+ return_dict = return_dict \
433
+ if return_dict is not None \
434
+ else self.config.use_return_dict
435
+
436
+ logits, all_hidden_states = self.backbone(
437
+ indices=input_ids,
438
+ sigma=timesteps,
439
+ output_hidden_states=output_hidden_states
440
+ )
441
+ if return_dict:
442
+ return modeling_outputs.MaskedLMOutput(
443
+ logits=logits,
444
+ hidden_states=all_hidden_states if output_hidden_states else None,
445
+ loss=None
446
+ )
447
+ elif output_hidden_states:
448
+ return logits, all_hidden_states
449
+ else:
450
+ return logits