-
Notifications
You must be signed in to change notification settings - Fork 2
/
predict_top_sequences.py
211 lines (155 loc) · 7.83 KB
/
predict_top_sequences.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import torch
from transformers import AutoTokenizer, EsmForMaskedLM
from itertools import product
import heapq
def predict_top_full_sequences(sequence: str, mask_positions: list, m: int):
# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
model = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D")
# Create a copy of the sequence for mutation
seq_list = list(sequence)
# Mask the positions
for pos in mask_positions:
seq_list[pos] = tokenizer.mask_token
# Convert the mutated sequence back to string
masked_sequence = "".join(seq_list)
# Tokenize the masked sequence
inputs = tokenizer(masked_sequence, return_tensors="pt")
# Get the model's output
with torch.no_grad():
outputs = model(**inputs)
# Get the logits
logits = outputs.logits
# Get the mask token indices
mask_indices = torch.where(inputs.input_ids.squeeze() == tokenizer.mask_token_id)[0]
# Get the logits for the masked positions
masked_logits = logits[0, mask_indices]
# Apply softmax to logits to get probabilities
masked_probs = torch.nn.functional.softmax(masked_logits, dim=-1)
# Create a list to store the top sequences and their scores
top_sequences = []
# Get all possible combinations of amino acids for the masked positions
amino_acids = tokenizer.get_vocab().keys()
combinations = list(product(amino_acids, repeat=len(mask_positions)))
for combination in combinations:
# Compute the sum of the log probabilities for this combination
score = sum(torch.log(masked_probs[i, tokenizer.convert_tokens_to_ids(a)]) for i, a in enumerate(combination))
# Update the list of top sequences
if len(top_sequences) < m:
# If there's room, just add the current sequence
heapq.heappush(top_sequences, (score.item(), combination))
else:
# If there's no room, replace the lowest-scoring sequence if the current sequence is better
heapq.heappushpop(top_sequences, (score.item(), combination))
# Create the full sequences by replacing the masked positions with the predicted amino acids
scores, top_sequences = zip(*top_sequences)
top_full_sequences = []
for seq in top_sequences:
full_seq_list = list(sequence)
for pos, aa in zip(mask_positions, seq):
full_seq_list[pos] = aa
top_full_sequences.append("".join(full_seq_list))
return scores, top_full_sequences
# Function to predict the bottom m sequences after masking (No Special Tokens)
def predict_bottom_full_sequences_nst(sequence: str, mask_positions: list, m: int):
# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
model = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D")
# Create a copy of the sequence for mutation
seq_list = list(sequence)
# Mask the positions
for pos in mask_positions:
seq_list[pos] = tokenizer.mask_token
# Convert the mutated sequence back to string
masked_sequence = "".join(seq_list)
# Tokenize the masked sequence
inputs = tokenizer(masked_sequence, return_tensors="pt")
# Get the model's output
with torch.no_grad():
outputs = model(**inputs)
# Get the logits
logits = outputs.logits
# Get the mask token indices
mask_indices = torch.where(inputs.input_ids.squeeze() == tokenizer.mask_token_id)[0]
# Get the logits for the masked positions
masked_logits = logits[0, mask_indices]
# Apply softmax to logits to get probabilities
masked_probs = torch.nn.functional.softmax(masked_logits, dim=-1)
# Create a list to store the bottom sequences and their scores
bottom_sequences = []
# Get all possible combinations of amino acids for the masked positions
amino_acids = tokenizer.get_vocab().keys()
combinations = list(product(amino_acids, repeat=len(mask_positions)))
for combination in combinations:
# Exclude sequences with special tokens (No Special Tokens)
if any(aa in ['<cls>', '<pad>', '<eos>', '<unk>', '.', '-', '<null_1>', '<mask>', 'X', 'B', 'U', 'Z', 'O'] for aa in combination):
continue
# Compute the sum of the log probabilities for this combination
score = sum(torch.log(masked_probs[i, tokenizer.convert_tokens_to_ids(a)]) for i, a in enumerate(combination))
# Update the list of bottom sequences
if len(bottom_sequences) < m:
# If there's room, just add the current sequence
heapq.heappush(bottom_sequences, (-score.item(), combination))
else:
# If there's no room, replace the highest-scoring sequence if the current sequence is worse
heapq.heappushpop(bottom_sequences, (-score.item(), combination))
# Create the full sequences by replacing the masked positions with the predicted amino acids
neg_scores, bottom_sequences = zip(*bottom_sequences)
scores = [-1 * neg_score for neg_score in neg_scores]
bottom_full_sequences = []
for seq in bottom_sequences:
full_seq_list = list(sequence)
for pos, aa in zip(mask_positions, seq):
full_seq_list[pos] = aa
bottom_full_sequences.append("".join(full_seq_list))
return scores, bottom_full_sequences
# Includes special tokens
def predict_bottom_full_sequences_st(sequence: str, mask_positions: list, m: int):
# Load the tokenizer and model
tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t6_8M_UR50D")
model = EsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D")
# Create a copy of the sequence for mutation
seq_list = list(sequence)
# Mask the positions
for pos in mask_positions:
seq_list[pos] = tokenizer.mask_token
# Convert the mutated sequence back to string
masked_sequence = "".join(seq_list)
# Tokenize the masked sequence
inputs = tokenizer(masked_sequence, return_tensors="pt")
# Get the model's output
with torch.no_grad():
outputs = model(**inputs)
# Get the logits
logits = outputs.logits
# Get the mask token indices
mask_indices = torch.where(inputs.input_ids.squeeze() == tokenizer.mask_token_id)[0]
# Get the logits for the masked positions
masked_logits = logits[0, mask_indices]
# Apply softmax to logits to get probabilities
masked_probs = torch.nn.functional.softmax(masked_logits, dim=-1)
# Create a list to store the bottom sequences and their scores
bottom_sequences = []
# Get all possible combinations of amino acids for the masked positions
amino_acids = tokenizer.get_vocab().keys()
combinations = list(product(amino_acids, repeat=len(mask_positions)))
for combination in combinations:
# Compute the sum of the log probabilities for this combination
score = sum(torch.log(masked_probs[i, tokenizer.convert_tokens_to_ids(a)]) for i, a in enumerate(combination))
# Update the list of bottom sequences
if len(bottom_sequences) < m:
# If there's room, just add the current sequence
heapq.heappush(bottom_sequences, (-score.item(), combination))
else:
# If there's no room, replace the highest-scoring sequence if the current sequence is worse
heapq.heappushpop(bottom_sequences, (-score.item(), combination))
# Create the full sequences by replacing the masked positions with the predicted amino acids
neg_scores, bottom_sequences = zip(*bottom_sequences)
scores = [-1 * neg_score for neg_score in neg_scores]
bottom_full_sequences = []
for seq in bottom_sequences:
full_seq_list = list(sequence)
for pos, aa in zip(mask_positions, seq):
full_seq_list[pos] = aa
bottom_full_sequences.append("".join(full_seq_list))
return scores, bottom_full_sequences