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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import numpy as np
|
| 4 |
+
import esm
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import os
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
CANONICAL_AAS = list("ACDEFGHIKLMNPQRSTVWY")
|
| 10 |
+
|
| 11 |
+
class EmbeddingToSequenceConverter:
|
| 12 |
+
"""
|
| 13 |
+
Decode contextual ESM2 hidden states to amino-acid sequences via the model's LM head.
|
| 14 |
+
Accepts [L, 1280] or [B, L, 1280] tensors (L≈50 in your pipeline).
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def __init__(self, device="cuda"):
|
| 18 |
+
self.device = torch.device(device if torch.cuda.is_available() else "cpu")
|
| 19 |
+
print("Loading ESM model for sequence decoding...")
|
| 20 |
+
self.model, self.alphabet = esm.pretrained.esm2_t33_650M_UR50D()
|
| 21 |
+
self.model.eval().to(self.device)
|
| 22 |
+
self.aa_list = CANONICAL_AAS
|
| 23 |
+
self.aa_token_ids = torch.tensor(
|
| 24 |
+
[self.alphabet.get_idx(a) for a in self.aa_list],
|
| 25 |
+
device=self.device, dtype=torch.long
|
| 26 |
+
)
|
| 27 |
+
print("✓ ESM model loaded for sequence decoding")
|
| 28 |
+
|
| 29 |
+
@torch.inference_mode()
|
| 30 |
+
def _logits_from_hidden(self, hidden):
|
| 31 |
+
# hidden: [L, D] or [B, L, D]; project exactly as ESM-2 does (LayerNorm → LM head)
|
| 32 |
+
if hidden.dim() == 2:
|
| 33 |
+
hidden = hidden.unsqueeze(0)
|
| 34 |
+
hidden = hidden.to(self.device)
|
| 35 |
+
# match model dtype to avoid dtype mismatches under autocast
|
| 36 |
+
hidden = hidden.to(self.model.lm_head.weight.dtype)
|
| 37 |
+
if hasattr(self.model, "emb_layer_norm_after"):
|
| 38 |
+
hidden = self.model.emb_layer_norm_after(hidden)
|
| 39 |
+
logits_full = self.model.lm_head(hidden) # [B, L, |V|]
|
| 40 |
+
logits_20 = logits_full.index_select(-1, self.aa_token_ids) # [B, L, 20]
|
| 41 |
+
return logits_20
|
| 42 |
+
|
| 43 |
+
@torch.inference_mode()
|
| 44 |
+
def embedding_to_sequence(self, embedding, method="diverse", temperature=0.8, top_p=0.9, top_k=0, seed=None, return_conf=False):
|
| 45 |
+
logits = self._logits_from_hidden(embedding) # [1, L, 20]
|
| 46 |
+
if method in ("nearest", "nearest_neighbor"):
|
| 47 |
+
idx = logits.argmax(-1)[0]
|
| 48 |
+
probs = logits.softmax(-1)[0]
|
| 49 |
+
else:
|
| 50 |
+
if seed is not None:
|
| 51 |
+
torch.manual_seed(seed)
|
| 52 |
+
if temperature and temperature > 0:
|
| 53 |
+
logits = logits / temperature
|
| 54 |
+
probs = logits.softmax(-1)[0] # [L, 20]
|
| 55 |
+
V = probs.size(-1)
|
| 56 |
+
if top_k and top_k < V:
|
| 57 |
+
kth = torch.topk(probs, top_k, dim=-1).values[..., -1:]
|
| 58 |
+
probs = torch.where(probs >= kth, probs, torch.zeros_like(probs))
|
| 59 |
+
probs = probs / probs.sum(-1, keepdim=True).clamp_min(1e-12)
|
| 60 |
+
if top_p and 0 < top_p < 1:
|
| 61 |
+
sorted_probs, sorted_idx = torch.sort(probs, descending=True, dim=-1)
|
| 62 |
+
cum = sorted_probs.cumsum(-1)
|
| 63 |
+
mask = cum > top_p
|
| 64 |
+
mask[..., 0] = False
|
| 65 |
+
sorted_probs = sorted_probs.masked_fill(mask, 0)
|
| 66 |
+
sorted_probs = sorted_probs / sorted_probs.sum(-1, keepdim=True).clamp_min(1e-12)
|
| 67 |
+
samples = torch.multinomial(sorted_probs, 1).squeeze(-1)
|
| 68 |
+
idx = sorted_idx.gather(-1, samples.unsqueeze(-1)).squeeze(-1)
|
| 69 |
+
else:
|
| 70 |
+
idx = torch.multinomial(probs, 1).squeeze(-1)
|
| 71 |
+
seq = "".join(self.aa_list[i] for i in idx.tolist())
|
| 72 |
+
if return_conf:
|
| 73 |
+
conf = probs.max(-1).values.mean().item() # avg per-pos max prob
|
| 74 |
+
return seq, conf
|
| 75 |
+
return seq
|
| 76 |
+
|
| 77 |
+
@torch.inference_mode()
|
| 78 |
+
def batch_embedding_to_sequences(self, embeddings, method="diverse", temperature=0.8, top_p=0.9, top_k=0, seed=None, return_conf=False, max_tokens=100_000):
|
| 79 |
+
if embeddings.dim() == 2:
|
| 80 |
+
return [self.embedding_to_sequence(embeddings, method, temperature, top_p, top_k, seed, return_conf)]
|
| 81 |
+
B, L, V = embeddings.shape
|
| 82 |
+
if seed is not None:
|
| 83 |
+
torch.manual_seed(seed)
|
| 84 |
+
# Batched logits to avoid OOM
|
| 85 |
+
logits = []
|
| 86 |
+
start = 0
|
| 87 |
+
while start < B:
|
| 88 |
+
chunk_bs = max(1, min(B - start, max_tokens // L))
|
| 89 |
+
logits.append(self._logits_from_hidden(embeddings[start:start+chunk_bs]))
|
| 90 |
+
start += chunk_bs
|
| 91 |
+
logits = torch.cat(logits, dim=0) # [B, L, 20]
|
| 92 |
+
if method in ("nearest", "nearest_neighbor"):
|
| 93 |
+
idx = logits.argmax(-1) # [B, L]
|
| 94 |
+
probs = logits.softmax(-1)
|
| 95 |
+
else:
|
| 96 |
+
if temperature and temperature > 0:
|
| 97 |
+
logits = logits / temperature
|
| 98 |
+
probs = logits.softmax(-1) # [B, L, 20]
|
| 99 |
+
B, L, V = probs.shape
|
| 100 |
+
if top_k and top_k < V:
|
| 101 |
+
kth = torch.topk(probs, top_k, dim=-1).values[..., -1:].expand_as(probs)
|
| 102 |
+
probs = torch.where(probs >= kth, probs, torch.zeros_like(probs))
|
| 103 |
+
probs = probs / probs.sum(-1, keepdim=True).clamp_min(1e-12)
|
| 104 |
+
if top_p and 0 < top_p < 1:
|
| 105 |
+
flat = probs.view(-1, V)
|
| 106 |
+
sorted_probs, sorted_idx = torch.sort(flat, descending=True, dim=-1)
|
| 107 |
+
cum = sorted_probs.cumsum(-1)
|
| 108 |
+
mask = cum > top_p
|
| 109 |
+
mask[:, 0] = False
|
| 110 |
+
sorted_probs = sorted_probs.masked_fill(mask, 0)
|
| 111 |
+
sorted_probs = sorted_probs / sorted_probs.sum(-1, keepdim=True).clamp_min(1e-12)
|
| 112 |
+
samples = torch.multinomial(sorted_probs, 1) # [B*L, 1]
|
| 113 |
+
idx = sorted_idx.gather(-1, samples).view(B, L) # [B, L]
|
| 114 |
+
else:
|
| 115 |
+
idx = torch.multinomial(probs.view(-1, V), 1).view(B, L)
|
| 116 |
+
seqs = ["".join(self.aa_list[i] for i in row.tolist()) for row in idx]
|
| 117 |
+
if return_conf:
|
| 118 |
+
conf = probs.max(-1).values.mean(-1).tolist() # [B]
|
| 119 |
+
return list(zip(seqs, conf))
|
| 120 |
+
return seqs
|
| 121 |
+
def validate_sequence(self, s):
|
| 122 |
+
return all(a in set(self.aa_list) for a in s)
|
| 123 |
+
|
| 124 |
+
def filter_valid_sequences(self, sequences):
|
| 125 |
+
valid = []
|
| 126 |
+
for seq in sequences:
|
| 127 |
+
if self.validate_sequence(seq):
|
| 128 |
+
valid.append(seq)
|
| 129 |
+
else:
|
| 130 |
+
print(f"Warning: Invalid sequence found: {seq}")
|
| 131 |
+
return valid
|
| 132 |
+
|
| 133 |
+
def main():
|
| 134 |
+
"""
|
| 135 |
+
Decode all CFG-generated peptide embeddings to sequences and analyze distribution.
|
| 136 |
+
Uses the best trained model (loss: 0.017183, step: 53).
|
| 137 |
+
"""
|
| 138 |
+
print("=== CFG-Generated Peptide Sequence Decoder (Best Model) ===")
|
| 139 |
+
|
| 140 |
+
# Initialize converter
|
| 141 |
+
converter = EmbeddingToSequenceConverter()
|
| 142 |
+
|
| 143 |
+
# Get today's date for filename
|
| 144 |
+
today = datetime.now().strftime('%Y%m%d')
|
| 145 |
+
|
| 146 |
+
# Load all CFG-generated embeddings (using best model)
|
| 147 |
+
cfg_files = {
|
| 148 |
+
'No CFG (0.0)': f'/data2/edwardsun/generated_samples/generated_amps_best_model_no_cfg_{today}.pt',
|
| 149 |
+
'Weak CFG (3.0)': f'/data2/edwardsun/generated_samples/generated_amps_best_model_weak_cfg_{today}.pt',
|
| 150 |
+
'Strong CFG (7.5)': f'/data2/edwardsun/generated_samples/generated_amps_best_model_strong_cfg_{today}.pt',
|
| 151 |
+
'Very Strong CFG (15.0)': f'/data2/edwardsun/generated_samples/generated_amps_best_model_very_strong_cfg_{today}.pt'
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
all_results = {}
|
| 155 |
+
|
| 156 |
+
for cfg_name, file_path in cfg_files.items():
|
| 157 |
+
print(f"\n{'='*50}")
|
| 158 |
+
print(f"Processing {cfg_name}...")
|
| 159 |
+
print(f"Loading: {file_path}")
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
# Load embeddings
|
| 163 |
+
embeddings = torch.load(file_path, map_location='cpu')
|
| 164 |
+
print(f"✓ Loaded {len(embeddings)} embeddings, shape: {embeddings.shape}")
|
| 165 |
+
|
| 166 |
+
# Decode to sequences using diverse method
|
| 167 |
+
print(f"Decoding sequences...")
|
| 168 |
+
sequences = converter.batch_embedding_to_sequences(embeddings, method='diverse', temperature=0.5)
|
| 169 |
+
|
| 170 |
+
# Filter valid sequences
|
| 171 |
+
valid_sequences = converter.filter_valid_sequences(sequences)
|
| 172 |
+
print(f"✓ Valid sequences: {len(valid_sequences)}/{len(sequences)}")
|
| 173 |
+
|
| 174 |
+
# Store results
|
| 175 |
+
all_results[cfg_name] = {
|
| 176 |
+
'sequences': valid_sequences,
|
| 177 |
+
'total': len(sequences),
|
| 178 |
+
'valid': len(valid_sequences)
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
# Show sample sequences
|
| 182 |
+
print(f"\nSample sequences ({cfg_name}):")
|
| 183 |
+
for i, seq in enumerate(valid_sequences[:5]):
|
| 184 |
+
print(f" {i+1}: {seq}")
|
| 185 |
+
|
| 186 |
+
except Exception as e:
|
| 187 |
+
print(f"❌ Error processing {file_path}: {e}")
|
| 188 |
+
all_results[cfg_name] = {'sequences': [], 'total': 0, 'valid': 0}
|
| 189 |
+
|
| 190 |
+
# Analysis and comparison
|
| 191 |
+
print(f"\n{'='*60}")
|
| 192 |
+
print("CFG ANALYSIS SUMMARY")
|
| 193 |
+
print(f"{'='*60}")
|
| 194 |
+
|
| 195 |
+
for cfg_name, results in all_results.items():
|
| 196 |
+
sequences = results['sequences']
|
| 197 |
+
if sequences:
|
| 198 |
+
# Calculate sequence statistics
|
| 199 |
+
lengths = [len(seq) for seq in sequences]
|
| 200 |
+
avg_length = np.mean(lengths)
|
| 201 |
+
std_length = np.std(lengths)
|
| 202 |
+
|
| 203 |
+
# Calculate amino acid composition
|
| 204 |
+
all_aas = ''.join(sequences)
|
| 205 |
+
aa_counts = {}
|
| 206 |
+
for aa in 'ACDEFGHIKLMNPQRSTVWY':
|
| 207 |
+
aa_counts[aa] = all_aas.count(aa)
|
| 208 |
+
|
| 209 |
+
# Calculate diversity (unique sequences)
|
| 210 |
+
unique_sequences = len(set(sequences))
|
| 211 |
+
diversity_ratio = unique_sequences / len(sequences)
|
| 212 |
+
|
| 213 |
+
print(f"\n{cfg_name}:")
|
| 214 |
+
print(f" Total sequences: {results['total']}")
|
| 215 |
+
print(f" Valid sequences: {results['valid']}")
|
| 216 |
+
print(f" Unique sequences: {unique_sequences}")
|
| 217 |
+
print(f" Diversity ratio: {diversity_ratio:.3f}")
|
| 218 |
+
print(f" Avg length: {avg_length:.1f} ± {std_length:.1f}")
|
| 219 |
+
print(f" Length range: {min(lengths)}-{max(lengths)}")
|
| 220 |
+
|
| 221 |
+
# Show top amino acids
|
| 222 |
+
sorted_aas = sorted(aa_counts.items(), key=lambda x: x[1], reverse=True)
|
| 223 |
+
print(f" Top 5 AAs: {', '.join([f'{aa}({count})' for aa, count in sorted_aas[:5]])}")
|
| 224 |
+
|
| 225 |
+
# Create output directory if it doesn't exist
|
| 226 |
+
output_dir = '/data2/edwardsun/decoded_sequences'
|
| 227 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 228 |
+
|
| 229 |
+
# Save sequences to file with date
|
| 230 |
+
output_file = os.path.join(output_dir, f"decoded_sequences_{cfg_name.lower().replace(' ', '_').replace('(', '').replace(')', '').replace('.', '')}_{today}.txt")
|
| 231 |
+
with open(output_file, 'w') as f:
|
| 232 |
+
f.write(f"# Decoded sequences from {cfg_name}\n")
|
| 233 |
+
f.write(f"# Total: {results['total']}, Valid: {results['valid']}, Unique: {unique_sequences}\n")
|
| 234 |
+
f.write(f"# Generated from best model (loss: 0.017183, step: 53)\n\n")
|
| 235 |
+
for i, seq in enumerate(sequences):
|
| 236 |
+
f.write(f"seq_{i+1:03d}\t{seq}\n")
|
| 237 |
+
print(f" ✓ Saved to: {output_file}")
|
| 238 |
+
|
| 239 |
+
# Overall comparison
|
| 240 |
+
print(f"\n{'='*60}")
|
| 241 |
+
print("OVERALL COMPARISON")
|
| 242 |
+
print(f"{'='*60}")
|
| 243 |
+
|
| 244 |
+
cfg_names = list(all_results.keys())
|
| 245 |
+
valid_counts = [all_results[name]['valid'] for name in cfg_names]
|
| 246 |
+
unique_counts = [len(set(all_results[name]['sequences'])) for name in cfg_names]
|
| 247 |
+
|
| 248 |
+
print(f"Valid sequences: {dict(zip(cfg_names, valid_counts))}")
|
| 249 |
+
print(f"Unique sequences: {dict(zip(cfg_names, unique_counts))}")
|
| 250 |
+
|
| 251 |
+
# Find most diverse and most similar
|
| 252 |
+
if all(valid_counts):
|
| 253 |
+
diversity_ratios = [unique_counts[i]/valid_counts[i] for i in range(len(valid_counts))]
|
| 254 |
+
most_diverse = cfg_names[diversity_ratios.index(max(diversity_ratios))]
|
| 255 |
+
least_diverse = cfg_names[diversity_ratios.index(min(diversity_ratios))]
|
| 256 |
+
|
| 257 |
+
print(f"\nMost diverse: {most_diverse} (ratio: {max(diversity_ratios):.3f})")
|
| 258 |
+
print(f"Least diverse: {least_diverse} (ratio: {min(diversity_ratios):.3f})")
|
| 259 |
+
|
| 260 |
+
print(f"\n✓ Decoding complete! Check the output files for detailed sequences.")
|
| 261 |
+
|
| 262 |
+
if __name__ == "__main__":
|
| 263 |
+
main()
|