exdysa s-sahoo commited on
Commit
eb94961
·
verified ·
0 Parent(s):

Duplicate from s-sahoo/duo

Browse files

Co-authored-by: Subham Sekhar Sahoo <s-sahoo@users.noreply.huggingface.co>

Files changed (6) hide show
  1. .gitattributes +35 -0
  2. README.md +53 -0
  3. config.json +23 -0
  4. config.py +29 -0
  5. model.py +601 -0
  6. model.safetensors +3 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ datasets:
3
+ - Skylion007/openwebtext
4
+ language:
5
+ - en
6
+ library_name: transformers
7
+ license: apache-2.0
8
+ metrics:
9
+ - perplexity
10
+ pipeline_tag: text-generation
11
+ ---
12
+
13
+ ## Using DUO
14
+ To use the pre-trained model for masked language modeling, use the following snippet:
15
+ ```python
16
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
17
+
18
+ # See the `MDLM` collection page on the hub for list of available models.
19
+ tokenizer = transformers.AutoTokenizer.from_pretrained('gpt2')
20
+ model = AutoModelForMaskedLM.from_pretrained('s-sahoo/duo')
21
+ ```
22
+ For a hands-on example, check out this [Colab notebook](https://colab.research.google.com/drive/1Sf7R-dqdR6gq-H8nyZ9E3ZkyvqMTqcwq?usp=sharing).
23
+ For more information and implementation details, visit our github repository: [DUO](https://github.com/s-sahoo/duo) and project page: [Project Page](https://s-sahoo.com/duo)
24
+
25
+ ## Model Details
26
+ The model, which has a context length of `1024` and is similar in size to GPT2-medium with approximately `130 million` non-embedding parameters,
27
+ was trained for 1M steps on the OpenWebText corpus.
28
+
29
+ For more details, please see our paper: [The Diffusion Duality](https://openreview.net/forum?id=CB0Ub2yXjC).
30
+
31
+
32
+
33
+ ## Citation
34
+
35
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
36
+ Please cite our work using the bibtex below:
37
+
38
+ **BibTeX:**
39
+
40
+ ```
41
+ @inproceedings{
42
+ sahoo2025the,
43
+ title={The Diffusion Duality},
44
+ author={Subham Sekhar Sahoo and Justin Deschenaux and Aaron Gokaslan and Guanghan Wang and Justin T Chiu and Volodymyr Kuleshov},
45
+ booktitle={Forty-second International Conference on Machine Learning},
46
+ year={2025},
47
+ url={https://openreview.net/forum?id=9P9Y8FOSOk}
48
+ }
49
+ ```
50
+
51
+
52
+ ## Model Card Contact
53
+ Subham Sekhar Sahoo (ssahoo@cs.cornell.edu)
config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "s-sahoo/duo",
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).to(x.device)
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:c9e98629579f5dc7c7fcf15cd10c66f585fd6cfa31a9ce4ac09255bc84ec9ad3
3
+ size 678522728