marriola commited on
Commit
753547c
·
verified ·
1 Parent(s): 6b17919

Upload BD3LM

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +30 -0
  3. configuration_bd3lm.py +47 -0
  4. model.safetensors +3 -0
  5. modeling_bd3lm.py +629 -0
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "kuleshov-group/ar-noeos-owt",
3
+ "adaln": false,
4
+ "architectures": [
5
+ "BD3LM"
6
+ ],
7
+ "attn_backend": "sdpa",
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_bd3lm.BD3LMConfig",
10
+ "AutoModelForMaskedLM": "modeling_bd3lm.BD3LM"
11
+ },
12
+ "block_size": 1024,
13
+ "causal": true,
14
+ "cond_dim": 128,
15
+ "cross_attn": false,
16
+ "dropout": 0.1,
17
+ "hidden_dim": 768,
18
+ "model_length": 1024,
19
+ "model_type": "bd3lm",
20
+ "n_blocks": 12,
21
+ "n_heads": 12,
22
+ "return_dict": false,
23
+ "sampling_eps_max": 0.999,
24
+ "sampling_eps_min": 0.001,
25
+ "time_conditioning": false,
26
+ "torch_dtype": "float32",
27
+ "transformers_version": "4.49.0",
28
+ "var_min": true,
29
+ "vocab_size": 50258
30
+ }
configuration_bd3lm.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BD3LM config for Hugging Face.
2
+
3
+ """
4
+
5
+ import transformers
6
+
7
+
8
+ class BD3LMConfig(transformers.PretrainedConfig):
9
+ """Hugging Face configuration class for BD3LM."""
10
+ model_type = "bd3lm"
11
+
12
+ def __init__(
13
+ self,
14
+ block_size: int = 1,
15
+ vocab_size: int = 50258,
16
+ model_length: int = 1024,
17
+ cross_attn: bool = True,
18
+ adaln: bool = True,
19
+ attn_backend: str = 'flex',
20
+ causal: bool = False,
21
+ hidden_dim: int = 768,
22
+ cond_dim: int = 129,
23
+ n_blocks: int = 12,
24
+ n_heads: int = 12,
25
+ dropout: float = 0.1,
26
+ time_conditioning: bool = False,
27
+ var_min: bool = True,
28
+ sampling_eps_min: float = 1e-3,
29
+ sampling_eps_max: float = 0.999,
30
+ ** kwargs):
31
+ super().__init__(**kwargs)
32
+ self.block_size = block_size
33
+ self.cross_attn = cross_attn
34
+ self.adaln = adaln
35
+ self.attn_backend = attn_backend
36
+ self.causal = causal
37
+ self.vocab_size = vocab_size
38
+ self.model_length = model_length
39
+ self.hidden_dim = hidden_dim
40
+ self.cond_dim = cond_dim
41
+ self.n_blocks = n_blocks
42
+ self.n_heads = n_heads
43
+ self.dropout = dropout
44
+ self.time_conditioning = time_conditioning
45
+ self.var_min = var_min
46
+ self.sampling_eps_min = sampling_eps_min
47
+ self.sampling_eps_max = sampling_eps_max
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0896cde3b9fbe7e45a28fb75377c98212f09087cd2515f6466dbcb3f3e013689
3
+ size 648996616
modeling_bd3lm.py ADDED
@@ -0,0 +1,629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BD3LM model for Hugging Face.
2
+
3
+ """
4
+ import math
5
+ import typing
6
+
7
+ import einops
8
+ from functools import partial
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ import transformers
13
+ from transformers import modeling_outputs
14
+ try:
15
+ from torch.nn.attention.flex_attention import flex_attention, create_block_mask
16
+ FLEX_ATTN_AVAILABLE = True
17
+ except:
18
+ FLEX_ATTN_AVAILABLE = False
19
+
20
+ from .configuration_bd3lm import BD3LMConfig
21
+
22
+ # Flags required to enable jit fusion kernels
23
+ torch._C._jit_set_profiling_mode(False)
24
+ torch._C._jit_set_profiling_executor(False)
25
+ torch._C._jit_override_can_fuse_on_cpu(True)
26
+ torch._C._jit_override_can_fuse_on_gpu(True)
27
+
28
+ def block_diff_mask(b, h, q_idx, kv_idx, block_size=None, n=None):
29
+ """
30
+ Constructs the specialized block diffusion attention mask for training
31
+ composed of three masks:
32
+ - **Block Diagonal Mask (M_BD)**: Self-attention within noised blocks
33
+ - **Offset Block Causal Mask (M_OBC)**: Cross-attention for conditional context
34
+ - **Block Causal Mask (M_BC)**: Attention to update x0
35
+
36
+ Args:
37
+ b, h: Batch and head indices (ignored for mask logic).
38
+ q_idx, kv_idx: Query and Key indices.
39
+ seq_len: Total sequence length.
40
+ block_size: Defines the block structure.
41
+
42
+ Returns:
43
+ A boolean attention mask.
44
+ """
45
+
46
+ # Indicate whether token belongs to xt or x0
47
+ x0_flag_q = (q_idx >= n)
48
+ x0_flag_kv = (kv_idx >= n)
49
+
50
+ # Compute block indices
51
+ block_q = torch.where(x0_flag_q == 1,
52
+ (q_idx - n) // block_size,
53
+ q_idx // block_size)
54
+ block_kv = torch.where(x0_flag_kv == 1,
55
+ (kv_idx - n) // block_size,
56
+ kv_idx // block_size)
57
+
58
+ # **1. Block Diagonal Mask (M_BD) **
59
+ block_diagonal = (block_q == block_kv) & (x0_flag_q == x0_flag_kv)
60
+
61
+ # **2. Offset Block-Causal Mask (M_OBC) **
62
+ offset_block_causal = (
63
+ (block_q > block_kv)
64
+ & (x0_flag_kv == 1)
65
+ & (x0_flag_q == 0)
66
+ )
67
+
68
+ # **3. Block-Causal Mask (M_BC) **
69
+ block_causal = (block_q >= block_kv) & (x0_flag_kv == 1) & (x0_flag_q == 1)
70
+
71
+ # **4. Combine Masks **
72
+ return block_diagonal | offset_block_causal | block_causal
73
+
74
+ @torch.compile(fullgraph=True, mode="max-autotune-no-cudagraphs")
75
+ def fused_flex_attention(q, k, v, mask=None):
76
+ return flex_attention(q, k, v, block_mask=mask)
77
+
78
+ def bias_dropout_add_scale(
79
+ x: torch.Tensor,
80
+ bias: typing.Optional[torch.Tensor],
81
+ scale: torch.Tensor,
82
+ residual: typing.Optional[torch.Tensor],
83
+ prob: float,
84
+ training: bool) -> torch.Tensor:
85
+ if bias is not None:
86
+ out = scale * F.dropout(x + bias, p=prob, training=training)
87
+ else:
88
+ out = scale * F.dropout(x, p=prob, training=training)
89
+
90
+ if residual is not None:
91
+ out = residual + out
92
+ return out
93
+
94
+
95
+ def get_bias_dropout_add_scale(training):
96
+ def _bias_dropout_add(x, bias, scale, residual, prob):
97
+ return bias_dropout_add_scale(
98
+ x, bias, scale, residual, prob, training)
99
+
100
+ return _bias_dropout_add
101
+
102
+
103
+ # function overload
104
+ def modulate(x: torch.Tensor,
105
+ shift: torch.Tensor,
106
+ scale: torch.Tensor) -> torch.Tensor:
107
+ return x * (1 + scale) + shift
108
+
109
+ @torch.jit.script
110
+ def bias_dropout_add_scale_fused_train(
111
+ x: torch.Tensor,
112
+ bias: typing.Optional[torch.Tensor],
113
+ scale: torch.Tensor,
114
+ residual: typing.Optional[torch.Tensor],
115
+ prob: float) -> torch.Tensor:
116
+ return bias_dropout_add_scale(
117
+ x, bias, scale, residual, prob, True)
118
+
119
+ @torch.jit.script
120
+ def bias_dropout_add_scale_fused_inference(
121
+ x: torch.Tensor,
122
+ bias: typing.Optional[torch.Tensor],
123
+ scale: torch.Tensor,
124
+ residual: typing.Optional[torch.Tensor],
125
+ prob: float) -> torch.Tensor:
126
+ return bias_dropout_add_scale(
127
+ x, bias, scale, residual, prob, False)
128
+
129
+ @torch.jit.script
130
+ def modulate_fused(x: torch.Tensor,
131
+ shift: torch.Tensor,
132
+ scale: torch.Tensor) -> torch.Tensor:
133
+ return modulate(x, shift, scale)
134
+
135
+
136
+ class Rotary(torch.nn.Module):
137
+ def __init__(self, dim, base=10_000):
138
+ super().__init__()
139
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
140
+ self.register_buffer('inv_freq', inv_freq)
141
+ self.seq_len_cached = None
142
+ self.cos_cached = None
143
+ self.sin_cached = None
144
+
145
+ def forward(self, x, seq_dim=1):
146
+ seq_len = x.shape[seq_dim]
147
+ if seq_len != self.seq_len_cached:
148
+ self.seq_len_cached = seq_len
149
+ t = torch.arange(x.shape[seq_dim], device=x.device).type_as(self.inv_freq)
150
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq.clone())
151
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
152
+ # dims are: batch, seq_len, qkv, head, dim
153
+ self.cos_cached = emb.cos()[None, :, None, None, :].repeat(1,1,3,1,1)
154
+ self.sin_cached = emb.sin()[None, :, None, None, :].repeat(1,1,3,1,1)
155
+ # This makes the transformation on v an identity.
156
+ self.cos_cached[:,:,2,:,:].fill_(1.)
157
+ self.sin_cached[:,:,2,:,:].fill_(0.)
158
+
159
+ return self.cos_cached, self.sin_cached
160
+
161
+
162
+ def rotate_half(x):
163
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2 :]
164
+ return torch.cat((-x2, x1), dim=-1)
165
+
166
+
167
+ def apply_rotary_pos_emb_torchscript(qkv, cos, sin):
168
+ return (qkv * cos) + (rotate_half(qkv) * sin)
169
+
170
+ # function overload
171
+ def modulate(x, shift, scale):
172
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
173
+
174
+
175
+ #################################################################################
176
+ # Layers #
177
+ #################################################################################
178
+ class LayerNorm(nn.Module):
179
+ def __init__(self, dim):
180
+ super().__init__()
181
+ self.weight = nn.Parameter(torch.ones([dim]))
182
+ self.dim = dim
183
+ def forward(self, x):
184
+ with torch.cuda.amp.autocast(enabled=False):
185
+ x = F.layer_norm(x.float(), [self.dim])
186
+ return x * self.weight[None,None,:]
187
+
188
+
189
+ def residual_linear(x, W, x_skip, residual_scale):
190
+ """x_skip + residual_scale * W @ x"""
191
+ dim_out, dim_in = W.shape[0], W.shape[1]
192
+ return torch.addmm(
193
+ x_skip.view(-1, dim_out),
194
+ x.view(-1, dim_in),
195
+ W.T,
196
+ alpha=residual_scale).view(*x.shape[:-1], dim_out)
197
+
198
+
199
+ #################################################################################
200
+ # Embedding Layers for Timesteps and Class Labels #
201
+ #################################################################################
202
+ class TimestepEmbedder(nn.Module):
203
+ """
204
+ Embeds scalar timesteps into vector representations.
205
+ """
206
+ def __init__(self, hidden_size, frequency_embedding_size=256):
207
+ super().__init__()
208
+ self.mlp = nn.Sequential(
209
+ nn.Linear(frequency_embedding_size, hidden_size, bias=True),
210
+ nn.SiLU(),
211
+ nn.Linear(hidden_size, hidden_size, bias=True))
212
+ self.frequency_embedding_size = frequency_embedding_size
213
+
214
+ @staticmethod
215
+ def timestep_embedding(t, dim, max_period=10000):
216
+ """
217
+ Create sinusoidal timestep embeddings.
218
+ :param t: a 1-D Tensor of N indices, one per batch element.
219
+ These may be fractional.
220
+ :param dim: the dimension of the output.
221
+ :param max_period: controls the minimum frequency of the embeddings.
222
+ :return: an (N, D) Tensor of positional embeddings.
223
+ """
224
+ # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
225
+ half = dim // 2
226
+ freqs = torch.exp(
227
+ - math.log(max_period)
228
+ * torch.arange(start=0, end=half, dtype=torch.float32)
229
+ / half).to(device=t.device)
230
+ args = t[:, None].float() * freqs[None]
231
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
232
+ if dim % 2:
233
+ embedding = torch.cat(
234
+ [embedding,
235
+ torch.zeros_like(embedding[:, :1])], dim=-1)
236
+ return embedding
237
+
238
+ def forward(self, t):
239
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
240
+ t_emb = self.mlp(t_freq)
241
+ return t_emb
242
+
243
+
244
+ class LabelEmbedder(nn.Module):
245
+ """Embeds class labels into vector representations.
246
+
247
+ Also handles label dropout for classifier-free guidance.
248
+ """
249
+ def __init__(self, num_classes, cond_size):
250
+ super().__init__()
251
+ self.embedding_table = nn.Embedding(num_classes + 1, cond_size)
252
+ self.num_classes = num_classes
253
+
254
+ # TODO think of initializing with 0.02 std deviation like in original DiT paper
255
+
256
+ def forward(self, labels):
257
+ embeddings = self.embedding_table(labels)
258
+ return embeddings
259
+
260
+
261
+ #################################################################################
262
+ # Core Model #
263
+ #################################################################################
264
+
265
+ def regular_attention_multi_headed(qkv):
266
+ # Assuming qkv is a tensor with shape [batch, seq_len, 3, num_heads, head_dim]
267
+ # where the 3 represents Q, K, V packed in that order
268
+ batch_size, seq_len, _, num_heads, head_dim = qkv.shape
269
+ # Separate Q, K, V from the packed qkv tensor
270
+ # [batch_size, seq_len, num_heads, head_dim]
271
+ q = qkv[:, :, 0, :, :]
272
+ k = qkv[:, :, 1, :, :]
273
+ v = qkv[:, :, 2, :, :]
274
+
275
+ # Transpose and reshape Q and K for batched matrix multiplication:
276
+ # [batch_size, num_heads, seq_len, head_dim]
277
+ q = q.transpose(1, 2)
278
+ k = k.transpose(1, 2)
279
+ v = v.transpose(1, 2)
280
+
281
+ # Compute scaled dot-product attention
282
+ # [batch_size, num_heads, seq_len, seq_len]
283
+ attention_scores = torch.matmul(
284
+ q, k.transpose(-2, -1)) / math.sqrt(head_dim)
285
+
286
+ # Apply softmax to calculate the attention weights
287
+ attention_probs = F.softmax(attention_scores, dim=-1)
288
+
289
+ # [batch_size, num_heads, seq_len, head_dim]
290
+ attention_output = torch.matmul(attention_probs, v)
291
+
292
+ # [batch_size, seq_len, num_heads, head_dim]
293
+ attention_output = attention_output.transpose(1, 2)
294
+ return einops.rearrange(attention_output,
295
+ 'b s h d -> b s (h d)')
296
+
297
+
298
+ class DDiTBlock(nn.Module):
299
+ def __init__(self, n, block_size, dim, n_heads, cond_dim, causal=False,
300
+ mlp_ratio=4, dropout=0.1, adaln=True, attn_backend='sdpa'):
301
+ super().__init__()
302
+ self.n = n
303
+ self.block_size = block_size
304
+ self.n_heads = n_heads
305
+ self.attn_backend = attn_backend
306
+ self.kv_cache = None
307
+ self.causal = causal
308
+
309
+ self.norm1 = LayerNorm(dim)
310
+ self.attn_qkv = nn.Linear(dim, 3 * dim, bias=False)
311
+ self.attn_out = nn.Linear(dim, dim, bias=False)
312
+ self.dropout1 = nn.Dropout(dropout)
313
+
314
+ self.norm2 = LayerNorm(dim)
315
+ self.mlp = nn.Sequential(
316
+ nn.Linear(dim, mlp_ratio * dim, bias=True),
317
+ nn.GELU(approximate='tanh'),
318
+ nn.Linear(mlp_ratio * dim, dim, bias=True))
319
+ self.dropout2 = nn.Dropout(dropout)
320
+ self.dropout = dropout
321
+ self.adaln = adaln
322
+ if self.adaln:
323
+ self.adaLN_modulation = nn.Linear(cond_dim, 6 * dim, bias=True)
324
+ self.adaLN_modulation.weight.data.zero_()
325
+ self.adaLN_modulation.bias.data.zero_()
326
+
327
+ def _get_bias_dropout_scale(self):
328
+ if self.training:
329
+ return bias_dropout_add_scale_fused_train
330
+ else:
331
+ return bias_dropout_add_scale_fused_inference
332
+
333
+ def get_qkv(self, x, rotary_cos_sin, store_kv=False):
334
+ # compute qkv (potentially use cache)
335
+ if self.kv_cache is not None:
336
+ new_qkv = self.attn_qkv(x[:, -self.block_size:])
337
+ qkv = torch.cat((self.kv_cache, new_qkv), dim=1)
338
+ else:
339
+ qkv = self.attn_qkv(x)
340
+ # store kv cache in a sliding window (can't exceed context len)
341
+ if store_kv:
342
+ self.kv_cache = qkv[:, -(self.n-self.block_size):]
343
+
344
+ qkv = einops.rearrange(
345
+ qkv,
346
+ 'b s (three h d) -> b s three h d',
347
+ three=3,
348
+ h=self.n_heads)
349
+ with torch.cuda.amp.autocast(enabled=False):
350
+ cos, sin = rotary_cos_sin
351
+ qkv = apply_rotary_pos_emb_torchscript(
352
+ qkv, cos.to(qkv.dtype), sin.to(qkv.dtype))
353
+ return qkv
354
+
355
+ def cross_attn(self, x, qkv, mask=None):
356
+ scale = qkv.shape[-1]
357
+ qkv = qkv.transpose(1, 3)
358
+ mask = mask.bool() if mask is not None else None
359
+ x = F.scaled_dot_product_attention(
360
+ query=qkv[:, :, 0],
361
+ key=qkv[:, :, 1],
362
+ value=qkv[:, :, 2],
363
+ attn_mask=mask,
364
+ is_causal=self.causal,
365
+ scale=1 / math.sqrt(scale))
366
+ x = x.transpose(1, 2)
367
+ x = einops.rearrange(x, 'b s h d -> b s (h d)')
368
+ return x
369
+
370
+ def cross_attn_flex(self, qkv, mask=None):
371
+ qkv = einops.rearrange(qkv, 'b s three h d -> b h three s d', h=self.n_heads)
372
+ x = fused_flex_attention(
373
+ qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], mask=mask)
374
+ x = einops.rearrange(x, 'b h s d -> b s (h d)')
375
+ return x
376
+
377
+ def forward(self, x, rotary_cos_sin, c, mask=None,
378
+ sample_mode=False, store_kv=False):
379
+ bias_dropout_scale_fn = self._get_bias_dropout_scale()
380
+
381
+ if self.adaln:
382
+ (shift_msa, scale_msa, gate_msa, shift_mlp,
383
+ scale_mlp, gate_mlp) = self.adaLN_modulation(c)[:, None].chunk(6, dim=2)
384
+
385
+ # attention operation
386
+ x_skip = x
387
+ if self.adaln:
388
+ x = modulate_fused(self.norm1(x), shift_msa, scale_msa)
389
+ else:
390
+ x = self.norm1(x)
391
+
392
+ # get qkvs
393
+ if mask is not None and not sample_mode:
394
+ n = mask.shape[-1] // 2
395
+ qkv_x = self.get_qkv(x[:,:n], rotary_cos_sin)
396
+ qkv_x0 = self.get_qkv(x[:,n:], rotary_cos_sin)
397
+ qkv = torch.cat((qkv_x, qkv_x0), dim=1)
398
+ else:
399
+ qkv = self.get_qkv(x, rotary_cos_sin, store_kv=store_kv)
400
+
401
+ if self.attn_backend == 'flex' and FLEX_ATTN_AVAILABLE:
402
+ x = self.cross_attn_flex(qkv, mask=mask)
403
+ elif self.attn_backend == 'sdpa' or not FLEX_ATTN_AVAILABLE:
404
+ x = self.cross_attn(x, qkv, mask=mask)
405
+ else:
406
+ raise ValueError('Unknown attention backend')
407
+
408
+ x = bias_dropout_scale_fn(self.attn_out(x),
409
+ None,
410
+ gate_msa,
411
+ x_skip,
412
+ self.dropout)
413
+
414
+ # mlp operation
415
+ if self.adaln:
416
+ x = bias_dropout_scale_fn(
417
+ self.mlp(modulate_fused(
418
+ self.norm2(x), shift_mlp, scale_mlp)),
419
+ None, gate_mlp, x, self.dropout)
420
+ else:
421
+ x = bias_dropout_scale_fn(
422
+ self.mlp(self.norm2(x)),
423
+ None, 1., x, self.dropout)
424
+ return x
425
+
426
+
427
+ class EmbeddingLayer(nn.Module):
428
+ def __init__(self, dim, vocab_dim):
429
+ super().__init__()
430
+ self.embedding = nn.Parameter(torch.empty((vocab_dim, dim)))
431
+ torch.nn.init.kaiming_uniform_(self.embedding, a=math.sqrt(5))
432
+
433
+ def forward(self, x):
434
+ return self.embedding[x]
435
+
436
+
437
+ class DDitFinalLayer(nn.Module):
438
+ def __init__(self, hidden_size, out_channels, cond_dim, adaln=True):
439
+ super().__init__()
440
+ self.norm_final = LayerNorm(hidden_size)
441
+ self.linear = nn.Linear(hidden_size, out_channels)
442
+ self.linear.weight.data.zero_()
443
+ self.linear.bias.data.zero_()
444
+
445
+ self.adaln = adaln
446
+ if self.adaln:
447
+ self.adaLN_modulation = nn.Linear(cond_dim,
448
+ 2 * hidden_size,
449
+ bias=True)
450
+ self.adaLN_modulation.weight.data.zero_()
451
+ self.adaLN_modulation.bias.data.zero_()
452
+
453
+
454
+ def forward(self, x, c):
455
+ if self.adaln:
456
+ shift, scale = self.adaLN_modulation(c)[:, None].chunk(2, dim=2)
457
+ x = modulate_fused(self.norm_final(x), shift, scale)
458
+ else:
459
+ x = self.norm_final(x)
460
+ x = self.linear(x)
461
+ return x
462
+
463
+
464
+ class DITBackbone(nn.Module):
465
+ def __init__(
466
+ self,
467
+ config: BD3LMConfig):
468
+ super().__init__()
469
+
470
+ self.config = config
471
+ self.cross_attn = config.cross_attn
472
+ self.block_size = config.block_size
473
+ self.vocab_size = config.vocab_size
474
+ self.n = config.model_length
475
+
476
+ self.vocab_embed = EmbeddingLayer(
477
+ config.hidden_dim,
478
+ config.vocab_size)
479
+ self.adaln = config.adaln
480
+ if self.adaln:
481
+ self.sigma_map = TimestepEmbedder(
482
+ config.cond_dim)
483
+ self.rotary_emb = Rotary(
484
+ config.hidden_dim // config.n_heads)
485
+
486
+ blocks = []
487
+ for _ in range(config.n_blocks):
488
+ blocks.append(DDiTBlock(self.n,
489
+ self.block_size,
490
+ config.hidden_dim,
491
+ config.n_heads,
492
+ config.cond_dim,
493
+ causal=config.causal,
494
+ dropout=config.dropout,
495
+ adaln=config.adaln,
496
+ attn_backend=config.attn_backend,))
497
+ self.blocks = nn.ModuleList(blocks)
498
+
499
+ self.output_layer = DDitFinalLayer(
500
+ config.hidden_dim,
501
+ config.vocab_size,
502
+ config.cond_dim,
503
+ adaln=config.adaln)
504
+ if self.cross_attn:
505
+ self.gen_mask(config.model_length, self.block_size, attn_backend=config.attn_backend)
506
+ self.precision = torch.float32
507
+
508
+ def _get_bias_dropout_scale(self):
509
+ if self.training:
510
+ return bias_dropout_add_scale_fused_train
511
+ else:
512
+ return bias_dropout_add_scale_fused_inference
513
+
514
+ def gen_mask(self, seqlen, block_size, attn_backend='sdpa'):
515
+ """Genererates attention mask"""
516
+ if attn_backend == 'flex' and FLEX_ATTN_AVAILABLE:
517
+ self.mask = create_block_mask(
518
+ partial(block_diff_mask, block_size=block_size, n=seqlen),
519
+ B=None, H=None, Q_LEN=seqlen*2, KV_LEN=seqlen*2)
520
+ elif attn_backend == 'sdpa' or not FLEX_ATTN_AVAILABLE:
521
+ self.mask = block_diff_mask(
522
+ b=None, h=None, q_idx=torch.arange(seqlen*2)[:, None],
523
+ kv_idx=torch.arange(seqlen*2)[None, :], block_size=block_size, n=seqlen)
524
+ else:
525
+ raise ValueError('Unknown attention backend')
526
+
527
+ def forward(self, indices, sigma, sample_mode=False,
528
+ store_kv=False, output_hidden_states=False):
529
+ if not self.config.time_conditioning:
530
+ sigma = torch.zeros_like(sigma)
531
+ all_hidden_states = []
532
+ x = self.vocab_embed(indices)
533
+ if output_hidden_states:
534
+ all_hidden_states.append(x)
535
+ c = None
536
+ if self.adaln:
537
+ c = F.silu(self.sigma_map(sigma))
538
+ if self.cross_attn:
539
+ n = self.mask.shape[-1] // 2
540
+ rotary_cos_sin = self.rotary_emb(x[:, :n])
541
+ mask = self.mask.to(x.device)
542
+ # use block-causal mask only during sampling
543
+ if sample_mode:
544
+ mask = mask[
545
+ n:n+x.shape[1], n:n+x.shape[1]]
546
+ else:
547
+ mask = None
548
+ rotary_cos_sin = self.rotary_emb(x)
549
+
550
+ with torch.cuda.amp.autocast(dtype=self.precision):
551
+ for i in range(len(self.blocks)):
552
+ x = self.blocks[i](x,
553
+ rotary_cos_sin,
554
+ c,
555
+ mask=mask,
556
+ sample_mode=sample_mode,
557
+ store_kv=store_kv)
558
+ if output_hidden_states:
559
+ all_hidden_states.append(x)
560
+ logits = self.output_layer(x, c)
561
+ if self.cross_attn and not sample_mode:
562
+ logits = logits[:, :n]
563
+ all_hidden_states = [hidden_states[:, :n] for hidden_states in all_hidden_states]
564
+ return logits, all_hidden_states
565
+
566
+ class BD3LM(transformers.PreTrainedModel):
567
+ """HF-compatible model."""
568
+ config_class = BD3LMConfig
569
+ base_model_prefix = "bd3lm"
570
+
571
+ def __init__(
572
+ self,
573
+ config: BD3LMConfig):
574
+ super().__init__(config)
575
+ self.config = config
576
+ self.backbone = DITBackbone(config)
577
+ if config.var_min:
578
+ self.register_buffer(
579
+ 'sampling_eps_min',
580
+ torch.tensor(config.sampling_eps_min))
581
+ self.register_buffer(
582
+ 'sampling_eps_max',
583
+ torch.tensor(config.sampling_eps_max))
584
+
585
+ def reset_kv_cache(self):
586
+ for block in self.backbone.blocks:
587
+ block.kv_cache = None
588
+
589
+ def forward(
590
+ self,
591
+ input_ids: torch.LongTensor = None,
592
+ timesteps: torch.FloatTensor = None,
593
+ sample_mode: typing.Optional[bool] = None,
594
+ store_kv: typing.Optional[bool] = None,
595
+ output_hidden_states: typing.Optional[bool] = None,
596
+ return_dict: typing.Optional[bool] = None,
597
+ ) -> typing.Union[
598
+ torch.Tensor, typing.Tuple,
599
+ modeling_outputs.MaskedLMOutput]:
600
+ """HF-compatible forward method."""
601
+ if sample_mode:
602
+ assert self.config.attn_backend == 'sdpa', 'Sampling only supported with SDPA'
603
+
604
+ output_hidden_states = (
605
+ output_hidden_states
606
+ if output_hidden_states is not None
607
+ else self.config.output_hidden_states
608
+ )
609
+ return_dict = return_dict \
610
+ if return_dict is not None \
611
+ else self.config.use_return_dict
612
+
613
+ logits, all_hidden_states = self.backbone(
614
+ indices=input_ids,
615
+ sigma=timesteps,
616
+ sample_mode=sample_mode,
617
+ store_kv=store_kv,
618
+ output_hidden_states=output_hidden_states,
619
+ )
620
+ if return_dict:
621
+ return modeling_outputs.MaskedLMOutput(
622
+ logits=logits,
623
+ hidden_states=all_hidden_states if output_hidden_states else None,
624
+ loss=None
625
+ )
626
+ elif output_hidden_states:
627
+ return logits, all_hidden_states
628
+ else:
629
+ return logits