jyliuAI commited on
Commit
9f86ec4
·
verified ·
1 Parent(s): 334a752

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. checkpoints/official/duo_dcd/owt/model.py +601 -0
  2. checkpoints/official/langflow/lm1b/README.md +61 -0
  3. checkpoints/official/langflow/lm1b/config.json +29 -0
  4. checkpoints/official/langflow/lm1b/model.py +560 -0
  5. checkpoints/official/langflow/owt/README.md +61 -0
  6. checkpoints/official/langflow/owt/__init__.py +6 -0
  7. checkpoints/official/langflow/owt/model.py +560 -0
  8. checkpoints/official/mdlm/owt/README.md +67 -0
  9. checkpoints/official/mdlm/owt/config.json +22 -0
  10. checkpoints/official/mdlm/owt/configuration_mdlm.py +31 -0
  11. checkpoints/official/mdlm/owt/modeling_mdlm.py +450 -0
  12. checkpoints/quarantine/20260802T040549Z/official/fmlm/lm1b/README.md +45 -0
  13. checkpoints/quarantine/20260802T040549Z/official/fmlm/lm1b/config.json +221 -0
  14. checkpoints/quarantine/20260802T040557Z/official/flm/owt/README.md +45 -0
  15. checkpoints/quarantine/20260802T040621Z/official/duo/owt/README.md +53 -0
  16. checkpoints/quarantine/20260802T040621Z/official/duo/owt/config.json +23 -0
  17. checkpoints/quarantine/20260802T040621Z/official/duo/owt/model.py +601 -0
  18. checkpoints/quarantine/20260802T040629Z/official/duo_dcd/owt/README.md +52 -0
  19. checkpoints/quarantine/20260802T040629Z/official/duo_dcd/owt/config.json +23 -0
  20. checkpoints/quarantine/20260802T040629Z/official/duo_dcd/owt/model.py +601 -0
  21. checkpoints/quarantine/20260802T040645Z/official/mdlm_sdtt/owt/config.json +207 -0
  22. checkpoints/quarantine/20260818T074854Z/official/duo_dcd/owt/model.py +601 -0
  23. checkpoints/quarantine/20260818T074907Z/official/mdlm/owt/config.json +22 -0
  24. checkpoints/quarantine/20260818T074907Z/official/mdlm/owt/configuration_mdlm.py +31 -0
  25. checkpoints/quarantine/20260820T072002Z/official/flm/owt/README.md +45 -0
  26. checkpoints/quarantine/20260820T072143Z/official/langflow/lm1b/config.json +29 -0
  27. checkpoints/quarantine/20260820T072143Z/official/langflow/lm1b/model.py +560 -0
  28. checkpoints/quarantine/20260821T024711Z/official/flm/lm1b/config.json +209 -0
  29. checkpoints/quarantine/20260821T024727Z/official/flm/owt/config.json +208 -0
  30. checkpoints/quarantine/20260821T024736Z/official/fmlm/owt/README.md +47 -0
  31. checkpoints/quarantine/20260821T024736Z/official/fmlm/owt/config.json +223 -0
  32. checkpoints/quarantine/20260821T024744Z/official/langflow/owt/config.json +29 -0
  33. checkpoints/quarantine/20260821T024744Z/official/langflow/owt/config.py +63 -0
  34. checkpoints/quarantine/20260825T100043Z/official/flm/lm1b/README.md +43 -0
  35. checkpoints/quarantine/20260825T100259Z/official/duo_dcd/owt/config.py +29 -0
  36. checkpoints/quarantine/20260825T100259Z/official/duo_dcd/owt/model.py +601 -0
  37. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/.hydra/config.yaml +179 -0
  38. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/.hydra/hydra.yaml +202 -0
  39. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/.hydra/overrides.yaml +40 -0
  40. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/config.yaml +179 -0
  41. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/logs_di4c_train.txt +53 -0
  42. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/stderr.log +0 -0
  43. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/stdout.log +0 -0
  44. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/.hydra/config.yaml +179 -0
  45. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/.hydra/hydra.yaml +202 -0
  46. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/.hydra/overrides.yaml +40 -0
  47. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/config.yaml +179 -0
  48. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/inputs/teacher_adapted.provenance.json +16 -0
  49. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/logs_di4c_train.txt +53 -0
  50. checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/stderr.log +0 -0
