Views
No views yet
RNA-TorsionBERTRNA-TorsionBERT is a 86.9 MB parameter BERT-based language model that predicts RNA torsional and pseudo-torsional angles from the sequence.RNA-TorsionBERT is a DNABERT model that was pre-trained on ~4200 RNA structures.RNA-TorsionBERT by using the following code snippet:1from transformers import AutoModel, AutoTokenizer
2
3tokenizer = AutoTokenizer.from_pretrained("sayby/rna_torsionbert", trust_remote_code=True)
4model = AutoModel.from_pretrained("sayby/rna_torsionbert", trust_remote_code=True)
5
6sequence = "ACG CGG GGT GTT"
7params_tokenizer = {
8 "return_tensors": "pt",
9 "padding": "max_length",
10 "max_length": 512,
11 "truncation": True,
12}
13inputs = tokenizer(sequence, **params_tokenizer)
14output = model(inputs)["logits"]U should therefore be replaced by T in the input sequence.alpha, beta,gamma,delta,epsilon,zeta,chi,eta,theta,eta',theta',v0,v1,v2,v3,v4.1import transformers
2from transformers import AutoModel, AutoTokenizer
3import numpy as np
4import pandas as pd
5from typing import Optional, Dict
6import os
7
8os.environ["TOKENIZERS_PARALLELISM"] = "false"
9
10transformers.logging.set_verbosity_error()
11
12
13BACKBONE = [
14 "alpha",
15 "beta",
16 "gamma",
17 "delta",
18 "epsilon",
19 "zeta",
20 "chi",
21 "eta",
22 "theta",
23 "eta'",
24 "theta'",
25 "v0",
26 "v1",
27 "v2",
28 "v3",
29 "v4",
30]
31
32
33class RNATorsionBERTHelper:
34 def __init__(self):
35 self.model_name = "sayby/rna_torsionbert"
36 self.tokenizer = AutoTokenizer.from_pretrained(
37 self.model_name, trust_remote_code=True
38 )
39 self.params_tokenizer = {
40 "return_tensors": "pt",
41 "padding": "max_length",
42 "max_length": 512,
43 "truncation": True,
44 }
45 self.model = AutoModel.from_pretrained(self.model_name, trust_remote_code=True)
46
47 def predict(self, sequence: str):
48 sequence_tok = self.convert_raw_sequence_to_k_mers(sequence)
49 inputs = self.tokenizer(sequence_tok, **self.params_tokenizer)
50 outputs = self.model(inputs)["logits"]
51 outputs = self.convert_sin_cos_to_angles(
52 outputs.cpu().detach().numpy(), inputs["input_ids"]
53 )
54 output_angles = self.convert_logits_to_dict(
55 outputs[0, :], inputs["input_ids"][0, :].cpu().detach().numpy()
56 )
57 output_angles.index = list(sequence)[:-2] # Because of the 3-mer representation
58 return output_angles
59
60 def convert_raw_sequence_to_k_mers(self, sequence: str, k_mers: int = 3):
61 """
62 Convert a raw RNA sequence into sequence readable for the tokenizer.
63 It converts the sequence into k-mers, and replace U by T
64 :return: input readable by the tokenizer
65 """
66 sequence = sequence.upper().replace("U", "T")
67 k_mers_sequence = [
68 sequence[i : i + k_mers]
69 for i in range(len(sequence))
70 if len(sequence[i : i + k_mers]) == k_mers
71 ]
72 return " ".join(k_mers_sequence)
73
74 def convert_sin_cos_to_angles(
75 self, output: np.ndarray, input_ids: Optional[np.ndarray] = None
76 ):
77 """
78 Convert the raw predictions of the RNA-TorsionBERT into angles.
79 It converts the cos and sinus into angles using:
80 alpha = arctan(sin(alpha)/cos(alpha))
81 :param output: Dictionary with the predictions of the RNA-TorsionBERT per angle
82 :param input_ids: the input_ids of the RNA-TorsionBERT. It allows to only select the of the sequence,
83 and not the special tokens.
84 :return: a np.ndarray with the angles for the sequence
85 """
86 if input_ids is not None:
87 output[
88 (input_ids == 0)
89 | (input_ids == 2)
90 | (input_ids == 3)
91 | (input_ids == 4)
92 ] = np.nan
93 pair_indexes, impair_indexes = np.arange(0, output.shape[-1], 2), np.arange(
94 1, output.shape[-1], 2
95 )
96 sin, cos = output[:, :, impair_indexes], output[:, :, pair_indexes]
97 tan = np.arctan2(sin, cos)
98 angles = np.degrees(tan)
99 return angles
100
101 def convert_logits_to_dict(self, output: np.ndarray, input_ids: np.ndarray) -> Dict:
102 """
103 Convert the raw predictions into dictionary format.
104 It removes the special tokens and only keeps the predictions for the sequence.
105 :param output: predictions from the models in angles
106 :param input_ids: input ids from the tokenizer
107 :return: a dictionary with the predictions for each angle
108 """
109 index_start, index_end = (
110 np.where(input_ids == 2)[0][0],
111 np.where(input_ids == 3)[0][0],
112 )
113 output_non_pad = output[index_start + 1 : index_end, :]
114 output_angles = {
115 angle: output_non_pad[:, angle_index]
116 for angle_index, angle in enumerate(BACKBONE)
117 }
118 out = pd.DataFrame(output_angles)
119 return out
120
121
122if __name__ == "__main__":
123 sequence = "AGGGCUUUAGUCUUUGGAG"
124 rna_torsionbert_helper = RNATorsionBERTHelper()
125 output_angles = rna_torsionbert_helper.predict(sequence)
126 print(output_angles)