Delete sct.py
Browse files
sct.py
DELETED
@@ -1,756 +0,0 @@
|
|
1 |
-
import math
|
2 |
-
from dataclasses import dataclass
|
3 |
-
from typing import Optional, Tuple
|
4 |
-
|
5 |
-
import numpy as np
|
6 |
-
import torch
|
7 |
-
import torch.nn as nn
|
8 |
-
import torch.nn.functional as F # noqa: N812
|
9 |
-
from transformers import PretrainedConfig, PreTrainedModel
|
10 |
-
|
11 |
-
|
12 |
-
class GeLU(nn.Module):
|
13 |
-
def __init__(self) -> None:
|
14 |
-
"""
|
15 |
-
This is the gelu implementation from the original ESM repo.
|
16 |
-
Using F.gelu yields subtly wrong results.
|
17 |
-
"""
|
18 |
-
super().__init__()
|
19 |
-
|
20 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
21 |
-
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
|
22 |
-
|
23 |
-
|
24 |
-
@dataclass
|
25 |
-
class RotaryEmbeddingConfig:
|
26 |
-
"""
|
27 |
-
Parameters to initialize the RotaryEmbedding layer. The rescaling factor allows
|
28 |
-
to adapt the rotary embeddings to larger lengths than what was used for training.
|
29 |
-
One of this strategy is presented in the Yarn paper: https://arxiv.org/pdf/2309.00071.pdf. # noqa
|
30 |
-
Args:
|
31 |
-
"""
|
32 |
-
|
33 |
-
rescaling_factor: Optional[float]
|
34 |
-
|
35 |
-
|
36 |
-
class RotaryEmbedding(torch.nn.Module):
|
37 |
-
"""
|
38 |
-
Rotary position embeddings based on those in
|
39 |
-
[RoFormer](https://huggingface.co/docs/transformers/model_doc/roformer).
|
40 |
-
Query and keys are transformed by rotation
|
41 |
-
matrices which depend on their relative positions.
|
42 |
-
"""
|
43 |
-
|
44 |
-
def __init__(self, dim: int, rotary_embedding_config: RotaryEmbeddingConfig):
|
45 |
-
super().__init__()
|
46 |
-
|
47 |
-
# Extract argument from the config
|
48 |
-
self.rescaling_factor = rotary_embedding_config.rescaling_factor
|
49 |
-
self.upper_freq = 10000
|
50 |
-
self.dim = dim
|
51 |
-
|
52 |
-
self._seq_len_cached = None
|
53 |
-
self._cos_cached = None
|
54 |
-
self._sin_cached = None
|
55 |
-
|
56 |
-
def _apply_rotary_pos_emb(
|
57 |
-
self,
|
58 |
-
heads: torch.Tensor,
|
59 |
-
cos: torch.Tensor,
|
60 |
-
sin: torch.Tensor,
|
61 |
-
) -> torch.Tensor:
|
62 |
-
""" """
|
63 |
-
x_first, x_second = (
|
64 |
-
heads[..., : heads.shape[-1] // 2],
|
65 |
-
heads[..., heads.shape[-1] // 2 :],
|
66 |
-
)
|
67 |
-
|
68 |
-
first_part = x_first * cos - x_second * sin
|
69 |
-
second_part = x_second * cos + x_first * sin
|
70 |
-
|
71 |
-
return torch.cat((first_part, second_part), dim=-1)
|
72 |
-
|
73 |
-
def _compute_cos_sin_tables(
|
74 |
-
self, x: torch.Tensor, inv_freq: torch.Tensor, seq_dimension: int = 2
|
75 |
-
) -> tuple[torch.Tensor, torch.Tensor]:
|
76 |
-
seq_len = x.shape[seq_dimension]
|
77 |
-
# Reset the tables if the sequence length has changed,
|
78 |
-
# or if we're on a new device (possibly due to tracing for instance)
|
79 |
-
self._seq_len_cached = seq_len
|
80 |
-
t = torch.arange(x.shape[seq_dimension], device=x.device).type_as(inv_freq)
|
81 |
-
# freqs = torch.outer(t, inv_freq)
|
82 |
-
freqs = torch.einsum("i, j -> ij", t, inv_freq)
|
83 |
-
|
84 |
-
self._cos_cached = torch.cos(freqs)[None, :, None, :]
|
85 |
-
self._sin_cached = torch.sin(freqs)[None, :, None, :]
|
86 |
-
# emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
|
87 |
-
|
88 |
-
# self._cos_cached = emb.cos()[None, None, :, :]
|
89 |
-
# self._sin_cached = emb.sin()[None, None, :, :]
|
90 |
-
|
91 |
-
return self._cos_cached, self._sin_cached
|
92 |
-
|
93 |
-
def forward(
|
94 |
-
self, q: torch.Tensor, k: torch.Tensor
|
95 |
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
96 |
-
if self.rescaling_factor is None:
|
97 |
-
inv_freq = 1.0 / (
|
98 |
-
self.upper_freq ** (torch.arange(0, self.dim, 2).float() / self.dim)
|
99 |
-
)
|
100 |
-
else:
|
101 |
-
updated_base = self.upper_freq * (
|
102 |
-
self.rescaling_factor ** (self.dim / (self.dim - 2))
|
103 |
-
)
|
104 |
-
inv_freq = 1.0 / (
|
105 |
-
updated_base ** (torch.arange(0, self.dim, 2).float() / self.dim)
|
106 |
-
)
|
107 |
-
|
108 |
-
self._cos_cached, self._sin_cached = self._compute_cos_sin_tables(
|
109 |
-
q,
|
110 |
-
inv_freq,
|
111 |
-
seq_dimension=-3,
|
112 |
-
)
|
113 |
-
|
114 |
-
return (
|
115 |
-
self._apply_rotary_pos_emb(q, self._cos_cached, self._sin_cached),
|
116 |
-
self._apply_rotary_pos_emb(k, self._cos_cached, self._sin_cached),
|
117 |
-
)
|
118 |
-
|
119 |
-
|
120 |
-
class ResidualConvBlock(nn.Module):
|
121 |
-
"""
|
122 |
-
Conv Block with Residual connection.
|
123 |
-
"""
|
124 |
-
|
125 |
-
def __init__(self, dim_in: int, dim_out: int, seq_len: int, kernel_size: int = 1):
|
126 |
-
super().__init__()
|
127 |
-
self.conv_block = ConvBlock(
|
128 |
-
dim_in=dim_in, dim_out=dim_out, seq_len=seq_len, kernel_size=kernel_size
|
129 |
-
)
|
130 |
-
|
131 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
132 |
-
y = self.conv_block(x)
|
133 |
-
return x.reshape(y.shape) + y
|
134 |
-
|
135 |
-
|
136 |
-
class ConvBlock(nn.Module):
|
137 |
-
"""
|
138 |
-
Conv Block.
|
139 |
-
"""
|
140 |
-
|
141 |
-
def __init__(self, dim_in: int, dim_out: int, seq_len: int, kernel_size: int = 1):
|
142 |
-
super().__init__()
|
143 |
-
self.conv = nn.Conv1d(
|
144 |
-
in_channels=dim_in,
|
145 |
-
out_channels=dim_out,
|
146 |
-
kernel_size=kernel_size,
|
147 |
-
padding="same",
|
148 |
-
)
|
149 |
-
self.layer_norm = nn.LayerNorm(seq_len, eps=1e-5)
|
150 |
-
|
151 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
152 |
-
x = self.layer_norm(x)
|
153 |
-
x = x.reshape(x.shape[0], x.shape[1], -1)
|
154 |
-
x = self.conv(x)
|
155 |
-
x = F.gelu(x, approximate="tanh")
|
156 |
-
return x
|
157 |
-
|
158 |
-
|
159 |
-
class ResidualDeConvBlock(nn.Module):
|
160 |
-
"""
|
161 |
-
Conv Block with Residual connection.
|
162 |
-
"""
|
163 |
-
|
164 |
-
def __init__(
|
165 |
-
self,
|
166 |
-
dim_in: int,
|
167 |
-
dim_out: int,
|
168 |
-
seq_len: int,
|
169 |
-
kernel_size: int = 1,
|
170 |
-
stride: int = 1,
|
171 |
-
):
|
172 |
-
super().__init__()
|
173 |
-
self.deconv_block = DeConvBlock(
|
174 |
-
dim_in=dim_in,
|
175 |
-
dim_out=dim_out,
|
176 |
-
seq_len=seq_len,
|
177 |
-
kernel_size=kernel_size,
|
178 |
-
stride=stride,
|
179 |
-
)
|
180 |
-
|
181 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
182 |
-
y = self.deconv_block(x)
|
183 |
-
return x.reshape(y.shape) + y
|
184 |
-
|
185 |
-
|
186 |
-
class DeConvBlock(nn.Module):
|
187 |
-
"""
|
188 |
-
DeConv Block.
|
189 |
-
"""
|
190 |
-
|
191 |
-
def __init__(
|
192 |
-
self,
|
193 |
-
dim_in: int,
|
194 |
-
dim_out: int,
|
195 |
-
seq_len: int,
|
196 |
-
kernel_size: int = 1,
|
197 |
-
stride: int = 1,
|
198 |
-
):
|
199 |
-
super().__init__()
|
200 |
-
self.deconv = nn.ConvTranspose1d(
|
201 |
-
in_channels=dim_in,
|
202 |
-
out_channels=dim_out,
|
203 |
-
kernel_size=kernel_size,
|
204 |
-
stride=stride,
|
205 |
-
padding=0,
|
206 |
-
)
|
207 |
-
self.layer_norm = nn.LayerNorm(seq_len)
|
208 |
-
self.kernel_size = kernel_size
|
209 |
-
|
210 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
211 |
-
x = self.layer_norm(x)
|
212 |
-
x = x.reshape(x.shape[0], x.shape[1], -1)
|
213 |
-
x = self.deconv(x)
|
214 |
-
if self.kernel_size == 5:
|
215 |
-
# handle the special case where haiku
|
216 |
-
# deconv removes padding automatically
|
217 |
-
x = x[:, :, 1:-2]
|
218 |
-
x = F.gelu(x, approximate="tanh")
|
219 |
-
return x
|
220 |
-
|
221 |
-
|
222 |
-
class SpatialEncoding(nn.Module):
|
223 |
-
"""
|
224 |
-
Spatial coordinates encoding module
|
225 |
-
"""
|
226 |
-
|
227 |
-
def __init__(
|
228 |
-
self,
|
229 |
-
embed_dim: int,
|
230 |
-
num_scales: int = 10,
|
231 |
-
sigma_min: float = 1.0,
|
232 |
-
sigma_max: float = 10.0,
|
233 |
-
):
|
234 |
-
super().__init__()
|
235 |
-
self.num_scales = num_scales
|
236 |
-
self.sigma_min = sigma_min
|
237 |
-
self.sigma_max = sigma_max
|
238 |
-
self.g = sigma_max / sigma_min
|
239 |
-
self.scales = torch.linspace(sigma_min, sigma_max, num_scales)
|
240 |
-
self.fc_layer = nn.Linear(embed_dim, embed_dim)
|
241 |
-
|
242 |
-
def scale_specific_encoder(
|
243 |
-
self, coordinates: torch.Tensor, scale: float
|
244 |
-
) -> torch.Tensor:
|
245 |
-
x, y = coordinates[..., 0], coordinates[..., 1]
|
246 |
-
constant = self.sigma_min * (self.g ** (scale / (self.num_scales - 1)))
|
247 |
-
x_transform = torch.cos(x / constant)
|
248 |
-
y_transform = torch.sin(y / constant)
|
249 |
-
transformed_coordinates = torch.stack([x_transform, y_transform], dim=-1)
|
250 |
-
return transformed_coordinates
|
251 |
-
|
252 |
-
def forward(self, coordinates: torch.Tensor) -> torch.Tensor:
|
253 |
-
transformed_coordinates = [
|
254 |
-
self.scale_specific_encoder(coordinates, scale) for scale in self.scales
|
255 |
-
]
|
256 |
-
transformed_coordinates = torch.cat(transformed_coordinates, dim=-1)
|
257 |
-
return self.fc_layer(transformed_coordinates)
|
258 |
-
|
259 |
-
|
260 |
-
class ConvTowerBlock(nn.Module):
|
261 |
-
def __init__(
|
262 |
-
self, dim_in: int, dim_out: int, seq_len: int, kernel_size: int, num_cells: int
|
263 |
-
) -> None:
|
264 |
-
super().__init__()
|
265 |
-
self.conv_layer = ConvBlock(
|
266 |
-
dim_in=dim_in, dim_out=dim_out, seq_len=seq_len, kernel_size=kernel_size
|
267 |
-
)
|
268 |
-
self.res_conv = ResidualConvBlock(
|
269 |
-
dim_in=dim_out, dim_out=dim_out, seq_len=seq_len, kernel_size=1
|
270 |
-
)
|
271 |
-
self.avg_pool = nn.AvgPool1d(kernel_size=2, stride=2)
|
272 |
-
self.num_cells = num_cells
|
273 |
-
|
274 |
-
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
275 |
-
residual = x
|
276 |
-
x = x.reshape(x.shape[0], x.shape[1], self.num_cells, -1) # noqa: FKA100
|
277 |
-
x = self.conv_layer(x)
|
278 |
-
x = x.reshape((x.shape[0], x.shape[1], self.num_cells, -1))
|
279 |
-
x = self.res_conv(x)
|
280 |
-
x = self.avg_pool(x)
|
281 |
-
return x, residual
|
282 |
-
|
283 |
-
|
284 |
-
class DeConvTowerBlock(nn.Module):
|
285 |
-
def __init__(
|
286 |
-
self,
|
287 |
-
dim_in: int,
|
288 |
-
dim_out: int,
|
289 |
-
kernel_size: int,
|
290 |
-
seq_len: int,
|
291 |
-
stride: int = 2,
|
292 |
-
num_cells: int = 1,
|
293 |
-
):
|
294 |
-
super().__init__()
|
295 |
-
self.deconv_block = DeConvBlock(
|
296 |
-
dim_in=dim_in,
|
297 |
-
dim_out=dim_out,
|
298 |
-
seq_len=seq_len,
|
299 |
-
kernel_size=kernel_size,
|
300 |
-
stride=stride,
|
301 |
-
)
|
302 |
-
self.res_deconv_block = ResidualDeConvBlock(
|
303 |
-
dim_in=dim_out, dim_out=dim_out, seq_len=seq_len * 2, kernel_size=1
|
304 |
-
)
|
305 |
-
self.num_cells = num_cells
|
306 |
-
|
307 |
-
def forward(self, x: torch.Tensor, res: torch.Tensor) -> torch.Tensor:
|
308 |
-
x = x.reshape((x.shape[0], x.shape[1], self.num_cells, -1))
|
309 |
-
x = self.deconv_block(x)
|
310 |
-
x = x.reshape((x.shape[0], x.shape[1], self.num_cells, -1))
|
311 |
-
x = self.res_deconv_block(x)
|
312 |
-
|
313 |
-
x = x + res
|
314 |
-
return x
|
315 |
-
|
316 |
-
|
317 |
-
class MultiHeadAttention(nn.Module):
|
318 |
-
def __init__(
|
319 |
-
self,
|
320 |
-
num_heads: int,
|
321 |
-
key_size: int,
|
322 |
-
rotary_embedding_config: Optional[RotaryEmbeddingConfig] = None,
|
323 |
-
add_bias_kv: bool = False,
|
324 |
-
value_size: Optional[int] = None,
|
325 |
-
model_size: Optional[int] = None,
|
326 |
-
name: Optional[str] = None,
|
327 |
-
):
|
328 |
-
super().__init__()
|
329 |
-
if not model_size:
|
330 |
-
model_size = key_size
|
331 |
-
if not value_size:
|
332 |
-
value_size = key_size
|
333 |
-
self.model_size = model_size
|
334 |
-
self.key_size = key_size
|
335 |
-
self.value_size = value_size
|
336 |
-
self.add_bias_kv = add_bias_kv
|
337 |
-
self.name = name
|
338 |
-
self.num_heads = num_heads
|
339 |
-
self._rotary_embedding_config = rotary_embedding_config
|
340 |
-
|
341 |
-
self.w_k = nn.Linear(self.model_size, self.num_heads * self.key_size)
|
342 |
-
self.w_q = nn.Linear(self.model_size, self.num_heads * self.key_size)
|
343 |
-
self.w_v = nn.Linear(self.model_size, self.num_heads * self.value_size)
|
344 |
-
self.output = nn.Linear(self.num_heads * self.value_size, self.model_size)
|
345 |
-
if self._rotary_embedding_config:
|
346 |
-
self._rotary_embedding = RotaryEmbedding(
|
347 |
-
self.key_size, self._rotary_embedding_config
|
348 |
-
)
|
349 |
-
|
350 |
-
def apply_rotary_embeddings(
|
351 |
-
self,
|
352 |
-
query: torch.Tensor,
|
353 |
-
key: torch.Tensor,
|
354 |
-
) -> tuple[torch.Tensor, torch.Tensor]:
|
355 |
-
""" """
|
356 |
-
query, key = self._rotary_embedding(query, key)
|
357 |
-
return query, key
|
358 |
-
|
359 |
-
def forward(
|
360 |
-
self,
|
361 |
-
query: torch.Tensor,
|
362 |
-
key: torch.Tensor,
|
363 |
-
value: torch.Tensor,
|
364 |
-
attention_mask: torch.Tensor | None = None,
|
365 |
-
attention_weight_bias: torch.Tensor | None = None,
|
366 |
-
) -> dict[str, torch.Tensor]:
|
367 |
-
"""
|
368 |
-
Returns:
|
369 |
-
dictionary containing attention weights
|
370 |
-
and outputs.
|
371 |
-
"""
|
372 |
-
key_heads = self.w_k(key).reshape(
|
373 |
-
(*key.shape[:-1], self.num_heads, self.key_size)
|
374 |
-
)
|
375 |
-
query_heads = self.w_q(query).reshape(
|
376 |
-
(*query.shape[:-1], self.num_heads, self.key_size)
|
377 |
-
)
|
378 |
-
value_heads = self.w_v(value).reshape(
|
379 |
-
(*value.shape[:-1], self.num_heads, self.value_size)
|
380 |
-
)
|
381 |
-
if self._rotary_embedding_config:
|
382 |
-
query_heads, key_heads = self.apply_rotary_embeddings(
|
383 |
-
query_heads, key_heads
|
384 |
-
)
|
385 |
-
attention_weights = torch.einsum(
|
386 |
-
"...thd, ...Thd -> ...htT", query_heads, key_heads
|
387 |
-
)
|
388 |
-
sqrt_key_size = np.sqrt(self.key_size)
|
389 |
-
attention_weights = attention_weights / sqrt_key_size
|
390 |
-
if attention_mask:
|
391 |
-
attention_weights = torch.where(attention_mask, attention_weights, -1e30)
|
392 |
-
if attention_weight_bias:
|
393 |
-
attention_weights = F.softmax(
|
394 |
-
attention_weights + attention_weight_bias, dim=-1
|
395 |
-
)
|
396 |
-
else:
|
397 |
-
attention_weights = F.softmax(attention_weights, dim=-1)
|
398 |
-
value_out = torch.einsum(
|
399 |
-
"...htT, ...Thd->...thd", attention_weights, value_heads
|
400 |
-
)
|
401 |
-
value_out = value_out.reshape((*value_out.shape[:-2], -1))
|
402 |
-
embeddings = self.output(value_out)
|
403 |
-
|
404 |
-
return {"attention_weights": attention_weights, "embeddings": embeddings}
|
405 |
-
|
406 |
-
|
407 |
-
class SelfAttentionBlock(nn.Module):
|
408 |
-
def __init__(
|
409 |
-
self,
|
410 |
-
num_heads: int,
|
411 |
-
embed_dim: int,
|
412 |
-
ffn_embed_dim: int,
|
413 |
-
key_size: Optional[int] = None,
|
414 |
-
add_bias_kv: bool = False,
|
415 |
-
add_bias_fnn: bool = True,
|
416 |
-
ffn_activation_name: str = "gelu-no-approx",
|
417 |
-
use_glu_in_ffn: bool = False,
|
418 |
-
layer_norm_eps: float = 1e-5, # this is the default haiku value
|
419 |
-
pre_layer_norm: bool = True,
|
420 |
-
name: Optional[str] = None,
|
421 |
-
rotary_embedding_config: Optional[RotaryEmbeddingConfig] = None,
|
422 |
-
):
|
423 |
-
super().__init__()
|
424 |
-
if key_size is None:
|
425 |
-
if embed_dim % num_heads != 0:
|
426 |
-
raise ValueError(
|
427 |
-
f"The embedding dimension should be divisible by the number of "
|
428 |
-
f"heads, however provided embedding dimension is {embed_dim} and "
|
429 |
-
f"the number of heads is {num_heads}."
|
430 |
-
)
|
431 |
-
else:
|
432 |
-
key_size = embed_dim // num_heads
|
433 |
-
|
434 |
-
# Get ffn activation function
|
435 |
-
self._pre_layer_norm = pre_layer_norm
|
436 |
-
self._use_glu_in_fnn = use_glu_in_ffn
|
437 |
-
# Define layers
|
438 |
-
if use_glu_in_ffn:
|
439 |
-
# user should multiply ffn_embed_dim by 2/3 when using GLU
|
440 |
-
# to keep total number of parameters equal
|
441 |
-
# see https://arxiv.org/pdf/2002.05202.pdf. for more details
|
442 |
-
# we multiply by 2 here as the output will be split in 2 for GLU
|
443 |
-
self.fc1 = nn.Linear(embed_dim, int(2 * ffn_embed_dim), bias=add_bias_fnn)
|
444 |
-
else:
|
445 |
-
self.fc1 = nn.Linear(embed_dim, ffn_embed_dim, bias=add_bias_fnn)
|
446 |
-
|
447 |
-
self.fc2 = nn.Linear(ffn_embed_dim, embed_dim, bias=add_bias_fnn)
|
448 |
-
|
449 |
-
self.layer_norm_self_attention = nn.LayerNorm(
|
450 |
-
embed_dim,
|
451 |
-
)
|
452 |
-
self.layer_norm_mlp = nn.LayerNorm(embed_dim)
|
453 |
-
if ffn_activation_name == "swish":
|
454 |
-
self._ffn_activation_fn = nn.SiLU()
|
455 |
-
elif ffn_activation_name == "gelu-no-approx":
|
456 |
-
self._ffn_activation_fn = nn.GeLU(approximate="tanh")
|
457 |
-
else:
|
458 |
-
self._ffn_activation_fn = getattr(torch.nn, ffn_activation_name)
|
459 |
-
|
460 |
-
self.mha = MultiHeadAttention(
|
461 |
-
num_heads=num_heads,
|
462 |
-
key_size=key_size,
|
463 |
-
add_bias_kv=add_bias_kv,
|
464 |
-
model_size=embed_dim,
|
465 |
-
name="self_attention",
|
466 |
-
rotary_embedding_config=rotary_embedding_config,
|
467 |
-
)
|
468 |
-
|
469 |
-
def mlp(self, embed: torch.Tensor) -> torch.Tensor:
|
470 |
-
|
471 |
-
if self._pre_layer_norm:
|
472 |
-
x = self.layer_norm_mlp(embed)
|
473 |
-
else:
|
474 |
-
x = embed
|
475 |
-
|
476 |
-
if self._use_glu_in_fnn:
|
477 |
-
x = self.fc1(x)
|
478 |
-
x1, x2 = torch.split(x, split_size_or_sections=x.shape[-1] // 2, dim=-1)
|
479 |
-
x = self._ffn_activation_fn(x1) * x2
|
480 |
-
else:
|
481 |
-
x = self._ffn_activation_fn(self.fc1(x))
|
482 |
-
x = self.fc2(x)
|
483 |
-
|
484 |
-
if not self._pre_layer_norm:
|
485 |
-
x = self.layer_norm_mlp(x + embed)
|
486 |
-
return x
|
487 |
-
|
488 |
-
def forward(
|
489 |
-
self,
|
490 |
-
x: torch.Tensor,
|
491 |
-
attention_mask: torch.Tensor | None = None,
|
492 |
-
attention_weight_bias: torch.Tensor | None = None,
|
493 |
-
) -> torch.Tensor:
|
494 |
-
|
495 |
-
res = x
|
496 |
-
if self._pre_layer_norm:
|
497 |
-
x = self.layer_norm_self_attention(x)
|
498 |
-
|
499 |
-
output = self.mha(
|
500 |
-
x,
|
501 |
-
x,
|
502 |
-
x,
|
503 |
-
attention_mask=attention_mask,
|
504 |
-
attention_weight_bias=attention_weight_bias,
|
505 |
-
)
|
506 |
-
|
507 |
-
if not self._pre_layer_norm:
|
508 |
-
output["embeddings"] = self.layer_norm_self_attention(
|
509 |
-
output["embeddings"] + res
|
510 |
-
)
|
511 |
-
|
512 |
-
x = output["embeddings"]
|
513 |
-
else:
|
514 |
-
x = output["embeddings"]
|
515 |
-
x = res + x
|
516 |
-
|
517 |
-
# MLP
|
518 |
-
if not self._pre_layer_norm:
|
519 |
-
x = self.mlp(x)
|
520 |
-
else:
|
521 |
-
x = x + self.mlp(x)
|
522 |
-
|
523 |
-
output["embeddings"] = x
|
524 |
-
return output
|
525 |
-
|
526 |
-
|
527 |
-
class LMHead(nn.Module):
|
528 |
-
def __init__(
|
529 |
-
self, dim_in: int, embed_dim: int, dim_out: int, num_hidden_layers: int
|
530 |
-
) -> None:
|
531 |
-
""" """
|
532 |
-
super().__init__()
|
533 |
-
self.num_hidden_layers = num_hidden_layers
|
534 |
-
self.linear_layers = nn.ModuleList([nn.Linear(dim_in, embed_dim)])
|
535 |
-
self.linear_layers.extend(
|
536 |
-
nn.ModuleList(
|
537 |
-
[nn.Linear(embed_dim, embed_dim)] for _ in range(num_hidden_layers - 1)
|
538 |
-
)
|
539 |
-
)
|
540 |
-
self.linear_out = nn.Linear(embed_dim, dim_out)
|
541 |
-
|
542 |
-
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
543 |
-
res = x # noqa: F841
|
544 |
-
x = F.gelu(x, approximate="tanh")
|
545 |
-
for layer in self.linear_layers:
|
546 |
-
x = layer(x)
|
547 |
-
x = F.gelu(x, approximate="tanh")
|
548 |
-
out = self.linear_out(x)
|
549 |
-
return out
|
550 |
-
|
551 |
-
|
552 |
-
@dataclass
|
553 |
-
class sCTConfig(PretrainedConfig): # noqa: N801
|
554 |
-
model_type = "sCT"
|
555 |
-
|
556 |
-
def __init__(self, **kwargs): # type: ignore
|
557 |
-
self.alphabet_size = kwargs.get("alphabet_size", 7)
|
558 |
-
self.pad_token_id = kwargs.get("pad_token_id", 5)
|
559 |
-
self.mask_token_id = kwargs.get("mask_token_id", 6)
|
560 |
-
self.cell_len = kwargs.get("cell_len", 19968)
|
561 |
-
|
562 |
-
self.num_downsamples = kwargs.get("num_downsamples", 8)
|
563 |
-
self.attention_heads = kwargs.get("attention_heads", 16)
|
564 |
-
self.key_size = kwargs.get("key_size", None)
|
565 |
-
self.token_embed_dim = kwargs.get("token_embed_dim", 16)
|
566 |
-
|
567 |
-
self.embed_dim = kwargs.get("embed_dim", 1024)
|
568 |
-
self.ffn_embed_dim = kwargs.get("ffn_embed_dim", 2048)
|
569 |
-
self.num_layers = kwargs.get("num_layers", 4)
|
570 |
-
self.layer_norm_eps = kwargs.get("layer_norm_eps", 1e-5)
|
571 |
-
self.interpolation_method = kwargs.get("interpolation_method", "nearest")
|
572 |
-
|
573 |
-
# bad hack to satisfy cellnt_celltype_annotation.py:312
|
574 |
-
self.max_positions: int = kwargs.get("max_positions", 20480)
|
575 |
-
self.num_cells: int = kwargs.get("num_cells", 50)
|
576 |
-
self.num_hidden_layers_head: int = kwargs.get("num_hidden_layers_head", 1)
|
577 |
-
|
578 |
-
self.use_skip_connection: bool = kwargs.get("use_skip_connection", True)
|
579 |
-
|
580 |
-
# logging
|
581 |
-
self.use_gradient_checkpointing: bool = False
|
582 |
-
|
583 |
-
# return
|
584 |
-
self.embeddings_layers_to_save: Tuple[int, ...] = kwargs.get(
|
585 |
-
"embeddings_layers_to_save", ()
|
586 |
-
)
|
587 |
-
self.attention_maps_to_save: list[tuple[int, int]] = kwargs.get(
|
588 |
-
"attention_maps_to_save", []
|
589 |
-
)
|
590 |
-
|
591 |
-
# Spatial info configuration
|
592 |
-
self.use_spatial_information: bool = kwargs.get(
|
593 |
-
"use_spatial_information", False
|
594 |
-
)
|
595 |
-
self.num_scales: int = kwargs.get("num_scales", 10)
|
596 |
-
self.sigma_min: float = kwargs.get("sigma_min", 1.0)
|
597 |
-
self.sigma_max: float = kwargs.get("sigma_max", 10.0)
|
598 |
-
|
599 |
-
super().__init__(**kwargs)
|
600 |
-
|
601 |
-
def __post_init__(self) -> None: # type: ignore # noqa: N807
|
602 |
-
"""
|
603 |
-
Checks that the given values are compatible.
|
604 |
-
"""
|
605 |
-
if self.key_size is None:
|
606 |
-
if not self.embed_dim % self.attention_heads == 0:
|
607 |
-
raise ValueError(
|
608 |
-
f"When no key size is provided, the embedding dimension"
|
609 |
-
f"should be divisible by the number of heads, however "
|
610 |
-
f"provided embedding dimension is {self.embed_dim} and "
|
611 |
-
f"the number of heads is {self.attention_heads}."
|
612 |
-
)
|
613 |
-
self.key_size = self.embed_dim // self.attention_heads
|
614 |
-
|
615 |
-
|
616 |
-
class sCT(PreTrainedModel): # noqa: N801
|
617 |
-
config_class = sCTConfig
|
618 |
-
|
619 |
-
def __init__(self, config: sCTConfig):
|
620 |
-
# super().__init__(config)
|
621 |
-
super().__init__(config=config)
|
622 |
-
if config.use_spatial_information:
|
623 |
-
self.spatial_embed_layer = SpatialEncoding(
|
624 |
-
embed_dim=config.token_embed_dim,
|
625 |
-
num_scales=config.num_scales,
|
626 |
-
sigma_min=config.sigma_min,
|
627 |
-
sigma_max=config.sigma_max,
|
628 |
-
)
|
629 |
-
self.cell_len = config.cell_len
|
630 |
-
|
631 |
-
self.token_embed = nn.Embedding(config.alphabet_size, config.token_embed_dim)
|
632 |
-
|
633 |
-
attention_maps_to_save = config.attention_maps_to_save
|
634 |
-
self._attention_layers_to_save = list({t[0] for t in attention_maps_to_save})
|
635 |
-
|
636 |
-
self._attention_maps_per_layer_to_save = {
|
637 |
-
layer: [t[1] for t in attention_maps_to_save if t[0] == layer]
|
638 |
-
for layer in self._attention_layers_to_save
|
639 |
-
}
|
640 |
-
|
641 |
-
max_layer = max(self._attention_layers_to_save + [0])
|
642 |
-
if max_layer > config.num_layers:
|
643 |
-
raise ValueError(
|
644 |
-
f"You are requiring attention maps for layer {max_layer}, "
|
645 |
-
f"while the model has {config.num_layers} layers only."
|
646 |
-
)
|
647 |
-
|
648 |
-
filter_list = np.linspace(
|
649 |
-
config.token_embed_dim,
|
650 |
-
config.embed_dim,
|
651 |
-
config.num_downsamples + 1,
|
652 |
-
)
|
653 |
-
|
654 |
-
filter_list = np.ceil(filter_list / 32) * 32
|
655 |
-
filter_list = filter_list.astype(int).tolist()
|
656 |
-
|
657 |
-
self._filter_list = filter_list
|
658 |
-
self._rotary_embedding_config = RotaryEmbeddingConfig(rescaling_factor=None)
|
659 |
-
|
660 |
-
self.stem_conv = nn.Sequential(
|
661 |
-
nn.Conv1d(
|
662 |
-
in_channels=config.token_embed_dim,
|
663 |
-
out_channels=config.token_embed_dim,
|
664 |
-
kernel_size=15,
|
665 |
-
padding="same",
|
666 |
-
),
|
667 |
-
nn.GELU(approximate="tanh"),
|
668 |
-
)
|
669 |
-
downsampled_seq_lens = [
|
670 |
-
self.cell_len // (2**i) for i in range(len(filter_list) - 1)
|
671 |
-
]
|
672 |
-
|
673 |
-
self.conv_tower = nn.ModuleList(
|
674 |
-
[
|
675 |
-
ConvTowerBlock(
|
676 |
-
dim_in=self._filter_list[i],
|
677 |
-
dim_out=self._filter_list[i + 1],
|
678 |
-
kernel_size=5,
|
679 |
-
seq_len=seq_len,
|
680 |
-
num_cells=config.num_cells,
|
681 |
-
)
|
682 |
-
for i, seq_len in zip(range(len(filter_list) - 1), downsampled_seq_lens)
|
683 |
-
]
|
684 |
-
)
|
685 |
-
|
686 |
-
self.deconv_tower = nn.ModuleList(
|
687 |
-
[
|
688 |
-
DeConvTowerBlock(
|
689 |
-
dim_in=filter_list[-1 - i],
|
690 |
-
dim_out=filter_list[-1 - i - 1],
|
691 |
-
kernel_size=5,
|
692 |
-
stride=2,
|
693 |
-
seq_len=seq_len // 2,
|
694 |
-
num_cells=config.num_cells,
|
695 |
-
)
|
696 |
-
for i, seq_len in zip(
|
697 |
-
range(len(filter_list) - 1), downsampled_seq_lens[::-1]
|
698 |
-
)
|
699 |
-
]
|
700 |
-
)
|
701 |
-
self.transformer_layers = nn.ModuleList(
|
702 |
-
[
|
703 |
-
SelfAttentionBlock(
|
704 |
-
num_heads=config.attention_heads,
|
705 |
-
embed_dim=config.embed_dim,
|
706 |
-
ffn_embed_dim=config.ffn_embed_dim,
|
707 |
-
key_size=config.key_size,
|
708 |
-
add_bias_kv=False,
|
709 |
-
add_bias_fnn=False,
|
710 |
-
ffn_activation_name="swish",
|
711 |
-
use_glu_in_ffn=True,
|
712 |
-
layer_norm_eps=1e-5, # this is the default haiku value
|
713 |
-
pre_layer_norm=True,
|
714 |
-
name=f"attention_layer_{layer_idx}",
|
715 |
-
rotary_embedding_config=self._rotary_embedding_config,
|
716 |
-
)
|
717 |
-
for layer_idx in range(config.num_layers)
|
718 |
-
]
|
719 |
-
)
|
720 |
-
|
721 |
-
self.lm_head = LMHead(
|
722 |
-
dim_in=config.token_embed_dim,
|
723 |
-
embed_dim=config.embed_dim,
|
724 |
-
dim_out=config.alphabet_size,
|
725 |
-
num_hidden_layers=config.num_hidden_layers_head,
|
726 |
-
)
|
727 |
-
|
728 |
-
def forward(self, input_ids: torch.Tensor) -> dict[str, torch.Tensor]:
|
729 |
-
outs = {}
|
730 |
-
embeddings = self.token_embed(input_ids)
|
731 |
-
x = embeddings.permute(0, 2, 1)
|
732 |
-
x = self.stem_conv(x)
|
733 |
-
residuals = []
|
734 |
-
for _idx, conv_block in enumerate(self.conv_tower):
|
735 |
-
x, res = conv_block(x)
|
736 |
-
residuals.append(res)
|
737 |
-
residuals = residuals[::-1]
|
738 |
-
x = x.permute(0, 2, 1)
|
739 |
-
|
740 |
-
for layer_idx, transformer in enumerate(self.transformer_layers):
|
741 |
-
output = transformer(x)
|
742 |
-
x = output["embeddings"]
|
743 |
-
if (layer_idx + 1) in self.config.embeddings_layers_to_save:
|
744 |
-
outs[f"embeddings_{(layer_idx + 1)}"] = output["embeddings"]
|
745 |
-
if (layer_idx + 1) in self._attention_layers_to_save:
|
746 |
-
for map_number in self._attention_maps_per_layer_to_save[layer_idx + 1]:
|
747 |
-
dkey = f"attention_map_layer_{layer_idx + 1}_number_{map_number}"
|
748 |
-
outs[dkey] = output["attention_weights"][:, map_number + 1]
|
749 |
-
x = x.permute(0, 2, 1)
|
750 |
-
for deconv_block, res in zip(self.deconv_tower, residuals):
|
751 |
-
x = deconv_block(x, res)
|
752 |
-
x = x.permute(0, 2, 1)
|
753 |
-
logits = self.lm_head(x)
|
754 |
-
outs["logits"] = logits
|
755 |
-
|
756 |
-
return outs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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