Subham Sekhar Sahoo commited on
Commit
32f5cf4
·
verified ·
1 Parent(s): bd040b9

Upload DUO

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +23 -0
  3. config.py +29 -0
  4. model.py +601 -0
  5. model.safetensors +3 -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,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "subbham/duo-distilled",
3
+ "architectures": [
4
+ "DUO"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "config.DUOConfig",
8
+ "AutoModelForMaskedLM": "model.DUO"
9
+ },
10
+ "causal": false,
11
+ "cond_dim": 128,
12
+ "dropout": 0.1,
13
+ "hidden_dim": 768,
14
+ "model_length": 1024,
15
+ "model_type": "DUO",
16
+ "n_blocks": 12,
17
+ "n_heads": 12,
18
+ "return_dict": false,
19
+ "torch_dtype": "float32",
20
+ "transformers_version": "4.38.2",
21
+ "var_min": true,
22
+ "vocab_size": 50258
23
+ }
config.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import transformers
2
+
3
+
4
+ class DUOConfig(transformers.PretrainedConfig):
5
+ """Hugging Face configuration class for DUO."""
6
+ model_type = 'DUO'
7
+
8
+ def __init__(
9
+ self,
10
+ vocab_size: int = 50258,
11
+ model_length: int = 1024,
12
+ causal: bool = False,
13
+ hidden_dim: int = 768,
14
+ cond_dim: int = 129,
15
+ n_blocks: int = 12,
16
+ n_heads: int = 12,
17
+ dropout: float = 0.1,
18
+ var_min: bool = True,
19
+ ** kwargs):
20
+ super().__init__(**kwargs)
21
+ self.causal = causal
22
+ self.vocab_size = vocab_size
23
+ self.model_length = model_length
24
+ self.hidden_dim = hidden_dim
25
+ self.cond_dim = cond_dim
26
+ self.n_blocks = n_blocks
27
+ self.n_heads = n_heads
28
+ self.dropout = dropout
29
+ self.var_min = var_min
model.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import typing
3
+
4
+ import einops
5
+ import flash_attn
6
+ import flash_attn.layers.rotary
7
+ import huggingface_hub
8
+ import omegaconf
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import transformers
13
+
14
+ from .config import DUOConfig
15
+
16
+ # Flags required to enable jit fusion kernels
17
+ torch._C._jit_set_profiling_mode(False)
18
+ torch._C._jit_set_profiling_executor(False)
19
+ torch._C._jit_override_can_fuse_on_cpu(True)
20
+ torch._C._jit_override_can_fuse_on_gpu(True)
21
+
22
+
23
+ def bias_dropout_add_scale(
24
+ x: torch.Tensor,
25
+ bias: typing.Optional[torch.Tensor],
26
+ scale: torch.Tensor,
27
+ residual: typing.Optional[torch.Tensor],
28
+ prob: float,
29
+ training: bool) -> torch.Tensor:
30
+ if bias is not None:
31
+ out = scale * F.dropout(x + bias, p=prob, training=training)
32
+ else:
33
+ out = scale * F.dropout(x, p=prob, training=training)
34
+
35
+ if residual is not None:
36
+ out = residual + out
37
+ return out
38
+
39
+
40
+ def get_bias_dropout_add_scale(training):
41
+ def _bias_dropout_add(x, bias, scale, residual, prob):
42
+ return bias_dropout_add_scale(
43
+ x, bias, scale, residual, prob, training)
44
+
45
+ return _bias_dropout_add
46
+
47
+
48
+ # function overload
49
+ def modulate(x: torch.Tensor,
50
+ shift: torch.Tensor,
51
+ scale: torch.Tensor) -> torch.Tensor:
52
+ return x * (1 + scale) + shift
53
+
54
+
55
+ @torch.jit.script
56
+ def bias_dropout_add_scale_fused_train(
57
+ x: torch.Tensor,
58
+ bias: typing.Optional[torch.Tensor],
59
+ scale: torch.Tensor,
60
+ residual: typing.Optional[torch.Tensor],
61
+ prob: float) -> torch.Tensor:
62
+ return bias_dropout_add_scale(
63
+ x, bias, scale, residual, prob, True)
64
+
65
+
66
+ @torch.jit.script
67
+ def bias_dropout_add_scale_fused_inference(
68
+ x: torch.Tensor,
69
+ bias: typing.Optional[torch.Tensor],
70
+ scale: torch.Tensor,
71
+ residual: typing.Optional[torch.Tensor],
72
+ prob: float) -> torch.Tensor:
73
+ return bias_dropout_add_scale(
74
+ x, bias, scale, residual, prob, False)
75
+
76
+
77
+ @torch.jit.script
78
+ def modulate_fused(x: torch.Tensor,
79
+ shift: torch.Tensor,
80
+ scale: torch.Tensor) -> torch.Tensor:
81
+ return modulate(x, shift, scale)
82
+
83
+
84
+ class Rotary(torch.nn.Module):
85
+ def __init__(self, dim, base=10_000):
86
+ super().__init__()
87
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
88
+ self.register_buffer('inv_freq', inv_freq)
89
+ self.seq_len_cached = None
90
+ self.cos_cached = None
91
+ self.sin_cached = None
92
+
93
+ def forward(self, x, seq_dim=1):
94
+ seq_len = x.shape[seq_dim]
95
+ if seq_len != self.seq_len_cached:
96
+ self.seq_len_cached = seq_len
97
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
98
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
99
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
100
+ # dims are: batch, seq_len, qkv, head, dim
101
+ self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1,1,3,1,1)
102
+ self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1,1,3,1,1)
103
+ # This makes the transformation on v an identity.
104
+ self.cos_cached[:,:,2,:,:].fill_(1.)
105
+ self.sin_cached[:,:,2,:,:].fill_(0.)
106
+
107
+ return self.cos_cached, self.sin_cached
108
+
109
+
110
+ def rotate_half(x):
111
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
112
+ return torch.cat((-x2, x1), dim=-1)
113
+
114
+
115
+ def split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin):
116
+ with torch.cuda.amp.autocast(enabled=False):
117
+ cos, sin = rotary_cos_sin
118
+ cos = cos.to(qkv.dtype)
119
+ sin = sin.to(qkv.dtype)
120
+ cos = cos[0,:,0,0,:cos.shape[-1]//2]
121
+ sin = sin[0,:,0,0,:sin.shape[-1]//2]
122
+ q, k, v = qkv.chunk(3, dim=2)
123
+ q = flash_attn.layers.rotary.apply_rotary_emb_torch(
124
+ q.squeeze(dim=2), cos, sin)
125
+ k = flash_attn.layers.rotary.apply_rotary_emb_torch(
126
+ k.squeeze(dim=2), cos, sin)
127
+ v = v.squeeze(dim=2)
128
+ return q, k, v
129
+
130
+
131
+ def apply_rotary_pos_emb(qkv, cos, sin):
132
+ cos = cos[0,:,0,0,:cos.shape[-1]//2]
133
+ sin = sin[0,:,0,0,:sin.shape[-1]//2]
134
+ return flash_attn.layers.rotary.apply_rotary_emb_qkv_(qkv, cos, sin)
135
+
136
+
137
+ def regular_attention_multi_headed(q, k, v):
138
+ # Assuming qkv is a tensor with shape [batch, seq_len, 3, num_heads, head_dim]
139
+ # where the 3 represents Q, K, V packed in that order
140
+ attention_output = F.scaled_dot_product_attention(
141
+ query=q.transpose(1, 2),
142
+ key=k.transpose(1, 2),
143
+ value=v.transpose(1, 2),
144
+ attn_mask=None,
145
+ dropout_p=0.0,
146
+ is_causal=False)
147
+ # [batch_size, seq_len, num_heads, head_dim]
148
+ attention_output = attention_output.transpose(1, 2)
149
+ return einops.rearrange(attention_output, 'b s h d -> b s (h d)')
150
+
151
+
152
+ #################################################################################
153
+ # Layers #
154
+ #################################################################################
155
+ class LayerNorm(nn.Module):
156
+ def __init__(self, dim):
157
+ super().__init__()
158
+ self.weight = nn.Parameter(torch.ones([dim]))
159
+ self.dim = dim
160
+ def forward(self, x):
161
+ with torch.cuda.amp.autocast(enabled=False):
162
+ x = F.layer_norm(x.float(), [self.dim])
163
+ return x * self.weight[None, None, :]
164
+
165
+
166
+ def residual_linear(x, W, x_skip, residual_scale):
167
+ """x_skip + residual_scale * W @ x"""
168
+ dim_out, dim_in = W.shape[0], W.shape[1]
169
+ return torch.addmm(
170
+ x_skip.view(-1, dim_out),
171
+ x.view(-1, dim_in),
172
+ W.T,
173
+ alpha=residual_scale).view(*x.shape[:-1], dim_out)
174
+
175
+
176
+ #################################################################################
177
+ # Embedding Layers for Timesteps and Class Labels #
178
+ #################################################################################
179
+ class TimestepEmbedder(nn.Module):
180
+ """
181
+ Embeds scalar timesteps into vector representations.
182
+ """
183
+ def __init__(self, hidden_size, frequency_embedding_size=256):
184
+ super().__init__()
185
+ self.mlp = nn.Sequential(
186
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
187
+ nn.SiLU(),
188
+ nn.Linear(hidden_size, hidden_size, bias=True))
189
+ self.frequency_embedding_size = frequency_embedding_size
190
+
191
+ @staticmethod
192
+ def timestep_embedding(t, dim, max_period=10000):
193
+ """
194
+ Create sinusoidal timestep embeddings.
195
+ :param t: a 1-D Tensor of N indices, one per batch element.
196
+ These may be fractional.
197
+ :param dim: the dimension of the output.
198
+ :param max_period: controls the minimum frequency of the embeddings.
199
+ :return: an (N, D) Tensor of positional embeddings.
200
+ """
201
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
202
+ half = dim // 2
203
+ freqs = torch.exp(
204
+ - math.log(max_period)
205
+ * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device)
206
+ / half)
207
+ args = t[:, None].float() * freqs[None]
208
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
209
+ if dim % 2:
210
+ embedding = torch.cat(
211
+ [embedding,
212
+ torch.zeros_like(embedding[:, :1])], dim=-1)
213
+ return embedding
214
+
215
+ def forward(self, t):
216
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
217
+ t_emb = self.mlp(t_freq)
218
+ return t_emb
219
+
220
+
221
+ class LabelEmbedder(nn.Module):
222
+ """Embeds class labels into vector representations.
223
+
224
+ Also handles label dropout for classifier-free guidance.
225
+ """
226
+ def __init__(self, num_classes, cond_size):
227
+ super().__init__()
228
+ self.embedding_table = nn.Embedding(num_classes + 1, cond_size)
229
+ self.num_classes = num_classes
230
+
231
+ # TODO think of initializing with 0.02 std deviation like in original DiT paper
232
+
233
+ def forward(self, labels):
234
+ embeddings = self.embedding_table(labels)
235
+ return embeddings
236
+
237
+
238
+ #################################################################################
239
+ # Core Model #
240
+ #################################################################################
241
+
242
+ class DDiTBlockCausal(nn.Module):
243
+ def __init__(self, dim, n_heads, mlp_ratio=4, dropout=0.1):
244
+ super().__init__()
245
+ self.n_heads = n_heads
246
+
247
+ self.norm1 = LayerNorm(dim)
248
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
249
+ self.attn_out = nn.Linear(dim, dim, bias=False)
250
+ self.dropout1 = nn.Dropout(dropout)
251
+
252
+ self.norm2 = LayerNorm(dim)
253
+ self.mlp = nn.Sequential(
254
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
255
+ nn.GELU(approximate='tanh'),
256
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
257
+ self.dropout2 = nn.Dropout(dropout)
258
+ self.dropout = dropout
259
+
260
+ def _get_bias_dropout_scale(self):
261
+ if self.training:
262
+ return bias_dropout_add_scale_fused_train
263
+ else:
264
+ return bias_dropout_add_scale_fused_inference
265
+
266
+ def forward(self, x, rotary_cos_sin, **kwargs):
267
+ del kwargs
268
+ batch_size, seq_len = x.shape[0], x.shape[1]
269
+
270
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
271
+
272
+ # attention operation
273
+ x_skip = x
274
+ x = self.norm1(x)
275
+
276
+ qkv = self.attn_qkv(x)
277
+ qkv = einops.rearrange(
278
+ qkv,
279
+ 'b s (three h d) -> b s three h d',
280
+ three=3,
281
+ h=self.n_heads)
282
+ with torch.cuda.amp.autocast(enabled=False):
283
+ cos, sin = rotary_cos_sin
284
+ qkv = apply_rotary_pos_emb(
285
+ qkv, cos.to(qkv.dtype), sin.to(qkv.dtype)
286
+ )
287
+ qkv = einops.rearrange(qkv, 'b s ... -> (b s) ...')
288
+ cu_seqlens = torch.arange(
289
+ 0, (batch_size + 1) * seq_len,
290
+ step=seq_len, dtype=torch.int32, device=qkv.device)
291
+ x = flash_attn.flash_attn_interface.flash_attn_varlen_qkvpacked_func(
292
+ qkv, cu_seqlens, seq_len, 0.0, causal=True)
293
+
294
+ x = einops.rearrange(x, '(b s) h d -> b s (h d)',
295
+ b=batch_size)
296
+
297
+ scale = torch.ones(1, device=x.device, dtype=x.dtype)
298
+ x = bias_dropout_scale_fn(
299
+ self.attn_out(x), None, scale, x_skip, self.dropout)
300
+
301
+ # mlp operation
302
+ x = bias_dropout_scale_fn(
303
+ self.mlp(self.norm2(x)), None, scale, x, self.dropout)
304
+ return x
305
+
306
+
307
+
308
+ class DDiTBlock(nn.Module):
309
+ def __init__(self, dim, n_heads, adaLN,
310
+ cond_dim=None, mlp_ratio=4,
311
+ dropout=0.1):
312
+ super().__init__()
313
+ self.n_heads = n_heads
314
+ self.adaLN = adaLN
315
+
316
+ self.norm1 = LayerNorm(dim)
317
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
318
+ self.attn_out = nn.Linear(dim, dim, bias=False)
319
+ self.dropout1 = nn.Dropout(dropout)
320
+
321
+ self.norm2 = LayerNorm(dim)
322
+ self.mlp = nn.Sequential(
323
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
324
+ nn.GELU(approximate='tanh'),
325
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
326
+ self.dropout2 = nn.Dropout(dropout)
327
+ self.dropout = dropout
328
+
329
+ if self.adaLN:
330
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim)
331
+ self.adaLN_modulation.weight.data.zero_()
332
+ self.adaLN_modulation.bias.data.zero_()
333
+
334
+
335
+ def _get_bias_dropout_scale(self):
336
+ if self.training:
337
+ return bias_dropout_add_scale_fused_train
338
+ else:
339
+ return bias_dropout_add_scale_fused_inference
340
+
341
+
342
+ def forward(self, x, rotary_cos_sin, c=None):
343
+
344
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
345
+
346
+ x_skip = x
347
+ x = self.norm1(x)
348
+
349
+ if self.adaLN:
350
+ # self.adaLN_modulation(c): (128, 1536)
351
+ # self.adaLN_modulation(c)[:, None]: (128, 1, 1536)
352
+ # "" .chunk(6, dim=2) returns 6 tuples of shapes (128, 1, 256)
353
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
354
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
355
+ x = modulate_fused(x, shift_msa, scale_msa)
356
+
357
+ qkv = einops.rearrange(
358
+ self.attn_qkv(x),
359
+ 'b s (three h d) -> b s three h d',
360
+ three=3,
361
+ h=self.n_heads)
362
+ q, k, v = split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin)
363
+
364
+ x = regular_attention_multi_headed(q, k, v)
365
+
366
+ if self.adaLN:
367
+ x = bias_dropout_scale_fn(self.attn_out(x),
368
+ None,
369
+ gate_msa,
370
+ x_skip,
371
+ self.dropout)
372
+ x = bias_dropout_scale_fn(
373
+ self.mlp(modulate_fused(
374
+ self.norm2(x), shift_mlp, scale_mlp)),
375
+ None, gate_mlp, x, self.dropout)
376
+ else:
377
+ scale = torch.ones(1, device=x.device, dtype=x.dtype)
378
+ x = bias_dropout_scale_fn(
379
+ self.attn_out(x), None, scale, x_skip, self.dropout)
380
+ x = bias_dropout_scale_fn(
381
+ self.mlp(self.norm2(x)), None, scale, x, self.dropout)
382
+ return x
383
+
384
+
385
+ class EmbeddingLayer(nn.Module):
386
+ def __init__(self, dim, vocab_dim):
387
+ super().__init__()
388
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
389
+ torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
390
+
391
+ def forward(self, x):
392
+ if x.ndim == 2:
393
+ return self.embedding[x]
394
+ assert x.ndim == 3
395
+ return torch.einsum(
396
+ "blv,ve->ble",
397
+ torch.nn.functional.softmax(x, dim=-1).float(),
398
+ self.embedding.float()).to(x.dtype)
399
+
400
+
401
+ class DDiTFinalLayer(nn.Module):
402
+ def __init__(self, hidden_size, out_channels, cond_dim,
403
+ adaLN):
404
+ super().__init__()
405
+ self.norm_final = LayerNorm(hidden_size)
406
+ self.linear = nn.Linear(hidden_size, out_channels)
407
+ self.linear.weight.data.zero_()
408
+ self.linear.bias.data.zero_()
409
+ self.adaLN = adaLN
410
+ if self.adaLN:
411
+ self.adaLN_modulation = nn.Linear(cond_dim,
412
+ 2 * hidden_size,
413
+ bias=True)
414
+ self.adaLN_modulation.weight.data.zero_()
415
+ self.adaLN_modulation.bias.data.zero_()
416
+
417
+
418
+ def forward(self, x, c):
419
+ x = self.norm_final(x)
420
+ if self.adaLN:
421
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
422
+ x = modulate_fused(x, shift, scale)
423
+ x = self.linear(x)
424
+ return x
425
+
426
+
427
+ class DIT(nn.Module, huggingface_hub.PyTorchModelHubMixin):
428
+ def __init__(self, config, vocab_size: int):
429
+ super().__init__()
430
+ if type(config) == dict:
431
+ config = omegaconf.OmegaConf.create(config)
432
+ self.causal = config.algo.causal_attention
433
+ self.adaLN = not self.causal
434
+ self.config = config
435
+ self.vocab_size = vocab_size
436
+ dim = config.model.hidden_size
437
+ cond_dim = config.model.cond_dim
438
+ self.vocab_embed = EmbeddingLayer(dim, vocab_size)
439
+ if not self.causal:
440
+ self.sigma_map = TimestepEmbedder(cond_dim)
441
+ self.rotary_emb = Rotary(dim // config.model.n_heads)
442
+
443
+ blocks = []
444
+ for _ in range(config.model.n_blocks):
445
+ if self.causal:
446
+ block = DDiTBlockCausal(
447
+ dim=dim,
448
+ n_heads=config.model.n_heads,
449
+ dropout=config.model.dropout)
450
+ else:
451
+ block = DDiTBlock(
452
+ dim=dim,
453
+ n_heads=config.model.n_heads,
454
+ cond_dim=cond_dim,
455
+ adaLN=self.adaLN,
456
+ dropout=config.model.dropout)
457
+ blocks.append(block)
458
+ self.blocks = nn.ModuleList(blocks)
459
+
460
+ self.output_layer = DDiTFinalLayer(
461
+ hidden_size=dim,
462
+ out_channels=vocab_size,
463
+ cond_dim=cond_dim,
464
+ adaLN=self.adaLN)
465
+ self.scale_by_sigma = config.model.scale_by_sigma
466
+
467
+ def _get_bias_dropout_scale(self):
468
+ if self.training:
469
+ return bias_dropout_add_scale_fused_train
470
+ else:
471
+ return bias_dropout_add_scale_fused_inference
472
+
473
+ def forward(self, x, sigma):
474
+ x = self.vocab_embed(x)
475
+ if self.causal:
476
+ t_cond = None
477
+ else:
478
+ t_cond = F.silu(self.sigma_map(sigma))
479
+
480
+ rotary_cos_sin = self.rotary_emb(x)
481
+
482
+ with torch.cuda.amp.autocast(dtype=torch.bfloat16):
483
+ for i in range(len(self.blocks)):
484
+ x = self.blocks[i](x, rotary_cos_sin, c=t_cond)
485
+ x = self.output_layer(x, c=t_cond)
486
+
487
+ return x
488
+
489
+
490
+
491
+ class HFDIT(torch.nn.Module):
492
+ def __init__(self, config):
493
+ super().__init__()
494
+ self.causal = config.causal
495
+ self.adaLN = not self.causal
496
+ self.vocab_size = config.vocab_size
497
+ dim = config.hidden_dim
498
+ cond_dim = config.cond_dim
499
+ self.vocab_embed = EmbeddingLayer(dim, self.vocab_size)
500
+ if not self.causal:
501
+ self.sigma_map = TimestepEmbedder(cond_dim)
502
+ self.rotary_emb = Rotary(dim // config.n_heads)
503
+
504
+ blocks = []
505
+ for _ in range(config.n_blocks):
506
+ if self.causal:
507
+ block = DDiTBlockCausal(
508
+ dim=dim,
509
+ n_heads=config.n_heads,
510
+ dropout=config.dropout)
511
+ else:
512
+ block = DDiTBlock(
513
+ dim=dim,
514
+ n_heads=config.n_heads,
515
+ cond_dim=cond_dim,
516
+ adaLN=self.adaLN,
517
+ dropout=config.dropout)
518
+ blocks.append(block)
519
+ self.blocks = torch.nn.ModuleList(blocks)
520
+
521
+ self.output_layer = DDiTFinalLayer(
522
+ hidden_size=dim,
523
+ out_channels=self.vocab_size,
524
+ cond_dim=cond_dim,
525
+ adaLN=self.adaLN)
526
+
527
+ def _get_bias_dropout_scale(self):
528
+ if self.training:
529
+ return bias_dropout_add_scale_fused_train
530
+ else:
531
+ return bias_dropout_add_scale_fused_inference
532
+
533
+ def forward(self, x, sigma, output_hidden_states=False):
534
+ all_hidden_states = []
535
+ x = self.vocab_embed(x)
536
+ if output_hidden_states:
537
+ all_hidden_states.append(x)
538
+ if self.causal:
539
+ t_cond = None
540
+ else:
541
+ t_cond = F.silu(self.sigma_map(sigma))
542
+
543
+ rotary_cos_sin = self.rotary_emb(x)
544
+ with torch.cuda.amp.autocast(
545
+ dtype=torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float32):
546
+ for i in range(len(self.blocks)):
547
+ x = self.blocks[i](x, rotary_cos_sin, c=t_cond)
548
+ if output_hidden_states:
549
+ all_hidden_states.append(x)
550
+ x = self.output_layer(x, c=t_cond)
551
+ return x, all_hidden_states
552
+
553
+
554
+ class DUO(transformers.PreTrainedModel):
555
+ """HF-compatible model."""
556
+ config_class = DUOConfig
557
+ base_model_prefix = 'duo'
558
+
559
+ def __init__(self, config: DUOConfig):
560
+ super().__init__(config)
561
+ self.config = config
562
+ self.backbone = HFDIT(config)
563
+
564
+ def reset_kv_cache(self):
565
+ for block in self.backbone.blocks:
566
+ block.kv_cache = None
567
+
568
+ def forward(
569
+ self,
570
+ input_ids: torch.LongTensor = None,
571
+ timesteps: torch.FloatTensor = None,
572
+ output_hidden_states: typing.Optional[bool] = None,
573
+ return_dict: typing.Optional[bool] = None,
574
+ ) -> typing.Union[
575
+ torch.Tensor, typing.Tuple,
576
+ transformers.modeling_outputs.MaskedLMOutput]:
577
+ """HF-compatible forward method."""
578
+ output_hidden_states = (
579
+ output_hidden_states
580
+ if output_hidden_states is not None
581
+ else self.config.output_hidden_states
582
+ )
583
+ return_dict = return_dict \
584
+ if return_dict is not None \
585
+ else self.config.use_return_dict
586
+
587
+ logits, all_hidden_states = self.backbone(
588
+ x=input_ids,
589
+ sigma=timesteps,
590
+ output_hidden_states=output_hidden_states,
591
+ )
592
+ if return_dict:
593
+ return transformers.modeling_outputs.MaskedLMOutput(
594
+ logits=logits,
595
+ hidden_states=all_hidden_states if output_hidden_states else None,
596
+ loss=None
597
+ )
598
+ elif output_hidden_states:
599
+ return logits, all_hidden_states
600
+ else:
601
+ return logits
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4b66c48780483f7079e47b1a56e6245a12d83057533455f447e822ef20fe93f
3
+ size 678522728