checkpoints/official/duo_dcd/owt/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
checkpoints/official/langflow/lm1b/README.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ datasets:
3
+ - dvruette/lm1b
4
+ papers:
5
+ - arxiv: 2604.11748
6
+ language:
7
+ - en
8
+ library_name: transformers
9
+ license: apache-2.0
10
+ metrics:
11
+ - perplexity
12
+ pipeline_tag: text-generation
13
+ ---
14
+
15
+ # LangFlow
16
+
17
+ LangFlow is a continuous diffusion language model that operates in embedding space. Unlike discrete diffusion models (MDLM, SEDD, DUO), LangFlow performs diffusion directly on continuous token embeddings, enabling smoother denoising dynamics.
18
+
19
+ For more details, please see our paper: [LangFlow: Continuous Diffusion Rivals Discrete in Language Modeling](https://arxiv.org/abs/2604.11748).
20
+
21
+
22
+ ## Using LangFlow
23
+
24
+ To use the pre-trained model for text generation, use the following snippet:
25
+
26
+ ```python
27
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
28
+
29
+ tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
30
+ model = AutoModelForMaskedLM.from_pretrained('Continuous-Rivals-Discrete/langflow-lm1b', trust_remote_code=True)
31
+
32
+ # Generate samples
33
+ samples = model.generate_samples(num_samples=5, num_steps=128)
34
+ texts = tokenizer.batch_decode(samples, skip_special_tokens=True)
35
+ for text in texts:
36
+ print(text)
37
+ ```
38
+
39
+ ## Model Details
40
+
41
+ - **Architecture**: DiT (Diffusion Transformer) backbone with adaptive layer normalization
42
+ - **Context Length**: 128 tokens
43
+ - **Parameters**: ~130M parameters (similar to GPT-2 small)
44
+ - **Training**: 1M steps on LM1B corpus
45
+ - **Tokenizer**: bert-base-uncased tokenizer (30,522 vocab size)
46
+
47
+ ## Citation
48
+
49
+ ```
50
+ @article{chen2026langflow,
51
+ title={LangFlow: Continuous Diffusion Rivals Discrete in Language Modeling},
52
+ author={Chen, Yuxin and Liang, Chumeng and Sui, Hangke and Guo, Ruihan and Cheng, Chaoran and You, Jiaxuan and Liu, Ge},
53
+ journal={arXiv preprint arXiv:2604.11748},
54
+ year={2026}
55
+ }
56
+ ```
57
+
58
+ ## Model Card Contact
59
+
60
+ Chumeng Liang (chumengl@illinois.edu)
61
+
checkpoints/official/langflow/lm1b/config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "nealchen/langflow-lm1b",
3
+ "architectures": [
4
+ "LangFlow"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "config.LangFlowConfig",
8
+ "AutoModelForMaskedLM": "model.LangFlow"
9
+ },
10
+ "model_type": "LangFlow",
11
+ "vocab_size": 30522,
12
+ "hidden_size": 768,
13
+ "cond_dim": 128,
14
+ "n_blocks": 12,
15
+ "n_heads": 12,
16
+ "dropout": 0.1,
17
+ "model_length": 128,
18
+ "use_normalized_embedding": true,
19
+ "embedding_norm_method": "layernorm",
20
+ "self_conditioning": true,
21
+ "use_bias": true,
22
+ "gumbel_loc": 4.723,
23
+ "gumbel_scale": 0.852,
24
+ "gumbel_cutoff": 1e-5,
25
+ "gumbel_entropy": 7.02,
26
+ "return_dict": true,
27
+ "torch_dtype": "float32",
28
+ "transformers_version": "4.38.2"
29
+ }
checkpoints/official/langflow/lm1b/model.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace model implementation for LangFlow.
2
+
3
+ LangFlow is a continuous diffusion language model that operates in embedding space.
4
+ """
5
+
6
+ import math
7
+ import typing
8
+
9
+ import einops
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import transformers
14
+
15
+ from .config import LangFlowConfig
16
+
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
+ @torch.jit.script
43
+ def bias_dropout_add_scale_fused_train(
44
+ x: torch.Tensor,
45
+ bias: typing.Optional[torch.Tensor],
46
+ scale: torch.Tensor,
47
+ residual: typing.Optional[torch.Tensor],
48
+ prob: float) -> torch.Tensor:
49
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, True)
50
+
51
+
52
+ @torch.jit.script
53
+ def bias_dropout_add_scale_fused_inference(
54
+ x: torch.Tensor,
55
+ bias: typing.Optional[torch.Tensor],
56
+ scale: torch.Tensor,
57
+ residual: typing.Optional[torch.Tensor],
58
+ prob: float) -> torch.Tensor:
59
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, False)
60
+
61
+
62
+ @torch.jit.script
63
+ def modulate_fused(x: torch.Tensor,
64
+ shift: torch.Tensor,
65
+ scale: torch.Tensor) -> torch.Tensor:
66
+ return x * (1 + scale) + shift
67
+
68
+
69
+ class Rotary(nn.Module):
70
+ def __init__(self, dim, base=10_000):
71
+ super().__init__()
72
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
73
+ self.register_buffer('inv_freq', inv_freq)
74
+ self.seq_len_cached = None
75
+ self.cos_cached = None
76
+ self.sin_cached = None
77
+
78
+ def forward(self, x, seq_dim=1):
79
+ seq_len = x.shape[seq_dim]
80
+ if seq_len != self.seq_len_cached:
81
+ self.seq_len_cached = seq_len
82
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
83
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
84
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
85
+ self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1, 1, 3, 1, 1)
86
+ self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1, 1, 3, 1, 1)
87
+ self.cos_cached[:, :, 2, :, :].fill_(1.)
88
+ self.sin_cached[:, :, 2, :, :].fill_(0.)
89
+ return self.cos_cached, self.sin_cached
90
+
91
+
92
+ def _apply_rotary_emb(x, cos, sin):
93
+ # x: [batch, seqlen, nheads, headdim]
94
+ # cos, sin: [seqlen, headdim//2]
95
+ ro_dim = cos.shape[-1] * 2
96
+ # Expand to [1, seqlen, 1, ro_dim] for broadcasting
97
+ cos = torch.cat([cos, cos], dim=-1)[None, :, None, :]
98
+ sin = torch.cat([sin, sin], dim=-1)[None, :, None, :]
99
+ x_rot = x[..., :ro_dim]
100
+ x1, x2 = x_rot.chunk(2, dim=-1)
101
+ x_rotated = torch.cat([-x2, x1], dim=-1)
102
+ return torch.cat([x_rot * cos + x_rotated * sin, x[..., ro_dim:]], dim=-1)
103
+
104
+
105
+ def split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin):
106
+ with torch.autocast(device_type='cuda', enabled=False):
107
+ cos, sin = rotary_cos_sin
108
+ cos = cos.to(qkv.dtype)
109
+ sin = sin.to(qkv.dtype)
110
+ cos = cos[0, :, 0, 0, :cos.shape[-1]//2]
111
+ sin = sin[0, :, 0, 0, :sin.shape[-1]//2]
112
+ q, k, v = qkv.chunk(3, dim=2)
113
+ q = _apply_rotary_emb(q.squeeze(dim=2), cos, sin)
114
+ k = _apply_rotary_emb(k.squeeze(dim=2), cos, sin)
115
+ v = v.squeeze(dim=2)
116
+ return q, k, v
117
+
118
+
119
+ def regular_attention_multi_headed(q, k, v):
120
+ attention_output = F.scaled_dot_product_attention(
121
+ query=q.transpose(1, 2),
122
+ key=k.transpose(1, 2),
123
+ value=v.transpose(1, 2),
124
+ attn_mask=None,
125
+ dropout_p=0.0,
126
+ is_causal=False)
127
+ attention_output = attention_output.transpose(1, 2)
128
+ return einops.rearrange(attention_output, 'b s h d -> b s (h d)')
129
+
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
+
137
+ def forward(self, x):
138
+ with torch.autocast(device_type='cuda', enabled=False):
139
+ x = F.layer_norm(x.float(), [self.dim])
140
+ return x * self.weight[None, None, :]
141
+
142
+
143
+ class TimestepEmbedder(nn.Module):
144
+ """Embeds scalar timesteps into vector representations."""
145
+
146
+ def __init__(self, hidden_size, frequency_embedding_size=256):
147
+ super().__init__()
148
+ self.mlp = nn.Sequential(
149
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
150
+ nn.SiLU(),
151
+ nn.Linear(hidden_size, hidden_size, bias=True))
152
+ self.frequency_embedding_size = frequency_embedding_size
153
+
154
+ @staticmethod
155
+ def timestep_embedding(t, dim, max_period=10000):
156
+ half = dim // 2
157
+ freqs = torch.exp(
158
+ -math.log(max_period)
159
+ * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device)
160
+ / half)
161
+ args = t[:, None].float() * freqs[None]
162
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
163
+ if dim % 2:
164
+ embedding = torch.cat(
165
+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
166
+ return embedding
167
+
168
+ def forward(self, t):
169
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
170
+ t_emb = self.mlp(t_freq)
171
+ return t_emb
172
+
173
+
174
+ class DDiTBlock(nn.Module):
175
+ def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4, dropout=0.1):
176
+ super().__init__()
177
+ self.n_heads = n_heads
178
+
179
+ self.norm1 = LayerNorm(dim)
180
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
181
+ self.attn_out = nn.Linear(dim, dim, bias=False)
182
+
183
+ self.norm2 = LayerNorm(dim)
184
+ self.mlp = nn.Sequential(
185
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
186
+ nn.GELU(approximate='tanh'),
187
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
188
+ self.dropout = dropout
189
+
190
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim)
191
+ self.adaLN_modulation.weight.data.zero_()
192
+ self.adaLN_modulation.bias.data.zero_()
193
+
194
+ def _get_bias_dropout_scale(self):
195
+ if self.training:
196
+ return bias_dropout_add_scale_fused_train
197
+ else:
198
+ return bias_dropout_add_scale_fused_inference
199
+
200
+ def forward(self, x, rotary_cos_sin, c):
201
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
202
+
203
+ x_skip = x
204
+ x = self.norm1(x)
205
+
206
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
207
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
208
+ x = modulate_fused(x, shift_msa, scale_msa)
209
+
210
+ qkv = einops.rearrange(
211
+ self.attn_qkv(x),
212
+ 'b s (three h d) -> b s three h d',
213
+ three=3,
214
+ h=self.n_heads)
215
+ q, k, v = split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin)
216
+ x = regular_attention_multi_headed(q, k, v)
217
+
218
+ x = bias_dropout_scale_fn(self.attn_out(x), None, gate_msa, x_skip, self.dropout)
219
+ x = bias_dropout_scale_fn(
220
+ self.mlp(modulate_fused(self.norm2(x), shift_mlp, scale_mlp)),
221
+ None, gate_mlp, x, self.dropout)
222
+ return x
223
+
224
+
225
+ def _normalize_embedding_layernorm(weight: torch.Tensor) -> torch.Tensor:
226
+ """Normalize embedding weights to unit norm per row, then scale by sqrt(dim)."""
227
+ normalized = F.normalize(weight.float(), dim=-1)
228
+ return (normalized * math.sqrt(weight.shape[-1])).to(weight.dtype)
229
+
230
+
231
+ class EmbeddingLayer(nn.Module):
232
+ """Embedding layer with optional layernorm normalization."""
233
+
234
+ def __init__(self, dim, vocab_dim, use_normalized_embedding=True):
235
+ super().__init__()
236
+ self.dim = dim
237
+ self.vocab_dim = vocab_dim
238
+ self.use_normalized_embedding = use_normalized_embedding
239
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
240
+ nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
241
+
242
+ def _get_embedding(self):
243
+ if self.use_normalized_embedding:
244
+ return _normalize_embedding_layernorm(self.embedding)
245
+ return self.embedding
246
+
247
+ def forward(self, x):
248
+ embedding = self._get_embedding()
249
+ if x.ndim == 2:
250
+ return embedding[x]
251
+ assert x.ndim == 3 # probabilities
252
+ return torch.einsum("blv,ve->ble", x.float(), embedding.float()).to(x.dtype)
253
+
254
+
255
+ class DDiTFinalLayer(nn.Module):
256
+ def __init__(self, hidden_size, out_channels, cond_dim):
257
+ super().__init__()
258
+ self.norm_final = LayerNorm(hidden_size)
259
+ self.linear = nn.Linear(hidden_size, out_channels)
260
+ self.linear.weight.data.zero_()
261
+ self.linear.bias.data.zero_()
262
+ self.adaLN_modulation = nn.Linear(cond_dim, 2 * hidden_size, bias=True)
263
+ self.adaLN_modulation.weight.data.zero_()
264
+ self.adaLN_modulation.bias.data.zero_()
265
+
266
+ def forward(self, x, c):
267
+ x = self.norm_final(x)
268
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
269
+ x = modulate_fused(x, shift, scale)
270
+ x = self.linear(x)
271
+ return x
272
+
273
+
274
+ class GumbelProposal(nn.Module):
275
+ """Learnable Gumbel distribution proposal for sampling gamma (log-SNR)."""
276
+
277
+ def __init__(self, loc: float = 4.723, scale: float = 0.852,
278
+ cutoff: float = 1e-5, entropy: float = 7.02):
279
+ super().__init__()
280
+ self.loc = nn.Parameter(torch.tensor(loc))
281
+ self.scale = nn.Parameter(torch.tensor(scale))
282
+ self.cutoff = cutoff
283
+ self.entropy = nn.Parameter(torch.tensor(entropy))
284
+
285
+ def _get_distribution(self) -> torch.distributions.Gumbel:
286
+ return torch.distributions.Gumbel(self.loc, self.scale)
287
+
288
+ @property
289
+ def gamma_min(self) -> float:
290
+ return float(self.loc - math.log(-math.log(self.cutoff)) * self.scale)
291
+
292
+ @property
293
+ def gamma_max(self) -> float:
294
+ return float(self.loc - math.log(self.cutoff) * self.scale)
295
+
296
+ def forward(self, q: torch.Tensor) -> torch.Tensor:
297
+ """Convert uniform samples to gamma values via inverse CDF."""
298
+ gamma = self._get_distribution().icdf(q)
299
+ return gamma.clamp(min=self.gamma_min, max=self.gamma_max)
300
+
301
+ def log_pdf(self, gamma: torch.Tensor) -> torch.Tensor:
302
+ """Compute log probability density at gamma."""
303
+ return self._get_distribution().log_prob(gamma)
304
+
305
+
306
+ class LangFlowBackbone(nn.Module):
307
+ """DiT backbone for LangFlow."""
308
+
309
+ def __init__(self, config: LangFlowConfig):
310
+ super().__init__()
311
+ self.config = config
312
+ dim = config.hidden_size
313
+ cond_dim = config.cond_dim
314
+
315
+ self.vocab_embed = EmbeddingLayer(
316
+ dim, config.vocab_size,
317
+ use_normalized_embedding=config.use_normalized_embedding)
318
+ self.sigma_map = TimestepEmbedder(cond_dim)
319
+ self.rotary_emb = Rotary(dim // config.n_heads)
320
+
321
+ self.blocks = nn.ModuleList([
322
+ DDiTBlock(dim=dim, n_heads=config.n_heads, cond_dim=cond_dim, dropout=config.dropout)
323
+ for _ in range(config.n_blocks)
324
+ ])
325
+
326
+ self.output_layer = DDiTFinalLayer(
327
+ hidden_size=dim, out_channels=config.vocab_size, cond_dim=cond_dim)
328
+
329
+ # Self-conditioning projection
330
+ if config.self_conditioning:
331
+ self.self_cond_proj = nn.Linear(dim * 2, dim, bias=False)
332
+ nn.init.zeros_(self.self_cond_proj.weight)
333
+
334
+ def forward(self, x_embed, sigma, x_self_cond=None, output_hidden_states=False):
335
+ """Forward pass from embeddings.
336
+
337
+ Args:
338
+ x_embed: [B, L, D] - Input embeddings (possibly noisy)
339
+ sigma: [B] - Gamma values (log-SNR)
340
+ x_self_cond: [B, L, D] - Self-conditioning embeddings (optional)
341
+ output_hidden_states: Whether to return all hidden states
342
+
343
+ Returns:
344
+ logits: [B, L, vocab_size]
345
+ hidden_states: List of hidden states if output_hidden_states=True
346
+ """
347
+ all_hidden_states = []
348
+ x = x_embed
349
+
350
+ if output_hidden_states:
351
+ all_hidden_states.append(x)
352
+
353
+ # Self-conditioning
354
+ if self.config.self_conditioning:
355
+ if x_self_cond is None:
356
+ x_self_cond = torch.zeros_like(x)
357
+ x = x + self.self_cond_proj(torch.cat([x, x_self_cond], dim=-1))
358
+
359
+ t_cond = F.silu(self.sigma_map(sigma))
360
+ rotary_cos_sin = self.rotary_emb(x)
361
+
362
+ with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
363
+ for block in self.blocks:
364
+ x = block(x, rotary_cos_sin, c=t_cond)
365
+ if output_hidden_states:
366
+ all_hidden_states.append(x)
367
+ x = self.output_layer(x, c=t_cond)
368
+
369
+ return x, all_hidden_states
370
+
371
+
372
+ class LangFlow(transformers.PreTrainedModel):
373
+ """HuggingFace-compatible LangFlow model.
374
+
375
+ LangFlow is a continuous diffusion language model that operates in embedding space.
376
+ It uses a DiT (Diffusion Transformer) backbone with:
377
+ - Self-conditioning: uses previous predictions as additional input
378
+ - Bias (preconditioning): skip connection for improved generation
379
+ - Normalized embeddings: layernorm on embedding vectors
380
+ - Learnable Gumbel proposal for gamma (log-SNR) sampling
381
+ """
382
+ config_class = LangFlowConfig
383
+ base_model_prefix = "langflow"
384
+
385
+ def __init__(self, config: LangFlowConfig):
386
+ super().__init__(config)
387
+ self.config = config
388
+ self.backbone = LangFlowBackbone(config)
389
+ self.proposal = GumbelProposal(
390
+ loc=config.gumbel_loc,
391
+ scale=config.gumbel_scale,
392
+ cutoff=config.gumbel_cutoff,
393
+ entropy=config.gumbel_entropy)
394
+
395
+ def _get_embedding_matrix(self) -> torch.Tensor:
396
+ """Get the embedding matrix for bias skip connection."""
397
+ return self.backbone.vocab_embed._get_embedding()
398
+
399
+ def _embed_tokens(self, x: torch.Tensor) -> torch.Tensor:
400
+ """Embed tokens or probabilities to continuous embeddings."""
401
+ return self.backbone.vocab_embed(x)
402
+
403
+ def _forward_diffusion(self, x_embed: torch.Tensor,
404
+ gamma: torch.Tensor) -> torch.Tensor:
405
+ """Add noise to embeddings (forward diffusion process)."""
406
+ gamma = gamma.float()
407
+ alpha = torch.sigmoid(-gamma).sqrt()[:, None, None]
408
+ sigma = torch.sigmoid(gamma).sqrt()[:, None, None]
409
+ noise = torch.randn_like(x_embed)
410
+ return (x_embed * alpha + noise * sigma).to(x_embed.dtype)
411
+
412
+ def _euler_edm_step(self, z: torch.Tensor, x_pred: torch.Tensor,
413
+ t: torch.Tensor, s: torch.Tensor) -> torch.Tensor:
414
+ """Single Euler step for EDM sampling."""
415
+ t_ = t.double()
416
+ s_ = s.double()
417
+ cur = z.double() * ((F.softplus(t_) - F.softplus(s_)) / 2).exp()
418
+ end = torch.sigmoid(-s_).sqrt() * x_pred.double()
419
+ z = end.lerp(cur, ((s_ - t_) / 2).exp()).to(z.dtype)
420
+ return z
421
+
422
+ def forward(
423
+ self,
424
+ input_ids: typing.Optional[torch.LongTensor] = None,
425
+ noisy_embeds: typing.Optional[torch.FloatTensor] = None,
426
+ timesteps: typing.Optional[torch.FloatTensor] = None,
427
+ x_self_cond: typing.Optional[torch.FloatTensor] = None,
428
+ output_hidden_states: typing.Optional[bool] = None,
429
+ return_dict: typing.Optional[bool] = None,
430
+ ) -> typing.Union[torch.Tensor, typing.Tuple, transformers.modeling_outputs.MaskedLMOutput]:
431
+ """Forward pass for LangFlow.
432
+
433
+ Args:
434
+ input_ids: [B, L] - Token IDs (will be embedded and noised if timesteps provided)
435
+ noisy_embeds: [B, L, D] - Pre-noised embeddings (alternative to input_ids)
436
+ timesteps: [B] - Gamma values (log-SNR) for conditioning
437
+ x_self_cond: [B, L, D] - Self-conditioning embeddings
438
+ output_hidden_states: Whether to return hidden states
439
+ return_dict: Whether to return MaskedLMOutput
440
+
441
+ Returns:
442
+ logits or MaskedLMOutput
443
+ """
444
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
445
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
446
+
447
+ # Get embeddings
448
+ if noisy_embeds is not None:
449
+ z = noisy_embeds
450
+ elif input_ids is not None:
451
+ x_embed = self._embed_tokens(input_ids)
452
+ if timesteps is not None:
453
+ z = self._forward_diffusion(x_embed, timesteps)
454
+ else:
455
+ z = x_embed
456
+ else:
457
+ raise ValueError("Either input_ids or noisy_embeds must be provided")
458
+
459
+ if timesteps is None:
460
+ # Use minimum gamma for clean input
461
+ timesteps = torch.full((z.shape[0],), self.proposal.gamma_min, device=z.device)
462
+
463
+ # Process sigma
464
+ sigma = timesteps
465
+ if sigma.ndim == 2:
466
+ sigma = sigma.mean(-1)
467
+
468
+ # Get model output
469
+ logits, all_hidden_states = self.backbone(
470
+ z, sigma, x_self_cond=x_self_cond, output_hidden_states=output_hidden_states)
471
+
472
+ # Add bias (preconditioning) skip connection
473
+ if self.config.use_bias:
474
+ c_skip = ((F.softplus(-sigma) - sigma) / 2).exp()
475
+ embedding = self._get_embedding_matrix()
476
+ skip_logits = torch.matmul(z.float(), embedding.t().float())
477
+ logits = logits + c_skip[:, None, None] * skip_logits.to(logits.dtype)
478
+
479
+ if return_dict:
480
+ return transformers.modeling_outputs.MaskedLMOutput(
481
+ logits=logits,
482
+ hidden_states=all_hidden_states if output_hidden_states else None,
483
+ loss=None)
484
+ elif output_hidden_states:
485
+ return logits, all_hidden_states
486
+ else:
487
+ return logits
488
+
489
+ @torch.no_grad()
490
+ def generate_samples(
491
+ self,
492
+ num_samples: int = 1,
493
+ seq_length: typing.Optional[int] = None,
494
+ num_steps: int = 128,
495
+ device: typing.Optional[torch.device] = None,
496
+ ) -> torch.LongTensor:
497
+ """Generate samples using Euler-EDM solver.
498
+
499
+ Args:
500
+ num_samples: Number of samples to generate
501
+ seq_length: Sequence length (defaults to config.model_length)
502
+ num_steps: Number of denoising steps
503
+ device: Device to generate on
504
+
505
+ Returns:
506
+ samples: [num_samples, seq_length] - Generated token IDs
507
+ """
508
+ if seq_length is None:
509
+ seq_length = self.config.model_length
510
+ if device is None:
511
+ device = next(self.parameters()).device
512
+
513
+ embed_dim = self.config.hidden_size
514
+ eps = 1e-5
515
+
516
+ # Initialize with Gaussian noise
517
+ z = torch.randn(num_samples, seq_length, embed_dim, device=device)
518
+
519
+ # Create gamma schedule from t=1-eps to t=eps
520
+ t = torch.linspace(1.0 - eps, eps, num_steps, device=device)
521
+ gamma = self.proposal(t)
522
+
523
+ # Self-conditioning state
524
+ x_self_cond = None
525
+
526
+ # Euler-EDM sampling loop
527
+ for i in range(len(gamma) - 1):
528
+ gamma_t = gamma[i]
529
+ gamma_s = gamma[i + 1]
530
+
531
+ # Get model prediction
532
+ gamma_expanded = gamma_t.unsqueeze(0).expand(num_samples)
533
+ logits = self.forward(
534
+ noisy_embeds=z,
535
+ timesteps=gamma_expanded,
536
+ x_self_cond=x_self_cond,
537
+ return_dict=False)
538
+
539
+ # Convert logits to embedding prediction
540
+ probs = F.softmax(logits.float(), dim=-1)
541
+ x_pred = self._embed_tokens(probs)
542
+
543
+ # Update self-conditioning
544
+ if self.config.self_conditioning:
545
+ x_self_cond = x_pred
546
+
547
+ # Euler step
548
+ z = self._euler_edm_step(z, x_pred, gamma_t, gamma_s)
549
+
550
+ # Final step: get logits and take argmax
551
+ gamma_final = gamma[-1]
552
+ gamma_expanded = gamma_final.unsqueeze(0).expand(num_samples)
553
+ logits = self.forward(
554
+ noisy_embeds=z,
555
+ timesteps=gamma_expanded,
556
+ x_self_cond=x_self_cond,
557
+ return_dict=False)
558
+ samples = logits.argmax(dim=-1)
559
+
560
+ return samples
checkpoints/official/langflow/owt/README.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ datasets:
3
+ - Skylion007/openwebtext
4
+ papers:
5
+ - arxiv: 2604.11748
6
+ language:
7
+ - en
8
+ library_name: transformers
9
+ license: apache-2.0
10
+ metrics:
11
+ - perplexity
12
+ pipeline_tag: text-generation
13
+ ---
14
+
15
+ # LangFlow
16
+
17
+ LangFlow is a continuous diffusion language model that operates in embedding space. Unlike discrete diffusion models (MDLM, SEDD, DUO), LangFlow performs diffusion directly on continuous token embeddings, enabling smoother denoising dynamics.
18
+
19
+ For more details, please see our paper: [LangFlow: Continuous Diffusion Rivals Discrete in Language Modeling](https://arxiv.org/abs/2604.11748).
20
+
21
+
22
+ ## Using LangFlow
23
+
24
+ To use the pre-trained model for text generation, use the following snippet:
25
+
26
+ ```python
27
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
28
+
29
+ tokenizer = AutoTokenizer.from_pretrained('gpt2')
30
+ model = AutoModelForMaskedLM.from_pretrained('chumengl/langflow-owt', trust_remote_code=True)
31
+
32
+ # Generate samples
33
+ samples = model.generate_samples(num_samples=5, num_steps=128)
34
+ texts = tokenizer.batch_decode(samples, skip_special_tokens=True)
35
+ for text in texts:
36
+ print(text)
37
+ ```
38
+
39
+ ## Model Details
40
+
41
+ - **Architecture**: DiT (Diffusion Transformer) backbone with adaptive layer normalization
42
+ - **Context Length**: 1024 tokens
43
+ - **Parameters**: ~130M non-embedding parameters (similar to GPT-2 medium)
44
+ - **Training**: 1M steps on OpenWebText corpus
45
+ - **Tokenizer**: GPT-2 tokenizer (50,257 vocab size)
46
+
47
+ ## Citation
48
+
49
+ ```
50
+ @article{chen2026langflow,
51
+ title={LangFlow: Continuous Diffusion Rivals Discrete in Language Modeling},
52
+ author={Chen, Yuxin and Liang, Chumeng and Sui, Hangke and Guo, Ruihan and Cheng, Chaoran and You, Jiaxuan and Liu, Ge},
53
+ journal={arXiv preprint arXiv:2604.11748},
54
+ year={2026}
55
+ }
56
+ ```
57
+
58
+ ## Model Card Contact
59
+
60
+ Chumeng Liang (chumengl@illinois.edu)
61
+
checkpoints/official/langflow/owt/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """HuggingFace release package for LangFlow."""
2
+
3
+ from .config import LangFlowConfig
4
+ from .model import LangFlow
5
+
6
+ __all__ = ["LangFlowConfig", "LangFlow"]
checkpoints/official/langflow/owt/model.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace model implementation for LangFlow.
2
+
3
+ LangFlow is a continuous diffusion language model that operates in embedding space.
4
+ """
5
+
6
+ import math
7
+ import typing
8
+
9
+ import einops
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import transformers
14
+
15
+ from .config import LangFlowConfig
16
+
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
+ @torch.jit.script
43
+ def bias_dropout_add_scale_fused_train(
44
+ x: torch.Tensor,
45
+ bias: typing.Optional[torch.Tensor],
46
+ scale: torch.Tensor,
47
+ residual: typing.Optional[torch.Tensor],
48
+ prob: float) -> torch.Tensor:
49
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, True)
50
+
51
+
52
+ @torch.jit.script
53
+ def bias_dropout_add_scale_fused_inference(
54
+ x: torch.Tensor,
55
+ bias: typing.Optional[torch.Tensor],
56
+ scale: torch.Tensor,
57
+ residual: typing.Optional[torch.Tensor],
58
+ prob: float) -> torch.Tensor:
59
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, False)
60
+
61
+
62
+ @torch.jit.script
63
+ def modulate_fused(x: torch.Tensor,
64
+ shift: torch.Tensor,
65
+ scale: torch.Tensor) -> torch.Tensor:
66
+ return x * (1 + scale) + shift
67
+
68
+
69
+ class Rotary(nn.Module):
70
+ def __init__(self, dim, base=10_000):
71
+ super().__init__()
72
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
73
+ self.register_buffer('inv_freq', inv_freq)
74
+ self.seq_len_cached = None
75
+ self.cos_cached = None
76
+ self.sin_cached = None
77
+
78
+ def forward(self, x, seq_dim=1):
79
+ seq_len = x.shape[seq_dim]
80
+ if seq_len != self.seq_len_cached:
81
+ self.seq_len_cached = seq_len
82
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
83
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
84
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
85
+ self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1, 1, 3, 1, 1)
86
+ self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1, 1, 3, 1, 1)
87
+ self.cos_cached[:, :, 2, :, :].fill_(1.)
88
+ self.sin_cached[:, :, 2, :, :].fill_(0.)
89
+ return self.cos_cached, self.sin_cached
90
+
91
+
92
+ def _apply_rotary_emb(x, cos, sin):
93
+ # x: [batch, seqlen, nheads, headdim]
94
+ # cos, sin: [seqlen, headdim//2]
95
+ ro_dim = cos.shape[-1] * 2
96
+ # Expand to [1, seqlen, 1, ro_dim] for broadcasting
97
+ cos = torch.cat([cos, cos], dim=-1)[None, :, None, :]
98
+ sin = torch.cat([sin, sin], dim=-1)[None, :, None, :]
99
+ x_rot = x[..., :ro_dim]
100
+ x1, x2 = x_rot.chunk(2, dim=-1)
101
+ x_rotated = torch.cat([-x2, x1], dim=-1)
102
+ return torch.cat([x_rot * cos + x_rotated * sin, x[..., ro_dim:]], dim=-1)
103
+
104
+
105
+ def split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin):
106
+ with torch.autocast(device_type='cuda', enabled=False):
107
+ cos, sin = rotary_cos_sin
108
+ cos = cos.to(qkv.dtype)
109
+ sin = sin.to(qkv.dtype)
110
+ cos = cos[0, :, 0, 0, :cos.shape[-1]//2]
111
+ sin = sin[0, :, 0, 0, :sin.shape[-1]//2]
112
+ q, k, v = qkv.chunk(3, dim=2)
113
+ q = _apply_rotary_emb(q.squeeze(dim=2), cos, sin)
114
+ k = _apply_rotary_emb(k.squeeze(dim=2), cos, sin)
115
+ v = v.squeeze(dim=2)
116
+ return q, k, v
117
+
118
+
119
+ def regular_attention_multi_headed(q, k, v):
120
+ attention_output = F.scaled_dot_product_attention(
121
+ query=q.transpose(1, 2),
122
+ key=k.transpose(1, 2),
123
+ value=v.transpose(1, 2),
124
+ attn_mask=None,
125
+ dropout_p=0.0,
126
+ is_causal=False)
127
+ attention_output = attention_output.transpose(1, 2)
128
+ return einops.rearrange(attention_output, 'b s h d -> b s (h d)')
129
+
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
+
137
+ def forward(self, x):
138
+ with torch.autocast(device_type='cuda', enabled=False):
139
+ x = F.layer_norm(x.float(), [self.dim])
140
+ return x * self.weight[None, None, :]
141
+
142
+
143
+ class TimestepEmbedder(nn.Module):
144
+ """Embeds scalar timesteps into vector representations."""
145
+
146
+ def __init__(self, hidden_size, frequency_embedding_size=256):
147
+ super().__init__()
148
+ self.mlp = nn.Sequential(
149
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
150
+ nn.SiLU(),
151
+ nn.Linear(hidden_size, hidden_size, bias=True))
152
+ self.frequency_embedding_size = frequency_embedding_size
153
+
154
+ @staticmethod
155
+ def timestep_embedding(t, dim, max_period=10000):
156
+ half = dim // 2
157
+ freqs = torch.exp(
158
+ -math.log(max_period)
159
+ * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device)
160
+ / half)
161
+ args = t[:, None].float() * freqs[None]
162
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
163
+ if dim % 2:
164
+ embedding = torch.cat(
165
+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
166
+ return embedding
167
+
168
+ def forward(self, t):
169
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
170
+ t_emb = self.mlp(t_freq)
171
+ return t_emb
172
+
173
+
174
+ class DDiTBlock(nn.Module):
175
+ def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4, dropout=0.1):
176
+ super().__init__()
177
+ self.n_heads = n_heads
178
+
179
+ self.norm1 = LayerNorm(dim)
180
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
181
+ self.attn_out = nn.Linear(dim, dim, bias=False)
182
+
183
+ self.norm2 = LayerNorm(dim)
184
+ self.mlp = nn.Sequential(
185
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
186
+ nn.GELU(approximate='tanh'),
187
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
188
+ self.dropout = dropout
189
+
190
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim)
191
+ self.adaLN_modulation.weight.data.zero_()
192
+ self.adaLN_modulation.bias.data.zero_()
193
+
194
+ def _get_bias_dropout_scale(self):
195
+ if self.training:
196
+ return bias_dropout_add_scale_fused_train
197
+ else:
198
+ return bias_dropout_add_scale_fused_inference
199
+
200
+ def forward(self, x, rotary_cos_sin, c):
201
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
202
+
203
+ x_skip = x
204
+ x = self.norm1(x)
205
+
206
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
207
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
208
+ x = modulate_fused(x, shift_msa, scale_msa)
209
+
210
+ qkv = einops.rearrange(
211
+ self.attn_qkv(x),
212
+ 'b s (three h d) -> b s three h d',
213
+ three=3,
214
+ h=self.n_heads)
215
+ q, k, v = split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin)
216
+ x = regular_attention_multi_headed(q, k, v)
217
+
218
+ x = bias_dropout_scale_fn(self.attn_out(x), None, gate_msa, x_skip, self.dropout)
219
+ x = bias_dropout_scale_fn(
220
+ self.mlp(modulate_fused(self.norm2(x), shift_mlp, scale_mlp)),
221
+ None, gate_mlp, x, self.dropout)
222
+ return x
223
+
224
+
225
+ def _normalize_embedding_layernorm(weight: torch.Tensor) -> torch.Tensor:
226
+ """Normalize embedding weights to unit norm per row, then scale by sqrt(dim)."""
227
+ normalized = F.normalize(weight.float(), dim=-1)
228
+ return (normalized * math.sqrt(weight.shape[-1])).to(weight.dtype)
229
+
230
+
231
+ class EmbeddingLayer(nn.Module):
232
+ """Embedding layer with optional layernorm normalization."""
233
+
234
+ def __init__(self, dim, vocab_dim, use_normalized_embedding=True):
235
+ super().__init__()
236
+ self.dim = dim
237
+ self.vocab_dim = vocab_dim
238
+ self.use_normalized_embedding = use_normalized_embedding
239
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
240
+ nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
241
+
242
+ def _get_embedding(self):
243
+ if self.use_normalized_embedding:
244
+ return _normalize_embedding_layernorm(self.embedding)
245
+ return self.embedding
246
+
247
+ def forward(self, x):
248
+ embedding = self._get_embedding()
249
+ if x.ndim == 2:
250
+ return embedding[x]
251
+ assert x.ndim == 3 # probabilities
252
+ return torch.einsum("blv,ve->ble", x.float(), embedding.float()).to(x.dtype)
253
+
254
+
255
+ class DDiTFinalLayer(nn.Module):
256
+ def __init__(self, hidden_size, out_channels, cond_dim):
257
+ super().__init__()
258
+ self.norm_final = LayerNorm(hidden_size)
259
+ self.linear = nn.Linear(hidden_size, out_channels)
260
+ self.linear.weight.data.zero_()
261
+ self.linear.bias.data.zero_()
262
+ self.adaLN_modulation = nn.Linear(cond_dim, 2 * hidden_size, bias=True)
263
+ self.adaLN_modulation.weight.data.zero_()
264
+ self.adaLN_modulation.bias.data.zero_()
265
+
266
+ def forward(self, x, c):
267
+ x = self.norm_final(x)
268
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
269
+ x = modulate_fused(x, shift, scale)
270
+ x = self.linear(x)
271
+ return x
272
+
273
+
274
+ class GumbelProposal(nn.Module):
275
+ """Learnable Gumbel distribution proposal for sampling gamma (log-SNR)."""
276
+
277
+ def __init__(self, loc: float = 4.723, scale: float = 0.852,
278
+ cutoff: float = 1e-5, entropy: float = 7.02):
279
+ super().__init__()
280
+ self.loc = nn.Parameter(torch.tensor(loc))
281
+ self.scale = nn.Parameter(torch.tensor(scale))
282
+ self.cutoff = cutoff
283
+ self.entropy = nn.Parameter(torch.tensor(entropy))
284
+
285
+ def _get_distribution(self) -> torch.distributions.Gumbel:
286
+ return torch.distributions.Gumbel(self.loc, self.scale)
287
+
288
+ @property
289
+ def gamma_min(self) -> float:
290
+ return float(self.loc - math.log(-math.log(self.cutoff)) * self.scale)
291
+
292
+ @property
293
+ def gamma_max(self) -> float:
294
+ return float(self.loc - math.log(self.cutoff) * self.scale)
295
+
296
+ def forward(self, q: torch.Tensor) -> torch.Tensor:
297
+ """Convert uniform samples to gamma values via inverse CDF."""
298
+ gamma = self._get_distribution().icdf(q)
299
+ return gamma.clamp(min=self.gamma_min, max=self.gamma_max)
300
+
301
+ def log_pdf(self, gamma: torch.Tensor) -> torch.Tensor:
302
+ """Compute log probability density at gamma."""
303
+ return self._get_distribution().log_prob(gamma)
304
+
305
+
306
+ class LangFlowBackbone(nn.Module):
307
+ """DiT backbone for LangFlow."""
308
+
309
+ def __init__(self, config: LangFlowConfig):
310
+ super().__init__()
311
+ self.config = config
312
+ dim = config.hidden_size
313
+ cond_dim = config.cond_dim
314
+
315
+ self.vocab_embed = EmbeddingLayer(
316
+ dim, config.vocab_size,
317
+ use_normalized_embedding=config.use_normalized_embedding)
318
+ self.sigma_map = TimestepEmbedder(cond_dim)
319
+ self.rotary_emb = Rotary(dim // config.n_heads)
320
+
321
+ self.blocks = nn.ModuleList([
322
+ DDiTBlock(dim=dim, n_heads=config.n_heads, cond_dim=cond_dim, dropout=config.dropout)
323
+ for _ in range(config.n_blocks)
324
+ ])
325
+
326
+ self.output_layer = DDiTFinalLayer(
327
+ hidden_size=dim, out_channels=config.vocab_size, cond_dim=cond_dim)
328
+
329
+ # Self-conditioning projection
330
+ if config.self_conditioning:
331
+ self.self_cond_proj = nn.Linear(dim * 2, dim, bias=False)
332
+ nn.init.zeros_(self.self_cond_proj.weight)
333
+
334
+ def forward(self, x_embed, sigma, x_self_cond=None, output_hidden_states=False):
335
+ """Forward pass from embeddings.
336
+
337
+ Args:
338
+ x_embed: [B, L, D] - Input embeddings (possibly noisy)
339
+ sigma: [B] - Gamma values (log-SNR)
340
+ x_self_cond: [B, L, D] - Self-conditioning embeddings (optional)
341
+ output_hidden_states: Whether to return all hidden states
342
+
343
+ Returns:
344
+ logits: [B, L, vocab_size]
345
+ hidden_states: List of hidden states if output_hidden_states=True
346
+ """
347
+ all_hidden_states = []
348
+ x = x_embed
349
+
350
+ if output_hidden_states:
351
+ all_hidden_states.append(x)
352
+
353
+ # Self-conditioning
354
+ if self.config.self_conditioning:
355
+ if x_self_cond is None:
356
+ x_self_cond = torch.zeros_like(x)
357
+ x = x + self.self_cond_proj(torch.cat([x, x_self_cond], dim=-1))
358
+
359
+ t_cond = F.silu(self.sigma_map(sigma))
360
+ rotary_cos_sin = self.rotary_emb(x)
361
+
362
+ with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
363
+ for block in self.blocks:
364
+ x = block(x, rotary_cos_sin, c=t_cond)
365
+ if output_hidden_states:
366
+ all_hidden_states.append(x)
367
+ x = self.output_layer(x, c=t_cond)
368
+
369
+ return x, all_hidden_states
370
+
371
+
372
+ class LangFlow(transformers.PreTrainedModel):
373
+ """HuggingFace-compatible LangFlow model.
374
+
375
+ LangFlow is a continuous diffusion language model that operates in embedding space.
376
+ It uses a DiT (Diffusion Transformer) backbone with:
377
+ - Self-conditioning: uses previous predictions as additional input
378
+ - Bias (preconditioning): skip connection for improved generation
379
+ - Normalized embeddings: layernorm on embedding vectors
380
+ - Learnable Gumbel proposal for gamma (log-SNR) sampling
381
+ """
382
+ config_class = LangFlowConfig
383
+ base_model_prefix = "langflow"
384
+
385
+ def __init__(self, config: LangFlowConfig):
386
+ super().__init__(config)
387
+ self.config = config
388
+ self.backbone = LangFlowBackbone(config)
389
+ self.proposal = GumbelProposal(
390
+ loc=config.gumbel_loc,
391
+ scale=config.gumbel_scale,
392
+ cutoff=config.gumbel_cutoff,
393
+ entropy=config.gumbel_entropy)
394
+
395
+ def _get_embedding_matrix(self) -> torch.Tensor:
396
+ """Get the embedding matrix for bias skip connection."""
397
+ return self.backbone.vocab_embed._get_embedding()
398
+
399
+ def _embed_tokens(self, x: torch.Tensor) -> torch.Tensor:
400
+ """Embed tokens or probabilities to continuous embeddings."""
401
+ return self.backbone.vocab_embed(x)
402
+
403
+ def _forward_diffusion(self, x_embed: torch.Tensor,
404
+ gamma: torch.Tensor) -> torch.Tensor:
405
+ """Add noise to embeddings (forward diffusion process)."""
406
+ gamma = gamma.float()
407
+ alpha = torch.sigmoid(-gamma).sqrt()[:, None, None]
408
+ sigma = torch.sigmoid(gamma).sqrt()[:, None, None]
409
+ noise = torch.randn_like(x_embed)
410
+ return (x_embed * alpha + noise * sigma).to(x_embed.dtype)
411
+
412
+ def _euler_edm_step(self, z: torch.Tensor, x_pred: torch.Tensor,
413
+ t: torch.Tensor, s: torch.Tensor) -> torch.Tensor:
414
+ """Single Euler step for EDM sampling."""
415
+ t_ = t.double()
416
+ s_ = s.double()
417
+ cur = z.double() * ((F.softplus(t_) - F.softplus(s_)) / 2).exp()
418
+ end = torch.sigmoid(-s_).sqrt() * x_pred.double()
419
+ z = end.lerp(cur, ((s_ - t_) / 2).exp()).to(z.dtype)
420
+ return z
421
+
422
+ def forward(
423
+ self,
424
+ input_ids: typing.Optional[torch.LongTensor] = None,
425
+ noisy_embeds: typing.Optional[torch.FloatTensor] = None,
426
+ timesteps: typing.Optional[torch.FloatTensor] = None,
427
+ x_self_cond: typing.Optional[torch.FloatTensor] = None,
428
+ output_hidden_states: typing.Optional[bool] = None,
429
+ return_dict: typing.Optional[bool] = None,
430
+ ) -> typing.Union[torch.Tensor, typing.Tuple, transformers.modeling_outputs.MaskedLMOutput]:
431
+ """Forward pass for LangFlow.
432
+
433
+ Args:
434
+ input_ids: [B, L] - Token IDs (will be embedded and noised if timesteps provided)
435
+ noisy_embeds: [B, L, D] - Pre-noised embeddings (alternative to input_ids)
436
+ timesteps: [B] - Gamma values (log-SNR) for conditioning
437
+ x_self_cond: [B, L, D] - Self-conditioning embeddings
438
+ output_hidden_states: Whether to return hidden states
439
+ return_dict: Whether to return MaskedLMOutput
440
+
441
+ Returns:
442
+ logits or MaskedLMOutput
443
+ """
444
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
445
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
446
+
447
+ # Get embeddings
448
+ if noisy_embeds is not None:
449
+ z = noisy_embeds
450
+ elif input_ids is not None:
451
+ x_embed = self._embed_tokens(input_ids)
452
+ if timesteps is not None:
453
+ z = self._forward_diffusion(x_embed, timesteps)
454
+ else:
455
+ z = x_embed
456
+ else:
457
+ raise ValueError("Either input_ids or noisy_embeds must be provided")
458
+
459
+ if timesteps is None:
460
+ # Use minimum gamma for clean input
461
+ timesteps = torch.full((z.shape[0],), self.proposal.gamma_min, device=z.device)
462
+
463
+ # Process sigma
464
+ sigma = timesteps
465
+ if sigma.ndim == 2:
466
+ sigma = sigma.mean(-1)
467
+
468
+ # Get model output
469
+ logits, all_hidden_states = self.backbone(
470
+ z, sigma, x_self_cond=x_self_cond, output_hidden_states=output_hidden_states)
471
+
472
+ # Add bias (preconditioning) skip connection
473
+ if self.config.use_bias:
474
+ c_skip = ((F.softplus(-sigma) - sigma) / 2).exp()
475
+ embedding = self._get_embedding_matrix()
476
+ skip_logits = torch.matmul(z.float(), embedding.t().float())
477
+ logits = logits + c_skip[:, None, None] * skip_logits.to(logits.dtype)
478
+
479
+ if return_dict:
480
+ return transformers.modeling_outputs.MaskedLMOutput(
481
+ logits=logits,
482
+ hidden_states=all_hidden_states if output_hidden_states else None,
483
+ loss=None)
484
+ elif output_hidden_states:
485
+ return logits, all_hidden_states
486
+ else:
487
+ return logits
488
+
489
+ @torch.no_grad()
490
+ def generate_samples(
491
+ self,
492
+ num_samples: int = 1,
493
+ seq_length: typing.Optional[int] = None,
494
+ num_steps: int = 128,
495
+ device: typing.Optional[torch.device] = None,
496
+ ) -> torch.LongTensor:
497
+ """Generate samples using Euler-EDM solver.
498
+
499
+ Args:
500
+ num_samples: Number of samples to generate
501
+ seq_length: Sequence length (defaults to config.model_length)
502
+ num_steps: Number of denoising steps
503
+ device: Device to generate on
504
+
505
+ Returns:
506
+ samples: [num_samples, seq_length] - Generated token IDs
507
+ """
508
+ if seq_length is None:
509
+ seq_length = self.config.model_length
510
+ if device is None:
511
+ device = next(self.parameters()).device
512
+
513
+ embed_dim = self.config.hidden_size
514
+ eps = 1e-5
515
+
516
+ # Initialize with Gaussian noise
517
+ z = torch.randn(num_samples, seq_length, embed_dim, device=device)
518
+
519
+ # Create gamma schedule from t=1-eps to t=eps
520
+ t = torch.linspace(1.0 - eps, eps, num_steps, device=device)
521
+ gamma = self.proposal(t)
522
+
523
+ # Self-conditioning state
524
+ x_self_cond = None
525
+
526
+ # Euler-EDM sampling loop
527
+ for i in range(len(gamma) - 1):
528
+ gamma_t = gamma[i]
529
+ gamma_s = gamma[i + 1]
530
+
531
+ # Get model prediction
532
+ gamma_expanded = gamma_t.unsqueeze(0).expand(num_samples)
533
+ logits = self.forward(
534
+ noisy_embeds=z,
535
+ timesteps=gamma_expanded,
536
+ x_self_cond=x_self_cond,
537
+ return_dict=False)
538
+
539
+ # Convert logits to embedding prediction
540
+ probs = F.softmax(logits.float(), dim=-1)
541
+ x_pred = self._embed_tokens(probs)
542
+
543
+ # Update self-conditioning
544
+ if self.config.self_conditioning:
545
+ x_self_cond = x_pred
546
+
547
+ # Euler step
548
+ z = self._euler_edm_step(z, x_pred, gamma_t, gamma_s)
549
+
550
+ # Final step: get logits and take argmax
551
+ gamma_final = gamma[-1]
552
+ gamma_expanded = gamma_final.unsqueeze(0).expand(num_samples)
553
+ logits = self.forward(
554
+ noisy_embeds=z,
555
+ timesteps=gamma_expanded,
556
+ x_self_cond=x_self_cond,
557
+ return_dict=False)
558
+ samples = logits.argmax(dim=-1)
559
+
560
+ return samples
checkpoints/official/mdlm/owt/README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ license: apache-2.0
4
+ language:
5
+ - en
6
+ datasets:
7
+ - Skylion007/openwebtext
8
+ metrics:
9
+ - perplexity
10
+ ---
11
+
12
+ ## Using MDLM
13
+ To use the pre-trained model for masked language modeling, use the following snippet:
14
+ ```python
15
+ from transformers import AutoModelForMaskedLM, AutoTokenizer
16
+
17
+ # See the `MDLM` collection page on the hub for list of available models.
18
+ tokenizer = transformers.AutoTokenizer.from_pretrained('gpt2')
19
+ model_name = 'kuleshov-group/mdlm-owt'
20
+ model = AutoModelForMaskedLM.from_pretrained(model_name)
21
+ ```
22
+
23
+ For more details, please see our github repository: [MDLM](https://github.com/kuleshov-group/mdlm)
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 using a forward diffusion process that generates inputs varying from fully masked to fully unmasked. Its objective is to
28
+ reconstruct the original input from these varying levels of masking, outputting logits in the process.
29
+ The training regimen comprised one million steps on the OpenWebText corpus, involving the processing of a total of `33 billion` tokens.
30
+
31
+ For more details, please see our paper: [Simple and Effective Masked Diffusion Language Models](http://arxiv.org/abs/2406.07524).
32
+
33
+
34
+
35
+ ## Citation
36
+
37
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
38
+ Please cite our work using the bibtex below:
39
+
40
+ **BibTeX:**
41
+
42
+ ```
43
+ @inproceedings{
44
+ sahoo2024simple,
45
+ title={Simple and Effective Masked Diffusion Language Models},
46
+ author={Subham Sekhar Sahoo and Marianne Arriola and Aaron Gokaslan and Edgar Mariano Marroquin and Alexander M Rush and Yair Schiff and Justin T Chiu and Volodymyr Kuleshov},
47
+ booktitle={The Thirty-eighth Annual Conference on Neural Information Processing Systems},
48
+ year={2024},
49
+ url={https://openreview.net/forum?id=L4uaAR4ArM}
50
+ }
51
+ ```
52
+
53
+ **APA:**
54
+
55
+ ```
56
+ @software{Sahoo_Simple_and_Effective_2024,
57
+ author = {Sahoo, Subham Sekhar and Arriola, Marianne and Schiff, Yair and Gokaslan, Aaron and Marroquin, Edgar and Chiu, Justin T and Rush, Alexander and Kuleshov, Volodymyr},
58
+ doi = {10.48550/arXiv.2406.07524},
59
+ month = jun,
60
+ title = {{Simple and Effective Masked Diffusion Language Models}},
61
+ version = {arXiv:2406.07524v1},
62
+ year = {2024}
63
+ }
64
+ ```
65
+
66
+ ## Model Card Contact
67
+ Subham Sekhar Sahoo (subbham@gmail.com)
checkpoints/official/mdlm/owt/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
+ }
checkpoints/official/mdlm/owt/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
checkpoints/official/mdlm/owt/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
checkpoints/quarantine/20260802T040549Z/official/fmlm/lm1b/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ license: apache-2.0
6
+ language:
7
+ - en
8
+ base_model:
9
+ - david3684/FLM-B-LM1B
10
+ ---
11
+
12
+ ## FMLM (LM1B)
13
+
14
+ For more information and implementation details, visit our github repository: [FLM](https://github.com/david3684/flm).
15
+
16
+ ## Model Details
17
+
18
+ The model has a context length of 128, distilled from 1M steps trained FLM checkpoint trained on the One Billion Words (LM1B) dataset.
19
+
20
+ For more details, please see our paper:
21
+ - [arXiv:2602.16813](https://arxiv.org/abs/2602.16813)
22
+ - [Huggingface Papers](https://huggingface.co/papers/2602.16813)
23
+
24
+ ## Citation
25
+
26
+ Please cite our work using the bibtex below:
27
+
28
+ **BibTeX:**
29
+
30
+
31
+ ```bibtex
32
+ @article{lee2026flow,
33
+ title={Flow Map Language Models: One-step Language Modeling via Continuous Denoising},
34
+ author={Chanhyuk Lee and Jaehoon Yoo and Manan Agarwal
35
+ and Sheel Shah and Jerry Huang
36
+ and Aditi Raghunathan and Seunghoon Hong
37
+ and Nicholas M. Boffi and Jinwoo Kim},
38
+ journal={arXiv preprint arXiv:2602.16813},
39
+ year={2026},
40
+ }
41
+ ```
42
+
43
+ ## Model Card Contact
44
+
45
+ Chanhyuk Lee (chanhyuk-lee@kaist.ac.kr)
checkpoints/quarantine/20260802T040549Z/official/fmlm/lm1b/config.json ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "algo": {
4
+ "T": 0,
5
+ "add_boundary": "fixed",
6
+ "backbone": "dit",
7
+ "backprop_entmax_temp_lsd": false,
8
+ "boundary_prob": 32,
9
+ "causal_attention": false,
10
+ "diagonal_fraction": 0.5,
11
+ "distillation_method": "PSD",
12
+ "double_temb": true,
13
+ "entmax_temp_lsd": 2.0,
14
+ "initialize_student_from_teacher": false,
15
+ "learnable_loss_weighting": false,
16
+ "loss_scale": "none",
17
+ "loss_type": null,
18
+ "name": "fmlm",
19
+ "offdiagonal_sampling": "uniform_diff",
20
+ "parameterization": "mean",
21
+ "pred_log_interval": 2000,
22
+ "rescale_offdiag_loss_psd": false,
23
+ "subs_masking": false,
24
+ "t_max": 1.0,
25
+ "t_min": 0.0,
26
+ "teacher_path": "/home/david3684/ours_flow_ce_1m.ckpt",
27
+ "time_condition": "alpha_t",
28
+ "time_conditioning": true,
29
+ "use_discrete_schedule": true,
30
+ "use_mse_loss_psd": false,
31
+ "use_simulated_entropy": false,
32
+ "use_teacher_for_D_t_lsd": false
33
+ },
34
+ "callbacks": {
35
+ "checkpoint_every_n_steps": {
36
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
37
+ "auto_insert_metric_name": false,
38
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
39
+ "every_n_train_steps": 25000,
40
+ "save_last": false,
41
+ "save_top_k": -1,
42
+ "verbose": true
43
+ },
44
+ "checkpoint_monitor": {
45
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
46
+ "auto_insert_metric_name": false,
47
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
48
+ "filename": "best_nll",
49
+ "mode": "min",
50
+ "monitor": "val/nll",
51
+ "save_last": true,
52
+ "save_top_k": 1,
53
+ "verbose": true
54
+ },
55
+ "learning_rate_monitor": {
56
+ "_target_": "lightning.pytorch.callbacks.LearningRateMonitor",
57
+ "logging_interval": "step"
58
+ }
59
+ },
60
+ "checkpointing": {
61
+ "resume_ckpt_path": "/home/david3684/projects/flm/hf_upload/checkpoints/last.ckpt",
62
+ "resume_from_ckpt": false,
63
+ "save_dir": "/home/david3684/projects/flm/hf_upload"
64
+ },
65
+ "data": {
66
+ "cache_dir": "/home/david3684/datasets/lm1b",
67
+ "insert_train_eos": true,
68
+ "insert_valid_eos": true,
69
+ "streaming": false,
70
+ "tokenizer_name_or_path": "bert-base-uncased",
71
+ "train": "lm1b",
72
+ "valid": "lm1b",
73
+ "wrap": true
74
+ },
75
+ "eval": {
76
+ "checkpoint_path": "",
77
+ "compute_generative_perplexity": true,
78
+ "compute_perplexity_on_sanity": false,
79
+ "disable_ema": false,
80
+ "ema_decay": null,
81
+ "gen_ppl_eval_model_name_or_path": "gpt2-large",
82
+ "generate_samples": true,
83
+ "generated_samples_path": "/home/david3684/projects/flm/hf_upload/samples.json",
84
+ "perplexity_batch_size": 8
85
+ },
86
+ "is_di4c": false,
87
+ "is_di4c_deterministic": true,
88
+ "loader": {
89
+ "batch_size": 128,
90
+ "eval_batch_size": 128,
91
+ "eval_global_batch_size": 512,
92
+ "global_batch_size": 512,
93
+ "num_workers": 0,
94
+ "pin_memory": true
95
+ },
96
+ "lr_scheduler": {
97
+ "_target_": "transformers.get_constant_schedule_with_warmup",
98
+ "num_warmup_steps": 2500
99
+ },
100
+ "mode": "train",
101
+ "model": {
102
+ "cond_dim": 128,
103
+ "dropout": 0.1,
104
+ "hidden_size": 768,
105
+ "length": 128,
106
+ "n_blocks": 12,
107
+ "n_heads": 12,
108
+ "name": "small",
109
+ "scale_by_sigma": true,
110
+ "tie_word_embeddings": false,
111
+ "type": "ddit",
112
+ "vocab_lookup": true
113
+ },
114
+ "noise": {
115
+ "denoiser_latent_conditioning": -1,
116
+ "eps": 0,
117
+ "freeze_decoder": false,
118
+ "freeze_encoder": false,
119
+ "parameterization": "log-linear",
120
+ "type": "log-linear"
121
+ },
122
+ "optim": {
123
+ "beta1": 0.9,
124
+ "beta2": 0.999,
125
+ "eps": 1e-08,
126
+ "ln_tune": "none",
127
+ "lr": 0.0003,
128
+ "muon_lr": 0.03,
129
+ "muon_momentum": 0.95,
130
+ "muon_weight_decay": 0.01,
131
+ "use_muon": false,
132
+ "weight_decay": 0
133
+ },
134
+ "prior": {
135
+ "latent_height": 0,
136
+ "latent_width": 0,
137
+ "type": "none"
138
+ },
139
+ "sampling": {
140
+ "argmax_correction": false,
141
+ "autoguidance_weight": 0.0,
142
+ "hard_start": false,
143
+ "noise_removal": "uniform_alpha",
144
+ "num_reflow_samples": 50000,
145
+ "num_sample_batches": 1,
146
+ "num_sample_log": 2,
147
+ "num_strides": 1,
148
+ "p_nucleus": 1.0,
149
+ "predictor": "ancestral",
150
+ "semi_ar": false,
151
+ "solver": "euler",
152
+ "steps": [
153
+ 1,
154
+ 2,
155
+ 4,
156
+ 8,
157
+ 16,
158
+ 32,
159
+ 64,
160
+ 128
161
+ ],
162
+ "stride_length": 1,
163
+ "tau_log10": -1.0,
164
+ "temperature": 1.0,
165
+ "use_float64": true
166
+ },
167
+ "seed": 1,
168
+ "strategy": {
169
+ "_target_": "lightning.pytorch.strategies.DDPStrategy",
170
+ "find_unused_parameters": false
171
+ },
172
+ "trainer": {
173
+ "_target_": "lightning.Trainer",
174
+ "accelerator": "cuda",
175
+ "accumulate_grad_batches": 1,
176
+ "devices": 8,
177
+ "gradient_clip_val": 1.0,
178
+ "limit_train_batches": 1.0,
179
+ "limit_val_batches": 10,
180
+ "log_every_n_steps": 100,
181
+ "max_steps": 1000000,
182
+ "num_nodes": 1,
183
+ "num_sanity_val_steps": 2,
184
+ "precision": "bf16",
185
+ "val_check_interval": 10000
186
+ },
187
+ "training": {
188
+ "antithetic_sampling": true,
189
+ "change_of_variables": false,
190
+ "double_ema": 0.0,
191
+ "ema": "0.9999, 0.999, 0.99, 0.95",
192
+ "finetune_path": "",
193
+ "importance_sampling": false,
194
+ "load_ema": false,
195
+ "loss_precision": "bf16",
196
+ "loss_type": "sd",
197
+ "loss_weighting": false,
198
+ "not_sampling_t": false,
199
+ "pred_type": "x0",
200
+ "sampling_eps": 0.001,
201
+ "t_curriculum_max": 1.0,
202
+ "t_curriculum_min": 0.0,
203
+ "t_curriculum_steps": 100000,
204
+ "torch_compile_mode": "default",
205
+ "use_torch_compile": true
206
+ },
207
+ "wandb": {
208
+ "group": null,
209
+ "id": "27d989c8",
210
+ "job_type": null,
211
+ "name": "lm1b_PSD_teacher_distill_DF_0.5_BP_32_SE_False_IT_False_EDMW_False_27d989c8",
212
+ "notes": "DOS",
213
+ "project": "dos_distill",
214
+ "tags": [
215
+ "lm1b",
216
+ "dos_denoiser"
217
+ ]
218
+ }
219
+ },
220
+ "vocab_size": 30522
221
+ }
checkpoints/quarantine/20260802T040557Z/official/flm/owt/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ license: apache-2.0
6
+ datasets:
7
+ - Skylion007/openwebtext
8
+ language:
9
+ - en
10
+ ---
11
+
12
+ ## FLM (OpenWebText)
13
+
14
+ For more information and implementation details, visit our github repository: [FLM](https://github.com/david3684/flm).
15
+
16
+ ## Model Details
17
+
18
+ The model has a context length of 1024, trained for 1M steps on the OpenWebText dataset.
19
+
20
+ For more details, please see our paper:
21
+ - [arXiv:2602.16813](https://arxiv.org/abs/2602.16813)
22
+ - [Huggingface Papers](https://huggingface.co/papers/2602.16813)
23
+
24
+ ## Citation
25
+
26
+ Please cite our work using the bibtex below:
27
+
28
+ **BibTeX:**
29
+
30
+
31
+ ```bibtex
32
+ @article{lee2026flow,
33
+ title={Flow Map Language Models: One-step Language Modeling via Continuous Denoising},
34
+ author={Chanhyuk Lee and Jaehoon Yoo and Manan Agarwal
35
+ and Sheel Shah and Jerry Huang
36
+ and Aditi Raghunathan and Seunghoon Hong
37
+ and Nicholas M. Boffi and Jinwoo Kim},
38
+ journal={arXiv preprint arXiv:2602.16813},
39
+ year={2026},
40
+ }
41
+ ```
42
+
43
+ ## Model Card Contact
44
+
45
+ Chanhyuk Lee (chanhyuk-lee@kaist.ac.kr)
checkpoints/quarantine/20260802T040621Z/official/duo/owt/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)
checkpoints/quarantine/20260802T040621Z/official/duo/owt/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
+ }
checkpoints/quarantine/20260802T040621Z/official/duo/owt/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
checkpoints/quarantine/20260802T040629Z/official/duo_dcd/owt/README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 `DUO` 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-distilled')
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)
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://huggingface.co/papers/2506.10892).
30
+
31
+ Project page: https://s-sahoo.com/duo
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
+ ## Model Card Contact
52
+ Subham Sekhar Sahoo (ssahoo@cs.cornell.edu)
checkpoints/quarantine/20260802T040629Z/official/duo_dcd/owt/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "s-sahoo/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
+ }
checkpoints/quarantine/20260802T040629Z/official/duo_dcd/owt/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
checkpoints/quarantine/20260802T040645Z/official/mdlm_sdtt/owt/config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "mode": "train",
3
+ "time_conditioning": false,
4
+ "T": 0,
5
+ "compile": false,
6
+ "eval_every": 5000,
7
+ "data_preprocess": {
8
+ "data_cache": "REDACTED",
9
+ "min_seq_len": -1,
10
+ "seq_len": "${model.length}",
11
+ "group_text": true,
12
+ "remove_text": true,
13
+ "num_seqs": -1,
14
+ "add_bos": false,
15
+ "add_eos": true,
16
+ "legacy_start_end_bos": true
17
+ },
18
+ "loader": {
19
+ "global_batch_size": 32,
20
+ "eval_global_batch_size": "${.global_batch_size}",
21
+ "batch_size": "${div_up:${.global_batch_size}, ${eval:${trainer.devices} * ${trainer.num_nodes}}}",
22
+ "eval_batch_size": "${div_up:${.eval_global_batch_size}, ${eval:${trainer.devices} * ${trainer.num_nodes}}}",
23
+ "num_workers": 32,
24
+ "pin_memory": true,
25
+ "persistent_workers": true
26
+ },
27
+ "training": {
28
+ "ema": 0.9999,
29
+ "antithetic_sampling": true,
30
+ "importance_sampling": false,
31
+ "sampling_eps": 1e-05,
32
+ "change_of_variables": false
33
+ },
34
+ "tokenizer": {
35
+ "name": "gpt2"
36
+ },
37
+ "optim": {
38
+ "name": "adamw",
39
+ "weight_decay": 0.0,
40
+ "lr": 0.0003,
41
+ "beta1": 0.9,
42
+ "beta2": 0.999,
43
+ "eps": 1e-08
44
+ },
45
+ "trainer": {
46
+ "_target_": "lightning.Trainer",
47
+ "accelerator": "cuda",
48
+ "num_nodes": 1,
49
+ "devices": 1,
50
+ "accumulate_grad_batches": "${div_up:${loader.global_batch_size}, ${eval:${trainer.devices} * ${loader.batch_size} * ${trainer.num_nodes}}}",
51
+ "gradient_clip_val": 1.0,
52
+ "precision": "bf16-mixed",
53
+ "num_sanity_val_steps": 2,
54
+ "max_steps": 1000000,
55
+ "log_every_n_steps": 10,
56
+ "limit_train_batches": 1.0,
57
+ "limit_val_batches": 1.0,
58
+ "val_check_interval": "${eval:${trainer.accumulate_grad_batches} * ${eval_every}}",
59
+ "check_val_every_n_epoch": null,
60
+ "benchmark": true
61
+ },
62
+ "wandb": {
63
+ "project": "text-diffusion",
64
+ "notes": "",
65
+ "group": null,
66
+ "job_type": null,
67
+ "name": null,
68
+ "tags": [
69
+ "${noise.type}",
70
+ "${data.train}",
71
+ "${data.valid}"
72
+ ]
73
+ },
74
+ "checkpointing": {
75
+ "save_dir": "${cwd:}",
76
+ "resume_from_ckpt": true,
77
+ "resume_ckpt_path": "/claire-rcp-scratch/home/deschena/fast-discrete-diff/dev/hf_downloads/baselines/kld/baselines/bwd_kl_double_dt_10k_lr_2x_sm/70000.ckpt"
78
+ },
79
+ "eval": {
80
+ "valid": {
81
+ "n_samples": 16,
82
+ "num_steps": 128
83
+ },
84
+ "ppl_with_ar": {
85
+ "run": true,
86
+ "model": "gpt2-large",
87
+ "batch_size": 8
88
+ },
89
+ "mauve": {
90
+ "run": false,
91
+ "num_rounds": 5,
92
+ "max_num_tokens": 100,
93
+ "batch_size": 8,
94
+ "scaling_factor": 5
95
+ },
96
+ "lambada_openai": {
97
+ "run": false,
98
+ "batch_size": 32,
99
+ "num_samples": 32,
100
+ "from_ema": true,
101
+ "add_bos": true,
102
+ "add_eos": true
103
+ }
104
+ },
105
+ "callbacks": {
106
+ "checkpoint_every_n_steps": {
107
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
108
+ "save_top_k": -1,
109
+ "save_last": true,
110
+ "dirpath": "${checkpointing.save_dir}/checkpoints",
111
+ "verbose": true,
112
+ "auto_insert_metric_name": false,
113
+ "every_n_train_steps": 10000
114
+ },
115
+ "learning_rate_monitor": {
116
+ "_target_": "lightning.pytorch.callbacks.LearningRateMonitor",
117
+ "logging_interval": "step"
118
+ },
119
+ "text_throughput": {
120
+ "_target_": "callbacks.text_throughput.TextThroughputMonitor"
121
+ },
122
+ "grad_norm": {
123
+ "_target_": "callbacks.gradient_norm.GradNormCallback"
124
+ }
125
+ },
126
+ "data": {
127
+ "train": "openwebtext-train",
128
+ "valid": "openwebtext-valid",
129
+ "test": "openwebtext-test",
130
+ "tokenizer_name_or_path": "gpt2",
131
+ "wrap": true,
132
+ "streaming": false
133
+ },
134
+ "model": {
135
+ "name": "small",
136
+ "type": "ddit-orig",
137
+ "hidden_size": 768,
138
+ "cond_dim": 128,
139
+ "length": 1024,
140
+ "n_blocks": 12,
141
+ "n_heads": 12,
142
+ "scale_by_sigma": true,
143
+ "dropout": 0.1,
144
+ "tie_word_embeddings": false
145
+ },
146
+ "strategy": {
147
+ "_target_": "lightning.pytorch.strategies.DDPStrategy",
148
+ "find_unused_parameters": false,
149
+ "process_group_backend": "nccl"
150
+ },
151
+ "noise": {
152
+ "type": "loglinear",
153
+ "sigma_min": 0.0001,
154
+ "sigma_max": 20
155
+ },
156
+ "lr_scheduler": {
157
+ "_target_": "transformers.get_constant_schedule_with_warmup",
158
+ "num_warmup_steps": 2500
159
+ },
160
+ "parameterization": {
161
+ "name": "multi-round-sdtt",
162
+ "log_loss_buckets": -1,
163
+ "checkpoint_path": "kuleshov-group/mdlm-owt",
164
+ "start_from_hf": false,
165
+ "distill_mode": "kl-bwd",
166
+ "num_distill_steps": 2,
167
+ "min_num_sampling_steps": 8,
168
+ "grow_dt_every": 10000,
169
+ "orig_num_sampling_steps": 1024,
170
+ "sampling_mode": "ancestral",
171
+ "loss_precision": null,
172
+ "reset_optimizer_on_growth": false,
173
+ "use_ema_on_growth": false,
174
+ "sampling": {
175
+ "uncond": {
176
+ "run": false,
177
+ "num_samples": 1024,
178
+ "batch_size": 32,
179
+ "from_ema": true,
180
+ "num_steps": 1024,
181
+ "seq_len": 1024,
182
+ "sampler": "ancestral",
183
+ "cache_preds": false,
184
+ "add_bos": false,
185
+ "add_eos": false
186
+ },
187
+ "cond_prefix": {
188
+ "run": false,
189
+ "num_samples": 1024,
190
+ "batch_size": 32,
191
+ "from_ema": true,
192
+ "dataset": "webtext",
193
+ "seq_len": 100,
194
+ "prefix_len": 50,
195
+ "num_cont_per_prefix": 5,
196
+ "min_seq_len": 1024,
197
+ "num_steps": 1024,
198
+ "sampler": "ancestral",
199
+ "cache_preds": false,
200
+ "add_bos": false,
201
+ "add_eos": false
202
+ }
203
+ }
204
+ },
205
+ "repo": "jdeschena/sdtt",
206
+ "revision": "baselines_kld"
207
+ }
checkpoints/quarantine/20260818T074854Z/official/duo_dcd/owt/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
checkpoints/quarantine/20260818T074907Z/official/mdlm/owt/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
+ }
checkpoints/quarantine/20260818T074907Z/official/mdlm/owt/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
checkpoints/quarantine/20260820T072002Z/official/flm/owt/README.md ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ license: apache-2.0
6
+ datasets:
7
+ - Skylion007/openwebtext
8
+ language:
9
+ - en
10
+ ---
11
+
12
+ ## FLM (OpenWebText)
13
+
14
+ For more information and implementation details, visit our github repository: [FLM](https://github.com/david3684/flm).
15
+
16
+ ## Model Details
17
+
18
+ The model has a context length of 1024, trained for 1M steps on the OpenWebText dataset.
19
+
20
+ For more details, please see our paper:
21
+ - [arXiv:2602.16813](https://arxiv.org/abs/2602.16813)
22
+ - [Huggingface Papers](https://huggingface.co/papers/2602.16813)
23
+
24
+ ## Citation
25
+
26
+ Please cite our work using the bibtex below:
27
+
28
+ **BibTeX:**
29
+
30
+
31
+ ```bibtex
32
+ @article{lee2026flow,
33
+ title={Flow Map Language Models: One-step Language Modeling via Continuous Denoising},
34
+ author={Chanhyuk Lee and Jaehoon Yoo and Manan Agarwal
35
+ and Sheel Shah and Jerry Huang
36
+ and Aditi Raghunathan and Seunghoon Hong
37
+ and Nicholas M. Boffi and Jinwoo Kim},
38
+ journal={arXiv preprint arXiv:2602.16813},
39
+ year={2026},
40
+ }
41
+ ```
42
+
43
+ ## Model Card Contact
44
+
45
+ Chanhyuk Lee (chanhyuk-lee@kaist.ac.kr)
checkpoints/quarantine/20260820T072143Z/official/langflow/lm1b/config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "nealchen/langflow-lm1b",
3
+ "architectures": [
4
+ "LangFlow"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "config.LangFlowConfig",
8
+ "AutoModelForMaskedLM": "model.LangFlow"
9
+ },
10
+ "model_type": "LangFlow",
11
+ "vocab_size": 30522,
12
+ "hidden_size": 768,
13
+ "cond_dim": 128,
14
+ "n_blocks": 12,
15
+ "n_heads": 12,
16
+ "dropout": 0.1,
17
+ "model_length": 128,
18
+ "use_normalized_embedding": true,
19
+ "embedding_norm_method": "layernorm",
20
+ "self_conditioning": true,
21
+ "use_bias": true,
22
+ "gumbel_loc": 4.723,
23
+ "gumbel_scale": 0.852,
24
+ "gumbel_cutoff": 1e-5,
25
+ "gumbel_entropy": 7.02,
26
+ "return_dict": true,
27
+ "torch_dtype": "float32",
28
+ "transformers_version": "4.38.2"
29
+ }
checkpoints/quarantine/20260820T072143Z/official/langflow/lm1b/model.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace model implementation for LangFlow.
2
+
3
+ LangFlow is a continuous diffusion language model that operates in embedding space.
4
+ """
5
+
6
+ import math
7
+ import typing
8
+
9
+ import einops
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import transformers
14
+
15
+ from .config import LangFlowConfig
16
+
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
+ @torch.jit.script
43
+ def bias_dropout_add_scale_fused_train(
44
+ x: torch.Tensor,
45
+ bias: typing.Optional[torch.Tensor],
46
+ scale: torch.Tensor,
47
+ residual: typing.Optional[torch.Tensor],
48
+ prob: float) -> torch.Tensor:
49
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, True)
50
+
51
+
52
+ @torch.jit.script
53
+ def bias_dropout_add_scale_fused_inference(
54
+ x: torch.Tensor,
55
+ bias: typing.Optional[torch.Tensor],
56
+ scale: torch.Tensor,
57
+ residual: typing.Optional[torch.Tensor],
58
+ prob: float) -> torch.Tensor:
59
+ return bias_dropout_add_scale(x, bias, scale, residual, prob, False)
60
+
61
+
62
+ @torch.jit.script
63
+ def modulate_fused(x: torch.Tensor,
64
+ shift: torch.Tensor,
65
+ scale: torch.Tensor) -> torch.Tensor:
66
+ return x * (1 + scale) + shift
67
+
68
+
69
+ class Rotary(nn.Module):
70
+ def __init__(self, dim, base=10_000):
71
+ super().__init__()
72
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
73
+ self.register_buffer('inv_freq', inv_freq)
74
+ self.seq_len_cached = None
75
+ self.cos_cached = None
76
+ self.sin_cached = None
77
+
78
+ def forward(self, x, seq_dim=1):
79
+ seq_len = x.shape[seq_dim]
80
+ if seq_len != self.seq_len_cached:
81
+ self.seq_len_cached = seq_len
82
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
83
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
84
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
85
+ self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1, 1, 3, 1, 1)
86
+ self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1, 1, 3, 1, 1)
87
+ self.cos_cached[:, :, 2, :, :].fill_(1.)
88
+ self.sin_cached[:, :, 2, :, :].fill_(0.)
89
+ return self.cos_cached, self.sin_cached
90
+
91
+
92
+ def _apply_rotary_emb(x, cos, sin):
93
+ # x: [batch, seqlen, nheads, headdim]
94
+ # cos, sin: [seqlen, headdim//2]
95
+ ro_dim = cos.shape[-1] * 2
96
+ # Expand to [1, seqlen, 1, ro_dim] for broadcasting
97
+ cos = torch.cat([cos, cos], dim=-1)[None, :, None, :]
98
+ sin = torch.cat([sin, sin], dim=-1)[None, :, None, :]
99
+ x_rot = x[..., :ro_dim]
100
+ x1, x2 = x_rot.chunk(2, dim=-1)
101
+ x_rotated = torch.cat([-x2, x1], dim=-1)
102
+ return torch.cat([x_rot * cos + x_rotated * sin, x[..., ro_dim:]], dim=-1)
103
+
104
+
105
+ def split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin):
106
+ with torch.autocast(device_type='cuda', enabled=False):
107
+ cos, sin = rotary_cos_sin
108
+ cos = cos.to(qkv.dtype)
109
+ sin = sin.to(qkv.dtype)
110
+ cos = cos[0, :, 0, 0, :cos.shape[-1]//2]
111
+ sin = sin[0, :, 0, 0, :sin.shape[-1]//2]
112
+ q, k, v = qkv.chunk(3, dim=2)
113
+ q = _apply_rotary_emb(q.squeeze(dim=2), cos, sin)
114
+ k = _apply_rotary_emb(k.squeeze(dim=2), cos, sin)
115
+ v = v.squeeze(dim=2)
116
+ return q, k, v
117
+
118
+
119
+ def regular_attention_multi_headed(q, k, v):
120
+ attention_output = F.scaled_dot_product_attention(
121
+ query=q.transpose(1, 2),
122
+ key=k.transpose(1, 2),
123
+ value=v.transpose(1, 2),
124
+ attn_mask=None,
125
+ dropout_p=0.0,
126
+ is_causal=False)
127
+ attention_output = attention_output.transpose(1, 2)
128
+ return einops.rearrange(attention_output, 'b s h d -> b s (h d)')
129
+
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
+
137
+ def forward(self, x):
138
+ with torch.autocast(device_type='cuda', enabled=False):
139
+ x = F.layer_norm(x.float(), [self.dim])
140
+ return x * self.weight[None, None, :]
141
+
142
+
143
+ class TimestepEmbedder(nn.Module):
144
+ """Embeds scalar timesteps into vector representations."""
145
+
146
+ def __init__(self, hidden_size, frequency_embedding_size=256):
147
+ super().__init__()
148
+ self.mlp = nn.Sequential(
149
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
150
+ nn.SiLU(),
151
+ nn.Linear(hidden_size, hidden_size, bias=True))
152
+ self.frequency_embedding_size = frequency_embedding_size
153
+
154
+ @staticmethod
155
+ def timestep_embedding(t, dim, max_period=10000):
156
+ half = dim // 2
157
+ freqs = torch.exp(
158
+ -math.log(max_period)
159
+ * torch.arange(start=0, end=half, dtype=torch.float32, device=t.device)
160
+ / half)
161
+ args = t[:, None].float() * freqs[None]
162
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
163
+ if dim % 2:
164
+ embedding = torch.cat(
165
+ [embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
166
+ return embedding
167
+
168
+ def forward(self, t):
169
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
170
+ t_emb = self.mlp(t_freq)
171
+ return t_emb
172
+
173
+
174
+ class DDiTBlock(nn.Module):
175
+ def __init__(self, dim, n_heads, cond_dim, mlp_ratio=4, dropout=0.1):
176
+ super().__init__()
177
+ self.n_heads = n_heads
178
+
179
+ self.norm1 = LayerNorm(dim)
180
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
181
+ self.attn_out = nn.Linear(dim, dim, bias=False)
182
+
183
+ self.norm2 = LayerNorm(dim)
184
+ self.mlp = nn.Sequential(
185
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
186
+ nn.GELU(approximate='tanh'),
187
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
188
+ self.dropout = dropout
189
+
190
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim)
191
+ self.adaLN_modulation.weight.data.zero_()
192
+ self.adaLN_modulation.bias.data.zero_()
193
+
194
+ def _get_bias_dropout_scale(self):
195
+ if self.training:
196
+ return bias_dropout_add_scale_fused_train
197
+ else:
198
+ return bias_dropout_add_scale_fused_inference
199
+
200
+ def forward(self, x, rotary_cos_sin, c):
201
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
202
+
203
+ x_skip = x
204
+ x = self.norm1(x)
205
+
206
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
207
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
208
+ x = modulate_fused(x, shift_msa, scale_msa)
209
+
210
+ qkv = einops.rearrange(
211
+ self.attn_qkv(x),
212
+ 'b s (three h d) -> b s three h d',
213
+ three=3,
214
+ h=self.n_heads)
215
+ q, k, v = split_and_apply_rotary_pos_emb(qkv, rotary_cos_sin)
216
+ x = regular_attention_multi_headed(q, k, v)
217
+
218
+ x = bias_dropout_scale_fn(self.attn_out(x), None, gate_msa, x_skip, self.dropout)
219
+ x = bias_dropout_scale_fn(
220
+ self.mlp(modulate_fused(self.norm2(x), shift_mlp, scale_mlp)),
221
+ None, gate_mlp, x, self.dropout)
222
+ return x
223
+
224
+
225
+ def _normalize_embedding_layernorm(weight: torch.Tensor) -> torch.Tensor:
226
+ """Normalize embedding weights to unit norm per row, then scale by sqrt(dim)."""
227
+ normalized = F.normalize(weight.float(), dim=-1)
228
+ return (normalized * math.sqrt(weight.shape[-1])).to(weight.dtype)
229
+
230
+
231
+ class EmbeddingLayer(nn.Module):
232
+ """Embedding layer with optional layernorm normalization."""
233
+
234
+ def __init__(self, dim, vocab_dim, use_normalized_embedding=True):
235
+ super().__init__()
236
+ self.dim = dim
237
+ self.vocab_dim = vocab_dim
238
+ self.use_normalized_embedding = use_normalized_embedding
239
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
240
+ nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
241
+
242
+ def _get_embedding(self):
243
+ if self.use_normalized_embedding:
244
+ return _normalize_embedding_layernorm(self.embedding)
245
+ return self.embedding
246
+
247
+ def forward(self, x):
248
+ embedding = self._get_embedding()
249
+ if x.ndim == 2:
250
+ return embedding[x]
251
+ assert x.ndim == 3 # probabilities
252
+ return torch.einsum("blv,ve->ble", x.float(), embedding.float()).to(x.dtype)
253
+
254
+
255
+ class DDiTFinalLayer(nn.Module):
256
+ def __init__(self, hidden_size, out_channels, cond_dim):
257
+ super().__init__()
258
+ self.norm_final = LayerNorm(hidden_size)
259
+ self.linear = nn.Linear(hidden_size, out_channels)
260
+ self.linear.weight.data.zero_()
261
+ self.linear.bias.data.zero_()
262
+ self.adaLN_modulation = nn.Linear(cond_dim, 2 * hidden_size, bias=True)
263
+ self.adaLN_modulation.weight.data.zero_()
264
+ self.adaLN_modulation.bias.data.zero_()
265
+
266
+ def forward(self, x, c):
267
+ x = self.norm_final(x)
268
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
269
+ x = modulate_fused(x, shift, scale)
270
+ x = self.linear(x)
271
+ return x
272
+
273
+
274
+ class GumbelProposal(nn.Module):
275
+ """Learnable Gumbel distribution proposal for sampling gamma (log-SNR)."""
276
+
277
+ def __init__(self, loc: float = 4.723, scale: float = 0.852,
278
+ cutoff: float = 1e-5, entropy: float = 7.02):
279
+ super().__init__()
280
+ self.loc = nn.Parameter(torch.tensor(loc))
281
+ self.scale = nn.Parameter(torch.tensor(scale))
282
+ self.cutoff = cutoff
283
+ self.entropy = nn.Parameter(torch.tensor(entropy))
284
+
285
+ def _get_distribution(self) -> torch.distributions.Gumbel:
286
+ return torch.distributions.Gumbel(self.loc, self.scale)
287
+
288
+ @property
289
+ def gamma_min(self) -> float:
290
+ return float(self.loc - math.log(-math.log(self.cutoff)) * self.scale)
291
+
292
+ @property
293
+ def gamma_max(self) -> float:
294
+ return float(self.loc - math.log(self.cutoff) * self.scale)
295
+
296
+ def forward(self, q: torch.Tensor) -> torch.Tensor:
297
+ """Convert uniform samples to gamma values via inverse CDF."""
298
+ gamma = self._get_distribution().icdf(q)
299
+ return gamma.clamp(min=self.gamma_min, max=self.gamma_max)
300
+
301
+ def log_pdf(self, gamma: torch.Tensor) -> torch.Tensor:
302
+ """Compute log probability density at gamma."""
303
+ return self._get_distribution().log_prob(gamma)
304
+
305
+
306
+ class LangFlowBackbone(nn.Module):
307
+ """DiT backbone for LangFlow."""
308
+
309
+ def __init__(self, config: LangFlowConfig):
310
+ super().__init__()
311
+ self.config = config
312
+ dim = config.hidden_size
313
+ cond_dim = config.cond_dim
314
+
315
+ self.vocab_embed = EmbeddingLayer(
316
+ dim, config.vocab_size,
317
+ use_normalized_embedding=config.use_normalized_embedding)
318
+ self.sigma_map = TimestepEmbedder(cond_dim)
319
+ self.rotary_emb = Rotary(dim // config.n_heads)
320
+
321
+ self.blocks = nn.ModuleList([
322
+ DDiTBlock(dim=dim, n_heads=config.n_heads, cond_dim=cond_dim, dropout=config.dropout)
323
+ for _ in range(config.n_blocks)
324
+ ])
325
+
326
+ self.output_layer = DDiTFinalLayer(
327
+ hidden_size=dim, out_channels=config.vocab_size, cond_dim=cond_dim)
328
+
329
+ # Self-conditioning projection
330
+ if config.self_conditioning:
331
+ self.self_cond_proj = nn.Linear(dim * 2, dim, bias=False)
332
+ nn.init.zeros_(self.self_cond_proj.weight)
333
+
334
+ def forward(self, x_embed, sigma, x_self_cond=None, output_hidden_states=False):
335
+ """Forward pass from embeddings.
336
+
337
+ Args:
338
+ x_embed: [B, L, D] - Input embeddings (possibly noisy)
339
+ sigma: [B] - Gamma values (log-SNR)
340
+ x_self_cond: [B, L, D] - Self-conditioning embeddings (optional)
341
+ output_hidden_states: Whether to return all hidden states
342
+
343
+ Returns:
344
+ logits: [B, L, vocab_size]
345
+ hidden_states: List of hidden states if output_hidden_states=True
346
+ """
347
+ all_hidden_states = []
348
+ x = x_embed
349
+
350
+ if output_hidden_states:
351
+ all_hidden_states.append(x)
352
+
353
+ # Self-conditioning
354
+ if self.config.self_conditioning:
355
+ if x_self_cond is None:
356
+ x_self_cond = torch.zeros_like(x)
357
+ x = x + self.self_cond_proj(torch.cat([x, x_self_cond], dim=-1))
358
+
359
+ t_cond = F.silu(self.sigma_map(sigma))
360
+ rotary_cos_sin = self.rotary_emb(x)
361
+
362
+ with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
363
+ for block in self.blocks:
364
+ x = block(x, rotary_cos_sin, c=t_cond)
365
+ if output_hidden_states:
366
+ all_hidden_states.append(x)
367
+ x = self.output_layer(x, c=t_cond)
368
+
369
+ return x, all_hidden_states
370
+
371
+
372
+ class LangFlow(transformers.PreTrainedModel):
373
+ """HuggingFace-compatible LangFlow model.
374
+
375
+ LangFlow is a continuous diffusion language model that operates in embedding space.
376
+ It uses a DiT (Diffusion Transformer) backbone with:
377
+ - Self-conditioning: uses previous predictions as additional input
378
+ - Bias (preconditioning): skip connection for improved generation
379
+ - Normalized embeddings: layernorm on embedding vectors
380
+ - Learnable Gumbel proposal for gamma (log-SNR) sampling
381
+ """
382
+ config_class = LangFlowConfig
383
+ base_model_prefix = "langflow"
384
+
385
+ def __init__(self, config: LangFlowConfig):
386
+ super().__init__(config)
387
+ self.config = config
388
+ self.backbone = LangFlowBackbone(config)
389
+ self.proposal = GumbelProposal(
390
+ loc=config.gumbel_loc,
391
+ scale=config.gumbel_scale,
392
+ cutoff=config.gumbel_cutoff,
393
+ entropy=config.gumbel_entropy)
394
+
395
+ def _get_embedding_matrix(self) -> torch.Tensor:
396
+ """Get the embedding matrix for bias skip connection."""
397
+ return self.backbone.vocab_embed._get_embedding()
398
+
399
+ def _embed_tokens(self, x: torch.Tensor) -> torch.Tensor:
400
+ """Embed tokens or probabilities to continuous embeddings."""
401
+ return self.backbone.vocab_embed(x)
402
+
403
+ def _forward_diffusion(self, x_embed: torch.Tensor,
404
+ gamma: torch.Tensor) -> torch.Tensor:
405
+ """Add noise to embeddings (forward diffusion process)."""
406
+ gamma = gamma.float()
407
+ alpha = torch.sigmoid(-gamma).sqrt()[:, None, None]
408
+ sigma = torch.sigmoid(gamma).sqrt()[:, None, None]
409
+ noise = torch.randn_like(x_embed)
410
+ return (x_embed * alpha + noise * sigma).to(x_embed.dtype)
411
+
412
+ def _euler_edm_step(self, z: torch.Tensor, x_pred: torch.Tensor,
413
+ t: torch.Tensor, s: torch.Tensor) -> torch.Tensor:
414
+ """Single Euler step for EDM sampling."""
415
+ t_ = t.double()
416
+ s_ = s.double()
417
+ cur = z.double() * ((F.softplus(t_) - F.softplus(s_)) / 2).exp()
418
+ end = torch.sigmoid(-s_).sqrt() * x_pred.double()
419
+ z = end.lerp(cur, ((s_ - t_) / 2).exp()).to(z.dtype)
420
+ return z
421
+
422
+ def forward(
423
+ self,
424
+ input_ids: typing.Optional[torch.LongTensor] = None,
425
+ noisy_embeds: typing.Optional[torch.FloatTensor] = None,
426
+ timesteps: typing.Optional[torch.FloatTensor] = None,
427
+ x_self_cond: typing.Optional[torch.FloatTensor] = None,
428
+ output_hidden_states: typing.Optional[bool] = None,
429
+ return_dict: typing.Optional[bool] = None,
430
+ ) -> typing.Union[torch.Tensor, typing.Tuple, transformers.modeling_outputs.MaskedLMOutput]:
431
+ """Forward pass for LangFlow.
432
+
433
+ Args:
434
+ input_ids: [B, L] - Token IDs (will be embedded and noised if timesteps provided)
435
+ noisy_embeds: [B, L, D] - Pre-noised embeddings (alternative to input_ids)
436
+ timesteps: [B] - Gamma values (log-SNR) for conditioning
437
+ x_self_cond: [B, L, D] - Self-conditioning embeddings
438
+ output_hidden_states: Whether to return hidden states
439
+ return_dict: Whether to return MaskedLMOutput
440
+
441
+ Returns:
442
+ logits or MaskedLMOutput
443
+ """
444
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
445
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
446
+
447
+ # Get embeddings
448
+ if noisy_embeds is not None:
449
+ z = noisy_embeds
450
+ elif input_ids is not None:
451
+ x_embed = self._embed_tokens(input_ids)
452
+ if timesteps is not None:
453
+ z = self._forward_diffusion(x_embed, timesteps)
454
+ else:
455
+ z = x_embed
456
+ else:
457
+ raise ValueError("Either input_ids or noisy_embeds must be provided")
458
+
459
+ if timesteps is None:
460
+ # Use minimum gamma for clean input
461
+ timesteps = torch.full((z.shape[0],), self.proposal.gamma_min, device=z.device)
462
+
463
+ # Process sigma
464
+ sigma = timesteps
465
+ if sigma.ndim == 2:
466
+ sigma = sigma.mean(-1)
467
+
468
+ # Get model output
469
+ logits, all_hidden_states = self.backbone(
470
+ z, sigma, x_self_cond=x_self_cond, output_hidden_states=output_hidden_states)
471
+
472
+ # Add bias (preconditioning) skip connection
473
+ if self.config.use_bias:
474
+ c_skip = ((F.softplus(-sigma) - sigma) / 2).exp()
475
+ embedding = self._get_embedding_matrix()
476
+ skip_logits = torch.matmul(z.float(), embedding.t().float())
477
+ logits = logits + c_skip[:, None, None] * skip_logits.to(logits.dtype)
478
+
479
+ if return_dict:
480
+ return transformers.modeling_outputs.MaskedLMOutput(
481
+ logits=logits,
482
+ hidden_states=all_hidden_states if output_hidden_states else None,
483
+ loss=None)
484
+ elif output_hidden_states:
485
+ return logits, all_hidden_states
486
+ else:
487
+ return logits
488
+
489
+ @torch.no_grad()
490
+ def generate_samples(
491
+ self,
492
+ num_samples: int = 1,
493
+ seq_length: typing.Optional[int] = None,
494
+ num_steps: int = 128,
495
+ device: typing.Optional[torch.device] = None,
496
+ ) -> torch.LongTensor:
497
+ """Generate samples using Euler-EDM solver.
498
+
499
+ Args:
500
+ num_samples: Number of samples to generate
501
+ seq_length: Sequence length (defaults to config.model_length)
502
+ num_steps: Number of denoising steps
503
+ device: Device to generate on
504
+
505
+ Returns:
506
+ samples: [num_samples, seq_length] - Generated token IDs
507
+ """
508
+ if seq_length is None:
509
+ seq_length = self.config.model_length
510
+ if device is None:
511
+ device = next(self.parameters()).device
512
+
513
+ embed_dim = self.config.hidden_size
514
+ eps = 1e-5
515
+
516
+ # Initialize with Gaussian noise
517
+ z = torch.randn(num_samples, seq_length, embed_dim, device=device)
518
+
519
+ # Create gamma schedule from t=1-eps to t=eps
520
+ t = torch.linspace(1.0 - eps, eps, num_steps, device=device)
521
+ gamma = self.proposal(t)
522
+
523
+ # Self-conditioning state
524
+ x_self_cond = None
525
+
526
+ # Euler-EDM sampling loop
527
+ for i in range(len(gamma) - 1):
528
+ gamma_t = gamma[i]
529
+ gamma_s = gamma[i + 1]
530
+
531
+ # Get model prediction
532
+ gamma_expanded = gamma_t.unsqueeze(0).expand(num_samples)
533
+ logits = self.forward(
534
+ noisy_embeds=z,
535
+ timesteps=gamma_expanded,
536
+ x_self_cond=x_self_cond,
537
+ return_dict=False)
538
+
539
+ # Convert logits to embedding prediction
540
+ probs = F.softmax(logits.float(), dim=-1)
541
+ x_pred = self._embed_tokens(probs)
542
+
543
+ # Update self-conditioning
544
+ if self.config.self_conditioning:
545
+ x_self_cond = x_pred
546
+
547
+ # Euler step
548
+ z = self._euler_edm_step(z, x_pred, gamma_t, gamma_s)
549
+
550
+ # Final step: get logits and take argmax
551
+ gamma_final = gamma[-1]
552
+ gamma_expanded = gamma_final.unsqueeze(0).expand(num_samples)
553
+ logits = self.forward(
554
+ noisy_embeds=z,
555
+ timesteps=gamma_expanded,
556
+ x_self_cond=x_self_cond,
557
+ return_dict=False)
558
+ samples = logits.argmax(dim=-1)
559
+
560
+ return samples
checkpoints/quarantine/20260821T024711Z/official/flm/lm1b/config.json ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "algo": {
4
+ "T": 0,
5
+ "backbone": "dit",
6
+ "causal_attention": false,
7
+ "curriculum_end": 1000000,
8
+ "curriculum_start": 0,
9
+ "double_temb": false,
10
+ "flow_loss_type": "ce",
11
+ "flow_ratio": 0.75,
12
+ "gumbel_tau_log10_end": -0.0,
13
+ "gumbel_tau_log10_start": -0.0,
14
+ "ignore_bos": false,
15
+ "jvp_api": "autograd",
16
+ "loss_scale": "none",
17
+ "n_separated_blocks": -1,
18
+ "name": "dos",
19
+ "parameterization": "mean",
20
+ "pred_log_interval": 2000,
21
+ "sigma_min": 0.0001,
22
+ "subs_masking": false,
23
+ "t_max": 1.0,
24
+ "t_min": 0.0,
25
+ "time_condition": "alpha_t",
26
+ "time_conditioning": true,
27
+ "use_curriculum": true,
28
+ "use_discrete_schedule": true
29
+ },
30
+ "callbacks": {
31
+ "checkpoint_every_n_steps": {
32
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
33
+ "auto_insert_metric_name": false,
34
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
35
+ "every_n_train_steps": 50000,
36
+ "save_last": false,
37
+ "save_top_k": -1,
38
+ "verbose": true
39
+ },
40
+ "checkpoint_monitor": {
41
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
42
+ "auto_insert_metric_name": false,
43
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
44
+ "filename": "best_nll",
45
+ "mode": "min",
46
+ "monitor": "val/nll",
47
+ "save_last": true,
48
+ "save_top_k": 1,
49
+ "verbose": true
50
+ },
51
+ "learning_rate_monitor": {
52
+ "_target_": "lightning.pytorch.callbacks.LearningRateMonitor",
53
+ "logging_interval": "step"
54
+ }
55
+ },
56
+ "checkpointing": {
57
+ "resume_ckpt_path": "/home/work/RADAR/workspace/KAIST/discrete-mean-flow/text/outputs/lm1b/2026.01.05/154016/checkpoints/47-650000.ckpt",
58
+ "resume_from_ckpt": true,
59
+ "save_dir": "/home/david3684/projects/flm/hf_upload"
60
+ },
61
+ "data": {
62
+ "cache_dir": "/home/work/RADAR/workspace/KAIST/cdBDD/datasets/lm1b",
63
+ "insert_train_eos": true,
64
+ "insert_valid_eos": true,
65
+ "streaming": false,
66
+ "tokenizer_name_or_path": "bert-base-uncased",
67
+ "train": "lm1b",
68
+ "valid": "lm1b",
69
+ "wrap": true
70
+ },
71
+ "eval": {
72
+ "checkpoint_path": "",
73
+ "compute_generative_perplexity": true,
74
+ "compute_perplexity_on_sanity": false,
75
+ "disable_ema": false,
76
+ "gen_ppl_eval_model_name_or_path": "gpt2-large",
77
+ "generate_samples": true,
78
+ "generated_samples_path": "/home/david3684/projects/flm/hf_upload/samples.json",
79
+ "perplexity_batch_size": 8
80
+ },
81
+ "is_di4c": false,
82
+ "is_di4c_deterministic": true,
83
+ "loader": {
84
+ "batch_size": 128,
85
+ "eval_batch_size": 128,
86
+ "eval_global_batch_size": 512,
87
+ "global_batch_size": 512,
88
+ "num_workers": 192,
89
+ "pin_memory": true
90
+ },
91
+ "lr_scheduler": {
92
+ "_target_": "transformers.get_constant_schedule_with_warmup",
93
+ "num_warmup_steps": 2500
94
+ },
95
+ "mode": "train",
96
+ "model": {
97
+ "cond_dim": 128,
98
+ "dropout": 0.1,
99
+ "hidden_size": 768,
100
+ "length": 128,
101
+ "n_blocks": 12,
102
+ "n_heads": 12,
103
+ "name": "small",
104
+ "scale_by_sigma": true,
105
+ "tie_word_embeddings": false,
106
+ "type": "ddit",
107
+ "vocab_lookup": true
108
+ },
109
+ "noise": {
110
+ "denoiser_latent_conditioning": -1,
111
+ "eps": 0,
112
+ "freeze_decoder": false,
113
+ "freeze_encoder": false,
114
+ "parameterization": "log-linear",
115
+ "type": "log-linear"
116
+ },
117
+ "optim": {
118
+ "beta1": 0.9,
119
+ "beta2": 0.999,
120
+ "eps": 1e-08,
121
+ "ln_tune": "none",
122
+ "lr": 0.0003,
123
+ "use_muon": false,
124
+ "weight_decay": 0
125
+ },
126
+ "prior": {
127
+ "latent_height": 0,
128
+ "latent_width": 0,
129
+ "type": "none"
130
+ },
131
+ "sampling": {
132
+ "argmax_correction": false,
133
+ "hard_start": false,
134
+ "noise_removal": "meanflow",
135
+ "noise_removal_list": [
136
+ "uniform",
137
+ "uniform_alpha"
138
+ ],
139
+ "num_reflow_samples": 50000,
140
+ "num_sample_batches": 1,
141
+ "num_sample_log": 2,
142
+ "num_strides": 1,
143
+ "p_nucleus": 1.0,
144
+ "predictor": "ancestral",
145
+ "semi_ar": false,
146
+ "solver": "euler",
147
+ "steps": [
148
+ 1024
149
+ ],
150
+ "stride_length": 1,
151
+ "tau_log10": 0.0,
152
+ "temperature": 1.0,
153
+ "use_float64": true
154
+ },
155
+ "seed": 1,
156
+ "strategy": {
157
+ "_target_": "lightning.pytorch.strategies.DDPStrategy",
158
+ "find_unused_parameters": true
159
+ },
160
+ "trainer": {
161
+ "_target_": "lightning.Trainer",
162
+ "accelerator": "cuda",
163
+ "accumulate_grad_batches": 1,
164
+ "devices": 8,
165
+ "gradient_clip_val": 1.0,
166
+ "limit_train_batches": 1.0,
167
+ "limit_val_batches": 1.0,
168
+ "log_every_n_steps": 100,
169
+ "max_steps": 1000000,
170
+ "num_nodes": 1,
171
+ "num_sanity_val_steps": 2,
172
+ "precision": "bf16",
173
+ "val_check_interval": 10000
174
+ },
175
+ "training": {
176
+ "antithetic_sampling": true,
177
+ "change_of_variables": false,
178
+ "double_ema": 0.0,
179
+ "ema": 0.9999,
180
+ "finetune_path": "",
181
+ "importance_sampling": false,
182
+ "load_ema": false,
183
+ "loss_precision": "bf16",
184
+ "loss_type": "flow",
185
+ "loss_weighting": false,
186
+ "not_sampling_t": false,
187
+ "pred_type": "x0",
188
+ "sampling_eps": 0.001,
189
+ "t_curriculum_max": 1.0,
190
+ "t_curriculum_min": 0.0,
191
+ "t_curriculum_steps": 100000,
192
+ "torch_compile_mode": "default",
193
+ "use_torch_compile": true
194
+ },
195
+ "wandb": {
196
+ "group": null,
197
+ "id": "fc867e70",
198
+ "job_type": null,
199
+ "name": "lm1b_full_flow_no_input_softmax_no_loss_scale_ce_loss_fc867e70",
200
+ "notes": "DOS",
201
+ "project": "lm1b_full",
202
+ "tags": [
203
+ "lm1b",
204
+ "dos"
205
+ ]
206
+ }
207
+ },
208
+ "vocab_size": 30522
209
+ }
checkpoints/quarantine/20260821T024727Z/official/flm/owt/config.json ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "algo": {
4
+ "T": 0,
5
+ "backbone": "dit",
6
+ "causal_attention": false,
7
+ "curriculum_end": 1000000,
8
+ "curriculum_start": 0,
9
+ "double_temb": false,
10
+ "flow_loss_type": "ce",
11
+ "flow_ratio": 0.75,
12
+ "gumbel_tau_log10_end": -0.0,
13
+ "gumbel_tau_log10_start": -0.0,
14
+ "ignore_bos": false,
15
+ "jvp_api": "autograd",
16
+ "learnable_loss_weighting": false,
17
+ "loss_scale": "none",
18
+ "n_separated_blocks": -1,
19
+ "name": "dos",
20
+ "parameterization": "mean",
21
+ "pred_log_interval": 2000,
22
+ "sigma_min": 0.0001,
23
+ "subs_masking": false,
24
+ "t_max": 1.0,
25
+ "t_min": 0.0,
26
+ "time_condition": "alpha_t",
27
+ "time_conditioning": true,
28
+ "use_curriculum": true,
29
+ "use_discrete_schedule": true
30
+ },
31
+ "callbacks": {
32
+ "checkpoint_every_n_steps": {
33
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
34
+ "auto_insert_metric_name": false,
35
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
36
+ "every_n_train_steps": 25000,
37
+ "save_last": false,
38
+ "save_top_k": -1,
39
+ "verbose": true
40
+ },
41
+ "checkpoint_monitor": {
42
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
43
+ "auto_insert_metric_name": false,
44
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
45
+ "filename": "best_nll",
46
+ "mode": "min",
47
+ "monitor": "val/nll",
48
+ "save_last": true,
49
+ "save_top_k": 1,
50
+ "verbose": true
51
+ },
52
+ "learning_rate_monitor": {
53
+ "_target_": "lightning.pytorch.callbacks.LearningRateMonitor",
54
+ "logging_interval": "step"
55
+ }
56
+ },
57
+ "checkpointing": {
58
+ "resume_ckpt_path": "/home/work/RADAR/workspace/KAIST/discrete-mean-flow/text/outputs/openwebtext-train/2026.02.05/005839/checkpoints/50-825000.ckpt",
59
+ "resume_from_ckpt": true,
60
+ "save_dir": "/home/david3684/projects/flm/hf_upload"
61
+ },
62
+ "data": {
63
+ "cache_dir": "/home/work/RADAR/workspace/KAIST/cdBDD/datasets/openwebtext",
64
+ "insert_train_eos": true,
65
+ "insert_valid_eos": true,
66
+ "streaming": false,
67
+ "tokenizer_name_or_path": "gpt2",
68
+ "train": "openwebtext-train",
69
+ "valid": "openwebtext-valid",
70
+ "wrap": true
71
+ },
72
+ "eval": {
73
+ "checkpoint_path": "",
74
+ "compute_generative_perplexity": true,
75
+ "compute_perplexity_on_sanity": false,
76
+ "disable_ema": false,
77
+ "ema_decay": null,
78
+ "gen_ppl_eval_model_name_or_path": "gpt2-large",
79
+ "generate_samples": true,
80
+ "generated_samples_path": "/home/david3684/projects/flm/hf_upload/samples.json",
81
+ "perplexity_batch_size": 8
82
+ },
83
+ "is_di4c": false,
84
+ "is_di4c_deterministic": true,
85
+ "loader": {
86
+ "batch_size": 32,
87
+ "eval_batch_size": 32,
88
+ "eval_global_batch_size": 512,
89
+ "global_batch_size": 512,
90
+ "num_workers": 4,
91
+ "pin_memory": true
92
+ },
93
+ "lr_scheduler": {
94
+ "_target_": "transformers.get_constant_schedule_with_warmup",
95
+ "num_warmup_steps": 2500
96
+ },
97
+ "mode": "train",
98
+ "model": {
99
+ "cond_dim": 128,
100
+ "dropout": 0.1,
101
+ "hidden_size": 768,
102
+ "length": 1024,
103
+ "n_blocks": 12,
104
+ "n_heads": 12,
105
+ "name": "small",
106
+ "scale_by_sigma": true,
107
+ "tie_word_embeddings": false,
108
+ "type": "ddit",
109
+ "vocab_lookup": true
110
+ },
111
+ "noise": {
112
+ "denoiser_latent_conditioning": -1,
113
+ "eps": 0,
114
+ "freeze_decoder": false,
115
+ "freeze_encoder": false,
116
+ "parameterization": "log-linear",
117
+ "type": "log-linear"
118
+ },
119
+ "optim": {
120
+ "beta1": 0.9,
121
+ "beta2": 0.999,
122
+ "eps": 1e-08,
123
+ "ln_tune": "none",
124
+ "lr": 0.0003,
125
+ "use_muon": false,
126
+ "weight_decay": 0
127
+ },
128
+ "prior": {
129
+ "latent_height": 0,
130
+ "latent_width": 0,
131
+ "type": "none"
132
+ },
133
+ "sampling": {
134
+ "argmax_correction": false,
135
+ "autoguidance_weight": 0.0,
136
+ "hard_start": false,
137
+ "noise_removal": "uniform_alpha",
138
+ "num_reflow_samples": 50000,
139
+ "num_sample_batches": 1,
140
+ "num_sample_log": 2,
141
+ "num_strides": 1,
142
+ "p_nucleus": 1.0,
143
+ "predictor": "ancestral",
144
+ "semi_ar": false,
145
+ "solver": "euler",
146
+ "steps": [
147
+ 1024
148
+ ],
149
+ "stride_length": 1,
150
+ "tau_log10": -1.0,
151
+ "temperature": 1.0,
152
+ "use_float64": true
153
+ },
154
+ "seed": 1,
155
+ "strategy": {
156
+ "_target_": "lightning.pytorch.strategies.DDPStrategy",
157
+ "find_unused_parameters": false
158
+ },
159
+ "trainer": {
160
+ "_target_": "lightning.Trainer",
161
+ "accelerator": "cuda",
162
+ "accumulate_grad_batches": 2,
163
+ "devices": 8,
164
+ "gradient_clip_val": 1.0,
165
+ "limit_train_batches": 1.0,
166
+ "limit_val_batches": 1.0,
167
+ "log_every_n_steps": 100,
168
+ "max_steps": 1000000,
169
+ "num_nodes": 1,
170
+ "num_sanity_val_steps": 2,
171
+ "precision": "bf16",
172
+ "val_check_interval": 20000
173
+ },
174
+ "training": {
175
+ "antithetic_sampling": true,
176
+ "change_of_variables": false,
177
+ "double_ema": 0.0,
178
+ "ema": "0.9999, 0.999, 0.99, 0.95",
179
+ "finetune_path": "",
180
+ "importance_sampling": false,
181
+ "load_ema": false,
182
+ "loss_precision": "bf16",
183
+ "loss_type": "flow",
184
+ "loss_weighting": false,
185
+ "not_sampling_t": false,
186
+ "pred_type": "x0",
187
+ "sampling_eps": 0.001,
188
+ "t_curriculum_max": 1.0,
189
+ "t_curriculum_min": 0.0,
190
+ "t_curriculum_steps": 100000,
191
+ "torch_compile_mode": "default",
192
+ "use_torch_compile": true
193
+ },
194
+ "wandb": {
195
+ "group": null,
196
+ "id": "abcde2",
197
+ "job_type": null,
198
+ "name": "owt_ce_full_abcde2",
199
+ "notes": "DOS",
200
+ "project": "owt_full",
201
+ "tags": [
202
+ "openwebtext-train",
203
+ "dos"
204
+ ]
205
+ }
206
+ },
207
+ "vocab_size": 50258
208
+ }
checkpoints/quarantine/20260821T024736Z/official/fmlm/owt/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ license: apache-2.0
6
+ datasets:
7
+ - Skylion007/openwebtext
8
+ language:
9
+ - en
10
+ base_model:
11
+ - david3684/FLM-B-OWT
12
+ ---
13
+
14
+ ## FMLM (OWT)
15
+
16
+ For more information and implementation details, visit our github repository: [FLM](https://github.com/david3684/flm).
17
+
18
+ ## Model Details
19
+
20
+ The model has a context length of 1024, distilled from 1M steps trained FLM checkpoint trained on the OpenWebText (OWT) dataset.
21
+
22
+ For more details, please see our paper:
23
+ - [arXiv:2602.16813](https://arxiv.org/abs/2602.16813)
24
+ - [Huggingface Papers](https://huggingface.co/papers/2602.16813)
25
+
26
+ ## Citation
27
+
28
+ Please cite our work using the bibtex below:
29
+
30
+ **BibTeX:**
31
+
32
+
33
+ ```bibtex
34
+ @article{lee2026flow,
35
+ title={Flow Map Language Models: One-step Language Modeling via Continuous Denoising},
36
+ author={Chanhyuk Lee and Jaehoon Yoo and Manan Agarwal
37
+ and Sheel Shah and Jerry Huang
38
+ and Aditi Raghunathan and Seunghoon Hong
39
+ and Nicholas M. Boffi and Jinwoo Kim},
40
+ journal={arXiv preprint arXiv:2602.16813},
41
+ year={2026},
42
+ }
43
+ ```
44
+
45
+ ## Model Card Contact
46
+
47
+ Chanhyuk Lee (chanhyuk-lee@kaist.ac.kr)
checkpoints/quarantine/20260821T024736Z/official/fmlm/owt/config.json ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config": {
3
+ "algo": {
4
+ "T": 0,
5
+ "add_boundary": "fixed",
6
+ "backbone": "dit",
7
+ "backprop_entmax_temp_lsd": false,
8
+ "boundary_prob": 32,
9
+ "causal_attention": false,
10
+ "diagonal_fraction": 0.5,
11
+ "distillation_method": "PSD",
12
+ "double_temb": true,
13
+ "entmax_temp_lsd": 2.0,
14
+ "initialize_student_from_teacher": true,
15
+ "learnable_loss_weighting": false,
16
+ "loss_scale": "none",
17
+ "loss_type": null,
18
+ "name": "fmlm",
19
+ "offdiagonal_sampling": "uniform_diff",
20
+ "parameterization": "mean",
21
+ "pred_log_interval": 2000,
22
+ "rescale_offdiag_loss_psd": false,
23
+ "subs_masking": false,
24
+ "t_max": 1.0,
25
+ "t_min": 0.0,
26
+ "teacher_path": "/home/irteam/ours_owt_flow_ce_1m.ckpt",
27
+ "time_condition": "alpha_t",
28
+ "time_conditioning": true,
29
+ "use_discrete_schedule": true,
30
+ "use_ema_for_psd_target": false,
31
+ "use_mse_loss_psd": false,
32
+ "use_simulated_entropy": false,
33
+ "use_teacher_for_D_t_lsd": false
34
+ },
35
+ "callbacks": {
36
+ "checkpoint_every_n_steps": {
37
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
38
+ "auto_insert_metric_name": false,
39
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
40
+ "every_n_train_steps": 5000,
41
+ "save_last": false,
42
+ "save_top_k": -1,
43
+ "verbose": true
44
+ },
45
+ "checkpoint_monitor": {
46
+ "_target_": "lightning.pytorch.callbacks.ModelCheckpoint",
47
+ "auto_insert_metric_name": false,
48
+ "dirpath": "/home/david3684/projects/flm/hf_upload/checkpoints",
49
+ "filename": "best_nll",
50
+ "mode": "min",
51
+ "monitor": "val/nll",
52
+ "save_last": true,
53
+ "save_top_k": 1,
54
+ "verbose": true
55
+ },
56
+ "learning_rate_monitor": {
57
+ "_target_": "lightning.pytorch.callbacks.LearningRateMonitor",
58
+ "logging_interval": "step"
59
+ }
60
+ },
61
+ "checkpointing": {
62
+ "resume_ckpt_path": "/home/david3684/projects/flm/hf_upload/checkpoints/last.ckpt",
63
+ "resume_from_ckpt": false,
64
+ "save_dir": "/home/david3684/projects/flm/hf_upload"
65
+ },
66
+ "data": {
67
+ "cache_dir": "/home/irteam/workspace/datasets/openwebtext",
68
+ "insert_train_eos": true,
69
+ "insert_valid_eos": true,
70
+ "streaming": false,
71
+ "tokenizer_name_or_path": "gpt2",
72
+ "train": "openwebtext-train",
73
+ "valid": "openwebtext-valid",
74
+ "wrap": true
75
+ },
76
+ "eval": {
77
+ "checkpoint_path": "",
78
+ "compute_generative_perplexity": true,
79
+ "compute_perplexity_on_sanity": false,
80
+ "disable_ema": false,
81
+ "ema_decay": null,
82
+ "gen_ppl_eval_model_name_or_path": "gpt2-large",
83
+ "generate_samples": true,
84
+ "generated_samples_path": "/home/david3684/projects/flm/hf_upload/samples.json",
85
+ "perplexity_batch_size": 8
86
+ },
87
+ "is_di4c": false,
88
+ "is_di4c_deterministic": true,
89
+ "loader": {
90
+ "batch_size": 16,
91
+ "eval_batch_size": 16,
92
+ "eval_global_batch_size": 128,
93
+ "global_batch_size": 128,
94
+ "num_workers": 4,
95
+ "pin_memory": true
96
+ },
97
+ "lr_scheduler": {
98
+ "_target_": "transformers.get_constant_schedule_with_warmup",
99
+ "num_warmup_steps": 2500
100
+ },
101
+ "mode": "train",
102
+ "model": {
103
+ "cond_dim": 128,
104
+ "dropout": 0.1,
105
+ "hidden_size": 768,
106
+ "l2_normalize_embeddings": false,
107
+ "length": 1024,
108
+ "n_blocks": 12,
109
+ "n_heads": 12,
110
+ "name": "small",
111
+ "scale_by_sigma": true,
112
+ "tie_word_embeddings": false,
113
+ "type": "ddit",
114
+ "vocab_lookup": true
115
+ },
116
+ "noise": {
117
+ "denoiser_latent_conditioning": -1,
118
+ "eps": 0,
119
+ "freeze_decoder": false,
120
+ "freeze_encoder": false,
121
+ "parameterization": "log-linear",
122
+ "type": "log-linear"
123
+ },
124
+ "optim": {
125
+ "beta1": 0.9,
126
+ "beta2": 0.95,
127
+ "eps": 1e-08,
128
+ "ln_tune": "none",
129
+ "lr": 0.0003,
130
+ "muon_lr": 0.03,
131
+ "muon_momentum": 0.95,
132
+ "muon_weight_decay": 0.01,
133
+ "use_muon": false,
134
+ "weight_decay": 0
135
+ },
136
+ "prior": {
137
+ "latent_height": 0,
138
+ "latent_width": 0,
139
+ "type": "none"
140
+ },
141
+ "sampling": {
142
+ "argmax_correction": false,
143
+ "autoguidance_weight": 0.0,
144
+ "hard_start": false,
145
+ "noise_removal": "uniform_alpha",
146
+ "num_reflow_samples": 50000,
147
+ "num_sample_batches": 1,
148
+ "num_sample_log": 2,
149
+ "num_strides": 1,
150
+ "p_nucleus": 1.0,
151
+ "predictor": "ancestral",
152
+ "semi_ar": false,
153
+ "solver": "euler",
154
+ "steps": [
155
+ 1,
156
+ 2,
157
+ 4,
158
+ 8,
159
+ 16,
160
+ 32,
161
+ 64,
162
+ 128
163
+ ],
164
+ "stride_length": 1,
165
+ "tau_log10": -1.0,
166
+ "temperature": 1.0,
167
+ "use_float64": true
168
+ },
169
+ "seed": 1,
170
+ "strategy": {
171
+ "_target_": "lightning.pytorch.strategies.DDPStrategy",
172
+ "find_unused_parameters": false
173
+ },
174
+ "trainer": {
175
+ "_target_": "lightning.Trainer",
176
+ "accelerator": "cuda",
177
+ "accumulate_grad_batches": 1,
178
+ "devices": 8,
179
+ "gradient_clip_val": 1.0,
180
+ "limit_train_batches": 1.0,
181
+ "limit_val_batches": 10,
182
+ "log_every_n_steps": 100,
183
+ "max_steps": 1000000,
184
+ "num_nodes": 1,
185
+ "num_sanity_val_steps": 2,
186
+ "precision": "bf16",
187
+ "val_check_interval": 10000
188
+ },
189
+ "training": {
190
+ "antithetic_sampling": true,
191
+ "change_of_variables": false,
192
+ "double_ema": 0.0,
193
+ "ema": "0.9999, 0.999, 0.99, 0.95",
194
+ "finetune_path": "",
195
+ "importance_sampling": false,
196
+ "load_ema": false,
197
+ "loss_precision": "bf16",
198
+ "loss_type": "sd",
199
+ "loss_weighting": false,
200
+ "not_sampling_t": false,
201
+ "pred_type": "x0",
202
+ "sampling_eps": 0.001,
203
+ "t_curriculum_max": 1.0,
204
+ "t_curriculum_min": 0.0,
205
+ "t_curriculum_steps": 100000,
206
+ "torch_compile_mode": "default",
207
+ "use_torch_compile": true
208
+ },
209
+ "wandb": {
210
+ "group": null,
211
+ "id": "9efb5cfb",
212
+ "job_type": null,
213
+ "name": "owt_PSD_teacher_distill_LR_3e-4_DF_0.5_BP_32_SE_False_IT_True_EDMW_False_EMA_False_beta2_0.95_9efb5cfb",
214
+ "notes": "DOS",
215
+ "project": "owt_full",
216
+ "tags": [
217
+ "openwebtext-train",
218
+ "dos_denoiser"
219
+ ]
220
+ }
221
+ },
222
+ "vocab_size": 50258
223
+ }
checkpoints/quarantine/20260821T024744Z/official/langflow/owt/config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "chumengl/langflow-owt",
3
+ "architectures": [
4
+ "LangFlow"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "config.LangFlowConfig",
8
+ "AutoModelForMaskedLM": "model.LangFlow"
9
+ },
10
+ "model_type": "LangFlow",
11
+ "vocab_size": 50257,
12
+ "hidden_size": 768,
13
+ "cond_dim": 128,
14
+ "n_blocks": 12,
15
+ "n_heads": 12,
16
+ "dropout": 0.1,
17
+ "model_length": 1024,
18
+ "use_normalized_embedding": true,
19
+ "embedding_norm_method": "layernorm",
20
+ "self_conditioning": true,
21
+ "use_bias": true,
22
+ "gumbel_loc": 4.723,
23
+ "gumbel_scale": 0.852,
24
+ "gumbel_cutoff": 1e-5,
25
+ "gumbel_entropy": 7.02,
26
+ "return_dict": true,
27
+ "torch_dtype": "float32",
28
+ "transformers_version": "4.38.2"
29
+ }
checkpoints/quarantine/20260821T024744Z/official/langflow/owt/config.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """HuggingFace configuration class for LangFlow."""
2
+
3
+ import transformers
4
+
5
+
6
+ class LangFlowConfig(transformers.PretrainedConfig):
7
+ """HuggingFace configuration class for LangFlow.
8
+
9
+ LangFlow is a continuous diffusion language model that operates in embedding space.
10
+ It uses a DiT (Diffusion Transformer) backbone with adaptive layer normalization.
11
+
12
+ Key features:
13
+ - Continuous diffusion in embedding space
14
+ - Self-conditioning: uses previous predictions as additional input
15
+ - Bias (preconditioning): skip connection for improved training
16
+ - Normalized embeddings: layernorm on embedding vectors
17
+ - Learnable Gumbel proposal for gamma (log-SNR) sampling
18
+ """
19
+ model_type = "LangFlow"
20
+
21
+ def __init__(
22
+ self,
23
+ vocab_size: int = 50257,
24
+ hidden_size: int = 768,
25
+ cond_dim: int = 128,
26
+ n_blocks: int = 12,
27
+ n_heads: int = 12,
28
+ dropout: float = 0.1,
29
+ model_length: int = 1024,
30
+ # Embedding normalization
31
+ use_normalized_embedding: bool = True,
32
+ embedding_norm_method: str = "layernorm",
33
+ # Self-conditioning
34
+ self_conditioning: bool = True,
35
+ # Bias (preconditioning) - always enabled for inference
36
+ use_bias: bool = True,
37
+ # Gumbel proposal parameters (learnable)
38
+ gumbel_loc: float = 4.723,
39
+ gumbel_scale: float = 0.852,
40
+ gumbel_cutoff: float = 1e-5,
41
+ gumbel_entropy: float = 7.02,
42
+ **kwargs
43
+ ):
44
+ super().__init__(**kwargs)
45
+ self.vocab_size = vocab_size
46
+ self.hidden_size = hidden_size
47
+ self.cond_dim = cond_dim
48
+ self.n_blocks = n_blocks
49
+ self.n_heads = n_heads
50
+ self.dropout = dropout
51
+ self.model_length = model_length
52
+ # Embedding normalization
53
+ self.use_normalized_embedding = use_normalized_embedding
54
+ self.embedding_norm_method = embedding_norm_method
55
+ # Self-conditioning
56
+ self.self_conditioning = self_conditioning
57
+ # Bias (preconditioning)
58
+ self.use_bias = use_bias
59
+ # Gumbel proposal parameters
60
+ self.gumbel_loc = gumbel_loc
61
+ self.gumbel_scale = gumbel_scale
62
+ self.gumbel_cutoff = gumbel_cutoff
63
+ self.gumbel_entropy = gumbel_entropy
checkpoints/quarantine/20260825T100043Z/official/flm/lm1b/README.md ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - model_hub_mixin
4
+ - pytorch_model_hub_mixin
5
+ language:
6
+ - en
7
+ license: apache-2.0
8
+ ---
9
+
10
+ ## FLM (LM1B)
11
+
12
+ For more information and implementation details, visit our github repository: [FLM](https://github.com/david3684/flm).
13
+
14
+ ## Model Details
15
+
16
+ The model has a context length of 128, trained for 1M steps on the One Billion Words (LM1B) dataset.
17
+
18
+ For more details, please see our paper:
19
+ - [arXiv:2602.16813](https://arxiv.org/abs/2602.16813)
20
+ - [Huggingface Papers](https://huggingface.co/papers/2602.16813)
21
+
22
+ ## Citation
23
+
24
+ Please cite our work using the bibtex below:
25
+
26
+ **BibTeX:**
27
+
28
+
29
+ ```bibtex
30
+ @article{lee2026flow,
31
+ title={Flow Map Language Models: One-step Language Modeling via Continuous Denoising},
32
+ author={Chanhyuk Lee and Jaehoon Yoo and Manan Agarwal
33
+ and Sheel Shah and Jerry Huang
34
+ and Aditi Raghunathan and Seunghoon Hong
35
+ and Nicholas M. Boffi and Jinwoo Kim},
36
+ journal={arXiv preprint arXiv:2602.16813},
37
+ year={2026},
38
+ }
39
+ ```
40
+
41
+ ## Model Card Contact
42
+
43
+ Chanhyuk Lee (chanhyuk-lee@kaist.ac.kr)
checkpoints/quarantine/20260825T100259Z/official/duo_dcd/owt/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
checkpoints/quarantine/20260825T100259Z/official/duo_dcd/owt/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
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/.hydra/config.yaml ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mode: train
2
+ time_conditioning: false
3
+ T: 1024
4
+ compile: false
5
+ eval_every: 5000000
6
+ is_di4c: true
7
+ is_teacher_di4c: false
8
+ latent_bsize: 16
9
+ alpha_t: sigmoid
10
+ alpha_const: 0.1
11
+ distil_delta: 0.02
12
+ log_unif: false
13
+ round: 7
14
+ data_preprocess:
15
+ data_cache: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
16
+ min_seq_len: -1
17
+ seq_len: 128
18
+ group_text: true
19
+ remove_text: true
20
+ num_seqs: -1
21
+ add_bos: false
22
+ add_eos: true
23
+ legacy_start_end_bos: true
24
+ loader:
25
+ global_batch_size: 2
26
+ eval_global_batch_size: 2
27
+ batch_size: 1
28
+ eval_batch_size: 1
29
+ num_workers: ${eval:"len(__import__('os').sched_getaffinity(0))"}
30
+ pin_memory: true
31
+ persistent_workers: true
32
+ training:
33
+ ema: 0.9999
34
+ antithetic_sampling: true
35
+ importance_sampling: false
36
+ sampling_eps: 1.0e-05
37
+ change_of_variables: false
38
+ tokenizer:
39
+ name: /home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
40
+ optim:
41
+ name: adamw
42
+ weight_decay: 0.0
43
+ lr: 3.0e-05
44
+ beta1: 0.9
45
+ beta2: 0.999
46
+ eps: 1.0e-08
47
+ trainer:
48
+ _target_: lightning.Trainer
49
+ accelerator: cuda
50
+ num_nodes: 1
51
+ devices: 1
52
+ accumulate_grad_batches: 2
53
+ gradient_clip_val: 1.0
54
+ precision: bf16-mixed
55
+ num_sanity_val_steps: 0
56
+ max_steps: 20000
57
+ log_every_n_steps: 10
58
+ limit_train_batches: 1.0
59
+ limit_val_batches: 1.0
60
+ val_check_interval: ${eval:${trainer.accumulate_grad_batches} * ${eval_every}}
61
+ check_val_every_n_epoch: null
62
+ benchmark: true
63
+ wandb: null
64
+ checkpointing:
65
+ save_dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
66
+ resume_from_ckpt: true
67
+ resume_ckpt_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/checkpoints/last.ckpt
68
+ eval:
69
+ valid:
70
+ n_samples: 16
71
+ num_steps: 128
72
+ ppl_with_ar:
73
+ run: true
74
+ model: gpt2-large
75
+ batch_size: 8
76
+ cond_ppl:
77
+ run: true
78
+ model: gpt2-large
79
+ batch_size: 8
80
+ mauve:
81
+ run: false
82
+ num_rounds: 5
83
+ max_num_tokens: 100
84
+ batch_size: 8
85
+ scaling_factor: 5
86
+ lambada_openai:
87
+ run: false
88
+ batch_size: 32
89
+ num_samples: 32
90
+ from_ema: false
91
+ add_bos: true
92
+ add_eos: true
93
+ callbacks:
94
+ checkpoint_every_n_steps:
95
+ _target_: lightning.pytorch.callbacks.ModelCheckpoint
96
+ save_top_k: -1
97
+ save_last: true
98
+ dirpath: ${checkpointing.save_dir}/checkpoints
99
+ verbose: true
100
+ auto_insert_metric_name: false
101
+ every_n_train_steps: 10000
102
+ learning_rate_monitor:
103
+ _target_: lightning.pytorch.callbacks.LearningRateMonitor
104
+ logging_interval: step
105
+ text_throughput:
106
+ _target_: callbacks.text_throughput.TextThroughputMonitor
107
+ grad_norm:
108
+ _target_: callbacks.gradient_norm.GradNormCallback
109
+ data:
110
+ train: lm1b
111
+ valid: lm1b
112
+ test: openwebtext-test
113
+ tokenizer_name_or_path: gpt2
114
+ wrap: true
115
+ streaming: false
116
+ model:
117
+ name: small
118
+ type: ddit-orig
119
+ hidden_size: 768
120
+ cond_dim: 128
121
+ length: 128
122
+ n_blocks: 12
123
+ n_heads: 12
124
+ scale_by_sigma: true
125
+ dropout: 0.1
126
+ tie_word_embeddings: false
127
+ strategy:
128
+ _target_: lightning.pytorch.strategies.DDPStrategy
129
+ find_unused_parameters: true
130
+ noise:
131
+ type: loglinear
132
+ sigma_min: 0.0001
133
+ sigma_max: 20
134
+ lr_scheduler:
135
+ _target_: transformers.get_constant_schedule_with_warmup
136
+ num_warmup_steps: 2500
137
+ parameterization:
138
+ name: multi-round-sdtt
139
+ log_loss_buckets: -1
140
+ checkpoint_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/inputs/teacher_adapted.ckpt
141
+ start_from_hf: false
142
+ distill_mode: kl-bwd
143
+ num_distill_steps: 2
144
+ min_num_sampling_steps: 8
145
+ grow_dt_every: 10000
146
+ orig_num_sampling_steps: 1024
147
+ sampling_mode: ancestral
148
+ loss_precision: null
149
+ reset_optimizer_on_growth: false
150
+ use_ema_on_growth: false
151
+ sampling:
152
+ uncond:
153
+ run: true
154
+ num_samples: 1024
155
+ batch_size: 16
156
+ from_ema: false
157
+ num_steps: 16
158
+ seq_len: 1024
159
+ sampler: ancestral
160
+ cache_preds: false
161
+ add_bos: false
162
+ add_eos: false
163
+ cond_prefix:
164
+ run: true
165
+ num_samples: 256
166
+ batch_size: 16
167
+ from_ema: false
168
+ dataset: webtext
169
+ seq_len: 100
170
+ prefix_len: 50
171
+ num_cont_per_prefix: 5
172
+ min_seq_len: 1024
173
+ num_steps: 128
174
+ sampler: ancestral
175
+ cache_preds: false
176
+ add_bos: false
177
+ add_eos: false
178
+ calc_sbleu: true
179
+ seed: 42
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/.hydra/hydra.yaml ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ hydra:
2
+ run:
3
+ dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
4
+ sweep:
5
+ dir: multirun/${now:%Y-%m-%d}/${now:%H-%M-%S}
6
+ subdir: ${hydra.job.num}
7
+ launcher:
8
+ _target_: hydra._internal.core_plugins.basic_launcher.BasicLauncher
9
+ sweeper:
10
+ _target_: hydra._internal.core_plugins.basic_sweeper.BasicSweeper
11
+ max_batch_size: null
12
+ params: null
13
+ help:
14
+ app_name: ${hydra.job.name}
15
+ header: '${hydra.help.app_name} is powered by Hydra.
16
+
17
+ '
18
+ footer: 'Powered by Hydra (https://hydra.cc)
19
+
20
+ Use --hydra-help to view Hydra specific help
21
+
22
+ '
23
+ template: '${hydra.help.header}
24
+
25
+ == Configuration groups ==
26
+
27
+ Compose your configuration from those groups (group=option)
28
+
29
+
30
+ $APP_CONFIG_GROUPS
31
+
32
+
33
+ == Config ==
34
+
35
+ Override anything in the config (foo.bar=value)
36
+
37
+
38
+ $CONFIG
39
+
40
+
41
+ ${hydra.help.footer}
42
+
43
+ '
44
+ hydra_help:
45
+ template: 'Hydra (${hydra.runtime.version})
46
+
47
+ See https://hydra.cc for more info.
48
+
49
+
50
+ == Flags ==
51
+
52
+ $FLAGS_HELP
53
+
54
+
55
+ == Configuration groups ==
56
+
57
+ Compose your configuration from those groups (For example, append hydra/job_logging=disabled
58
+ to command line)
59
+
60
+
61
+ $HYDRA_CONFIG_GROUPS
62
+
63
+
64
+ Use ''--cfg hydra'' to Show the Hydra config.
65
+
66
+ '
67
+ hydra_help: ???
68
+ hydra_logging:
69
+ version: 1
70
+ formatters:
71
+ simple:
72
+ format: '[%(asctime)s][HYDRA] %(message)s'
73
+ handlers:
74
+ console:
75
+ class: logging.StreamHandler
76
+ formatter: simple
77
+ stream: ext://sys.stdout
78
+ root:
79
+ level: INFO
80
+ handlers:
81
+ - console
82
+ loggers:
83
+ logging_example:
84
+ level: DEBUG
85
+ disable_existing_loggers: false
86
+ job_logging:
87
+ version: 1
88
+ formatters:
89
+ simple:
90
+ format: '[%(asctime)s][%(name)s][%(levelname)s] - %(message)s'
91
+ handlers:
92
+ console:
93
+ class: logging.StreamHandler
94
+ formatter: simple
95
+ stream: ext://sys.stdout
96
+ file:
97
+ class: logging.FileHandler
98
+ formatter: simple
99
+ filename: ${hydra.runtime.output_dir}/${hydra.job.name}.log
100
+ root:
101
+ level: INFO
102
+ handlers:
103
+ - console
104
+ - file
105
+ disable_existing_loggers: false
106
+ env: {}
107
+ mode: RUN
108
+ searchpath: []
109
+ callbacks: {}
110
+ output_subdir: .hydra
111
+ overrides:
112
+ hydra:
113
+ - hydra.run.dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
114
+ - hydra.job.chdir=true
115
+ - hydra.mode=RUN
116
+ task:
117
+ - mode=train
118
+ - data.train=lm1b
119
+ - data.valid=lm1b
120
+ - tokenizer.name=/home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
121
+ - data_preprocess.data_cache=/home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
122
+ - data_preprocess.seq_len=128
123
+ - data_preprocess.group_text=true
124
+ - data_preprocess.remove_text=true
125
+ - data_preprocess.add_bos=false
126
+ - data_preprocess.add_eos=true
127
+ - data_preprocess.legacy_start_end_bos=true
128
+ - model=dit-orig-small
129
+ - model.length=128
130
+ - parameterization=multi-round-sdtt
131
+ - parameterization.checkpoint_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/inputs/teacher_adapted.ckpt
132
+ - parameterization.start_from_hf=false
133
+ - parameterization.grow_dt_every=10000
134
+ - parameterization.orig_num_sampling_steps=1024
135
+ - loader.global_batch_size=2
136
+ - loader.eval_global_batch_size=2
137
+ - loader.batch_size=1
138
+ - loader.eval_batch_size=1
139
+ - trainer.devices=1
140
+ - trainer.num_nodes=1
141
+ - trainer.accumulate_grad_batches=2
142
+ - trainer.max_steps=20000
143
+ - trainer.precision=bf16-mixed
144
+ - optim.lr=3e-05
145
+ - lr_scheduler.num_warmup_steps=2500
146
+ - callbacks.checkpoint_every_n_steps.every_n_train_steps=10000
147
+ - checkpointing.save_dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
148
+ - checkpointing.resume_from_ckpt=true
149
+ - checkpointing.resume_ckpt_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/checkpoints/last.ckpt
150
+ - wandb=null
151
+ - +seed=42
152
+ - is_di4c=true
153
+ - is_teacher_di4c=false
154
+ - T=1024
155
+ - latent_bsize=16
156
+ - round=7
157
+ job:
158
+ name: main
159
+ chdir: true
160
+ override_dirname: +seed=42,T=1024,callbacks.checkpoint_every_n_steps.every_n_train_steps=10000,checkpointing.resume_ckpt_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/checkpoints/last.ckpt,checkpointing.resume_from_ckpt=true,checkpointing.save_dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b,data.train=lm1b,data.valid=lm1b,data_preprocess.add_bos=false,data_preprocess.add_eos=true,data_preprocess.data_cache=/home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b,data_preprocess.group_text=true,data_preprocess.legacy_start_end_bos=true,data_preprocess.remove_text=true,data_preprocess.seq_len=128,is_di4c=true,is_teacher_di4c=false,latent_bsize=16,loader.batch_size=1,loader.eval_batch_size=1,loader.eval_global_batch_size=2,loader.global_batch_size=2,lr_scheduler.num_warmup_steps=2500,mode=train,model.length=128,model=dit-orig-small,optim.lr=3e-05,parameterization.checkpoint_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/inputs/teacher_adapted.ckpt,parameterization.grow_dt_every=10000,parameterization.orig_num_sampling_steps=1024,parameterization.start_from_hf=false,parameterization=multi-round-sdtt,round=7,tokenizer.name=/home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594,trainer.accumulate_grad_batches=2,trainer.devices=1,trainer.max_steps=20000,trainer.num_nodes=1,trainer.precision=bf16-mixed,wandb=null
161
+ id: ???
162
+ num: ???
163
+ config_name: config
164
+ env_set: {}
165
+ env_copy: []
166
+ config:
167
+ override_dirname:
168
+ kv_sep: '='
169
+ item_sep: ','
170
+ exclude_keys: []
171
+ runtime:
172
+ version: 1.3.2
173
+ version_base: '1.3'
174
+ cwd: /home/ruizzhao/diffusion_baseline/upstreams/di4c
175
+ config_sources:
176
+ - path: hydra.conf
177
+ schema: pkg
178
+ provider: hydra
179
+ - path: /home/ruizzhao/diffusion_baseline/upstreams/di4c/sdtt/src/sdtt/configs
180
+ schema: file
181
+ provider: main
182
+ - path: ''
183
+ schema: structured
184
+ provider: schema
185
+ output_dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
186
+ choices:
187
+ parameterization: multi-round-sdtt
188
+ lr_scheduler: constant_warmup
189
+ noise: loglinear
190
+ strategy: ddp
191
+ model: dit-orig-small
192
+ data: openwebtext-split
193
+ hydra/env: default
194
+ hydra/callbacks: null
195
+ hydra/job_logging: default
196
+ hydra/hydra_logging: default
197
+ hydra/hydra_help: default
198
+ hydra/help: default
199
+ hydra/sweeper: basic
200
+ hydra/launcher: basic
201
+ hydra/output: default
202
+ verbose: false
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/.hydra/overrides.yaml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - mode=train
2
+ - data.train=lm1b
3
+ - data.valid=lm1b
4
+ - tokenizer.name=/home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
5
+ - data_preprocess.data_cache=/home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
6
+ - data_preprocess.seq_len=128
7
+ - data_preprocess.group_text=true
8
+ - data_preprocess.remove_text=true
9
+ - data_preprocess.add_bos=false
10
+ - data_preprocess.add_eos=true
11
+ - data_preprocess.legacy_start_end_bos=true
12
+ - model=dit-orig-small
13
+ - model.length=128
14
+ - parameterization=multi-round-sdtt
15
+ - parameterization.checkpoint_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/inputs/teacher_adapted.ckpt
16
+ - parameterization.start_from_hf=false
17
+ - parameterization.grow_dt_every=10000
18
+ - parameterization.orig_num_sampling_steps=1024
19
+ - loader.global_batch_size=2
20
+ - loader.eval_global_batch_size=2
21
+ - loader.batch_size=1
22
+ - loader.eval_batch_size=1
23
+ - trainer.devices=1
24
+ - trainer.num_nodes=1
25
+ - trainer.accumulate_grad_batches=2
26
+ - trainer.max_steps=20000
27
+ - trainer.precision=bf16-mixed
28
+ - optim.lr=3e-05
29
+ - lr_scheduler.num_warmup_steps=2500
30
+ - callbacks.checkpoint_every_n_steps.every_n_train_steps=10000
31
+ - checkpointing.save_dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
32
+ - checkpointing.resume_from_ckpt=true
33
+ - checkpointing.resume_ckpt_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/checkpoints/last.ckpt
34
+ - wandb=null
35
+ - +seed=42
36
+ - is_di4c=true
37
+ - is_teacher_di4c=false
38
+ - T=1024
39
+ - latent_bsize=16
40
+ - round=7
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/config.yaml ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mode: train
2
+ time_conditioning: false
3
+ T: 1024
4
+ compile: false
5
+ eval_every: 5000000
6
+ is_di4c: true
7
+ is_teacher_di4c: false
8
+ latent_bsize: 16
9
+ alpha_t: sigmoid
10
+ alpha_const: 0.1
11
+ distil_delta: 0.02
12
+ log_unif: false
13
+ round: 7
14
+ data_preprocess:
15
+ data_cache: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
16
+ min_seq_len: -1
17
+ seq_len: 128
18
+ group_text: true
19
+ remove_text: true
20
+ num_seqs: -1
21
+ add_bos: false
22
+ add_eos: true
23
+ legacy_start_end_bos: true
24
+ loader:
25
+ global_batch_size: 2
26
+ eval_global_batch_size: 2
27
+ batch_size: 1
28
+ eval_batch_size: 1
29
+ num_workers: ${eval:"len(__import__('os').sched_getaffinity(0))"}
30
+ pin_memory: true
31
+ persistent_workers: true
32
+ training:
33
+ ema: 0.9999
34
+ antithetic_sampling: true
35
+ importance_sampling: false
36
+ sampling_eps: 1.0e-05
37
+ change_of_variables: false
38
+ tokenizer:
39
+ name: /home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
40
+ optim:
41
+ name: adamw
42
+ weight_decay: 0.0
43
+ lr: 3.0e-05
44
+ beta1: 0.9
45
+ beta2: 0.999
46
+ eps: 1.0e-08
47
+ trainer:
48
+ _target_: lightning.Trainer
49
+ accelerator: cuda
50
+ num_nodes: 1
51
+ devices: 1
52
+ accumulate_grad_batches: 2
53
+ gradient_clip_val: 1.0
54
+ precision: bf16-mixed
55
+ num_sanity_val_steps: 0
56
+ max_steps: 20000
57
+ log_every_n_steps: 10
58
+ limit_train_batches: 1.0
59
+ limit_val_batches: 1.0
60
+ val_check_interval: ${eval:${trainer.accumulate_grad_batches} * ${eval_every}}
61
+ check_val_every_n_epoch: null
62
+ benchmark: true
63
+ wandb: null
64
+ checkpointing:
65
+ save_dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b
66
+ resume_from_ckpt: true
67
+ resume_ckpt_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/checkpoints/last.ckpt
68
+ eval:
69
+ valid:
70
+ n_samples: 16
71
+ num_steps: 128
72
+ ppl_with_ar:
73
+ run: true
74
+ model: gpt2-large
75
+ batch_size: 8
76
+ cond_ppl:
77
+ run: true
78
+ model: gpt2-large
79
+ batch_size: 8
80
+ mauve:
81
+ run: false
82
+ num_rounds: 5
83
+ max_num_tokens: 100
84
+ batch_size: 8
85
+ scaling_factor: 5
86
+ lambada_openai:
87
+ run: false
88
+ batch_size: 32
89
+ num_samples: 32
90
+ from_ema: false
91
+ add_bos: true
92
+ add_eos: true
93
+ callbacks:
94
+ checkpoint_every_n_steps:
95
+ _target_: lightning.pytorch.callbacks.ModelCheckpoint
96
+ save_top_k: -1
97
+ save_last: true
98
+ dirpath: ${checkpointing.save_dir}/checkpoints
99
+ verbose: true
100
+ auto_insert_metric_name: false
101
+ every_n_train_steps: 10000
102
+ learning_rate_monitor:
103
+ _target_: lightning.pytorch.callbacks.LearningRateMonitor
104
+ logging_interval: step
105
+ text_throughput:
106
+ _target_: callbacks.text_throughput.TextThroughputMonitor
107
+ grad_norm:
108
+ _target_: callbacks.gradient_norm.GradNormCallback
109
+ data:
110
+ train: lm1b
111
+ valid: lm1b
112
+ test: openwebtext-test
113
+ tokenizer_name_or_path: gpt2
114
+ wrap: true
115
+ streaming: false
116
+ model:
117
+ name: small
118
+ type: ddit-orig
119
+ hidden_size: 768
120
+ cond_dim: 128
121
+ length: 128
122
+ n_blocks: 12
123
+ n_heads: 12
124
+ scale_by_sigma: true
125
+ dropout: 0.1
126
+ tie_word_embeddings: false
127
+ strategy:
128
+ _target_: lightning.pytorch.strategies.DDPStrategy
129
+ find_unused_parameters: true
130
+ noise:
131
+ type: loglinear
132
+ sigma_min: 0.0001
133
+ sigma_max: 20
134
+ lr_scheduler:
135
+ _target_: transformers.get_constant_schedule_with_warmup
136
+ num_warmup_steps: 2500
137
+ parameterization:
138
+ name: multi-round-sdtt
139
+ log_loss_buckets: -1
140
+ checkpoint_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/duo_di4c/lm1b/inputs/teacher_adapted.ckpt
141
+ start_from_hf: false
142
+ distill_mode: kl-bwd
143
+ num_distill_steps: 2
144
+ min_num_sampling_steps: 8
145
+ grow_dt_every: 10000
146
+ orig_num_sampling_steps: 1024
147
+ sampling_mode: ancestral
148
+ loss_precision: null
149
+ reset_optimizer_on_growth: false
150
+ use_ema_on_growth: false
151
+ sampling:
152
+ uncond:
153
+ run: true
154
+ num_samples: 1024
155
+ batch_size: 16
156
+ from_ema: false
157
+ num_steps: 16
158
+ seq_len: 1024
159
+ sampler: ancestral
160
+ cache_preds: false
161
+ add_bos: false
162
+ add_eos: false
163
+ cond_prefix:
164
+ run: true
165
+ num_samples: 256
166
+ batch_size: 16
167
+ from_ema: false
168
+ dataset: webtext
169
+ seq_len: 100
170
+ prefix_len: 50
171
+ num_cont_per_prefix: 5
172
+ min_seq_len: 1024
173
+ num_steps: 128
174
+ sampler: ancestral
175
+ cache_preds: false
176
+ add_bos: false
177
+ add_eos: false
178
+ calc_sbleu: true
179
+ seed: 42
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/logs_di4c_train.txt ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-08-20 17:43:21.308 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Starting training
2
+ 2026-08-20 17:43:21.309 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Training starting from scratch (no checkpoint to reload)
3
+ 2026-08-20 17:43:22.879 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Skipping HF student tensors with incompatible shapes: [('backbone.output_layer.linear.bias', (50258,), (30523,)), ('backbone.output_layer.linear.weight', (50258, 768), (30523, 768)), ('backbone.vocab_embed.embedding', (50258, 768), (30523, 768))]
4
+ 2026-08-20 17:43:30.787 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
5
+ 2026-08-20 17:43:30.791 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_train_bs128_wrapped.dat
6
+ 2026-08-20 17:43:30.830 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
7
+ 2026-08-20 17:43:30.830 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using LM1B test set as validation set
8
+ 2026-08-20 17:43:30.830 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_test_bs128_wrapped.dat
9
+ 2026-08-20 17:43:30.832 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Printing train batch.
10
+ 2026-08-20 17:43:30.833 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Batch input_ids.shape: torch.Size([1, 128])
11
+ 2026-08-20 17:43:30.833 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - First 64 tokens: [CLS] while athletes in different professions dealt with doping scandals and other controversies, woods continued to do what he did best : dominate the field of professional golf and rake in endorsements. [SEP] the minutes could shed light on an internal debate, which has been evident in fed officials'recent speeches, over when to consider raising rates.
12
+ 2026-08-20 17:43:30.834 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 101, 2096, 7576, 1999, 2367, 22797, 9411, 2007, 23799, 29609,
13
+ 1998, 2060, 25962, 1010, 5249, 2506, 2000, 2079, 2054, 2002,
14
+ 2106, 2190, 1024, 16083, 1996, 2492, 1997, 2658, 5439, 1998,
15
+ 26008, 1999, 20380, 2015, 1012, 102, 1996, 2781, 2071, 8328,
16
+ 2422, 2006, 2019, 4722, 5981, 1010, 2029, 2038, 2042, 10358,
17
+ 1999, 7349, 4584, 1005, 3522, 13867, 1010, 2058, 2043, 2000,
18
+ 5136, 6274, 6165, 1012])
19
+ 2026-08-20 17:43:30.834 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Last 64 tokens: [SEP] but metro's definition of " urbanite " is not accurate, says matthew gandy, director of the urban laboratory at university college london. [SEP] goodrich petroleum is an independent oil and gas exploration and production company listed on the new york stock exchange. [SEP] the support from spears is to end on november 15 [SEP]
20
+ 2026-08-20 17:43:30.834 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 102, 2021, 6005, 1005, 1055, 6210, 1997, 1000, 3923, 4221,
21
+ 1000, 2003, 2025, 8321, 1010, 2758, 5487, 25957, 5149, 1010,
22
+ 2472, 1997, 1996, 3923, 5911, 2012, 2118, 2267, 2414, 1012,
23
+ 102, 2204, 13149, 11540, 2003, 2019, 2981, 3514, 1998, 3806,
24
+ 8993, 1998, 2537, 2194, 3205, 2006, 1996, 2047, 2259, 4518,
25
+ 3863, 1012, 102, 1996, 2490, 2013, 13957, 2003, 2000, 2203,
26
+ 2006, 2281, 2321, 102])
27
+ 2026-08-20 17:43:30.834 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ==================================================
28
+ 2026-08-20 17:43:30.834 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Printing valid batch.
29
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Batch input_ids.shape: torch.Size([1, 128])
30
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - First 64 tokens: [CLS] in medieval times, the townspeople from norcia were so practised at butchering pigs that they gained an in - depth knowledge of anatomy and were allowed to practise as surgeons along with members of the clergy. [SEP] the satellite weighs some 660 pounds, the israeli haaretz newspaper reported, citing unnamed company officials.
31
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 101, 1999, 5781, 2335, 1010, 1996, 27938, 2013, 4496, 7405,
32
+ 2020, 2061, 20439, 2012, 14998, 2075, 14695, 2008, 2027, 4227,
33
+ 2019, 1999, 1011, 5995, 3716, 1997, 13336, 1998, 2020, 3039,
34
+ 2000, 10975, 18908, 5562, 2004, 16804, 2247, 2007, 2372, 1997,
35
+ 1996, 11646, 1012, 102, 1996, 5871, 21094, 2070, 20982, 7038,
36
+ 1010, 1996, 5611, 5292, 12069, 5753, 3780, 2988, 1010, 8951,
37
+ 13294, 2194, 4584, 1012])
38
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Last 64 tokens: [SEP] the situation has been further complicated by growing indications that the us treasury is preparing to make funds available for recapitalsing us banks. [SEP] as north korea's close neighbor, traditional ally and main provider of economic aid, china is widely believed to hold the key to solving the north korea conundrum. [SEP]
39
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 102, 1996, 3663, 2038, 2042, 2582, 8552, 2011, 3652, 24936,
40
+ 2008, 1996, 2149, 9837, 2003, 8225, 2000, 2191, 5029, 2800,
41
+ 2005, 28667, 9331, 18400, 7741, 2149, 5085, 1012, 102, 2004,
42
+ 2167, 4420, 1005, 1055, 2485, 11429, 1010, 3151, 9698, 1998,
43
+ 2364, 10802, 1997, 3171, 4681, 1010, 2859, 2003, 4235, 3373,
44
+ 2000, 2907, 1996, 3145, 2000, 13729, 1996, 2167, 4420, 9530,
45
+ 8630, 6824, 1012, 102])
46
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ==================================================
47
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Train set length: 7102854
48
+ 2026-08-20 17:43:30.835 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Valid set length: 71979
49
+ 2026-08-20 17:43:30.853 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
50
+ 2026-08-20 17:43:30.854 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_train_bs128_wrapped.dat
51
+ 2026-08-20 17:43:30.936 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
52
+ 2026-08-20 17:43:30.936 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using LM1B test set as validation set
53
+ 2026-08-20 17:43:30.936 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_test_bs128_wrapped.dat
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/stderr.log ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/duo_di4c_lm1b/stdout.log ADDED
The diff for this file is too large to render. See raw diff
 
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/.hydra/config.yaml ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mode: train
2
+ time_conditioning: false
3
+ T: 1024
4
+ compile: false
5
+ eval_every: 5000000
6
+ is_di4c: true
7
+ is_teacher_di4c: false
8
+ latent_bsize: 16
9
+ alpha_t: sigmoid
10
+ alpha_const: 0.1
11
+ distil_delta: 0.02
12
+ log_unif: false
13
+ round: 7
14
+ data_preprocess:
15
+ data_cache: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
16
+ min_seq_len: -1
17
+ seq_len: 128
18
+ group_text: true
19
+ remove_text: true
20
+ num_seqs: -1
21
+ add_bos: false
22
+ add_eos: true
23
+ legacy_start_end_bos: true
24
+ loader:
25
+ global_batch_size: 2
26
+ eval_global_batch_size: 2
27
+ batch_size: 1
28
+ eval_batch_size: 1
29
+ num_workers: ${eval:"len(__import__('os').sched_getaffinity(0))"}
30
+ pin_memory: true
31
+ persistent_workers: true
32
+ training:
33
+ ema: 0.9999
34
+ antithetic_sampling: true
35
+ importance_sampling: false
36
+ sampling_eps: 1.0e-05
37
+ change_of_variables: false
38
+ tokenizer:
39
+ name: /home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
40
+ optim:
41
+ name: adamw
42
+ weight_decay: 0.0
43
+ lr: 3.0e-05
44
+ beta1: 0.9
45
+ beta2: 0.999
46
+ eps: 1.0e-08
47
+ trainer:
48
+ _target_: lightning.Trainer
49
+ accelerator: cuda
50
+ num_nodes: 1
51
+ devices: 1
52
+ accumulate_grad_batches: 2
53
+ gradient_clip_val: 1.0
54
+ precision: bf16-mixed
55
+ num_sanity_val_steps: 0
56
+ max_steps: 20000
57
+ log_every_n_steps: 10
58
+ limit_train_batches: 1.0
59
+ limit_val_batches: 1.0
60
+ val_check_interval: ${eval:${trainer.accumulate_grad_batches} * ${eval_every}}
61
+ check_val_every_n_epoch: null
62
+ benchmark: true
63
+ wandb: null
64
+ checkpointing:
65
+ save_dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
66
+ resume_from_ckpt: true
67
+ resume_ckpt_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/checkpoints/last.ckpt
68
+ eval:
69
+ valid:
70
+ n_samples: 16
71
+ num_steps: 128
72
+ ppl_with_ar:
73
+ run: true
74
+ model: gpt2-large
75
+ batch_size: 8
76
+ cond_ppl:
77
+ run: true
78
+ model: gpt2-large
79
+ batch_size: 8
80
+ mauve:
81
+ run: false
82
+ num_rounds: 5
83
+ max_num_tokens: 100
84
+ batch_size: 8
85
+ scaling_factor: 5
86
+ lambada_openai:
87
+ run: false
88
+ batch_size: 32
89
+ num_samples: 32
90
+ from_ema: false
91
+ add_bos: true
92
+ add_eos: true
93
+ callbacks:
94
+ checkpoint_every_n_steps:
95
+ _target_: lightning.pytorch.callbacks.ModelCheckpoint
96
+ save_top_k: -1
97
+ save_last: true
98
+ dirpath: ${checkpointing.save_dir}/checkpoints
99
+ verbose: true
100
+ auto_insert_metric_name: false
101
+ every_n_train_steps: 10000
102
+ learning_rate_monitor:
103
+ _target_: lightning.pytorch.callbacks.LearningRateMonitor
104
+ logging_interval: step
105
+ text_throughput:
106
+ _target_: callbacks.text_throughput.TextThroughputMonitor
107
+ grad_norm:
108
+ _target_: callbacks.gradient_norm.GradNormCallback
109
+ data:
110
+ train: lm1b
111
+ valid: lm1b
112
+ test: openwebtext-test
113
+ tokenizer_name_or_path: gpt2
114
+ wrap: true
115
+ streaming: false
116
+ model:
117
+ name: small
118
+ type: ddit-orig
119
+ hidden_size: 768
120
+ cond_dim: 128
121
+ length: 128
122
+ n_blocks: 12
123
+ n_heads: 12
124
+ scale_by_sigma: true
125
+ dropout: 0.1
126
+ tie_word_embeddings: false
127
+ strategy:
128
+ _target_: lightning.pytorch.strategies.DDPStrategy
129
+ find_unused_parameters: true
130
+ noise:
131
+ type: loglinear
132
+ sigma_min: 0.0001
133
+ sigma_max: 20
134
+ lr_scheduler:
135
+ _target_: transformers.get_constant_schedule_with_warmup
136
+ num_warmup_steps: 2500
137
+ parameterization:
138
+ name: multi-round-sdtt
139
+ log_loss_buckets: -1
140
+ checkpoint_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/inputs/teacher_adapted.ckpt
141
+ start_from_hf: false
142
+ distill_mode: kl-bwd
143
+ num_distill_steps: 2
144
+ min_num_sampling_steps: 8
145
+ grow_dt_every: 10000
146
+ orig_num_sampling_steps: 1024
147
+ sampling_mode: ancestral
148
+ loss_precision: null
149
+ reset_optimizer_on_growth: false
150
+ use_ema_on_growth: false
151
+ sampling:
152
+ uncond:
153
+ run: true
154
+ num_samples: 1024
155
+ batch_size: 16
156
+ from_ema: false
157
+ num_steps: 16
158
+ seq_len: 1024
159
+ sampler: ancestral
160
+ cache_preds: false
161
+ add_bos: false
162
+ add_eos: false
163
+ cond_prefix:
164
+ run: true
165
+ num_samples: 256
166
+ batch_size: 16
167
+ from_ema: false
168
+ dataset: webtext
169
+ seq_len: 100
170
+ prefix_len: 50
171
+ num_cont_per_prefix: 5
172
+ min_seq_len: 1024
173
+ num_steps: 128
174
+ sampler: ancestral
175
+ cache_preds: false
176
+ add_bos: false
177
+ add_eos: false
178
+ calc_sbleu: true
179
+ seed: 42
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/.hydra/hydra.yaml ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ hydra:
2
+ run:
3
+ dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
4
+ sweep:
5
+ dir: multirun/${now:%Y-%m-%d}/${now:%H-%M-%S}
6
+ subdir: ${hydra.job.num}
7
+ launcher:
8
+ _target_: hydra._internal.core_plugins.basic_launcher.BasicLauncher
9
+ sweeper:
10
+ _target_: hydra._internal.core_plugins.basic_sweeper.BasicSweeper
11
+ max_batch_size: null
12
+ params: null
13
+ help:
14
+ app_name: ${hydra.job.name}
15
+ header: '${hydra.help.app_name} is powered by Hydra.
16
+
17
+ '
18
+ footer: 'Powered by Hydra (https://hydra.cc)
19
+
20
+ Use --hydra-help to view Hydra specific help
21
+
22
+ '
23
+ template: '${hydra.help.header}
24
+
25
+ == Configuration groups ==
26
+
27
+ Compose your configuration from those groups (group=option)
28
+
29
+
30
+ $APP_CONFIG_GROUPS
31
+
32
+
33
+ == Config ==
34
+
35
+ Override anything in the config (foo.bar=value)
36
+
37
+
38
+ $CONFIG
39
+
40
+
41
+ ${hydra.help.footer}
42
+
43
+ '
44
+ hydra_help:
45
+ template: 'Hydra (${hydra.runtime.version})
46
+
47
+ See https://hydra.cc for more info.
48
+
49
+
50
+ == Flags ==
51
+
52
+ $FLAGS_HELP
53
+
54
+
55
+ == Configuration groups ==
56
+
57
+ Compose your configuration from those groups (For example, append hydra/job_logging=disabled
58
+ to command line)
59
+
60
+
61
+ $HYDRA_CONFIG_GROUPS
62
+
63
+
64
+ Use ''--cfg hydra'' to Show the Hydra config.
65
+
66
+ '
67
+ hydra_help: ???
68
+ hydra_logging:
69
+ version: 1
70
+ formatters:
71
+ simple:
72
+ format: '[%(asctime)s][HYDRA] %(message)s'
73
+ handlers:
74
+ console:
75
+ class: logging.StreamHandler
76
+ formatter: simple
77
+ stream: ext://sys.stdout
78
+ root:
79
+ level: INFO
80
+ handlers:
81
+ - console
82
+ loggers:
83
+ logging_example:
84
+ level: DEBUG
85
+ disable_existing_loggers: false
86
+ job_logging:
87
+ version: 1
88
+ formatters:
89
+ simple:
90
+ format: '[%(asctime)s][%(name)s][%(levelname)s] - %(message)s'
91
+ handlers:
92
+ console:
93
+ class: logging.StreamHandler
94
+ formatter: simple
95
+ stream: ext://sys.stdout
96
+ file:
97
+ class: logging.FileHandler
98
+ formatter: simple
99
+ filename: ${hydra.runtime.output_dir}/${hydra.job.name}.log
100
+ root:
101
+ level: INFO
102
+ handlers:
103
+ - console
104
+ - file
105
+ disable_existing_loggers: false
106
+ env: {}
107
+ mode: RUN
108
+ searchpath: []
109
+ callbacks: {}
110
+ output_subdir: .hydra
111
+ overrides:
112
+ hydra:
113
+ - hydra.run.dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
114
+ - hydra.job.chdir=true
115
+ - hydra.mode=RUN
116
+ task:
117
+ - mode=train
118
+ - data.train=lm1b
119
+ - data.valid=lm1b
120
+ - tokenizer.name=/home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
121
+ - data_preprocess.data_cache=/home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
122
+ - data_preprocess.seq_len=128
123
+ - data_preprocess.group_text=true
124
+ - data_preprocess.remove_text=true
125
+ - data_preprocess.add_bos=false
126
+ - data_preprocess.add_eos=true
127
+ - data_preprocess.legacy_start_end_bos=true
128
+ - model=dit-orig-small
129
+ - model.length=128
130
+ - parameterization=multi-round-sdtt
131
+ - parameterization.checkpoint_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/inputs/teacher_adapted.ckpt
132
+ - parameterization.start_from_hf=false
133
+ - parameterization.grow_dt_every=10000
134
+ - parameterization.orig_num_sampling_steps=1024
135
+ - loader.global_batch_size=2
136
+ - loader.eval_global_batch_size=2
137
+ - loader.batch_size=1
138
+ - loader.eval_batch_size=1
139
+ - trainer.devices=1
140
+ - trainer.num_nodes=1
141
+ - trainer.accumulate_grad_batches=2
142
+ - trainer.max_steps=20000
143
+ - trainer.precision=bf16-mixed
144
+ - optim.lr=3e-05
145
+ - lr_scheduler.num_warmup_steps=2500
146
+ - callbacks.checkpoint_every_n_steps.every_n_train_steps=10000
147
+ - checkpointing.save_dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
148
+ - checkpointing.resume_from_ckpt=true
149
+ - checkpointing.resume_ckpt_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/checkpoints/last.ckpt
150
+ - wandb=null
151
+ - +seed=42
152
+ - is_di4c=true
153
+ - is_teacher_di4c=false
154
+ - T=1024
155
+ - latent_bsize=16
156
+ - round=7
157
+ job:
158
+ name: main
159
+ chdir: true
160
+ override_dirname: +seed=42,T=1024,callbacks.checkpoint_every_n_steps.every_n_train_steps=10000,checkpointing.resume_ckpt_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/checkpoints/last.ckpt,checkpointing.resume_from_ckpt=true,checkpointing.save_dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b,data.train=lm1b,data.valid=lm1b,data_preprocess.add_bos=false,data_preprocess.add_eos=true,data_preprocess.data_cache=/home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b,data_preprocess.group_text=true,data_preprocess.legacy_start_end_bos=true,data_preprocess.remove_text=true,data_preprocess.seq_len=128,is_di4c=true,is_teacher_di4c=false,latent_bsize=16,loader.batch_size=1,loader.eval_batch_size=1,loader.eval_global_batch_size=2,loader.global_batch_size=2,lr_scheduler.num_warmup_steps=2500,mode=train,model.length=128,model=dit-orig-small,optim.lr=3e-05,parameterization.checkpoint_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/inputs/teacher_adapted.ckpt,parameterization.grow_dt_every=10000,parameterization.orig_num_sampling_steps=1024,parameterization.start_from_hf=false,parameterization=multi-round-sdtt,round=7,tokenizer.name=/home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594,trainer.accumulate_grad_batches=2,trainer.devices=1,trainer.max_steps=20000,trainer.num_nodes=1,trainer.precision=bf16-mixed,wandb=null
161
+ id: ???
162
+ num: ???
163
+ config_name: config
164
+ env_set: {}
165
+ env_copy: []
166
+ config:
167
+ override_dirname:
168
+ kv_sep: '='
169
+ item_sep: ','
170
+ exclude_keys: []
171
+ runtime:
172
+ version: 1.3.2
173
+ version_base: '1.3'
174
+ cwd: /home/ruizzhao/diffusion_baseline/upstreams/di4c
175
+ config_sources:
176
+ - path: hydra.conf
177
+ schema: pkg
178
+ provider: hydra
179
+ - path: /home/ruizzhao/diffusion_baseline/upstreams/di4c/sdtt/src/sdtt/configs
180
+ schema: file
181
+ provider: main
182
+ - path: ''
183
+ schema: structured
184
+ provider: schema
185
+ output_dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
186
+ choices:
187
+ parameterization: multi-round-sdtt
188
+ lr_scheduler: constant_warmup
189
+ noise: loglinear
190
+ strategy: ddp
191
+ model: dit-orig-small
192
+ data: openwebtext-split
193
+ hydra/env: default
194
+ hydra/callbacks: null
195
+ hydra/job_logging: default
196
+ hydra/hydra_logging: default
197
+ hydra/hydra_help: default
198
+ hydra/help: default
199
+ hydra/sweeper: basic
200
+ hydra/launcher: basic
201
+ hydra/output: default
202
+ verbose: false
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/.hydra/overrides.yaml ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ - mode=train
2
+ - data.train=lm1b
3
+ - data.valid=lm1b
4
+ - tokenizer.name=/home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
5
+ - data_preprocess.data_cache=/home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
6
+ - data_preprocess.seq_len=128
7
+ - data_preprocess.group_text=true
8
+ - data_preprocess.remove_text=true
9
+ - data_preprocess.add_bos=false
10
+ - data_preprocess.add_eos=true
11
+ - data_preprocess.legacy_start_end_bos=true
12
+ - model=dit-orig-small
13
+ - model.length=128
14
+ - parameterization=multi-round-sdtt
15
+ - parameterization.checkpoint_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/inputs/teacher_adapted.ckpt
16
+ - parameterization.start_from_hf=false
17
+ - parameterization.grow_dt_every=10000
18
+ - parameterization.orig_num_sampling_steps=1024
19
+ - loader.global_batch_size=2
20
+ - loader.eval_global_batch_size=2
21
+ - loader.batch_size=1
22
+ - loader.eval_batch_size=1
23
+ - trainer.devices=1
24
+ - trainer.num_nodes=1
25
+ - trainer.accumulate_grad_batches=2
26
+ - trainer.max_steps=20000
27
+ - trainer.precision=bf16-mixed
28
+ - optim.lr=3e-05
29
+ - lr_scheduler.num_warmup_steps=2500
30
+ - callbacks.checkpoint_every_n_steps.every_n_train_steps=10000
31
+ - checkpointing.save_dir=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
32
+ - checkpointing.resume_from_ckpt=true
33
+ - checkpointing.resume_ckpt_path=/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/checkpoints/last.ckpt
34
+ - wandb=null
35
+ - +seed=42
36
+ - is_di4c=true
37
+ - is_teacher_di4c=false
38
+ - T=1024
39
+ - latent_bsize=16
40
+ - round=7
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/config.yaml ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mode: train
2
+ time_conditioning: false
3
+ T: 1024
4
+ compile: false
5
+ eval_every: 5000000
6
+ is_di4c: true
7
+ is_teacher_di4c: false
8
+ latent_bsize: 16
9
+ alpha_t: sigmoid
10
+ alpha_const: 0.1
11
+ distil_delta: 0.02
12
+ log_unif: false
13
+ round: 7
14
+ data_preprocess:
15
+ data_cache: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b
16
+ min_seq_len: -1
17
+ seq_len: 128
18
+ group_text: true
19
+ remove_text: true
20
+ num_seqs: -1
21
+ add_bos: false
22
+ add_eos: true
23
+ legacy_start_end_bos: true
24
+ loader:
25
+ global_batch_size: 2
26
+ eval_global_batch_size: 2
27
+ batch_size: 1
28
+ eval_batch_size: 1
29
+ num_workers: ${eval:"len(__import__('os').sched_getaffinity(0))"}
30
+ pin_memory: true
31
+ persistent_workers: true
32
+ training:
33
+ ema: 0.9999
34
+ antithetic_sampling: true
35
+ importance_sampling: false
36
+ sampling_eps: 1.0e-05
37
+ change_of_variables: false
38
+ tokenizer:
39
+ name: /home/ruizzhao/diffusion_baseline/data/raw/huggingface/hub/models--bert-base-uncased/snapshots/86b5e0934494bd15c9632b12f734a8a67f723594
40
+ optim:
41
+ name: adamw
42
+ weight_decay: 0.0
43
+ lr: 3.0e-05
44
+ beta1: 0.9
45
+ beta2: 0.999
46
+ eps: 1.0e-08
47
+ trainer:
48
+ _target_: lightning.Trainer
49
+ accelerator: cuda
50
+ num_nodes: 1
51
+ devices: 1
52
+ accumulate_grad_batches: 2
53
+ gradient_clip_val: 1.0
54
+ precision: bf16-mixed
55
+ num_sanity_val_steps: 0
56
+ max_steps: 20000
57
+ log_every_n_steps: 10
58
+ limit_train_batches: 1.0
59
+ limit_val_batches: 1.0
60
+ val_check_interval: ${eval:${trainer.accumulate_grad_batches} * ${eval_every}}
61
+ check_val_every_n_epoch: null
62
+ benchmark: true
63
+ wandb: null
64
+ checkpointing:
65
+ save_dir: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b
66
+ resume_from_ckpt: true
67
+ resume_ckpt_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/checkpoints/last.ckpt
68
+ eval:
69
+ valid:
70
+ n_samples: 16
71
+ num_steps: 128
72
+ ppl_with_ar:
73
+ run: true
74
+ model: gpt2-large
75
+ batch_size: 8
76
+ cond_ppl:
77
+ run: true
78
+ model: gpt2-large
79
+ batch_size: 8
80
+ mauve:
81
+ run: false
82
+ num_rounds: 5
83
+ max_num_tokens: 100
84
+ batch_size: 8
85
+ scaling_factor: 5
86
+ lambada_openai:
87
+ run: false
88
+ batch_size: 32
89
+ num_samples: 32
90
+ from_ema: false
91
+ add_bos: true
92
+ add_eos: true
93
+ callbacks:
94
+ checkpoint_every_n_steps:
95
+ _target_: lightning.pytorch.callbacks.ModelCheckpoint
96
+ save_top_k: -1
97
+ save_last: true
98
+ dirpath: ${checkpointing.save_dir}/checkpoints
99
+ verbose: true
100
+ auto_insert_metric_name: false
101
+ every_n_train_steps: 10000
102
+ learning_rate_monitor:
103
+ _target_: lightning.pytorch.callbacks.LearningRateMonitor
104
+ logging_interval: step
105
+ text_throughput:
106
+ _target_: callbacks.text_throughput.TextThroughputMonitor
107
+ grad_norm:
108
+ _target_: callbacks.gradient_norm.GradNormCallback
109
+ data:
110
+ train: lm1b
111
+ valid: lm1b
112
+ test: openwebtext-test
113
+ tokenizer_name_or_path: gpt2
114
+ wrap: true
115
+ streaming: false
116
+ model:
117
+ name: small
118
+ type: ddit-orig
119
+ hidden_size: 768
120
+ cond_dim: 128
121
+ length: 128
122
+ n_blocks: 12
123
+ n_heads: 12
124
+ scale_by_sigma: true
125
+ dropout: 0.1
126
+ tie_word_embeddings: false
127
+ strategy:
128
+ _target_: lightning.pytorch.strategies.DDPStrategy
129
+ find_unused_parameters: true
130
+ noise:
131
+ type: loglinear
132
+ sigma_min: 0.0001
133
+ sigma_max: 20
134
+ lr_scheduler:
135
+ _target_: transformers.get_constant_schedule_with_warmup
136
+ num_warmup_steps: 2500
137
+ parameterization:
138
+ name: multi-round-sdtt
139
+ log_loss_buckets: -1
140
+ checkpoint_path: /home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/inputs/teacher_adapted.ckpt
141
+ start_from_hf: false
142
+ distill_mode: kl-bwd
143
+ num_distill_steps: 2
144
+ min_num_sampling_steps: 8
145
+ grow_dt_every: 10000
146
+ orig_num_sampling_steps: 1024
147
+ sampling_mode: ancestral
148
+ loss_precision: null
149
+ reset_optimizer_on_growth: false
150
+ use_ema_on_growth: false
151
+ sampling:
152
+ uncond:
153
+ run: true
154
+ num_samples: 1024
155
+ batch_size: 16
156
+ from_ema: false
157
+ num_steps: 16
158
+ seq_len: 1024
159
+ sampler: ancestral
160
+ cache_preds: false
161
+ add_bos: false
162
+ add_eos: false
163
+ cond_prefix:
164
+ run: true
165
+ num_samples: 256
166
+ batch_size: 16
167
+ from_ema: false
168
+ dataset: webtext
169
+ seq_len: 100
170
+ prefix_len: 50
171
+ num_cont_per_prefix: 5
172
+ min_seq_len: 1024
173
+ num_steps: 128
174
+ sampler: ancestral
175
+ cache_preds: false
176
+ add_bos: false
177
+ add_eos: false
178
+ calc_sbleu: true
179
+ seed: 42
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/inputs/teacher_adapted.provenance.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "hidden_size": 768,
3
+ "output_path": "/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/mdlm_di4c/lm1b/inputs/teacher_adapted.ckpt",
4
+ "output_sha256": "4e97e6db6a0fbe5ab0f7a86d1e6990664303755ca6eb60a0c7976ee88e78a3ec",
5
+ "schema_version": 1,
6
+ "source_mask_index": 103,
7
+ "source_path": "/home/ruizzhao/diffusion_baseline/checkpoints/reference_reproduction/flm_baselines/lm1b/lm1b_MDLM_.ckpt",
8
+ "source_sha256": "d42739e5a99bbd7c0f604dff7fe4c9ab12348b475e30f1d807e70ef32249e514",
9
+ "source_vocab_size": 30522,
10
+ "state_keys_sha256": "8212d507b6931a59375f8127f0ccb9e51c24da74fe05e974648d92c5612fb803",
11
+ "target_mask_index": 30522,
12
+ "target_vocab_size": 30523,
13
+ "teacher_family": "masked_mdlm",
14
+ "transformation": "masked_to_absorbing",
15
+ "transformation_sha256": "0d4b7caaa7c4c2de75b488026be396440bb4ea6c4dd11dd3edfbfb83a3364711"
16
+ }
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/logs_di4c_train.txt ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 2026-08-20 19:11:57.885 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Starting training
2
+ 2026-08-20 19:11:57.885 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Training starting from scratch (no checkpoint to reload)
3
+ 2026-08-20 19:12:00.016 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Skipping HF student tensors with incompatible shapes: [('backbone.output_layer.linear.bias', (50258,), (30523,)), ('backbone.output_layer.linear.weight', (50258, 768), (30523, 768)), ('backbone.vocab_embed.embedding', (50258, 768), (30523, 768))]
4
+ 2026-08-20 19:12:06.762 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
5
+ 2026-08-20 19:12:06.764 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_train_bs128_wrapped.dat
6
+ 2026-08-20 19:12:06.815 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
7
+ 2026-08-20 19:12:06.815 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using LM1B test set as validation set
8
+ 2026-08-20 19:12:06.815 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_test_bs128_wrapped.dat
9
+ 2026-08-20 19:12:06.818 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Printing train batch.
10
+ 2026-08-20 19:12:06.819 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Batch input_ids.shape: torch.Size([1, 128])
11
+ 2026-08-20 19:12:06.819 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - First 64 tokens: [CLS] while athletes in different professions dealt with doping scandals and other controversies, woods continued to do what he did best : dominate the field of professional golf and rake in endorsements. [SEP] the minutes could shed light on an internal debate, which has been evident in fed officials'recent speeches, over when to consider raising rates.
12
+ 2026-08-20 19:12:06.820 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 101, 2096, 7576, 1999, 2367, 22797, 9411, 2007, 23799, 29609,
13
+ 1998, 2060, 25962, 1010, 5249, 2506, 2000, 2079, 2054, 2002,
14
+ 2106, 2190, 1024, 16083, 1996, 2492, 1997, 2658, 5439, 1998,
15
+ 26008, 1999, 20380, 2015, 1012, 102, 1996, 2781, 2071, 8328,
16
+ 2422, 2006, 2019, 4722, 5981, 1010, 2029, 2038, 2042, 10358,
17
+ 1999, 7349, 4584, 1005, 3522, 13867, 1010, 2058, 2043, 2000,
18
+ 5136, 6274, 6165, 1012])
19
+ 2026-08-20 19:12:06.820 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Last 64 tokens: [SEP] but metro's definition of " urbanite " is not accurate, says matthew gandy, director of the urban laboratory at university college london. [SEP] goodrich petroleum is an independent oil and gas exploration and production company listed on the new york stock exchange. [SEP] the support from spears is to end on november 15 [SEP]
20
+ 2026-08-20 19:12:06.820 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 102, 2021, 6005, 1005, 1055, 6210, 1997, 1000, 3923, 4221,
21
+ 1000, 2003, 2025, 8321, 1010, 2758, 5487, 25957, 5149, 1010,
22
+ 2472, 1997, 1996, 3923, 5911, 2012, 2118, 2267, 2414, 1012,
23
+ 102, 2204, 13149, 11540, 2003, 2019, 2981, 3514, 1998, 3806,
24
+ 8993, 1998, 2537, 2194, 3205, 2006, 1996, 2047, 2259, 4518,
25
+ 3863, 1012, 102, 1996, 2490, 2013, 13957, 2003, 2000, 2203,
26
+ 2006, 2281, 2321, 102])
27
+ 2026-08-20 19:12:06.820 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ==================================================
28
+ 2026-08-20 19:12:06.820 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Printing valid batch.
29
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Batch input_ids.shape: torch.Size([1, 128])
30
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - First 64 tokens: [CLS] in medieval times, the townspeople from norcia were so practised at butchering pigs that they gained an in - depth knowledge of anatomy and were allowed to practise as surgeons along with members of the clergy. [SEP] the satellite weighs some 660 pounds, the israeli haaretz newspaper reported, citing unnamed company officials.
31
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 101, 1999, 5781, 2335, 1010, 1996, 27938, 2013, 4496, 7405,
32
+ 2020, 2061, 20439, 2012, 14998, 2075, 14695, 2008, 2027, 4227,
33
+ 2019, 1999, 1011, 5995, 3716, 1997, 13336, 1998, 2020, 3039,
34
+ 2000, 10975, 18908, 5562, 2004, 16804, 2247, 2007, 2372, 1997,
35
+ 1996, 11646, 1012, 102, 1996, 5871, 21094, 2070, 20982, 7038,
36
+ 1010, 1996, 5611, 5292, 12069, 5753, 3780, 2988, 1010, 8951,
37
+ 13294, 2194, 4584, 1012])
38
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Last 64 tokens: [SEP] the situation has been further complicated by growing indications that the us treasury is preparing to make funds available for recapitalsing us banks. [SEP] as north korea's close neighbor, traditional ally and main provider of economic aid, china is widely believed to hold the key to solving the north korea conundrum. [SEP]
39
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ids: tensor([ 102, 1996, 3663, 2038, 2042, 2582, 8552, 2011, 3652, 24936,
40
+ 2008, 1996, 2149, 9837, 2003, 8225, 2000, 2191, 5029, 2800,
41
+ 2005, 28667, 9331, 18400, 7741, 2149, 5085, 1012, 102, 2004,
42
+ 2167, 4420, 1005, 1055, 2485, 11429, 1010, 3151, 9698, 1998,
43
+ 2364, 10802, 1997, 3171, 4681, 1010, 2859, 2003, 4235, 3373,
44
+ 2000, 2907, 1996, 3145, 2000, 13729, 1996, 2167, 4420, 9530,
45
+ 8630, 6824, 1012, 102])
46
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - ==================================================
47
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Train set length: 7102854
48
+ 2026-08-20 19:12:06.821 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Valid set length: 71979
49
+ 2026-08-20 19:12:06.839 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
50
+ 2026-08-20 19:12:06.839 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_train_bs128_wrapped.dat
51
+ 2026-08-20 19:12:06.919 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using Legacy dataloader!!!
52
+ 2026-08-20 19:12:06.920 | WARNING | lightning_utilities.core.rank_zero:wrapped_fn:42 - Using LM1B test set as validation set
53
+ 2026-08-20 19:12:06.920 | INFO | lightning_utilities.core.rank_zero:wrapped_fn:42 - Loading data from: /home/ruizzhao/diffusion_baseline/data/training_cache/di4c/lm1b/lm1b_test_bs128_wrapped.dat
checkpoints/reference_reproduction/_invalid/old_di4c_shape_skip_20260825_095622/mdlm_di4c_lm1b/stderr.log ADDED
The diff for this file is too large to render. See raw diff