lhallee commited on
Commit
3fb79b3
·
verified ·
1 Parent(s): 1af5d50

Upload embedding_mixin.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. embedding_mixin.py +302 -0
embedding_mixin.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import networkx as nx
3
+ import numpy as np
4
+ import torch
5
+ from tqdm.auto import tqdm
6
+ from typing import Callable, List, Optional
7
+ from torch.utils.data import DataLoader
8
+ from torch.utils.data import Dataset as TorchDataset
9
+ from transformers import PreTrainedTokenizerBase
10
+
11
+
12
+ class Pooler:
13
+ def __init__(self, pooling_types: List[str]):
14
+ self.pooling_types = pooling_types
15
+ self.pooling_options = {
16
+ 'mean': self.mean_pooling,
17
+ 'max': self.max_pooling,
18
+ 'norm': self.norm_pooling,
19
+ 'median': self.median_pooling,
20
+ 'std': self.std_pooling,
21
+ 'var': self.var_pooling,
22
+ 'cls': self.cls_pooling,
23
+ 'parti': self._pool_parti,
24
+ }
25
+
26
+ def _create_pooled_matrices_across_layers(self, attentions: torch.Tensor) -> torch.Tensor:
27
+ maxed_attentions = torch.max(attentions, dim=1)[0]
28
+ return maxed_attentions
29
+
30
+ def _page_rank(self, attention_matrix, personalization=None, nstart=None, prune_type="top_k_outdegree"):
31
+ # Run PageRank on the attention matrix converted to a graph.
32
+ # Raises exceptions if the graph doesn't match the token sequence or has no edges.
33
+ # Returns the PageRank scores for each token node.
34
+ G = self._convert_to_graph(attention_matrix)
35
+ if G.number_of_nodes() != attention_matrix.shape[0]:
36
+ raise Exception(
37
+ 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.")
38
+ if G.number_of_edges() == 0:
39
+ raise Exception(f"You don't seem to have any attention edges left in the graph.")
40
+
41
+ return nx.pagerank(G, alpha=0.85, tol=1e-06, weight='weight', personalization=personalization, nstart=nstart, max_iter=100)
42
+
43
+ def _convert_to_graph(self, matrix):
44
+ # Convert a matrix (e.g., attention scores) to a directed graph using networkx.
45
+ # Each element in the matrix represents a directed edge with a weight.
46
+ G = nx.from_numpy_array(matrix, create_using=nx.DiGraph)
47
+ return G
48
+
49
+ def _calculate_importance_weights(self, dict_importance, attention_mask: Optional[torch.Tensor] = None):
50
+ # Remove keys where attention_mask is 0
51
+ if attention_mask is not None:
52
+ for k in list(dict_importance.keys()):
53
+ if attention_mask[k] == 0:
54
+ del dict_importance[k]
55
+
56
+ #dict_importance[0] # remove cls
57
+ #dict_importance[-1] # remove eos
58
+ total = sum(dict_importance.values())
59
+ return np.array([v / total for _, v in dict_importance.items()])
60
+
61
+ def _pool_parti(self, emb: torch.Tensor, attentions: torch.Tensor, attention_mask: Optional[torch.Tensor] = None): # (b, L, d) -> (b, d)
62
+ maxed_attentions = self._create_pooled_matrices_across_layers(attentions).numpy()
63
+ # emb is (b, L, d), maxed_attentions is (b, L, L)
64
+ emb_pooled = []
65
+ for e, a, mask in zip(emb, maxed_attentions, attention_mask):
66
+ dict_importance = self._page_rank(a)
67
+ importance_weights = self._calculate_importance_weights(dict_importance, mask)
68
+ num_tokens = int(mask.sum().item())
69
+ emb_pooled.append(np.average(e[:num_tokens], weights=importance_weights, axis=0))
70
+ pooled = torch.tensor(np.array(emb_pooled))
71
+ return pooled
72
+
73
+ def mean_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
74
+ if attention_mask is None:
75
+ return emb.mean(dim=1)
76
+ else:
77
+ attention_mask = attention_mask.unsqueeze(-1)
78
+ return (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1)
79
+
80
+ def max_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
81
+ if attention_mask is None:
82
+ return emb.max(dim=1).values
83
+ else:
84
+ attention_mask = attention_mask.unsqueeze(-1)
85
+ return (emb * attention_mask).max(dim=1).values
86
+
87
+ def norm_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
88
+ if attention_mask is None:
89
+ return emb.norm(dim=1, p=2)
90
+ else:
91
+ attention_mask = attention_mask.unsqueeze(-1)
92
+ return (emb * attention_mask).norm(dim=1, p=2)
93
+
94
+ def median_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
95
+ if attention_mask is None:
96
+ return emb.median(dim=1).values
97
+ else:
98
+ attention_mask = attention_mask.unsqueeze(-1)
99
+ return (emb * attention_mask).median(dim=1).values
100
+
101
+ def std_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
102
+ if attention_mask is None:
103
+ return emb.std(dim=1)
104
+ else:
105
+ # Compute variance correctly over non-masked positions, then take sqrt
106
+ var = self.var_pooling(emb, attention_mask, **kwargs)
107
+ return torch.sqrt(var)
108
+
109
+ def var_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
110
+ if attention_mask is None:
111
+ return emb.var(dim=1)
112
+ else:
113
+ # Correctly compute variance over only non-masked positions
114
+ attention_mask = attention_mask.unsqueeze(-1) # (b, L, 1)
115
+ # Compute mean over non-masked positions
116
+ mean = (emb * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
117
+ mean = mean.unsqueeze(1) # (b, 1, d)
118
+ # Compute squared differences from mean, only over non-masked positions
119
+ squared_diff = (emb - mean) ** 2 # (b, L, d)
120
+ # Sum squared differences over non-masked positions and divide by count
121
+ var = (squared_diff * attention_mask).sum(dim=1) / attention_mask.sum(dim=1) # (b, d)
122
+ return var
123
+
124
+ def cls_pooling(self, emb: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, **kwargs): # (b, L, d) -> (b, d)
125
+ return emb[:, 0, :]
126
+
127
+ def __call__(
128
+ self,
129
+ emb: torch.Tensor,
130
+ attention_mask: Optional[torch.Tensor] = None,
131
+ attentions: Optional[torch.Tensor] = None
132
+ ): # [mean, max]
133
+ final_emb = []
134
+ for pooling_type in self.pooling_types:
135
+ final_emb.append(self.pooling_options[pooling_type](emb=emb, attention_mask=attention_mask, attentions=attentions)) # (b, d)
136
+ return torch.cat(final_emb, dim=-1) # (b, n_pooling_types * d)
137
+
138
+
139
+ class ProteinDataset(TorchDataset):
140
+ """Simple dataset for protein sequences."""
141
+ def __init__(self, sequences: list[str]):
142
+ self.sequences = sequences
143
+
144
+ def __len__(self) -> int:
145
+ return len(self.sequences)
146
+
147
+ def __getitem__(self, idx: int) -> str:
148
+ return self.sequences[idx]
149
+
150
+
151
+ def build_collator(tokenizer: PreTrainedTokenizerBase) -> Callable[[list[str]], dict[str, torch.Tensor]]:
152
+ def _collate_fn(sequences: list[str]) -> dict[str, torch.Tensor]:
153
+ return tokenizer(sequences, return_tensors="pt", padding='longest')
154
+ return _collate_fn
155
+
156
+
157
+ class EmbeddingMixin:
158
+ def _embed(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
159
+ raise NotImplementedError
160
+
161
+ @property
162
+ def device(self) -> torch.device:
163
+ """Get the device of the model."""
164
+ return next(self.parameters()).device
165
+
166
+ def _read_sequences_from_db(self, db_path: str) -> set[str]:
167
+ """Read sequences from SQLite database."""
168
+ import sqlite3
169
+ sequences = []
170
+ with sqlite3.connect(db_path) as conn:
171
+ c = conn.cursor()
172
+ c.execute("SELECT sequence FROM embeddings")
173
+ while True:
174
+ row = c.fetchone()
175
+ if row is None:
176
+ break
177
+ sequences.append(row[0])
178
+ return set(sequences)
179
+
180
+ def embed_dataset(
181
+ self,
182
+ sequences: List[str],
183
+ tokenizer: Optional[PreTrainedTokenizerBase] = None,
184
+ batch_size: int = 2,
185
+ max_len: int = 512,
186
+ truncate: bool = True,
187
+ full_embeddings: bool = False,
188
+ embed_dtype: torch.dtype = torch.float32,
189
+ pooling_types: List[str] = ['mean'],
190
+ num_workers: int = 0,
191
+ sql: bool = False,
192
+ save: bool = True,
193
+ sql_db_path: str = 'embeddings.db',
194
+ save_path: str = 'embeddings.pth',
195
+ **kwargs,
196
+ ) -> Optional[dict[str, torch.Tensor]]:
197
+ """
198
+ Embed a dataset of protein sequences.
199
+
200
+ Supports two modes:
201
+ - Tokenizer mode (ESM2/ESM++): provide `tokenizer`, `_embed(input_ids, attention_mask)` is used.
202
+ - Sequence mode (E1): pass `tokenizer=None`, `_embed(sequences, return_attention_mask=True, **kwargs)` is used.
203
+ """
204
+ sequences = list(set([seq[:max_len] if truncate else seq for seq in sequences]))
205
+ sequences = sorted(sequences, key=len, reverse=True)
206
+ hidden_size = self.config.hidden_size
207
+ pooler = Pooler(pooling_types) if not full_embeddings else None
208
+ tokenizer_mode = tokenizer is not None
209
+ if tokenizer_mode:
210
+ collate_fn = build_collator(tokenizer)
211
+ device = self.device
212
+ else:
213
+ collate_fn = None
214
+ device = None
215
+
216
+ def get_embeddings(residue_embeddings: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
217
+ if full_embeddings or residue_embeddings.ndim == 2:
218
+ return residue_embeddings
219
+ return pooler(residue_embeddings, attention_mask)
220
+
221
+ def iter_batches(to_embed: List[str]):
222
+ if tokenizer_mode:
223
+ assert collate_fn is not None
224
+ assert device is not None
225
+ dataset = ProteinDataset(to_embed)
226
+ dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, collate_fn=collate_fn, shuffle=False)
227
+ for i, batch in tqdm(enumerate(dataloader), total=len(dataloader), desc='Embedding batches'):
228
+ seqs = to_embed[i * batch_size:(i + 1) * batch_size]
229
+ input_ids = batch['input_ids'].to(device)
230
+ attention_mask = batch['attention_mask'].to(device)
231
+ residue_embeddings = self._embed(input_ids, attention_mask)
232
+ yield seqs, residue_embeddings, attention_mask
233
+ else:
234
+ for batch_start in tqdm(range(0, len(to_embed), batch_size), desc='Embedding batches'):
235
+ seqs = to_embed[batch_start:batch_start + batch_size]
236
+ batch_output = self._embed(seqs, return_attention_mask=True, **kwargs)
237
+ assert isinstance(batch_output, tuple), "Sequence mode _embed must return (last_hidden_state, attention_mask)."
238
+ assert len(batch_output) == 2, "Sequence mode _embed must return exactly two values."
239
+ residue_embeddings, attention_mask = batch_output
240
+ assert isinstance(attention_mask, torch.Tensor), "Sequence mode _embed must return attention_mask as a torch.Tensor."
241
+ yield seqs, residue_embeddings, attention_mask
242
+
243
+ if sql:
244
+ import sqlite3
245
+ conn = sqlite3.connect(sql_db_path)
246
+ c = conn.cursor()
247
+ c.execute('CREATE TABLE IF NOT EXISTS embeddings (sequence text PRIMARY KEY, embedding blob)')
248
+ already_embedded = self._read_sequences_from_db(sql_db_path)
249
+ to_embed = [seq for seq in sequences if seq not in already_embedded]
250
+ print(f"Found {len(already_embedded)} already embedded sequences in {sql_db_path}")
251
+ print(f"Embedding {len(to_embed)} new sequences")
252
+ if len(to_embed) > 0:
253
+ with torch.no_grad():
254
+ for i, (seqs, residue_embeddings, attention_mask) in enumerate(iter_batches(to_embed)):
255
+ embeddings = get_embeddings(residue_embeddings, attention_mask).float()
256
+ for seq, emb, mask in zip(seqs, embeddings, attention_mask):
257
+ if full_embeddings:
258
+ emb = emb[mask.bool()].reshape(-1, hidden_size)
259
+ c.execute("INSERT OR REPLACE INTO embeddings VALUES (?, ?)", (seq, emb.cpu().numpy().tobytes()))
260
+ if tokenizer_mode and (i + 1) % 100 == 0:
261
+ conn.commit()
262
+ conn.commit()
263
+ conn.close()
264
+ return None
265
+
266
+ embeddings_dict = {}
267
+ if os.path.exists(save_path):
268
+ embeddings_dict = torch.load(save_path, map_location='cpu', weights_only=True)
269
+ to_embed = [seq for seq in sequences if seq not in embeddings_dict]
270
+ print(f"Found {len(embeddings_dict)} already embedded sequences in {save_path}")
271
+ print(f"Embedding {len(to_embed)} new sequences")
272
+ else:
273
+ to_embed = sequences
274
+ print(f"Embedding {len(to_embed)} new sequences")
275
+
276
+ if len(to_embed) > 0:
277
+ with torch.no_grad():
278
+ for seqs, residue_embeddings, attention_mask in iter_batches(to_embed):
279
+ embeddings = get_embeddings(residue_embeddings, attention_mask).to(embed_dtype)
280
+ for seq, emb, mask in zip(seqs, embeddings, attention_mask):
281
+ if full_embeddings:
282
+ emb = emb[mask.bool()].reshape(-1, hidden_size)
283
+ embeddings_dict[seq] = emb.cpu()
284
+
285
+ if save:
286
+ torch.save(embeddings_dict, save_path)
287
+
288
+ return embeddings_dict
289
+
290
+
291
+ if __name__ == "__main__":
292
+ # py -m pooler
293
+ pooler = Pooler(pooling_types=['max', 'parti'])
294
+ batch_size = 8
295
+ seq_len = 64
296
+ hidden_size = 128
297
+ num_layers = 12
298
+ emb = torch.randn(batch_size, seq_len, hidden_size)
299
+ attentions = torch.randn(batch_size, num_layers, seq_len, seq_len)
300
+ attention_mask = torch.ones(batch_size, seq_len)
301
+ y = pooler(emb=emb, attention_mask=attention_mask, attentions=attentions)
302
+ print(y.shape)