|
| 1 | +import numpy |
| 2 | +import torch |
| 3 | +import h5py |
| 4 | +from tqdm import tqdm |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from vespa.predict.config import ( |
| 8 | + DEVICE, CACHE_DIR, VERBOSE, |
| 9 | + EMBED, EMB_MAX_SEQ_LEN, EMB_MAX_RESIDUES, EMB_MAX_BATCH, EMB_STORE_FREQ |
| 10 | +) |
| 11 | +from vespa.predict.utils import parse_fasta_input |
| 12 | +from vespa.predict.utils_t5 import ProtT5 |
| 13 | + |
| 14 | + |
| 15 | +class T5_Embed: |
| 16 | + def __init__(self, cache_dir): |
| 17 | + self.prott5 = ProtT5(cache_dir) |
| 18 | + self.saving_pattern = 'w' |
| 19 | + |
| 20 | + def embed_from_fasta(self, fasta_path, output_path): |
| 21 | + self.saving_pattern = 'w' |
| 22 | + if VERBOSE: |
| 23 | + print('Load model: ProtT5') |
| 24 | + self.model, self.tokenizer = self.prott5.get_model(EMBED) |
| 25 | + if VERBOSE: |
| 26 | + print('Compute embeddings!') |
| 27 | + self.get_embeddings(fasta_path, output_path) |
| 28 | + |
| 29 | + def embedding_init(self, fasta_path): |
| 30 | + seq_dict = parse_fasta_input(fasta_path) |
| 31 | + seq_dict = sorted(seq_dict.items(), key=lambda kv: len(seq_dict[kv[0]]), reverse=True) |
| 32 | + return seq_dict |
| 33 | + |
| 34 | + def process_batch(self, batch, emb_dict): |
| 35 | + pdb_ids, seqs, seq_lens = zip(*batch) |
| 36 | + |
| 37 | + token_encoding = self.tokenizer(seqs, add_special_tokens=True, padding='longest', return_tensors="pt") |
| 38 | + input_ids = token_encoding['input_ids'].to(DEVICE) |
| 39 | + attention_mask = token_encoding['attention_mask'].to(DEVICE) |
| 40 | + |
| 41 | + try: |
| 42 | + # batch-size x seq_len x embedding_dim |
| 43 | + with torch.no_grad(): |
| 44 | + embedding_repr = self.model(input_ids, attention_mask=attention_mask) |
| 45 | + except RuntimeError: |
| 46 | + print("RuntimeError for {} (L={})".format(pdb_ids, seq_lens)) |
| 47 | + return emb_dict |
| 48 | + |
| 49 | + new_emb_dict = dict() |
| 50 | + for batch_idx, identifier in enumerate(pdb_ids): |
| 51 | + s_len = seq_lens[batch_idx] |
| 52 | + emb = embedding_repr.last_hidden_state[batch_idx, :s_len] |
| 53 | + new_emb_dict[identifier] = emb.detach().cpu().numpy().squeeze() |
| 54 | + |
| 55 | + if new_emb_dict: |
| 56 | + emb_dict.update(new_emb_dict) |
| 57 | + return emb_dict |
| 58 | + |
| 59 | + def save_embeddings(self, output_path, emb_dict): |
| 60 | + Path(str(output_path.absolute())).parent.mkdir(parents=True, exist_ok=True) |
| 61 | + with h5py.File(str(output_path.absolute()), self.saving_pattern) as hf: |
| 62 | + for sequence_id, embedding in emb_dict.items(): |
| 63 | + hf.create_dataset(sequence_id, data=embedding) |
| 64 | + self.saving_pattern = 'a' |
| 65 | + |
| 66 | + def get_embeddings(self, fasta_path, output_path): |
| 67 | + seq_dict = self.embedding_init(fasta_path) |
| 68 | + |
| 69 | + emb_dict = dict() |
| 70 | + batch, n_res_batch = [], 0 |
| 71 | + |
| 72 | + for seq_idx, (pdb_id, seq) in tqdm(enumerate(seq_dict, 1), total=len(seq_dict)): |
| 73 | + seq_len = len(seq) |
| 74 | + seq = ' '.join(list(seq)) |
| 75 | + |
| 76 | + if seq_len >= EMB_MAX_SEQ_LEN: |
| 77 | + emb_dict = self.process_batch([(pdb_id, seq, seq_len)], emb_dict) |
| 78 | + else: |
| 79 | + if len(batch) >= EMB_MAX_BATCH or n_res_batch >= EMB_MAX_RESIDUES: |
| 80 | + emb_dict = self.process_batch(batch, emb_dict) |
| 81 | + batch = [] |
| 82 | + n_res_batch = 0 |
| 83 | + |
| 84 | + batch.append((pdb_id, seq, seq_len)) |
| 85 | + n_res_batch += seq_len |
| 86 | + |
| 87 | + if len(emb_dict) > EMB_STORE_FREQ: |
| 88 | + self.save_embeddings(output_path, emb_dict) |
| 89 | + emb_dict = dict() |
| 90 | + |
| 91 | + if batch: |
| 92 | + emb_dict = self.process_batch(batch, emb_dict) |
| 93 | + |
| 94 | + if emb_dict: |
| 95 | + self.save_embeddings(output_path, emb_dict) |
0 commit comments