Views
No views yet

1import logging
2import functools
3from tqdm import tqdm
4import torch
5from datasets import load_dataset
6from transformers import AutoModel, AutoTokenizer, AutoConfig
7
8logger = logging.getLogger(__name__)
9
10
11def tokenize_protein(example, protein_tokenizer=None, padding=None):
12 protein_seqs = example["prot_seq"]
13
14 protein_inputs = protein_tokenizer(protein_seqs, padding=padding, add_special_tokens=True)
15 example["protein_input_ids"] = protein_inputs.input_ids
16 example["protein_attention_mask"] = protein_inputs.attention_mask
17
18 return example
19
20
21def label_embedding(labels, text_tokenizer, text_model, device):
22 # embed label descriptions
23 label_feature = []
24 with torch.inference_mode():
25 for label in labels:
26 label_input_ids = text_tokenizer.encode(label, max_length=128,
27 truncation=True, add_special_tokens=False)
28 label_input_ids = [text_tokenizer.cls_token_id] + label_input_ids
29 label_input_ids = torch.tensor(label_input_ids, dtype=torch.long, device=device).unsqueeze(0)
30 attention_mask = label_input_ids != text_tokenizer.pad_token_id
31 attention_mask = attention_mask.to(device)
32
33 text_outputs = text_model(label_input_ids, attention_mask=attention_mask)
34
35 label_feature.append(text_outputs["text_feature"])
36 label_feature = torch.cat(label_feature, dim=0)
37 label_feature = label_feature / label_feature.norm(dim=-1, keepdim=True)
38
39 return label_feature
40
41def zero_shot_eval(logger, device,
42 test_dataset, target_field, protein_model, logit_scale, label_feature):
43
44 # get prediction and target
45 test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=1, shuffle=False)
46 preds, targets = [], []
47 with torch.inference_mode():
48 for data in tqdm(test_dataloader):
49 target = data[target_field]
50 targets.append(target)
51
52 protein_input_ids = torch.tensor(data["protein_input_ids"], dtype=torch.long, device=device).unsqueeze(0)
53 attention_mask = torch.tensor(data["protein_attention_mask"], dtype=torch.long, device=device).unsqueeze(0)
54
55 protein_outputs = protein_model(protein_input_ids, attention_mask=attention_mask)
56
57 protein_feature = protein_outputs["protein_feature"]
58 protein_feature = protein_feature / protein_feature.norm(dim=-1, keepdim=True)
59 pred = logit_scale * protein_feature @ label_feature.t()
60 preds.append(pred)
61
62 preds = torch.cat(preds, dim=0)
63 targets = torch.tensor(targets, dtype=torch.long, device=device)
64 accuracy = (preds.argmax(dim=-1) == targets).float().mean().item()
65 logger.warning("Zero-shot accuracy: %.6f" % accuracy)
66
67
68if __name__ == "__main__":
69 # get datasets
70 raw_datasets = load_dataset("Jiqing/ProtST-SubcellularLocalization", cache_dir="~/.cache/huggingface/datasets", split='test') # cache_dir defaults to "~/.cache/huggingface/datasets"
71
72 #device = torch.device("cuda:0")
73 device = torch.device("cpu")
74
75 protst_model = AutoModel.from_pretrained("Jiqing/ProtST-esm1b", trust_remote_code=True, torch_dtype=torch.bfloat16).to(device)
76 protein_model = protst_model.protein_model
77 + import intel_extension_for_pytorch as ipex
78 + from optimum.intel.generation.modeling import jit_trace
79 + protein_model = ipex.optimize(protein_model, dtype=torch.bfloat16, inplace=True)
80 + protein_model = jit_trace(protein_model, "sequence-classification")
81 text_model = protst_model.text_model
82 logit_scale = protst_model.logit_scale
83 logit_scale.requires_grad = False
84 logit_scale = logit_scale.to(device)
85 logit_scale = logit_scale.exp()
86
87 protein_tokenizer = AutoTokenizer.from_pretrained("facebook/esm1b_t33_650M_UR50S")
88 text_tokenizer = AutoTokenizer.from_pretrained("microsoft/BiomedNLP-PubMedBERT-base-uncased-abstract")
89
90 func_tokenize_protein = functools.partial(tokenize_protein, protein_tokenizer=protein_tokenizer, padding=False)
91 test_dataset = raw_datasets.map(
92 func_tokenize_protein, batched=False,
93 remove_columns=["prot_seq"],
94 desc="Running tokenize_proteins on dataset",
95 )
96
97 labels = load_dataset("Jiqing/subloc_template", cache_dir="~/.cache/huggingface/datasets")["train"]["name"]
98
99 text_tokenizer.encode(labels[0], max_length=128, truncation=True, add_special_tokens=False)
100 label_feature = label_embedding(labels, text_tokenizer, text_model, device)
101 zero_shot_eval(logger, device, test_dataset, "localization",
102 protein_model, logit_scale, label_feature)