lhallee commited on
Commit
61d2004
·
verified ·
1 Parent(s): fc48fbc

Upload vb_modules_transformersv2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. vb_modules_transformersv2.py +263 -263
vb_modules_transformersv2.py CHANGED
@@ -1,263 +1,263 @@
1
- # started from code from https://github.com/lucidrains/alphafold3-pytorch, MIT License, Copyright (c) 2024 Phil Wang
2
-
3
- import torch
4
- from torch import nn, sigmoid
5
- from torch.nn import (
6
- LayerNorm,
7
- Linear,
8
- Module,
9
- ModuleList,
10
- Sequential,
11
- )
12
-
13
- from .vb_layers_attentionv2 import AttentionPairBias
14
- from .vb_modules_utils import LinearNoBias, SwiGLU, default
15
-
16
-
17
- class AdaLN(Module):
18
- """Algorithm 26"""
19
-
20
- def __init__(self, dim, dim_single_cond):
21
- super().__init__()
22
- self.a_norm = LayerNorm(dim, elementwise_affine=False, bias=False)
23
- self.s_norm = LayerNorm(dim_single_cond, bias=False)
24
- self.s_scale = Linear(dim_single_cond, dim)
25
- self.s_bias = LinearNoBias(dim_single_cond, dim)
26
-
27
- def forward(self, a, s):
28
- a = self.a_norm(a)
29
- s = self.s_norm(s)
30
- a = sigmoid(self.s_scale(s)) * a + self.s_bias(s)
31
- return a
32
-
33
-
34
- class ConditionedTransitionBlock(Module):
35
- """Algorithm 25"""
36
-
37
- def __init__(self, dim_single, dim_single_cond, expansion_factor=2):
38
- super().__init__()
39
-
40
- self.adaln = AdaLN(dim_single, dim_single_cond)
41
-
42
- dim_inner = int(dim_single * expansion_factor)
43
- self.swish_gate = Sequential(
44
- LinearNoBias(dim_single, dim_inner * 2),
45
- SwiGLU(),
46
- )
47
- self.a_to_b = LinearNoBias(dim_single, dim_inner)
48
- self.b_to_a = LinearNoBias(dim_inner, dim_single)
49
-
50
- output_projection_linear = Linear(dim_single_cond, dim_single)
51
- nn.init.zeros_(output_projection_linear.weight)
52
- nn.init.constant_(output_projection_linear.bias, -2.0)
53
-
54
- self.output_projection = nn.Sequential(output_projection_linear, nn.Sigmoid())
55
-
56
- def forward(
57
- self,
58
- a, # Float['... d']
59
- s,
60
- ): # -> Float['... d']:
61
- a = self.adaln(a, s)
62
- b = self.swish_gate(a) * self.a_to_b(a)
63
- a = self.output_projection(s) * self.b_to_a(b)
64
-
65
- return a
66
-
67
-
68
- class DiffusionTransformer(Module):
69
- """Algorithm 23"""
70
-
71
- def __init__(
72
- self,
73
- depth,
74
- heads,
75
- dim=384,
76
- dim_single_cond=None,
77
- pair_bias_attn=True,
78
- activation_checkpointing=False,
79
- post_layer_norm=False,
80
- ):
81
- super().__init__()
82
- self.activation_checkpointing = activation_checkpointing
83
- dim_single_cond = default(dim_single_cond, dim)
84
- self.pair_bias_attn = pair_bias_attn
85
-
86
- self.layers = ModuleList()
87
- for _ in range(depth):
88
- self.layers.append(
89
- DiffusionTransformerLayer(
90
- heads,
91
- dim,
92
- dim_single_cond,
93
- post_layer_norm,
94
- )
95
- )
96
-
97
- def forward(
98
- self,
99
- a, # Float['bm n d'],
100
- s, # Float['bm n ds'],
101
- bias=None, # Float['b n n dp']
102
- mask=None, # Bool['b n'] | None = None
103
- to_keys=None,
104
- multiplicity=1,
105
- ):
106
- if self.pair_bias_attn:
107
- B, N, M, D = bias.shape
108
- L = len(self.layers)
109
- bias = bias.view(B, N, M, L, D // L)
110
-
111
- for i, layer in enumerate(self.layers):
112
- if self.pair_bias_attn:
113
- bias_l = bias[:, :, :, i]
114
- else:
115
- bias_l = None
116
-
117
- if self.activation_checkpointing:
118
- a = torch.utils.checkpoint.checkpoint(
119
- layer,
120
- a,
121
- s,
122
- bias_l,
123
- mask,
124
- to_keys,
125
- multiplicity,
126
- use_reentrant=False,
127
- )
128
-
129
- else:
130
- a = layer(
131
- a, # Float['bm n d'],
132
- s, # Float['bm n ds'],
133
- bias_l, # Float['b n n dp']
134
- mask, # Bool['b n'] | None = None
135
- to_keys,
136
- multiplicity,
137
- )
138
- return a
139
-
140
-
141
- class DiffusionTransformerLayer(Module):
142
- """Algorithm 23"""
143
-
144
- def __init__(
145
- self,
146
- heads,
147
- dim=384,
148
- dim_single_cond=None,
149
- post_layer_norm=False,
150
- ):
151
- super().__init__()
152
-
153
- dim_single_cond = default(dim_single_cond, dim)
154
-
155
- self.adaln = AdaLN(dim, dim_single_cond)
156
- self.pair_bias_attn = AttentionPairBias(
157
- c_s=dim, num_heads=heads, compute_pair_bias=False
158
- )
159
-
160
- self.output_projection_linear = Linear(dim_single_cond, dim)
161
- nn.init.zeros_(self.output_projection_linear.weight)
162
- nn.init.constant_(self.output_projection_linear.bias, -2.0)
163
-
164
- self.output_projection = nn.Sequential(
165
- self.output_projection_linear, nn.Sigmoid()
166
- )
167
- self.transition = ConditionedTransitionBlock(
168
- dim_single=dim, dim_single_cond=dim_single_cond
169
- )
170
-
171
- if post_layer_norm:
172
- self.post_lnorm = nn.LayerNorm(dim)
173
- else:
174
- self.post_lnorm = nn.Identity()
175
-
176
- def forward(
177
- self,
178
- a, # Float['bm n d'],
179
- s, # Float['bm n ds'],
180
- bias=None, # Float['b n n dp']
181
- mask=None, # Bool['b n'] | None = None
182
- to_keys=None,
183
- multiplicity=1,
184
- ):
185
- b = self.adaln(a, s)
186
-
187
- k_in = b
188
- if to_keys is not None:
189
- k_in = to_keys(b)
190
- mask = to_keys(mask.unsqueeze(-1)).squeeze(-1)
191
-
192
- if self.pair_bias_attn:
193
- b = self.pair_bias_attn(
194
- s=b,
195
- z=bias,
196
- mask=mask,
197
- multiplicity=multiplicity,
198
- k_in=k_in,
199
- )
200
- else:
201
- b = self.no_pair_bias_attn(s=b, mask=mask, k_in=k_in)
202
-
203
- b = self.output_projection(s) * b
204
-
205
- a = a + b
206
- a = a + self.transition(a, s)
207
-
208
- a = self.post_lnorm(a)
209
- return a
210
-
211
-
212
- class AtomTransformer(Module):
213
- """Algorithm 7"""
214
-
215
- def __init__(
216
- self,
217
- attn_window_queries,
218
- attn_window_keys,
219
- **diffusion_transformer_kwargs,
220
- ):
221
- super().__init__()
222
- self.attn_window_queries = attn_window_queries
223
- self.attn_window_keys = attn_window_keys
224
- self.diffusion_transformer = DiffusionTransformer(
225
- **diffusion_transformer_kwargs
226
- )
227
-
228
- def forward(
229
- self,
230
- q, # Float['b m d'],
231
- c, # Float['b m ds'],
232
- bias, # Float['b m m dp']
233
- to_keys,
234
- mask, # Bool['b m'] | None = None
235
- multiplicity=1,
236
- ):
237
- W = self.attn_window_queries
238
- H = self.attn_window_keys
239
-
240
- B, N, D = q.shape
241
- NW = N // W
242
-
243
- # reshape tokens
244
- q = q.view((B * NW, W, -1))
245
- c = c.view((B * NW, W, -1))
246
- mask = mask.view(B * NW, W)
247
- bias = bias.repeat_interleave(multiplicity, 0)
248
- bias = bias.view((bias.shape[0] * NW, W, H, -1))
249
-
250
- to_keys_new = lambda x: to_keys(x.view(B, NW * W, -1)).view(B * NW, H, -1)
251
-
252
- # main transformer
253
- q = self.diffusion_transformer(
254
- a=q,
255
- s=c,
256
- bias=bias,
257
- mask=mask.float(),
258
- multiplicity=1, # bias term already expanded with multiplicity
259
- to_keys=to_keys_new,
260
- )
261
-
262
- q = q.view((B, NW * W, D))
263
- return q
 
1
+ # started from code from https://github.com/lucidrains/alphafold3-pytorch, MIT License, Copyright (c) 2024 Phil Wang
2
+
3
+ import torch
4
+ from torch import nn, sigmoid
5
+ from torch.nn import (
6
+ LayerNorm,
7
+ Linear,
8
+ Module,
9
+ ModuleList,
10
+ Sequential,
11
+ )
12
+
13
+ from .vb_layers_attentionv2 import AttentionPairBias
14
+ from .vb_modules_utils import LinearNoBias, SwiGLU, default
15
+
16
+
17
+ class AdaLN(Module):
18
+ """Algorithm 26"""
19
+
20
+ def __init__(self, dim, dim_single_cond):
21
+ super().__init__()
22
+ self.a_norm = LayerNorm(dim, elementwise_affine=False, bias=False)
23
+ self.s_norm = LayerNorm(dim_single_cond, bias=False)
24
+ self.s_scale = Linear(dim_single_cond, dim)
25
+ self.s_bias = LinearNoBias(dim_single_cond, dim)
26
+
27
+ def forward(self, a, s):
28
+ a = self.a_norm(a)
29
+ s = self.s_norm(s)
30
+ a = sigmoid(self.s_scale(s)) * a + self.s_bias(s)
31
+ return a
32
+
33
+
34
+ class ConditionedTransitionBlock(Module):
35
+ """Algorithm 25"""
36
+
37
+ def __init__(self, dim_single, dim_single_cond, expansion_factor=2):
38
+ super().__init__()
39
+
40
+ self.adaln = AdaLN(dim_single, dim_single_cond)
41
+
42
+ dim_inner = int(dim_single * expansion_factor)
43
+ self.swish_gate = Sequential(
44
+ LinearNoBias(dim_single, dim_inner * 2),
45
+ SwiGLU(),
46
+ )
47
+ self.a_to_b = LinearNoBias(dim_single, dim_inner)
48
+ self.b_to_a = LinearNoBias(dim_inner, dim_single)
49
+
50
+ output_projection_linear = Linear(dim_single_cond, dim_single)
51
+ nn.init.zeros_(output_projection_linear.weight)
52
+ nn.init.constant_(output_projection_linear.bias, -2.0)
53
+
54
+ self.output_projection = nn.Sequential(output_projection_linear, nn.Sigmoid())
55
+
56
+ def forward(
57
+ self,
58
+ a, # Float['... d']
59
+ s,
60
+ ): # -> Float['... d']:
61
+ a = self.adaln(a, s)
62
+ b = self.swish_gate(a) * self.a_to_b(a)
63
+ a = self.output_projection(s) * self.b_to_a(b)
64
+
65
+ return a
66
+
67
+
68
+ class DiffusionTransformer(Module):
69
+ """Algorithm 23"""
70
+
71
+ def __init__(
72
+ self,
73
+ depth,
74
+ heads,
75
+ dim=384,
76
+ dim_single_cond=None,
77
+ pair_bias_attn=True,
78
+ activation_checkpointing=False,
79
+ post_layer_norm=False,
80
+ ):
81
+ super().__init__()
82
+ self.activation_checkpointing = activation_checkpointing
83
+ dim_single_cond = default(dim_single_cond, dim)
84
+ self.pair_bias_attn = pair_bias_attn
85
+
86
+ self.layers = ModuleList()
87
+ for _ in range(depth):
88
+ self.layers.append(
89
+ DiffusionTransformerLayer(
90
+ heads,
91
+ dim,
92
+ dim_single_cond,
93
+ post_layer_norm,
94
+ )
95
+ )
96
+
97
+ def forward(
98
+ self,
99
+ a, # Float['bm n d'],
100
+ s, # Float['bm n ds'],
101
+ bias=None, # Float['b n n dp']
102
+ mask=None, # Bool['b n'] | None = None
103
+ to_keys=None,
104
+ multiplicity=1,
105
+ ):
106
+ if self.pair_bias_attn:
107
+ B, N, M, D = bias.shape
108
+ L = len(self.layers)
109
+ bias = bias.view(B, N, M, L, D // L)
110
+
111
+ for i, layer in enumerate(self.layers):
112
+ if self.pair_bias_attn:
113
+ bias_l = bias[:, :, :, i]
114
+ else:
115
+ bias_l = None
116
+
117
+ if self.activation_checkpointing:
118
+ a = torch.utils.checkpoint.checkpoint(
119
+ layer,
120
+ a,
121
+ s,
122
+ bias_l,
123
+ mask,
124
+ to_keys,
125
+ multiplicity,
126
+ use_reentrant=False,
127
+ )
128
+
129
+ else:
130
+ a = layer(
131
+ a, # Float['bm n d'],
132
+ s, # Float['bm n ds'],
133
+ bias_l, # Float['b n n dp']
134
+ mask, # Bool['b n'] | None = None
135
+ to_keys,
136
+ multiplicity,
137
+ )
138
+ return a
139
+
140
+
141
+ class DiffusionTransformerLayer(Module):
142
+ """Algorithm 23"""
143
+
144
+ def __init__(
145
+ self,
146
+ heads,
147
+ dim=384,
148
+ dim_single_cond=None,
149
+ post_layer_norm=False,
150
+ ):
151
+ super().__init__()
152
+
153
+ dim_single_cond = default(dim_single_cond, dim)
154
+
155
+ self.adaln = AdaLN(dim, dim_single_cond)
156
+ self.pair_bias_attn = AttentionPairBias(
157
+ c_s=dim, num_heads=heads, compute_pair_bias=False
158
+ )
159
+
160
+ self.output_projection_linear = Linear(dim_single_cond, dim)
161
+ nn.init.zeros_(self.output_projection_linear.weight)
162
+ nn.init.constant_(self.output_projection_linear.bias, -2.0)
163
+
164
+ self.output_projection = nn.Sequential(
165
+ self.output_projection_linear, nn.Sigmoid()
166
+ )
167
+ self.transition = ConditionedTransitionBlock(
168
+ dim_single=dim, dim_single_cond=dim_single_cond
169
+ )
170
+
171
+ if post_layer_norm:
172
+ self.post_lnorm = nn.LayerNorm(dim)
173
+ else:
174
+ self.post_lnorm = nn.Identity()
175
+
176
+ def forward(
177
+ self,
178
+ a, # Float['bm n d'],
179
+ s, # Float['bm n ds'],
180
+ bias=None, # Float['b n n dp']
181
+ mask=None, # Bool['b n'] | None = None
182
+ to_keys=None,
183
+ multiplicity=1,
184
+ ):
185
+ b = self.adaln(a, s)
186
+
187
+ k_in = b
188
+ if to_keys is not None:
189
+ k_in = to_keys(b)
190
+ mask = to_keys(mask.unsqueeze(-1)).squeeze(-1)
191
+
192
+ if self.pair_bias_attn:
193
+ b = self.pair_bias_attn(
194
+ s=b,
195
+ z=bias,
196
+ mask=mask,
197
+ multiplicity=multiplicity,
198
+ k_in=k_in,
199
+ )
200
+ else:
201
+ b = self.no_pair_bias_attn(s=b, mask=mask, k_in=k_in)
202
+
203
+ b = self.output_projection(s) * b
204
+
205
+ a = a + b
206
+ a = a + self.transition(a, s)
207
+
208
+ a = self.post_lnorm(a)
209
+ return a
210
+
211
+
212
+ class AtomTransformer(Module):
213
+ """Algorithm 7"""
214
+
215
+ def __init__(
216
+ self,
217
+ attn_window_queries,
218
+ attn_window_keys,
219
+ **diffusion_transformer_kwargs,
220
+ ):
221
+ super().__init__()
222
+ self.attn_window_queries = attn_window_queries
223
+ self.attn_window_keys = attn_window_keys
224
+ self.diffusion_transformer = DiffusionTransformer(
225
+ **diffusion_transformer_kwargs
226
+ )
227
+
228
+ def forward(
229
+ self,
230
+ q, # Float['b m d'],
231
+ c, # Float['b m ds'],
232
+ bias, # Float['b m m dp']
233
+ to_keys,
234
+ mask, # Bool['b m'] | None = None
235
+ multiplicity=1,
236
+ ):
237
+ W = self.attn_window_queries
238
+ H = self.attn_window_keys
239
+
240
+ B, N, D = q.shape
241
+ NW = N // W
242
+
243
+ # reshape tokens
244
+ q = q.view((B * NW, W, -1))
245
+ c = c.view((B * NW, W, -1))
246
+ mask = mask.view(B * NW, W)
247
+ bias = bias.repeat_interleave(multiplicity, 0)
248
+ bias = bias.view((bias.shape[0] * NW, W, H, -1))
249
+
250
+ to_keys_new = lambda x: to_keys(x.view(B, NW * W, -1)).view(B * NW, H, -1)
251
+
252
+ # main transformer
253
+ q = self.diffusion_transformer(
254
+ a=q,
255
+ s=c,
256
+ bias=bias,
257
+ mask=mask.float(),
258
+ multiplicity=1, # bias term already expanded with multiplicity
259
+ to_keys=to_keys_new,
260
+ )
261
+
262
+ q = q.view((B, NW * W, D))
263
+ return q