lhallee commited on
Commit
76d2d94
·
verified ·
1 Parent(s): 7c861d8

Upload embedding_mixin.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. embedding_mixin.py +399 -399
embedding_mixin.py CHANGED
@@ -1,399 +1,399 @@
1
- import os
2
- import sqlite3
3
- import networkx as nx
4
- import numpy as np
5
- import torch
6
- from tqdm.auto import tqdm
7
- from typing import Callable, List, Optional
8
- from torch.utils.data import DataLoader
9
- from torch.utils.data import Dataset as TorchDataset
10
- from transformers import PreTrainedTokenizerBase
11
-
12
-
13
- class Pooler:
14
- def __init__(self, pooling_types: List[str]):
15
- self.pooling_types = pooling_types
16
- self.pooling_options = {
17
- 'mean': self.mean_pooling,
18
- 'max': self.max_pooling,
19
- 'norm': self.norm_pooling,
20
- 'median': self.median_pooling,
21
- 'std': self.std_pooling,
22
- 'var': self.var_pooling,
23
- 'cls': self.cls_pooling,
24
- 'parti': self._pool_parti,
25
- }
26
-
27
- def _create_pooled_matrices_across_layers(self, attentions: torch.Tensor) -> torch.Tensor:
28
- maxed_attentions = torch.max(attentions, dim=1)[0]
29
- return maxed_attentions
30
-
31
- def _page_rank(self, attention_matrix, personalization=None, nstart=None, prune_type="top_k_outdegree"):
32
- # Run PageRank on the attention matrix converted to a graph.
33
- # Raises exceptions if the graph doesn't match the token sequence or has no edges.
34
- # Returns the PageRank scores for each token node.
35
- G = self._convert_to_graph(attention_matrix)
36
- if G.number_of_nodes() != attention_matrix.shape[0]:
37
- raise Exception(
38
- f"The number of nodes in the graph should be equal to the number of tokens in sequence! You have {G.number_of_nodes()} nodes for {attention_matrix.shape[0]} tokens.")
39
- if G.number_of_edges() == 0:
40
- raise Exception(f"You don't seem to have any attention edges left in the graph.")
41
-
42
- return nx.pagerank(G, alpha=0.85, tol=1e-06, weight='weight', personalization=personalization, nstart=nstart, max_iter=100)
43
-
44
- def _convert_to_graph(self, matrix):
45
- # Convert a matrix (e.g., attention scores) to a directed graph using networkx.
46
- # Each element in the matrix represents a directed edge with a weight.
47
- G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
48
- return G
49
-
50
- def _calculate_importance_weights(self, dict_importance, attention_mask: Optional[torch.Tensor] = None):
51
- # Remove keys where attention_mask is 0
52
- if attention_mask is not None:
53
- for k in list(dict_importance.keys()):
54
- if attention_mask[k] == 0:
55
- del dict_importance[k]
56
-
57
- #dict_importance[0] # remove cls
58
- #dict_importance[-1] # remove eos
59
- total = sum(dict_importance.values())
60
- return np.array([v / total for _, v in dict_importance.items()])
61
-
62
- def _pool_parti(self, emb: torch.Tensor, attentions: torch.Tensor, attention_mask: Optional[torch.Tensor] = None): # (b, L, d) -> (b, d)
63
- maxed_attentions = self._create_pooled_matrices_across_layers(attentions).numpy()
64
- # emb is (b, L, d), maxed_attentions is (b, L, L)
65
- emb_pooled = []
66
- for e, a, mask in zip(emb, maxed_attentions, attention_mask):
67
- dict_importance = self._page_rank(a)
68
- importance_weights = self._calculate_importance_weights(dict_importance, mask)
69
- num_tokens = int(mask.sum().item())
70
- emb_pooled.append(np.average(e[:num_tokens], weights=importance_weights, axis=0))
71
- pooled = torch.tensor(np.array(emb_pooled))
72
- return pooled
73
-
74
- def mean_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
75
- if attention_mask is None:
76
- return emb.mean(dim=1)
77
- else:
78
- attention_mask = attention_mask.unsqueeze(-1)
79
- return (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1)
80
-
81
- def max_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
82
- if attention_mask is None:
83
- return emb.max(dim=1).values
84
- else:
85
- attention_mask = attention_mask.unsqueeze(-1)
86
- return (emb * attention_mask).max(dim=1).values
87
-
88
- def norm_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
89
- if attention_mask is None:
90
- return emb.norm(dim=1, p=2)
91
- else:
92
- attention_mask = attention_mask.unsqueeze(-1)
93
- return (emb * attention_mask).norm(dim=1, p=2)
94
-
95
- def median_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
96
- if attention_mask is None:
97
- return emb.median(dim=1).values
98
- else:
99
- attention_mask = attention_mask.unsqueeze(-1)
100
- return (emb * attention_mask).median(dim=1).values
101
-
102
- def std_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
103
- if attention_mask is None:
104
- return emb.std(dim=1)
105
- else:
106
- # Compute variance correctly over non-masked positions, then take sqrt
107
- var = self.var_pooling(emb, attention_mask, **kwargs)
108
- return torch.sqrt(var)
109
-
110
- def var_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
111
- if attention_mask is None:
112
- return emb.var(dim=1)
113
- else:
114
- # Correctly compute variance over only non-masked positions
115
- attention_mask = attention_mask.unsqueeze(-1) # (b, L, 1)
116
- # Compute mean over non-masked positions
117
- mean = (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
118
- mean = mean.unsqueeze(1) # (b, 1, d)
119
- # Compute squared differences from mean, only over non-masked positions
120
- squared_diff = (emb - mean) ** 2 # (b, L, d)
121
- # Sum squared differences over non-masked positions and divide by count
122
- var = (squared_diff * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
123
- return var
124
-
125
- def cls_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
126
- return emb[:, 0, :]
127
-
128
- def __call__(
129
- self,
130
- emb: torch.Tensor,
131
- attention_mask: Optional[torch.Tensor] = None,
132
- attentions: Optional[torch.Tensor] = None
133
- ): # [mean, max]
134
- final_emb = []
135
- for pooling_type in self.pooling_types:
136
- final_emb.append(self.pooling_options[pooling_type](emb=emb, attention_mask=attention_mask, attentions=attentions)) # (b, d)
137
- return torch.cat(final_emb, dim=-1) # (b, n_pooling_types * d)
138
-
139
-
140
- class ProteinDataset(TorchDataset):
141
- """Simple dataset for protein sequences."""
142
- def __init__(self, sequences: list[str]):
143
- self.sequences = sequences
144
-
145
- def __len__(self) -> int:
146
- return len(self.sequences)
147
-
148
- def __getitem__(self, idx: int) -> str:
149
- return self.sequences[idx]
150
-
151
-
152
- def build_collator(tokenizer: PreTrainedTokenizerBase) -> Callable[[list[str]], dict[str, torch.Tensor]]:
153
- def _collate_fn(sequences: list[str]) -> dict[str, torch.Tensor]:
154
- return tokenizer(sequences, return_tensors="pt", padding='longest')
155
- return _collate_fn
156
-
157
-
158
- def parse_fasta(fasta_path: str) -> List[str]:
159
- assert os.path.exists(fasta_path), f"FASTA file does not exist: {fasta_path}"
160
- sequences = []
161
- current_seq = []
162
- with open(fasta_path, 'r') as f:
163
- for line in f:
164
- line = line.strip()
165
- if not line:
166
- continue
167
- if line.startswith('>'):
168
- if current_seq:
169
- sequences.append(''.join(current_seq))
170
- current_seq = []
171
- else:
172
- current_seq.append(line)
173
- if current_seq:
174
- sequences.append(''.join(current_seq))
175
- return sequences
176
-
177
-
178
- class EmbeddingMixin:
179
- def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
180
- raise NotImplementedError
181
-
182
- @property
183
- def device(self) -> torch.device:
184
- """Get the device of the model."""
185
- return next(self.parameters()).device
186
-
187
- def _read_sequences_from_db(self, db_path: str) -> set[str]:
188
- """Read sequences from SQLite database."""
189
- sequences = []
190
- with sqlite3.connect(db_path) as conn:
191
- c = conn.cursor()
192
- c.execute("SELECT sequence FROM embeddings")
193
- while True:
194
- row = c.fetchone()
195
- if row is None:
196
- break
197
- sequences.append(row[0])
198
- return set(sequences)
199
-
200
- def _ensure_embeddings_table(self, conn: sqlite3.Connection) -> None:
201
- cursor = conn.cursor()
202
- cursor.execute(
203
- "CREATE TABLE IF NOT EXISTS embeddings ("
204
- "sequence TEXT PRIMARY KEY, "
205
- "embedding BLOB NOT NULL, "
206
- "shape TEXT, "
207
- "dtype TEXT"
208
- ")"
209
- )
210
- cursor.execute("PRAGMA table_info(embeddings)")
211
- rows = cursor.fetchall()
212
- column_names = [row[1] for row in rows]
213
- if "shape" not in column_names:
214
- cursor.execute("ALTER TABLE embeddings ADD COLUMN shape TEXT")
215
- if "dtype" not in column_names:
216
- cursor.execute("ALTER TABLE embeddings ADD COLUMN dtype TEXT")
217
- conn.commit()
218
-
219
- def load_embeddings_from_pth(self, save_path: str) -> dict[str, torch.Tensor]:
220
- assert os.path.exists(save_path), f"Embedding file does not exist: {save_path}"
221
- payload = torch.load(save_path, map_location="cpu", weights_only=True)
222
- assert isinstance(payload, dict), "Expected .pth embeddings file to contain a dictionary."
223
- for sequence, tensor in payload.items():
224
- assert isinstance(sequence, str), "Expected embedding dictionary keys to be sequences (str)."
225
- assert isinstance(tensor, torch.Tensor), "Expected embedding dictionary values to be tensors."
226
- return payload
227
-
228
- def load_embeddings_from_db(self, db_path: str, sequences: Optional[List[str]] = None) -> dict[str, torch.Tensor]:
229
- assert os.path.exists(db_path), f"Embedding database does not exist: {db_path}"
230
- loaded: dict[str, torch.Tensor] = {}
231
- with sqlite3.connect(db_path) as conn:
232
- self._ensure_embeddings_table(conn)
233
- cursor = conn.cursor()
234
- if sequences is None:
235
- cursor.execute("SELECT sequence, embedding, shape, dtype FROM embeddings")
236
- else:
237
- if len(sequences) == 0:
238
- return loaded
239
- placeholders = ",".join(["?"] * len(sequences))
240
- cursor.execute(
241
- f"SELECT sequence, embedding, shape, dtype FROM embeddings WHERE sequence IN ({placeholders})",
242
- tuple(sequences),
243
- )
244
-
245
- rows = cursor.fetchall()
246
- for row in rows:
247
- sequence = row[0]
248
- embedding_bytes = row[1]
249
- shape_text = row[2]
250
- dtype_text = row[3]
251
- assert shape_text is not None, "Missing shape metadata in embeddings table."
252
- assert dtype_text is not None, "Missing dtype metadata in embeddings table."
253
- shape_values = [int(value) for value in shape_text.split(",") if len(value) > 0]
254
- assert len(shape_values) > 0, f"Invalid shape metadata for sequence: {sequence}"
255
- expected_size = int(np.prod(shape_values))
256
- np_dtype = np.dtype(dtype_text)
257
- array = np.frombuffer(embedding_bytes, dtype=np_dtype)
258
- assert array.size == expected_size, f"Shape mismatch while reading sequence: {sequence}"
259
- reshaped = array.copy().reshape(tuple(shape_values))
260
- loaded[sequence] = torch.from_numpy(reshaped)
261
- return loaded
262
-
263
- def embed_dataset(
264
- self,
265
- sequences: Optional[List[str]] = None,
266
- tokenizer: Optional[PreTrainedTokenizerBase] = None,
267
- batch_size: int = 2,
268
- max_len: int = 512,
269
- truncate: bool = True,
270
- full_embeddings: bool = False,
271
- embed_dtype: torch.dtype = torch.float32,
272
- pooling_types: List[str] = ['mean'],
273
- num_workers: int = 0,
274
- sql: bool = False,
275
- save: bool = True,
276
- sql_db_path: str = 'embeddings.db',
277
- save_path: str = 'embeddings.pth',
278
- fasta_path: Optional[str] = None,
279
- **kwargs,
280
- ) -> Optional[dict[str, torch.Tensor]]:
281
- """
282
- Embed a dataset of protein sequences.
283
-
284
- Supports two modes:
285
- - Tokenizer mode (ESM2/ESM++): provide `tokenizer`, `_embed(input_ids, attention_mask)` is used.
286
- - Sequence mode (E1): pass `tokenizer=None`, `_embed(sequences, return_attention_mask=True, **kwargs)` is used.
287
-
288
- Sequences can be supplied as a list via `sequences`, parsed from a FASTA file via
289
- `fasta_path`, or both (the two sources are combined). At least one must be provided.
290
- """
291
- if fasta_path is not None:
292
- fasta_sequences = parse_fasta(fasta_path)
293
- sequences = list(sequences or []) + fasta_sequences
294
- assert sequences is not None and len(sequences) > 0, \
295
- "Must provide at least one sequence via `sequences` or `fasta_path`."
296
- sequences = list(set([seq[:max_len] if truncate else seq for seq in sequences]))
297
- sequences = sorted(sequences, key=len, reverse=True)
298
- hidden_size = self.config.hidden_size
299
- pooler = Pooler(pooling_types) if not full_embeddings else None
300
- tokenizer_mode = tokenizer is not None
301
- if tokenizer_mode:
302
- collate_fn = build_collator(tokenizer)
303
- device = self.device
304
- else:
305
- collate_fn = None
306
- device = None
307
-
308
- def get_embeddings(residue_embeddings: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
309
- if full_embeddings or residue_embeddings.ndim == 2:
310
- return residue_embeddings
311
- return pooler(residue_embeddings, attention_mask)
312
-
313
- def iter_batches(to_embed: List[str]):
314
- if tokenizer_mode:
315
- assert collate_fn is not None
316
- assert device is not None
317
- dataset = ProteinDataset(to_embed)
318
- dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn, shuffle=False)
319
- for i, batch in tqdm(enumerate(dataloader), total=len(dataloader), desc='Embedding batches'):
320
- seqs = to_embed[i * batch_size:(i + 1) * batch_size]
321
- input_ids = batch['input_ids'].to(device)
322
- attention_mask = batch['attention_mask'].to(device)
323
- residue_embeddings = self._embed(input_ids, attention_mask)
324
- yield seqs, residue_embeddings, attention_mask
325
- else:
326
- for batch_start in tqdm(range(0, len(to_embed), batch_size), desc='Embedding batches'):
327
- seqs = to_embed[batch_start:batch_start + batch_size]
328
- batch_output = self._embed(seqs, return_attention_mask=True, **kwargs)
329
- assert isinstance(batch_output, tuple), "Sequence mode _embed must return (last_hidden_state, attention_mask)."
330
- assert len(batch_output) == 2, "Sequence mode _embed must return exactly two values."
331
- residue_embeddings, attention_mask = batch_output
332
- assert isinstance(attention_mask, torch.Tensor), "Sequence mode _embed must return attention_mask as a torch.Tensor."
333
- yield seqs, residue_embeddings, attention_mask
334
-
335
- if sql:
336
- conn = sqlite3.connect(sql_db_path)
337
- self._ensure_embeddings_table(conn)
338
- c = conn.cursor()
339
- already_embedded = self._read_sequences_from_db(sql_db_path)
340
- to_embed = [seq for seq in sequences if seq not in already_embedded]
341
- print(f"Found {len(already_embedded)} already embedded sequences in {sql_db_path}")
342
- print(f"Embedding {len(to_embed)} new sequences")
343
- if len(to_embed) > 0:
344
- with torch.no_grad():
345
- for i, (seqs, residue_embeddings, attention_mask) in enumerate(iter_batches(to_embed)):
346
- embeddings = get_embeddings(residue_embeddings, attention_mask).to(embed_dtype)
347
- for seq, emb, mask in zip(seqs, embeddings, attention_mask):
348
- if full_embeddings:
349
- emb = emb[mask.bool()].reshape(-1, hidden_size)
350
- emb_np = emb.cpu().numpy()
351
- emb_shape = ",".join([str(dim) for dim in emb_np.shape])
352
- emb_dtype = str(emb_np.dtype)
353
- c.execute(
354
- "INSERT OR REPLACE INTO embeddings (sequence, embedding, shape, dtype) VALUES (?, ?, ?, ?)",
355
- (seq, emb_np.tobytes(), emb_shape, emb_dtype),
356
- )
357
- if tokenizer_mode and (i + 1) % 100 == 0:
358
- conn.commit()
359
- conn.commit()
360
- conn.close()
361
- return None
362
-
363
- embeddings_dict = {}
364
- if os.path.exists(save_path):
365
- embeddings_dict = self.load_embeddings_from_pth(save_path)
366
- to_embed = [seq for seq in sequences if seq not in embeddings_dict]
367
- print(f"Found {len(embeddings_dict)} already embedded sequences in {save_path}")
368
- print(f"Embedding {len(to_embed)} new sequences")
369
- else:
370
- to_embed = sequences
371
- print(f"Embedding {len(to_embed)} new sequences")
372
-
373
- if len(to_embed) > 0:
374
- with torch.no_grad():
375
- for seqs, residue_embeddings, attention_mask in iter_batches(to_embed):
376
- embeddings = get_embeddings(residue_embeddings, attention_mask).to(embed_dtype)
377
- for seq, emb, mask in zip(seqs, embeddings, attention_mask):
378
- if full_embeddings:
379
- emb = emb[mask.bool()].reshape(-1, hidden_size)
380
- embeddings_dict[seq] = emb.cpu()
381
-
382
- if save:
383
- torch.save(embeddings_dict, save_path)
384
-
385
- return embeddings_dict
386
-
387
-
388
- if __name__ == "__main__":
389
- # py -m pooler
390
- pooler = Pooler(pooling_types=['max', 'parti'])
391
- batch_size = 8
392
- seq_len = 64
393
- hidden_size = 128
394
- num_layers = 12
395
- emb = torch.randn(batch_size, seq_len, hidden_size)
396
- attentions = torch.randn(batch_size, num_layers, seq_len, seq_len)
397
- attention_mask = torch.ones(batch_size, seq_len)
398
- y = pooler(emb=emb, attention_mask=attention_mask, attentions=attentions)
399
- print(y.shape)
 
1
+ import os
2
+ import sqlite3
3
+ import networkx as nx
4
+ import numpy as np
5
+ import torch
6
+ from tqdm.auto import tqdm
7
+ from typing import Callable, List, Optional
8
+ from torch.utils.data import DataLoader
9
+ from torch.utils.data import Dataset as TorchDataset
10
+ from transformers import PreTrainedTokenizerBase
11
+
12
+
13
+ class Pooler:
14
+ def __init__(self, pooling_types: List[str]):
15
+ self.pooling_types = pooling_types
16
+ self.pooling_options = {
17
+ 'mean': self.mean_pooling,
18
+ 'max': self.max_pooling,
19
+ 'norm': self.norm_pooling,
20
+ 'median': self.median_pooling,
21
+ 'std': self.std_pooling,
22
+ 'var': self.var_pooling,
23
+ 'cls': self.cls_pooling,
24
+ 'parti': self._pool_parti,
25
+ }
26
+
27
+ def _create_pooled_matrices_across_layers(self, attentions: torch.Tensor) -> torch.Tensor:
28
+ maxed_attentions = torch.max(attentions, dim=1)[0]
29
+ return maxed_attentions
30
+
31
+ def _page_rank(self, attention_matrix, personalization=None, nstart=None, prune_type="top_k_outdegree"):
32
+ # Run PageRank on the attention matrix converted to a graph.
33
+ # Raises exceptions if the graph doesn't match the token sequence or has no edges.
34
+ # Returns the PageRank scores for each token node.
35
+ G = self._convert_to_graph(attention_matrix)
36
+ if G.number_of_nodes() != attention_matrix.shape[0]:
37
+ raise Exception(
38
+ f"The number of nodes in the graph should be equal to the number of tokens in sequence! You have {G.number_of_nodes()} nodes for {attention_matrix.shape[0]} tokens.")
39
+ if G.number_of_edges() == 0:
40
+ raise Exception(f"You don't seem to have any attention edges left in the graph.")
41
+
42
+ return nx.pagerank(G, alpha=0.85, tol=1e-06, weight='weight', personalization=personalization, nstart=nstart, max_iter=100)
43
+
44
+ def _convert_to_graph(self, matrix):
45
+ # Convert a matrix (e.g., attention scores) to a directed graph using networkx.
46
+ # Each element in the matrix represents a directed edge with a weight.
47
+ G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
48
+ return G
49
+
50
+ def _calculate_importance_weights(self, dict_importance, attention_mask: Optional[torch.Tensor] = None):
51
+ # Remove keys where attention_mask is 0
52
+ if attention_mask is not None:
53
+ for k in list(dict_importance.keys()):
54
+ if attention_mask[k] == 0:
55
+ del dict_importance[k]
56
+
57
+ #dict_importance[0] # remove cls
58
+ #dict_importance[-1] # remove eos
59
+ total = sum(dict_importance.values())
60
+ return np.array([v / total for _, v in dict_importance.items()])
61
+
62
+ def _pool_parti(self, emb: torch.Tensor, attentions: torch.Tensor, attention_mask: Optional[torch.Tensor] = None): # (b, L, d) -> (b, d)
63
+ maxed_attentions = self._create_pooled_matrices_across_layers(attentions).numpy()
64
+ # emb is (b, L, d), maxed_attentions is (b, L, L)
65
+ emb_pooled = []
66
+ for e, a, mask in zip(emb, maxed_attentions, attention_mask):
67
+ dict_importance = self._page_rank(a)
68
+ importance_weights = self._calculate_importance_weights(dict_importance, mask)
69
+ num_tokens = int(mask.sum().item())
70
+ emb_pooled.append(np.average(e[:num_tokens], weights=importance_weights, axis=0))
71
+ pooled = torch.tensor(np.array(emb_pooled))
72
+ return pooled
73
+
74
+ def mean_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
75
+ if attention_mask is None:
76
+ return emb.mean(dim=1)
77
+ else:
78
+ attention_mask = attention_mask.unsqueeze(-1)
79
+ return (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1)
80
+
81
+ def max_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
82
+ if attention_mask is None:
83
+ return emb.max(dim=1).values
84
+ else:
85
+ attention_mask = attention_mask.unsqueeze(-1)
86
+ return (emb * attention_mask).max(dim=1).values
87
+
88
+ def norm_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
89
+ if attention_mask is None:
90
+ return emb.norm(dim=1, p=2)
91
+ else:
92
+ attention_mask = attention_mask.unsqueeze(-1)
93
+ return (emb * attention_mask).norm(dim=1, p=2)
94
+
95
+ def median_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
96
+ if attention_mask is None:
97
+ return emb.median(dim=1).values
98
+ else:
99
+ attention_mask = attention_mask.unsqueeze(-1)
100
+ return (emb * attention_mask).median(dim=1).values
101
+
102
+ def std_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
103
+ if attention_mask is None:
104
+ return emb.std(dim=1)
105
+ else:
106
+ # Compute variance correctly over non-masked positions, then take sqrt
107
+ var = self.var_pooling(emb, attention_mask, **kwargs)
108
+ return torch.sqrt(var)
109
+
110
+ def var_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
111
+ if attention_mask is None:
112
+ return emb.var(dim=1)
113
+ else:
114
+ # Correctly compute variance over only non-masked positions
115
+ attention_mask = attention_mask.unsqueeze(-1) # (b, L, 1)
116
+ # Compute mean over non-masked positions
117
+ mean = (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
118
+ mean = mean.unsqueeze(1) # (b, 1, d)
119
+ # Compute squared differences from mean, only over non-masked positions
120
+ squared_diff = (emb - mean) ** 2 # (b, L, d)
121
+ # Sum squared differences over non-masked positions and divide by count
122
+ var = (squared_diff * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
123
+ return var
124
+
125
+ def cls_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
126
+ return emb[:, 0, :]
127
+
128
+ def __call__(
129
+ self,
130
+ emb: torch.Tensor,
131
+ attention_mask: Optional[torch.Tensor] = None,
132
+ attentions: Optional[torch.Tensor] = None
133
+ ): # [mean, max]
134
+ final_emb = []
135
+ for pooling_type in self.pooling_types:
136
+ final_emb.append(self.pooling_options[pooling_type](emb=emb, attention_mask=attention_mask, attentions=attentions)) # (b, d)
137
+ return torch.cat(final_emb, dim=-1) # (b, n_pooling_types * d)
138
+
139
+
140
+ class ProteinDataset(TorchDataset):
141
+ """Simple dataset for protein sequences."""
142
+ def __init__(self, sequences: list[str]):
143
+ self.sequences = sequences
144
+
145
+ def __len__(self) -> int:
146
+ return len(self.sequences)
147
+
148
+ def __getitem__(self, idx: int) -> str:
149
+ return self.sequences[idx]
150
+
151
+
152
+ def build_collator(tokenizer: PreTrainedTokenizerBase) -> Callable[[list[str]], dict[str, torch.Tensor]]:
153
+ def _collate_fn(sequences: list[str]) -> dict[str, torch.Tensor]:
154
+ return tokenizer(sequences, return_tensors="pt", padding='longest')
155
+ return _collate_fn
156
+
157
+
158
+ def parse_fasta(fasta_path: str) -> List[str]:
159
+ assert os.path.exists(fasta_path), f"FASTA file does not exist: {fasta_path}"
160
+ sequences = []
161
+ current_seq = []
162
+ with open(fasta_path, 'r') as f:
163
+ for line in f:
164
+ line = line.strip()
165
+ if not line:
166
+ continue
167
+ if line.startswith('>'):
168
+ if current_seq:
169
+ sequences.append(''.join(current_seq))
170
+ current_seq = []
171
+ else:
172
+ current_seq.append(line)
173
+ if current_seq:
174
+ sequences.append(''.join(current_seq))
175
+ return sequences
176
+
177
+
178
+ class EmbeddingMixin:
179
+ def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
180
+ raise NotImplementedError
181
+
182
+ @property
183
+ def device(self) -> torch.device:
184
+ """Get the device of the model."""
185
+ return next(self.parameters()).device
186
+
187
+ def _read_sequences_from_db(self, db_path: str) -> set[str]:
188
+ """Read sequences from SQLite database."""
189
+ sequences = []
190
+ with sqlite3.connect(db_path) as conn:
191
+ c = conn.cursor()
192
+ c.execute("SELECT sequence FROM embeddings")
193
+ while True:
194
+ row = c.fetchone()
195
+ if row is None:
196
+ break
197
+ sequences.append(row[0])
198
+ return set(sequences)
199
+
200
+ def _ensure_embeddings_table(self, conn: sqlite3.Connection) -> None:
201
+ cursor = conn.cursor()
202
+ cursor.execute(
203
+ "CREATE TABLE IF NOT EXISTS embeddings ("
204
+ "sequence TEXT PRIMARY KEY, "
205
+ "embedding BLOB NOT NULL, "
206
+ "shape TEXT, "
207
+ "dtype TEXT"
208
+ ")"
209
+ )
210
+ cursor.execute("PRAGMA table_info(embeddings)")
211
+ rows = cursor.fetchall()
212
+ column_names = [row[1] for row in rows]
213
+ if "shape" not in column_names:
214
+ cursor.execute("ALTER TABLE embeddings ADD COLUMN shape TEXT")
215
+ if "dtype" not in column_names:
216
+ cursor.execute("ALTER TABLE embeddings ADD COLUMN dtype TEXT")
217
+ conn.commit()
218
+
219
+ def load_embeddings_from_pth(self, save_path: str) -> dict[str, torch.Tensor]:
220
+ assert os.path.exists(save_path), f"Embedding file does not exist: {save_path}"
221
+ payload = torch.load(save_path, map_location="cpu", weights_only=True)
222
+ assert isinstance(payload, dict), "Expected .pth embeddings file to contain a dictionary."
223
+ for sequence, tensor in payload.items():
224
+ assert isinstance(sequence, str), "Expected embedding dictionary keys to be sequences (str)."
225
+ assert isinstance(tensor, torch.Tensor), "Expected embedding dictionary values to be tensors."
226
+ return payload
227
+
228
+ def load_embeddings_from_db(self, db_path: str, sequences: Optional[List[str]] = None) -> dict[str, torch.Tensor]:
229
+ assert os.path.exists(db_path), f"Embedding database does not exist: {db_path}"
230
+ loaded: dict[str, torch.Tensor] = {}
231
+ with sqlite3.connect(db_path) as conn:
232
+ self._ensure_embeddings_table(conn)
233
+ cursor = conn.cursor()
234
+ if sequences is None:
235
+ cursor.execute("SELECT sequence, embedding, shape, dtype FROM embeddings")
236
+ else:
237
+ if len(sequences) == 0:
238
+ return loaded
239
+ placeholders = ",".join(["?"] * len(sequences))
240
+ cursor.execute(
241
+ f"SELECT sequence, embedding, shape, dtype FROM embeddings WHERE sequence IN ({placeholders})",
242
+ tuple(sequences),
243
+ )
244
+
245
+ rows = cursor.fetchall()
246
+ for row in rows:
247
+ sequence = row[0]
248
+ embedding_bytes = row[1]
249
+ shape_text = row[2]
250
+ dtype_text = row[3]
251
+ assert shape_text is not None, "Missing shape metadata in embeddings table."
252
+ assert dtype_text is not None, "Missing dtype metadata in embeddings table."
253
+ shape_values = [int(value) for value in shape_text.split(",") if len(value) > 0]
254
+ assert len(shape_values) > 0, f"Invalid shape metadata for sequence: {sequence}"
255
+ expected_size = int(np.prod(shape_values))
256
+ np_dtype = np.dtype(dtype_text)
257
+ array = np.frombuffer(embedding_bytes, dtype=np_dtype)
258
+ assert array.size == expected_size, f"Shape mismatch while reading sequence: {sequence}"
259
+ reshaped = array.copy().reshape(tuple(shape_values))
260
+ loaded[sequence] = torch.from_numpy(reshaped)
261
+ return loaded
262
+
263
+ def embed_dataset(
264
+ self,
265
+ sequences: Optional[List[str]] = None,
266
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
267
+ batch_size: int = 2,
268
+ max_len: int = 512,
269
+ truncate: bool = True,
270
+ full_embeddings: bool = False,
271
+ embed_dtype: torch.dtype = torch.float32,
272
+ pooling_types: List[str] = ['mean'],
273
+ num_workers: int = 0,
274
+ sql: bool = False,
275
+ save: bool = True,
276
+ sql_db_path: str = 'embeddings.db',
277
+ save_path: str = 'embeddings.pth',
278
+ fasta_path: Optional[str] = None,
279
+ **kwargs,
280
+ ) -> Optional[dict[str, torch.Tensor]]:
281
+ """
282
+ Embed a dataset of protein sequences.
283
+
284
+ Supports two modes:
285
+ - Tokenizer mode (ESM2/ESM++): provide `tokenizer`, `_embed(input_ids, attention_mask)` is used.
286
+ - Sequence mode (E1): pass `tokenizer=None`, `_embed(sequences, return_attention_mask=True, **kwargs)` is used.
287
+
288
+ Sequences can be supplied as a list via `sequences`, parsed from a FASTA file via
289
+ `fasta_path`, or both (the two sources are combined). At least one must be provided.
290
+ """
291
+ if fasta_path is not None:
292
+ fasta_sequences = parse_fasta(fasta_path)
293
+ sequences = list(sequences or []) + fasta_sequences
294
+ assert sequences is not None and len(sequences) > 0, \
295
+ "Must provide at least one sequence via `sequences` or `fasta_path`."
296
+ sequences = list(set([seq[:max_len] if truncate else seq for seq in sequences]))
297
+ sequences = sorted(sequences, key=len, reverse=True)
298
+ hidden_size = self.config.hidden_size
299
+ pooler = Pooler(pooling_types) if not full_embeddings else None
300
+ tokenizer_mode = tokenizer is not None
301
+ if tokenizer_mode:
302
+ collate_fn = build_collator(tokenizer)
303
+ device = self.device
304
+ else:
305
+ collate_fn = None
306
+ device = None
307
+
308
+ def get_embeddings(residue_embeddings: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
309
+ if full_embeddings or residue_embeddings.ndim == 2:
310
+ return residue_embeddings
311
+ return pooler(residue_embeddings, attention_mask)
312
+
313
+ def iter_batches(to_embed: List[str]):
314
+ if tokenizer_mode:
315
+ assert collate_fn is not None
316
+ assert device is not None
317
+ dataset = ProteinDataset(to_embed)
318
+ dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn, shuffle=False)
319
+ for i, batch in tqdm(enumerate(dataloader), total=len(dataloader), desc='Embedding batches'):
320
+ seqs = to_embed[i * batch_size:(i + 1) * batch_size]
321
+ input_ids = batch['input_ids'].to(device)
322
+ attention_mask = batch['attention_mask'].to(device)
323
+ residue_embeddings = self._embed(input_ids, attention_mask)
324
+ yield seqs, residue_embeddings, attention_mask
325
+ else:
326
+ for batch_start in tqdm(range(0, len(to_embed), batch_size), desc='Embedding batches'):
327
+ seqs = to_embed[batch_start:batch_start + batch_size]
328
+ batch_output = self._embed(seqs, return_attention_mask=True, **kwargs)
329
+ assert isinstance(batch_output, tuple), "Sequence mode _embed must return (last_hidden_state, attention_mask)."
330
+ assert len(batch_output) == 2, "Sequence mode _embed must return exactly two values."
331
+ residue_embeddings, attention_mask = batch_output
332
+ assert isinstance(attention_mask, torch.Tensor), "Sequence mode _embed must return attention_mask as a torch.Tensor."
333
+ yield seqs, residue_embeddings, attention_mask
334
+
335
+ if sql:
336
+ conn = sqlite3.connect(sql_db_path)
337
+ self._ensure_embeddings_table(conn)
338
+ c = conn.cursor()
339
+ already_embedded = self._read_sequences_from_db(sql_db_path)
340
+ to_embed = [seq for seq in sequences if seq not in already_embedded]
341
+ print(f"Found {len(already_embedded)} already embedded sequences in {sql_db_path}")
342
+ print(f"Embedding {len(to_embed)} new sequences")
343
+ if len(to_embed) > 0:
344
+ with torch.no_grad():
345
+ for i, (seqs, residue_embeddings, attention_mask) in enumerate(iter_batches(to_embed)):
346
+ embeddings = get_embeddings(residue_embeddings, attention_mask).to(embed_dtype)
347
+ for seq, emb, mask in zip(seqs, embeddings, attention_mask):
348
+ if full_embeddings:
349
+ emb = emb[mask.bool()].reshape(-1, hidden_size)
350
+ emb_np = emb.cpu().numpy()
351
+ emb_shape = ",".join([str(dim) for dim in emb_np.shape])
352
+ emb_dtype = str(emb_np.dtype)
353
+ c.execute(
354
+ "INSERT OR REPLACE INTO embeddings (sequence, embedding, shape, dtype) VALUES (?, ?, ?, ?)",
355
+ (seq, emb_np.tobytes(), emb_shape, emb_dtype),
356
+ )
357
+ if tokenizer_mode and (i + 1) % 100 == 0:
358
+ conn.commit()
359
+ conn.commit()
360
+ conn.close()
361
+ return None
362
+
363
+ embeddings_dict = {}
364
+ if os.path.exists(save_path):
365
+ embeddings_dict = self.load_embeddings_from_pth(save_path)
366
+ to_embed = [seq for seq in sequences if seq not in embeddings_dict]
367
+ print(f"Found {len(embeddings_dict)} already embedded sequences in {save_path}")
368
+ print(f"Embedding {len(to_embed)} new sequences")
369
+ else:
370
+ to_embed = sequences
371
+ print(f"Embedding {len(to_embed)} new sequences")
372
+
373
+ if len(to_embed) > 0:
374
+ with torch.no_grad():
375
+ for seqs, residue_embeddings, attention_mask in iter_batches(to_embed):
376
+ embeddings = get_embeddings(residue_embeddings, attention_mask).to(embed_dtype)
377
+ for seq, emb, mask in zip(seqs, embeddings, attention_mask):
378
+ if full_embeddings:
379
+ emb = emb[mask.bool()].reshape(-1, hidden_size)
380
+ embeddings_dict[seq] = emb.cpu()
381
+
382
+ if save:
383
+ torch.save(embeddings_dict, save_path)
384
+
385
+ return embeddings_dict
386
+
387
+
388
+ if __name__ == "__main__":
389
+ # py -m pooler
390
+ pooler = Pooler(pooling_types=['max', 'parti'])
391
+ batch_size = 8
392
+ seq_len = 64
393
+ hidden_size = 128
394
+ num_layers = 12
395
+ emb = torch.randn(batch_size, seq_len, hidden_size)
396
+ attentions = torch.randn(batch_size, num_layers, seq_len, seq_len)
397
+ attention_mask = torch.ones(batch_size, seq_len)
398
+ y = pooler(emb=emb, attention_mask=attention_mask, attentions=attentions)
399
+ print(y.shape)