Views
No views yet
1from transformers import AutoTokenizer, AutoModel
2tokenizer = AutoTokenizer.from_pretrained("facebook/esm2_t33_650M_UR50D")
3model = AutoModel.from_pretrained("h4duan/PAIR-esm1b").to("cuda")
4protein = ["AETCZAO"]
5
6def extract_feature(protein):
7 ids = tokenizer(protein, return_tensors="pt", padding=True, max_length=1024, truncation=True, return_attention_mask=True)
8 input_ids = torch.tensor(ids['input_ids']).to("cuda")
9 attention_mask = torch.tensor(ids['attention_mask']).to("cuda")
10 with torch.no_grad():
11 embedding_repr = model(input_ids=input_ids,attention_mask=attention_mask).last_hidden_state
12 return torch.mean(embedding_repr, dim=1)
13
14feature = extract_feature(protein)1proteins = ["AETCZAO","SKTZP"]
2
3def extract_features_batch(proteins):
4 ids = tokenizer(proteins, return_tensors="pt", padding=True, max_length=1024, truncation=True, return_attention_mask=True)
5 input_ids = torch.tensor(ids['input_ids']).to("cuda")
6 attention_mask = torch.tensor(ids['attention_mask']).to("cuda")
7 with torch.no_grad():
8 embedding_repr = model(input_ids=input_ids,attention_mask=attention_mask).last_hidden_state
9 attention_mask = attention_mask.unsqueeze(-1)
10 attention_mask = attention_mask.expand(-1, -1, embedding_repr.size(-1))
11 masked_embedding_repr = embedding_repr * attention_mask
12 sum_embedding_repr = masked_embedding_repr.sum(dim=1)
13 non_zero_count = attention_mask.sum(dim=1)
14 mean_embedding_repr = sum_embedding_repr / non_zero_count
15 return mean_embedding_repr
16
17feature = extract_feature_batch(proteins)