Yanisadel commited on
Commit
187fa63
·
verified ·
1 Parent(s): 39795f0

Upload sCT

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