| | import os |
| | import sys |
| | import torch |
| | import json |
| | import argparse |
| | import numpy as np |
| | import pandas as pd |
| | from torch.utils.data import Dataset, DataLoader |
| | from tqdm import tqdm |
| | from Bio import SeqIO |
| | from transformers import AutoTokenizer |
| |
|
| | |
| | sys.path.append(os.path.join(os.path.dirname(__file__), 'src')) |
| | from model import TaxonomyAwareESM |
| |
|
| | class InferenceDataset(Dataset): |
| | def __init__(self, fasta_path, species_vector_path, max_len=1024, esm_tokenizer=None): |
| | self.max_len = max_len |
| | self.tokenizer = esm_tokenizer |
| | |
| | |
| | print(f"Loading species vectors from {species_vector_path}...") |
| | self.tax_vectors = {} |
| | with open(species_vector_path, 'r') as f: |
| | for line in f: |
| | parts = line.strip().split('\t') |
| | if len(parts) >= 2: |
| | tax_id = int(parts[0]) |
| | vector_str = parts[1] |
| | vector = json.loads(vector_str) |
| | self.tax_vectors[tax_id] = vector |
| | |
| | |
| | print(f"Indexing sequences from {fasta_path}...") |
| | self.ids = [] |
| | self.tax_ids = [] |
| | self.seqs = [] |
| | |
| | |
| | for record in SeqIO.parse(fasta_path, "fasta"): |
| | entry_id = self._parse_entry_id(record.id) |
| | tax_id = self._parse_tax_id(record.description) |
| | |
| | if tax_id is None or tax_id not in self.tax_vectors: |
| | |
| | |
| | tax_id = -1 |
| | |
| | self.ids.append(entry_id) |
| | self.tax_ids.append(tax_id) |
| | self.seqs.append(str(record.seq)) |
| | |
| | print(f"Loaded {len(self.ids)} sequences.") |
| |
|
| | def _parse_entry_id(self, header_id): |
| | |
| | parts = header_id.split('|') |
| | if len(parts) >= 2: |
| | return parts[1] |
| | return header_id |
| |
|
| | def _parse_tax_id(self, header_desc): |
| | try: |
| | if "OX=" in header_desc: |
| | part = header_desc.split("OX=")[1].split(" ")[0] |
| | return int(part) |
| | parts = header_desc.split() |
| | if len(parts) >= 2: |
| | potential_taxid = parts[1] |
| | if potential_taxid.isdigit(): |
| | return int(potential_taxid) |
| | return None |
| | except Exception: |
| | return None |
| |
|
| | def __len__(self): |
| | return len(self.ids) |
| |
|
| | def __getitem__(self, idx): |
| | seq_str = self.seqs[idx] |
| | tax_id = self.tax_ids[idx] |
| | entry_id = self.ids[idx] |
| | |
| | encoded = self.tokenizer( |
| | seq_str, |
| | padding=False, |
| | truncation=True, |
| | max_length=self.max_len, |
| | return_tensors='pt' |
| | ) |
| | |
| | input_ids = encoded['input_ids'].squeeze(0) |
| | attention_mask = encoded['attention_mask'].squeeze(0) |
| | |
| | if tax_id in self.tax_vectors: |
| | tax_vector = torch.tensor(self.tax_vectors[tax_id], dtype=torch.long) |
| | else: |
| | tax_vector = torch.zeros(7, dtype=torch.long) |
| | |
| | return { |
| | 'input_ids': input_ids, |
| | 'attention_mask': attention_mask, |
| | 'tax_vector': tax_vector, |
| | 'entry_id': entry_id |
| | } |
| |
|
| | def get_vocab_sizes(species_vector_path): |
| | |
| | |
| | tax_ranks = ["phylum", "class", "order", "family", "genus", "species", "subspecies"] |
| | vocab_sizes = [] |
| | |
| | vector_dir = os.path.dirname(species_vector_path) |
| | vocab_dir = os.path.join(vector_dir, "vocab") |
| | |
| | print(f"Loading taxonomy vocabs from {vocab_dir}...") |
| | for rank in tax_ranks: |
| | v_path = os.path.join(vocab_dir, f"{rank}_vocab.json") |
| | if os.path.exists(v_path): |
| | with open(v_path, 'r') as f: |
| | v_map = json.load(f) |
| | vocab_sizes.append(len(v_map) + 1) |
| | else: |
| | print(f"Warning: Vocab file {v_path} not found. Using default 1000.") |
| | vocab_sizes.append(1000) |
| | return vocab_sizes |
| |
|
| | def main(): |
| | parser = argparse.ArgumentParser() |
| | parser.add_argument("--test_fasta", type=str, required=True) |
| | parser.add_argument("--model_path", type=str, required=True) |
| | parser.add_argument("--output_file", type=str, required=True) |
| | parser.add_argument("--go_json", type=str, default="src/go_terms.json") |
| | parser.add_argument("--species_vec", type=str, default="dataset/taxon_embedding/species_vectors.tsv") |
| | parser.add_argument("--batch_size", type=int, default=256) |
| | parser.add_argument("--lora_rank", type=int, default=512) |
| | parser.add_argument("--dry_run", action="store_true") |
| | |
| | parser.add_argument("--num_workers", type=int, default=8) |
| | |
| | args = parser.parse_args() |
| | |
| | device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| | print(f"Using device: {device}") |
| | |
| | |
| | print(f"Loading GO terms from {args.go_json}...") |
| | with open(args.go_json, 'r') as f: |
| | go_to_idx = json.load(f) |
| | idx_to_go = {v: k for k, v in go_to_idx.items()} |
| | num_classes = len(go_to_idx) |
| | |
| | |
| | vocab_sizes = get_vocab_sizes(args.species_vec) |
| | print(f"Vocab Sizes: {vocab_sizes}") |
| | |
| | |
| | print("Initialize Model...") |
| | |
| | |
| | |
| | model = TaxonomyAwareESM( |
| | num_classes=num_classes, |
| | pretrained_model_name="facebook/esm2_t33_650M_UR50D", |
| | use_lora=True, |
| | lora_rank=args.lora_rank, |
| | vocab_sizes=vocab_sizes |
| | ) |
| | |
| | |
| | print(f"Loading weights from {args.model_path}...") |
| | checkpoint = torch.load(args.model_path, map_location=device) |
| | |
| | if 'model_state_dict' in checkpoint: |
| | state_dict = checkpoint['model_state_dict'] |
| | else: |
| | state_dict = checkpoint |
| | |
| | model.load_state_dict(state_dict) |
| | model.to(device) |
| | model.eval() |
| | |
| | |
| | tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t33_650M_UR50D") |
| | |
| | |
| | dataset = InferenceDataset( |
| | args.test_fasta, |
| | args.species_vec, |
| | esm_tokenizer=tokenizer |
| | ) |
| | |
| | |
| | def collate_fn(batch): |
| | |
| | input_ids = [item['input_ids'] for item in batch] |
| | attention_mask = [item['attention_mask'] for item in batch] |
| | tax_vectors = [item['tax_vector'] for item in batch] |
| | entry_ids = [item['entry_id'] for item in batch] |
| | |
| | |
| | input_ids_padded = torch.nn.utils.rnn.pad_sequence(input_ids, batch_first=True, padding_value=tokenizer.pad_token_id) |
| | attention_mask_padded = torch.nn.utils.rnn.pad_sequence(attention_mask, batch_first=True, padding_value=0) |
| | |
| | tax_vectors_stacked = torch.stack(tax_vectors) |
| | |
| | return { |
| | 'input_ids': input_ids_padded, |
| | 'attention_mask': attention_mask_padded, |
| | 'tax_vector': tax_vectors_stacked, |
| | 'entry_id': entry_ids |
| | } |
| |
|
| | loader = DataLoader( |
| | dataset, |
| | batch_size=args.batch_size, |
| | shuffle=False, |
| | num_workers=args.num_workers, |
| | pin_memory=True, |
| | collate_fn=collate_fn, |
| | persistent_workers=True if args.num_workers > 0 else False, |
| | prefetch_factor=2 if args.num_workers > 0 else None |
| | ) |
| | |
| |
|
| | |
| | print(f"Starting Inference on {len(dataset)} sequences...") |
| | |
| | |
| | buffer = [] |
| | BUFFER_SIZE = 10000 |
| | |
| | os.makedirs(os.path.dirname(os.path.abspath(args.output_file)), exist_ok=True) |
| | |
| | |
| | scaler = torch.cuda.amp.GradScaler() |
| | |
| | with open(args.output_file, 'w') as f: |
| | with torch.no_grad(): |
| | for i, batch in enumerate(tqdm(loader)): |
| | if args.dry_run and i >= 2: |
| | break |
| | |
| | input_ids = batch['input_ids'].to(device) |
| | attention_mask = batch['attention_mask'].to(device) |
| | tax_vector = batch['tax_vector'].to(device) |
| | entry_ids = batch['entry_id'] |
| | |
| | |
| | with torch.cuda.amp.autocast(): |
| | logits = model(input_ids, attention_mask, tax_vector) |
| | probs = torch.sigmoid(logits) |
| | |
| | probs = probs.float().cpu().numpy() |
| | |
| | for j, entry_id in enumerate(entry_ids): |
| | row_probs = probs[j] |
| | |
| | top_k = 500 |
| | if len(row_probs) <= top_k: |
| | top_indices = np.argsort(row_probs)[::-1] |
| | else: |
| | |
| | ind = np.argpartition(row_probs, -top_k)[-top_k:] |
| | |
| | top_indices = ind[np.argsort(row_probs[ind])][::-1] |
| |
|
| | for idx in top_indices: |
| | score = row_probs[idx] |
| | if score > 0.0: |
| | term = idx_to_go[idx] |
| | |
| | buffer.append(f"{entry_id}\t{term}\t{score:.5f}\n") |
| | |
| | if len(buffer) >= BUFFER_SIZE: |
| | f.writelines(buffer) |
| | buffer = [] |
| | |
| | |
| | if buffer: |
| | f.writelines(buffer) |
| | |
| | print(f"Done. Predictions saved to {args.output_file}") |
| |
|
| |
|
| | if __name__ == "__main__": |
| | main() |
| |
|