Views
No views yet

1from transformers import T5Tokenizer, T5EncoderModel
2import torch
3device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
4
5# Load the tokenizer
6tokenizer = T5Tokenizer.from_pretrained('Rostlab/ProstT5', do_lower_case=False).to(device)
7
8# Load the model
9model = T5EncoderModel.from_pretrained("Rostlab/ProstT5").to(device)
10
11# only GPUs support half-precision currently; if you want to run on CPU use full-precision (not recommended, much slower)
12model.full() if device=='cpu' else model.half()
13
14# prepare your protein sequences/structures as a list. Amino acid sequences are expected to be upper-case ("PRTEINO" below) while 3Di-sequences need to be lower-case ("strctr" below).
15sequence_examples = ["PRTEINO", "strct"]
16
17# replace all rare/ambiguous amino acids by X (3Di sequences does not have those) and introduce white-space between all sequences (AAs and 3Di)
18sequence_examples = [" ".join(list(re.sub(r"[UZOB]", "X", sequence))) for sequence in sequence_examples]
19
20# add pre-fixes accordingly (this already expects 3Di-sequences to be lower-case)
21# if you go from AAs to 3Di (or if you want to embed AAs), you need to prepend "<AA2fold>"
22# if you go from 3Di to AAs (or if you want to embed 3Di), you need to prepend "<fold2AA>"
23sequence_examples = [ "<AA2fold>" + " " + s if s.isupper() else "<fold2AA>" + " " + s
24 for s in sequence_examples
25 ]
26
27# tokenize sequences and pad up to the longest sequence in the batch
28ids = tokenizer.batch_encode_plus(sequences_example, add_special_tokens=True, padding="longest",return_tensors='pt').to(device))
29
30# generate embeddings
31with torch.no_grad():
32 embedding_rpr = model(
33 ids.input_ids,
34 attention_mask=ids.attention_mask
35 )
36
37# extract residue embeddings for the first ([0,:]) sequence in the batch and remove padded & special tokens, incl. prefix ([0,1:8])
38emb_0 = embedding_repr.last_hidden_state[0,1:8] # shape (7 x 1024)
39# same for the second ([1,:]) sequence but taking into account different sequence lengths ([1,:6])
40emb_1 = embedding_repr.last_hidden_state[1,1:6] # shape (5 x 1024)
41
42# if you want to derive a single representation (per-protein embedding) for the whole protein
43emb_0_per_protein = emb_0.mean(dim=0) # shape (1024)1from transformers import T5Tokenizer, AutoModelForSeq2SeqLM
2import torch
3device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
4
5# Load the tokenizer
6tokenizer = T5Tokenizer.from_pretrained('Rostlab/ProstT5', do_lower_case=False).to(device)
7
8# Load the model
9model = AutoModelForSeq2SeqLM.from_pretrained("Rostlab/ProstT5").to(device)
10
11# only GPUs support half-precision currently; if you want to run on CPU use full-precision (not recommended, much slower)
12model.full() if device=='cpu' else model.half()
13
14# prepare your protein sequences/structures as a list.
15# Amino acid sequences are expected to be upper-case ("PRTEINO" below)
16# while 3Di-sequences need to be lower-case.
17sequence_examples = ["PRTEINO", "SEQWENCE"]
18min_len = min([ len(s) for s in folding_example])
19max_len = max([ len(s) for s in folding_example])
20
21# replace all rare/ambiguous amino acids by X (3Di sequences does not have those) and introduce white-space between all sequences (AAs and 3Di)
22sequence_examples = [" ".join(list(re.sub(r"[UZOB]", "X", sequence))) for sequence in sequence_examples]
23
24# add pre-fixes accordingly. For the translation from AAs to 3Di, you need to prepend "<AA2fold>"
25sequence_examples = [ "<AA2fold>" + " " + s for s in sequence_examples]
26
27# tokenize sequences and pad up to the longest sequence in the batch
28ids = tokenizer.batch_encode_plus(sequences_example,
29 add_special_tokens=True,
30 padding="longest",
31 return_tensors='pt').to(device))
32
33# Generation configuration for "folding" (AA-->3Di)
34gen_kwargs_aa2fold = {
35 "do_sample": True,
36 "num_beams": 3,
37 "top_p" : 0.95,
38 "temperature" : 1.2,
39 "top_k" : 6,
40 "repetition_penalty" : 1.2,
41}
42
43# translate from AA to 3Di (AA-->3Di)
44with torch.no_grad():
45 translations = model.generate(
46 ids.input_ids,
47 attention_mask=ids.attention_mask,
48 max_length=max_len, # max length of generated text
49 min_length=min_len, # minimum length of the generated text
50 early_stopping=True, # stop early if end-of-text token is generated
51 num_return_sequences=1, # return only a single sequence
52 **gen_kwargs_aa2fold
53 )
54# Decode and remove white-spaces between tokens
55decoded_translations = tokenizer.batch_decode( translations, skip_special_tokens=True )
56structure_sequences = [ "".join(ts.split(" ")) for ts in decoded_translations ] # predicted 3Di strings
57
58# Now we can use the same model and invert the translation logic
59# to generate an amino acid sequence from the predicted 3Di-sequence (3Di-->AA)
60
61# add pre-fixes accordingly. For the translation from 3Di to AA (3Di-->AA), you need to prepend "<fold2AA>"
62sequence_examples_backtranslation = [ "<fold2AA>" + " " + s for s in decoded_translations]
63
64# tokenize sequences and pad up to the longest sequence in the batch
65ids_backtranslation = tokenizer.batch_encode_plus(sequence_examples_backtranslation,
66 add_special_tokens=True,
67 padding="longest",
68 return_tensors='pt').to(device))
69
70# Example generation configuration for "inverse folding" (3Di-->AA)
71gen_kwargs_fold2AA = {
72 "do_sample": True,
73 "top_p" : 0.90,
74 "temperature" : 1.1,
75 "top_k" : 6,
76 "repetition_penalty" : 1.2,
77}
78
79# translate from 3Di to AA (3Di-->AA)
80with torch.no_grad():
81 backtranslations = model.generate(
82 ids_backtranslation.input_ids,
83 attention_mask=ids_backtranslation.attention_mask,
84 max_length=max_len, # max length of generated text
85 min_length=min_len, # minimum length of the generated text
86 early_stopping=True, # stop early if end-of-text token is generated
87 num_return_sequences=1, # return only a single sequence
88 **gen_kwargs_fold2AA
89 )
90# Decode and remove white-spaces between tokens
91decoded_backtranslations = tokenizer.batch_decode( backtranslations, skip_special_tokens=True )
92aminoAcid_sequences = [ "".join(ts.split(" ")) for ts in decoded_backtranslations ] # predicted amino acid strings
93