Taykhoom commited on
Commit
7ba311b
·
verified ·
1 Parent(s): 167a64d

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - rna
4
+ library_name: transformers
5
+ tags:
6
+ - RNA
7
+ - language-model
8
+ license: mit
9
+ ---
10
+
11
+ # mRNA-FM
12
+
13
+ A 12-layer BERT-style transformer pre-trained on 45 million mRNA coding sequences (CDS) using
14
+ codon (3-mer) tokenisation.
15
+
16
+ ## Architecture
17
+
18
+ | Parameter | Value |
19
+ |---|---|
20
+ | Layers | 12 |
21
+ | Attention heads | 20 |
22
+ | Embedding dimension | 1280 |
23
+ | FFN dimension | 5120 |
24
+ | Vocabulary size | 73 |
25
+ | Positional encoding | Learned |
26
+ | Architecture | ESM-1b-style pre-LN Transformer |
27
+ | Max sequence length | 1024 codon tokens (1022 codons = 3066 nucleotides) |
28
+
29
+ Vocabulary: `<cls>` (0), `<pad>` (1), `<eos>` (2), `<unk>` (3), 64 standard RNA codons
30
+ (indices 4-67), 4 null-padding tokens (68-71), `<mask>` (72).
31
+
32
+ ## Pretraining
33
+
34
+ - **Objective:** Masked language modelling (codon-level, 15% masking rate)
35
+ - **Data:** RefSeq -- 45 million mRNA coding sequences
36
+ - **Source checkpoint:** `mRNA-FM_pretrained.pth` from [cuhkaih/rnafm](https://huggingface.co/cuhkaih/rnafm)
37
+
38
+ ### Tokenisation
39
+
40
+ mRNA-FM uses **codon (3-mer) tokenisation**: the input sequence is split into consecutive
41
+ non-overlapping codons (triplets) and each codon is mapped to a single token. The model
42
+ therefore only accepts sequences whose length is a **multiple of 3**.
43
+
44
+ Input sequences must use **RNA notation (U, not T)**. Convert before tokenising:
45
+ ```python
46
+ seq = seq.replace("T", "U")
47
+ ```
48
+
49
+ ## Parity Verification
50
+
51
+ Hidden-state representations verified identical (max abs diff = 0.00) to the original
52
+ implementation at all 13 representation levels (embedding + 12 transformer layers).
53
+ Verified on GPU (CUDA) with PyTorch 2.7 / transformers 4.57.6. SDPA numerical
54
+ differences are expected (~3e-4 max diff over 12 layers) and are not a correctness issue.
55
+
56
+ ## Related Models
57
+
58
+ See the full [RNA-FM collection](https://huggingface.co/collections/Taykhoom/rna-fm-TODO).
59
+
60
+ | Model | Training data | Embedding dim | Notes |
61
+ |---|---|---|---|
62
+ | [RNA-FM](https://huggingface.co/Taykhoom/RNA-FM) | 23.7 M ncRNA | 640 | Character tokenisation |
63
+ | **[mRNA-FM](https://huggingface.co/Taykhoom/mRNA-FM)** | 45 M CDS | 1280 | This model |
64
+
65
+ ## Usage
66
+
67
+ ### Embedding generation
68
+
69
+ ```python
70
+ import torch
71
+ from transformers import AutoTokenizer, AutoModel
72
+
73
+ tokenizer = AutoTokenizer.from_pretrained("Taykhoom/mRNA-FM", trust_remote_code=True)
74
+ model = AutoModel.from_pretrained("Taykhoom/mRNA-FM", trust_remote_code=True)
75
+ model.eval()
76
+
77
+ # Sequences must be RNA (U not T) and length divisible by 3 (codons)
78
+ sequences = [
79
+ "AUGGGGUGCGAUCAUACCAGCACUAAUGCCCUCCUGGGAAGUCCUCGUGUUGCA",
80
+ "AUGCUAGCUAGCUAGCUAUG",
81
+ ]
82
+ enc = tokenizer(sequences, return_tensors="pt", padding=True)
83
+
84
+ with torch.no_grad():
85
+ out = model(**enc)
86
+
87
+ cls_emb = out.last_hidden_state[:, 0, :] # (batch, 1280) -- CLS token
88
+ token_emb = out.last_hidden_state # (batch, n_codons+2, 1280) -- per-codon
89
+
90
+ # Intermediate layers
91
+ out_all = model(**enc, output_hidden_states=True)
92
+ layer6_emb = out_all.hidden_states[6]
93
+ ```
94
+
95
+ ### MLM logits
96
+
97
+ ```python
98
+ import torch
99
+ from transformers import AutoTokenizer, AutoModelForMaskedLM
100
+
101
+ tokenizer = AutoTokenizer.from_pretrained("Taykhoom/mRNA-FM", trust_remote_code=True)
102
+ model = AutoModelForMaskedLM.from_pretrained("Taykhoom/mRNA-FM", trust_remote_code=True)
103
+ model.eval()
104
+
105
+ enc = tokenizer(["AUG<mask>GCUAUG"], return_tensors="pt")
106
+ with torch.no_grad():
107
+ logits = model(**enc).logits # (1, n_codons+2, 73)
108
+ ```
109
+
110
+ ### Fine-tuning
111
+
112
+ Standard HF conventions. Use the CLS token embedding (`out.last_hidden_state[:, 0, :]`) as
113
+ input to a classification or regression head for sequence-level tasks. Mean-pool over codon
114
+ positions (excluding CLS and EOS) for codon-level aggregation.
115
+
116
+ ## Implementation Notes
117
+
118
+ The original implementation uses `F.multi_head_attention_forward` (eager). This HF port adds
119
+ `attn_implementation="sdpa"` and `attn_implementation="flash_attention_2"` support, which were
120
+ not part of the original codebase.
121
+
122
+ Each codon token represents exactly one triplet of nucleotides. The tokeniser splits the raw
123
+ sequence into non-overlapping codons; any trailing nucleotides that do not form a complete codon
124
+ are silently discarded.
125
+
126
+ ## Citation
127
+
128
+ ```bibtex
129
+ @article{chen2022_rnafm,
130
+ title = {Interpretable {RNA} Foundation Model from Unannotated Data for Highly Accurate {RNA} Structure and Function Predictions},
131
+ author = {Chen, Jiayang and Hu, Zhihang and Sun, Siqi and Tan, Qingxiong and Wang, Yixuan and Yu, Qinze and Zong, Licheng and Hong, Liang and Xiao, Jin and Shen, Tao and King, Irwin and Li, Yu},
132
+ journal = {arXiv preprint arXiv:2204.00300},
133
+ year = {2022},
134
+ doi = {10.48550/arXiv.2204.00300}
135
+ }
136
+ ```
137
+
138
+ ## Credits
139
+
140
+ Original model and code by Chen et al. Source: [GitHub](https://github.com/ml4bio/RNA-FM).
141
+ The HF conversion code was authored primarily by [Claude Code](https://claude.ai/code)
142
+ and reviewed manually by Taykhoom Dalal.
143
+
144
+ ## License
145
+
146
+ MIT, following the original repository.
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "RnaFmForMaskedLM"
4
+ ],
5
+ "attention_heads": 20,
6
+ "cls_idx": 0,
7
+ "dtype": "float32",
8
+ "emb_layer_norm_before": false,
9
+ "embed_dim": 1280,
10
+ "eos_idx": 2,
11
+ "ffn_embed_dim": 5120,
12
+ "mask_idx": 72,
13
+ "model_max_length": 1024,
14
+ "model_type": "rnafm",
15
+ "model_variant": "rna-3mer",
16
+ "num_layers": 12,
17
+ "padding_idx": 1,
18
+ "token_dropout": false,
19
+ "transformers_version": "4.57.6",
20
+ "vocab_size": 73
21
+ }
configuration_rnafm.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class RnaFmConfig(PretrainedConfig):
5
+ model_type = "rnafm"
6
+
7
+ auto_map = {
8
+ "AutoConfig": "configuration_rnafm.RnaFmConfig",
9
+ "AutoModel": "modeling_rnafm.RnaFmModel",
10
+ "AutoModelForMaskedLM": "modeling_rnafm.RnaFmForMaskedLM",
11
+ "AutoTokenizer": ["tokenization_rnafm.RnaFmTokenizer", None],
12
+ }
13
+
14
+ def __init__(
15
+ self,
16
+ vocab_size: int = 25,
17
+ num_layers: int = 12,
18
+ embed_dim: int = 640,
19
+ ffn_embed_dim: int = 5120,
20
+ attention_heads: int = 20,
21
+ padding_idx: int = 1,
22
+ mask_idx: int = 24,
23
+ cls_idx: int = 0,
24
+ eos_idx: int = 2,
25
+ token_dropout: bool = False,
26
+ emb_layer_norm_before: bool = True,
27
+ model_max_length: int = 1024,
28
+ model_variant: str = "rna",
29
+ **kwargs,
30
+ ):
31
+ super().__init__(padding_idx=padding_idx, **kwargs)
32
+ self.vocab_size = vocab_size
33
+ self.num_layers = num_layers
34
+ self.embed_dim = embed_dim
35
+ self.ffn_embed_dim = ffn_embed_dim
36
+ self.attention_heads = attention_heads
37
+ self.mask_idx = mask_idx
38
+ self.cls_idx = cls_idx
39
+ self.eos_idx = eos_idx
40
+ self.token_dropout = token_dropout
41
+ self.emb_layer_norm_before = emb_layer_norm_before
42
+ self.model_max_length = model_max_length
43
+ self.model_variant = model_variant
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:33d9243386d47b34cde21ddb5d41fc410cef22542d2dc50bf4dfa0ed9ae24de4
3
+ size 956744972
modeling_rnafm.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from transformers import PreTrainedModel
8
+ from transformers.modeling_outputs import BaseModelOutput, MaskedLMOutput
9
+
10
+ try:
11
+ from .configuration_rnafm import RnaFmConfig
12
+ except ImportError:
13
+ from configuration_rnafm import RnaFmConfig
14
+
15
+
16
+ def gelu(x):
17
+ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
18
+
19
+
20
+ class RnaFmLearnedPositionalEmbedding(nn.Embedding):
21
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int):
22
+ num_embeddings_ = num_embeddings + padding_idx + 1
23
+ super().__init__(num_embeddings_, embedding_dim, padding_idx)
24
+ self.max_positions = num_embeddings
25
+
26
+ def forward(self, input: torch.Tensor):
27
+ mask = input.ne(self.padding_idx).int()
28
+ positions = (torch.cumsum(mask, dim=1).type_as(mask) * mask).long() + self.padding_idx
29
+ return F.embedding(
30
+ positions,
31
+ self.weight,
32
+ self.padding_idx,
33
+ self.max_norm,
34
+ self.norm_type,
35
+ self.scale_grad_by_freq,
36
+ self.sparse,
37
+ )
38
+
39
+
40
+ class RnaFmAttention(nn.Module):
41
+ def __init__(self, config: RnaFmConfig):
42
+ super().__init__()
43
+ self.embed_dim = config.embed_dim
44
+ self.num_heads = config.attention_heads
45
+ self.head_dim = config.embed_dim // config.attention_heads
46
+ self.scaling = self.head_dim ** -0.5
47
+
48
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
49
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
50
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
51
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
52
+
53
+ def _project(self, x):
54
+ tgt_len, bsz, _ = x.size()
55
+ q = self.q_proj(x) * self.scaling
56
+ k = self.k_proj(x)
57
+ v = self.v_proj(x)
58
+ q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
59
+ k = k.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
60
+ v = v.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
61
+ return q, k, v, tgt_len, bsz
62
+
63
+ def forward(self, x, key_padding_mask=None, output_attentions=False):
64
+ q, k, v, tgt_len, bsz = self._project(x)
65
+
66
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
67
+
68
+ if key_padding_mask is not None:
69
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, tgt_len)
70
+ attn_weights = attn_weights.masked_fill(
71
+ key_padding_mask.unsqueeze(1).unsqueeze(2), float("-inf")
72
+ )
73
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, tgt_len)
74
+
75
+ attn_weights_float = F.softmax(attn_weights, dim=-1, dtype=torch.float32)
76
+ attn_probs = attn_weights_float.type_as(attn_weights)
77
+
78
+ attn = torch.bmm(attn_probs, v)
79
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, self.embed_dim)
80
+ attn = self.out_proj(attn)
81
+
82
+ if output_attentions:
83
+ weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, tgt_len)
84
+ return attn, weights
85
+ return attn, None
86
+
87
+
88
+ class RnaFmSdpaAttention(RnaFmAttention):
89
+ def forward(self, x, key_padding_mask=None, output_attentions=False):
90
+ if output_attentions:
91
+ return super().forward(x, key_padding_mask, output_attentions=True)
92
+
93
+ tgt_len, bsz, _ = x.size()
94
+ q = self.q_proj(x)
95
+ k = self.k_proj(x)
96
+ v = self.v_proj(x)
97
+
98
+ q = q.view(tgt_len, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3)
99
+ k = k.view(tgt_len, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3)
100
+ v = v.view(tgt_len, bsz, self.num_heads, self.head_dim).permute(1, 2, 0, 3)
101
+
102
+ attn_mask = None
103
+ if key_padding_mask is not None:
104
+ attn_mask = torch.zeros(bsz, 1, 1, tgt_len, dtype=q.dtype, device=q.device)
105
+ attn_mask = attn_mask.masked_fill(
106
+ key_padding_mask.unsqueeze(1).unsqueeze(2), float("-inf")
107
+ )
108
+
109
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
110
+
111
+ out = out.permute(2, 0, 1, 3).contiguous().view(tgt_len, bsz, self.embed_dim)
112
+ return self.out_proj(out), None
113
+
114
+
115
+ class RnaFmFlashAttention2(RnaFmAttention):
116
+ def forward(self, x, key_padding_mask=None, output_attentions=False):
117
+ if output_attentions:
118
+ return super().forward(x, key_padding_mask, output_attentions=True)
119
+
120
+ try:
121
+ from flash_attn import flash_attn_func
122
+ from flash_attn.bert_padding import pad_input, unpad_input
123
+ except ImportError as e:
124
+ raise ImportError(
125
+ "flash_attn is required for attn_implementation='flash_attention_2'. "
126
+ "Install with: pip install flash-attn --no-build-isolation"
127
+ ) from e
128
+
129
+ tgt_len, bsz, _ = x.size()
130
+ q = self.q_proj(x)
131
+ k = self.k_proj(x)
132
+ v = self.v_proj(x)
133
+
134
+ q = q.view(tgt_len, bsz, self.num_heads, self.head_dim).permute(1, 0, 2, 3)
135
+ k = k.view(tgt_len, bsz, self.num_heads, self.head_dim).permute(1, 0, 2, 3)
136
+ v = v.view(tgt_len, bsz, self.num_heads, self.head_dim).permute(1, 0, 2, 3)
137
+
138
+ orig_dtype = q.dtype
139
+ if q.dtype not in (torch.float16, torch.bfloat16):
140
+ q, k, v = q.to(torch.bfloat16), k.to(torch.bfloat16), v.to(torch.bfloat16)
141
+
142
+ softmax_scale = self.head_dim ** -0.5
143
+
144
+ if key_padding_mask is not None and key_padding_mask.any():
145
+ attention_mask_bool = ~key_padding_mask
146
+ q_unpad, indices, cu_seqlens, max_seqlen, _ = unpad_input(q, attention_mask_bool)
147
+ k_unpad, *_ = unpad_input(k, attention_mask_bool)
148
+ v_unpad, *_ = unpad_input(v, attention_mask_bool)
149
+
150
+ from flash_attn import flash_attn_varlen_func
151
+ out_unpad = flash_attn_varlen_func(
152
+ q_unpad, k_unpad, v_unpad,
153
+ cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens,
154
+ max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen,
155
+ softmax_scale=softmax_scale,
156
+ causal=False,
157
+ )
158
+ out = pad_input(out_unpad, indices, bsz, tgt_len)
159
+ else:
160
+ out = flash_attn_func(q, k, v, softmax_scale=softmax_scale, causal=False)
161
+
162
+ out = out.to(orig_dtype).permute(1, 0, 2, 3).contiguous().view(tgt_len, bsz, self.embed_dim)
163
+ return self.out_proj(out), None
164
+
165
+
166
+ RNAFM_ATTENTION_CLASSES = {
167
+ "eager": RnaFmAttention,
168
+ "sdpa": RnaFmSdpaAttention,
169
+ "flash_attention_2": RnaFmFlashAttention2,
170
+ }
171
+
172
+
173
+ class RnaFmLayer(nn.Module):
174
+ def __init__(self, config: RnaFmConfig):
175
+ super().__init__()
176
+ attn_cls = RNAFM_ATTENTION_CLASSES[getattr(config, "_attn_implementation", "eager")]
177
+ self.self_attn = attn_cls(config)
178
+ self.self_attn_layer_norm = nn.LayerNorm(config.embed_dim)
179
+ self.fc1 = nn.Linear(config.embed_dim, config.ffn_embed_dim)
180
+ self.fc2 = nn.Linear(config.ffn_embed_dim, config.embed_dim)
181
+ self.final_layer_norm = nn.LayerNorm(config.embed_dim)
182
+
183
+ def forward(self, x, key_padding_mask=None, output_attentions=False):
184
+ residual = x
185
+ x = self.self_attn_layer_norm(x)
186
+ x, attn = self.self_attn(x, key_padding_mask=key_padding_mask, output_attentions=output_attentions)
187
+ x = residual + x
188
+
189
+ residual = x
190
+ x = self.final_layer_norm(x)
191
+ x = gelu(self.fc1(x))
192
+ x = self.fc2(x)
193
+ x = residual + x
194
+
195
+ return x, attn
196
+
197
+
198
+ class RnaFmPreTrainedModel(PreTrainedModel):
199
+ config_class = RnaFmConfig
200
+ base_model_prefix = "rnafm"
201
+ _supports_sdpa = True
202
+ _supports_flash_attn_2 = True
203
+
204
+ def _init_weights(self, module):
205
+ if isinstance(module, nn.Linear):
206
+ nn.init.xavier_uniform_(module.weight)
207
+ if module.bias is not None:
208
+ nn.init.constant_(module.bias, 0.0)
209
+ elif isinstance(module, nn.Embedding):
210
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
211
+ if module.padding_idx is not None:
212
+ module.weight.data[module.padding_idx].zero_()
213
+
214
+
215
+ class RnaFmModel(RnaFmPreTrainedModel):
216
+ def __init__(self, config: RnaFmConfig):
217
+ super().__init__(config)
218
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.embed_dim, padding_idx=config.padding_idx)
219
+ self.embed_positions = RnaFmLearnedPositionalEmbedding(config.model_max_length, config.embed_dim, config.padding_idx)
220
+ self.emb_layer_norm_before = nn.LayerNorm(config.embed_dim) if config.emb_layer_norm_before else None
221
+ self.layers = nn.ModuleList([RnaFmLayer(config) for _ in range(config.num_layers)])
222
+ self.emb_layer_norm_after = nn.LayerNorm(config.embed_dim)
223
+ self.post_init()
224
+
225
+ def forward(
226
+ self,
227
+ input_ids,
228
+ attention_mask=None,
229
+ output_hidden_states=None,
230
+ output_attentions=None,
231
+ return_dict=None,
232
+ ):
233
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
234
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
235
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
236
+
237
+ if attention_mask is not None:
238
+ padding_mask = attention_mask.eq(0)
239
+ else:
240
+ padding_mask = input_ids.eq(self.config.padding_idx)
241
+
242
+ x = self.embed_tokens(input_ids)
243
+
244
+ if self.config.token_dropout:
245
+ x.masked_fill_((input_ids == self.config.mask_idx).unsqueeze(-1), 0.0)
246
+ mask_ratio_train = 0.15 * 0.8
247
+ src_lengths = (~padding_mask).sum(-1)
248
+ mask_ratio_observed = (input_ids == self.config.mask_idx).sum(-1).to(x.dtype) / src_lengths.to(x.dtype)
249
+ x = x * (1 - mask_ratio_train) / (1 - mask_ratio_observed)[:, None, None]
250
+
251
+ x = x + self.embed_positions(input_ids)
252
+
253
+ if self.emb_layer_norm_before is not None:
254
+ x = self.emb_layer_norm_before(x)
255
+
256
+ if padding_mask.any():
257
+ x = x * (1 - padding_mask.unsqueeze(-1).to(x.dtype))
258
+ else:
259
+ padding_mask = None
260
+
261
+ all_hidden_states = []
262
+ all_attentions = []
263
+
264
+ if output_hidden_states:
265
+ all_hidden_states.append(x)
266
+
267
+ x = x.transpose(0, 1)
268
+
269
+ for layer in self.layers:
270
+ x, attn = layer(x, key_padding_mask=padding_mask, output_attentions=output_attentions)
271
+ if output_hidden_states:
272
+ all_hidden_states.append(x.transpose(0, 1))
273
+ if output_attentions and attn is not None:
274
+ all_attentions.append(attn)
275
+
276
+ x = self.emb_layer_norm_after(x)
277
+ x = x.transpose(0, 1)
278
+
279
+ if output_hidden_states:
280
+ all_hidden_states[-1] = x
281
+
282
+ return BaseModelOutput(
283
+ last_hidden_state=x,
284
+ hidden_states=tuple(all_hidden_states) if output_hidden_states else None,
285
+ attentions=tuple(all_attentions) if output_attentions else None,
286
+ )
287
+
288
+
289
+ class RnaFmLMHead(nn.Module):
290
+ def __init__(self, config: RnaFmConfig):
291
+ super().__init__()
292
+ self.dense = nn.Linear(config.embed_dim, config.embed_dim)
293
+ self.layer_norm = nn.LayerNorm(config.embed_dim)
294
+ self.decoder = nn.Linear(config.embed_dim, config.vocab_size, bias=True)
295
+
296
+ def forward(self, features):
297
+ x = self.dense(features)
298
+ x = gelu(x)
299
+ x = self.layer_norm(x)
300
+ x = self.decoder(x)
301
+ return x
302
+
303
+
304
+ class RnaFmForMaskedLM(RnaFmPreTrainedModel):
305
+ _tied_weights_keys = ["lm_head.decoder.weight"]
306
+
307
+ def __init__(self, config: RnaFmConfig):
308
+ super().__init__(config)
309
+ self.rnafm = RnaFmModel(config)
310
+ self.lm_head = RnaFmLMHead(config)
311
+ self.post_init()
312
+
313
+ def get_input_embeddings(self):
314
+ return self.rnafm.embed_tokens
315
+
316
+ def set_input_embeddings(self, value):
317
+ self.rnafm.embed_tokens = value
318
+
319
+ def get_output_embeddings(self):
320
+ return self.lm_head.decoder
321
+
322
+ def set_output_embeddings(self, new_embeddings):
323
+ self.lm_head.decoder = new_embeddings
324
+
325
+ def forward(
326
+ self,
327
+ input_ids,
328
+ attention_mask=None,
329
+ labels=None,
330
+ output_hidden_states=None,
331
+ output_attentions=None,
332
+ return_dict=None,
333
+ ):
334
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
335
+ out = self.rnafm(
336
+ input_ids,
337
+ attention_mask=attention_mask,
338
+ output_hidden_states=output_hidden_states,
339
+ output_attentions=output_attentions,
340
+ return_dict=return_dict,
341
+ )
342
+ logits = self.lm_head(out.last_hidden_state)
343
+ loss = None
344
+ if labels is not None:
345
+ loss = F.cross_entropy(
346
+ logits.view(-1, self.config.vocab_size),
347
+ labels.view(-1),
348
+ ignore_index=-100,
349
+ )
350
+ return MaskedLMOutput(
351
+ loss=loss,
352
+ logits=logits,
353
+ hidden_states=out.hidden_states,
354
+ attentions=out.attentions,
355
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "<cls>",
3
+ "eos_token": "<eos>",
4
+ "mask_token": "<mask>",
5
+ "pad_token": "<pad>",
6
+ "unk_token": "<unk>"
7
+ }
tokenization_rnafm.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ from transformers import PreTrainedTokenizer
5
+
6
+
7
+ _RNA_VOCAB = {
8
+ "<cls>": 0, "<pad>": 1, "<eos>": 2, "<unk>": 3,
9
+ "A": 4, "C": 5, "G": 6, "U": 7,
10
+ "R": 8, "Y": 9, "K": 10, "M": 11,
11
+ "S": 12, "W": 13, "B": 14, "D": 15,
12
+ "H": 16, "V": 17, "N": 18, "-": 19,
13
+ "<null_1>": 20, "<null_2>": 21, "<null_3>": 22, "<null_4>": 23,
14
+ "<mask>": 24,
15
+ }
16
+
17
+ _MRNA_VOCAB = {
18
+ "<cls>": 0, "<pad>": 1, "<eos>": 2, "<unk>": 3,
19
+ "GAG": 4, "AAG": 5, "GAA": 6, "CUG": 7, "CAG": 8, "GAU": 9,
20
+ "AAA": 10, "GUG": 11, "GAC": 12, "AUG": 13, "GCC": 14, "AAC": 15,
21
+ "GCU": 16, "AAU": 17, "AUC": 18, "UUC": 19, "GGA": 20, "AUU": 21,
22
+ "GGC": 22, "UUU": 23, "CCA": 24, "AGC": 25, "GCA": 26, "UCU": 27,
23
+ "CUC": 28, "ACC": 29, "CAA": 30, "CCU": 31, "UCC": 32, "ACA": 33,
24
+ "UUG": 34, "GUU": 35, "CUU": 36, "UAC": 37, "ACU": 38, "CCC": 39,
25
+ "UCA": 40, "GUC": 41, "GGU": 42, "CAC": 43, "AGU": 44, "UAU": 45,
26
+ "AGA": 46, "CAU": 47, "GGG": 48, "UGG": 49, "UGC": 50, "AGG": 51,
27
+ "UGU": 52, "AUA": 53, "CGC": 54, "UUA": 55, "GCG": 56, "CGG": 57,
28
+ "CCG": 58, "GUA": 59, "CUA": 60, "ACG": 61, "UCG": 62, "CGA": 63,
29
+ "CGU": 64, "UGA": 65, "UAA": 66, "UAG": 67,
30
+ "<null_1>": 68, "<null_2>": 69, "<null_3>": 70, "<null_4>": 71,
31
+ "<mask>": 72,
32
+ }
33
+
34
+
35
+ class RnaFmTokenizer(PreTrainedTokenizer):
36
+ vocab_files_names = {"vocab_file": "vocab.json"}
37
+ model_input_names = ["input_ids", "attention_mask"]
38
+
39
+ def __init__(
40
+ self,
41
+ vocab_file=None,
42
+ k_mer: int = 1,
43
+ cls_token="<cls>",
44
+ pad_token="<pad>",
45
+ eos_token="<eos>",
46
+ unk_token="<unk>",
47
+ mask_token="<mask>",
48
+ **kwargs,
49
+ ):
50
+ self.k_mer = k_mer
51
+ if vocab_file and os.path.isfile(vocab_file):
52
+ with open(vocab_file) as f:
53
+ self._vocab = json.load(f)
54
+ else:
55
+ self._vocab = dict(_MRNA_VOCAB if k_mer == 3 else _RNA_VOCAB)
56
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
57
+ super().__init__(
58
+ cls_token=cls_token,
59
+ pad_token=pad_token,
60
+ eos_token=eos_token,
61
+ unk_token=unk_token,
62
+ mask_token=mask_token,
63
+ k_mer=k_mer,
64
+ **kwargs,
65
+ )
66
+
67
+ @property
68
+ def vocab_size(self):
69
+ return len(self._vocab)
70
+
71
+ def get_vocab(self):
72
+ return dict(self._vocab)
73
+
74
+ def _tokenize(self, text):
75
+ if self.k_mer == 1:
76
+ return list(text)
77
+ return [text[i:i + self.k_mer] for i in range(0, len(text), self.k_mer)]
78
+
79
+ def _convert_token_to_id(self, token):
80
+ return self._vocab.get(token, self._vocab["<unk>"])
81
+
82
+ def _convert_id_to_token(self, index):
83
+ return self._ids_to_tokens.get(index, "<unk>")
84
+
85
+ def save_vocabulary(self, save_directory, filename_prefix=None):
86
+ os.makedirs(save_directory, exist_ok=True)
87
+ fname = (filename_prefix + "-" if filename_prefix else "") + "vocab.json"
88
+ path = os.path.join(save_directory, fname)
89
+ with open(path, "w") as f:
90
+ json.dump(self._vocab, f, indent=2)
91
+ return (path,)
92
+
93
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
94
+ cls = [self.cls_token_id]
95
+ eos = [self.eos_token_id]
96
+ if token_ids_1 is None:
97
+ return cls + token_ids_0 + eos
98
+ return cls + token_ids_0 + eos + cls + token_ids_1 + eos
99
+
100
+ def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
101
+ if already_has_special_tokens:
102
+ return super().get_special_tokens_mask(token_ids_0, token_ids_1, already_has_special_tokens=True)
103
+ mask = [1] + [0] * len(token_ids_0) + [1]
104
+ if token_ids_1 is not None:
105
+ mask += [1] + [0] * len(token_ids_1) + [1]
106
+ return mask
107
+
108
+ def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
109
+ if token_ids_1 is None:
110
+ return [0] * (len(token_ids_0) + 2)
111
+ return [0] * (len(token_ids_0) + 2) + [0] * (len(token_ids_1) + 2)
tokenizer_config.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<cls>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "<eos>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "72": {
36
+ "content": "<mask>",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "<cls>",
46
+ "eos_token": "<eos>",
47
+ "extra_special_tokens": {},
48
+ "k_mer": 3,
49
+ "mask_token": "<mask>",
50
+ "model_max_length": 1024,
51
+ "pad_token": "<pad>",
52
+ "tokenizer_class": "RnaFmTokenizer",
53
+ "unk_token": "<unk>"
54
+ }
vocab.json ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<cls>": 0,
3
+ "<pad>": 1,
4
+ "<eos>": 2,
5
+ "<unk>": 3,
6
+ "GAG": 4,
7
+ "AAG": 5,
8
+ "GAA": 6,
9
+ "CUG": 7,
10
+ "CAG": 8,
11
+ "GAU": 9,
12
+ "AAA": 10,
13
+ "GUG": 11,
14
+ "GAC": 12,
15
+ "AUG": 13,
16
+ "GCC": 14,
17
+ "AAC": 15,
18
+ "GCU": 16,
19
+ "AAU": 17,
20
+ "AUC": 18,
21
+ "UUC": 19,
22
+ "GGA": 20,
23
+ "AUU": 21,
24
+ "GGC": 22,
25
+ "UUU": 23,
26
+ "CCA": 24,
27
+ "AGC": 25,
28
+ "GCA": 26,
29
+ "UCU": 27,
30
+ "CUC": 28,
31
+ "ACC": 29,
32
+ "CAA": 30,
33
+ "CCU": 31,
34
+ "UCC": 32,
35
+ "ACA": 33,
36
+ "UUG": 34,
37
+ "GUU": 35,
38
+ "CUU": 36,
39
+ "UAC": 37,
40
+ "ACU": 38,
41
+ "CCC": 39,
42
+ "UCA": 40,
43
+ "GUC": 41,
44
+ "GGU": 42,
45
+ "CAC": 43,
46
+ "AGU": 44,
47
+ "UAU": 45,
48
+ "AGA": 46,
49
+ "CAU": 47,
50
+ "GGG": 48,
51
+ "UGG": 49,
52
+ "UGC": 50,
53
+ "AGG": 51,
54
+ "UGU": 52,
55
+ "AUA": 53,
56
+ "CGC": 54,
57
+ "UUA": 55,
58
+ "GCG": 56,
59
+ "CGG": 57,
60
+ "CCG": 58,
61
+ "GUA": 59,
62
+ "CUA": 60,
63
+ "ACG": 61,
64
+ "UCG": 62,
65
+ "CGA": 63,
66
+ "CGU": 64,
67
+ "UGA": 65,
68
+ "UAA": 66,
69
+ "UAG": 67,
70
+ "<null_1>": 68,
71
+ "<null_2>": 69,
72
+ "<null_3>": 70,
73
+ "<null_4>": 71,
74
+ "<mask>": 72
75
+ }