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