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