lhallee commited on
Commit
56152c9
·
verified ·
1 Parent(s): 97fcc38

Upload modeling_dplm.py with huggingface_hub

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