Fill-Mask
Transformers
Safetensors
udlm
custom_code
yairschiff commited on
Commit
8b5f951
·
verified ·
1 Parent(s): 3d2c59c

Upload UDLM

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