Taykhoom commited on
Commit
b9cd116
·
0 Parent(s):

Initial SpliceBERT-human-510nt Hugging Face port

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - rna
5
+ - language-model
6
+ - splicing
7
+ license: cc-by-4.0
8
+ ---
9
+
10
+ # SpliceBERT-human-510nt
11
+
12
+ Minimal HuggingFace port of the **human-510nt** variant of
13
+ [SpliceBERT](https://github.com/biomed-AI/SpliceBERT) -- a BERT-based RNA
14
+ language model trained with masked language modeling on fixed-length 510 nt
15
+ fragments from human mRNA sequences.
16
+
17
+ **WARNING:** This model was trained on exactly 510 nt of input (excluding
18
+ [CLS] and [SEP]). Sequences of other lengths were not validated upstream and
19
+ may not work properly without fine-tuning.
20
+ For general-purpose RNA embedding, use [SpliceBERT-1024nt](https://huggingface.co/Taykhoom/SpliceBERT-1024nt) instead.
21
+
22
+ ## Architecture
23
+
24
+ | Parameter | Value |
25
+ |---|---|
26
+ | Layers | 6 |
27
+ | Attention heads | 16 |
28
+ | Embedding dimension | 512 |
29
+ | FFN hidden dimension | 2048 (GELU) |
30
+ | Vocabulary size | 10 |
31
+ | Positional encoding | Learned absolute |
32
+ | Normalization | LayerNorm (post-residual, eps=1e-12) |
33
+ | Architecture | Post-LN BERT encoder |
34
+ | Max sequence length | 510 nt (512 tokens; fixed-length training) |
35
+ | Checkpoint size | ~19.5M parameters |
36
+
37
+ **Vocabulary:** `[PAD]`=0, `[UNK]`=1, `[CLS]`=2, `[SEP]`=3,
38
+ `[MASK]`=4, `N`=5, `A`=6, `C`=7, `G`=8, `T`=9. Input `U` is
39
+ normalized to `T`.
40
+
41
+ ## Pretraining
42
+
43
+ - **Objective:** Masked language modeling (MLM)
44
+ - **Data:** Human primary RNA sequences
45
+ - **Sequence format:** Single-nucleotide tokenization with spaces; U converted to T; fixed 510 nt fragments
46
+ - **Source checkpoint:** `SpliceBERT-human.510nt/pytorch_model.bin` (from [zenodo:7995778](https://doi.org/10.5281/zenodo.7995778))
47
+
48
+ ### Checkpoint selection
49
+
50
+ This human-only variant may outperform the multi-species 510nt model on human-specific
51
+ splicing tasks. For cross-species generalization or variable-length sequences, use
52
+ [SpliceBERT-1024nt](https://huggingface.co/Taykhoom/SpliceBERT-1024nt).
53
+
54
+ ## Parity Verification
55
+
56
+ Hidden-state representations verified (max abs diff < 1e-5) against the original
57
+ checkpoint at all 7 representation levels (embedding + 6 transformer layers),
58
+ for both `eager` and `sdpa` attention backends.
59
+ Verified on GPU with PyTorch 2.7.1 / CUDA 12.9.
60
+
61
+ ## Related Models
62
+
63
+ See the full [SpliceBERT collection](https://huggingface.co/collections/Taykhoom/splicebert-6a20b72e9bec05b79ce009aa).
64
+
65
+ | Model | Context | Training data | Notes |
66
+ |---|---|---|---|
67
+ | [SpliceBERT-1024nt](https://huggingface.co/Taykhoom/SpliceBERT-1024nt) | 1024 nt | 72 vertebrates | Variable-length; general purpose |
68
+ | [SpliceBERT-510nt](https://huggingface.co/Taykhoom/SpliceBERT-510nt) | 510 nt (fixed) | 72 vertebrates | Multi-species 510 nt |
69
+ | **[SpliceBERT-human-510nt](https://huggingface.co/Taykhoom/SpliceBERT-human-510nt)** | 510 nt (fixed) | Human only | This model |
70
+
71
+ ## Usage
72
+
73
+ ```python
74
+ import torch
75
+ from transformers import AutoTokenizer, AutoModel
76
+
77
+ tokenizer = AutoTokenizer.from_pretrained("Taykhoom/SpliceBERT-human-510nt", trust_remote_code=True)
78
+ model = AutoModel.from_pretrained("Taykhoom/SpliceBERT-human-510nt", trust_remote_code=True)
79
+ model.eval()
80
+
81
+ # The model was trained on exactly 510 nt; tokenizer handles U->T automatically
82
+ seq = ("ATCGATCG" * 64)[:510] # exactly 510 nt
83
+ enc = tokenizer(seq, return_tensors="pt")
84
+
85
+ with torch.no_grad():
86
+ out = model(**enc, output_hidden_states=True)
87
+
88
+ hidden = out.last_hidden_state[0] # (512, 512)
89
+ token_emb = hidden[1:-1] # strip [CLS] and [SEP] -> (510, 512)
90
+ mean_emb = token_emb.mean(dim=0) # (512,)
91
+ ```
92
+
93
+ ### Fine-tuning
94
+
95
+ Standard HF conventions. For splice site prediction, token-level classification
96
+ using all 510 token positions (excluding special tokens) is the typical setup.
97
+
98
+ ## Implementation Notes
99
+
100
+ The original checkpoint was saved as `BertForMaskedLM` with `transformers==4.18.0`.
101
+ This port uses [BERT-updated](https://huggingface.co/Taykhoom/BERT-updated), which
102
+ adds `attn_implementation="sdpa"` and `attn_implementation="flash_attention_2"` support
103
+ not present in the original codebase.
104
+
105
+ The pooler weights (`pooler.dense`) are not present in the original checkpoint and are
106
+ not included in the saved `model.safetensors`. `add_pooling_layer=True` (the default)
107
+ allocates the pooler layer but its weights are randomly initialized -- do not use
108
+ `pooler_output` without fine-tuning.
109
+
110
+ ## Citation
111
+
112
+ ```bibtex
113
+ @article{chen2024_splicebert,
114
+ title = {Self-supervised learning on millions of primary {RNA} sequences from 72 vertebrates improves sequence-based {RNA} splicing prediction},
115
+ author = {Chen, Ken and Zhou, Yue and Ding, Maolin and Wang, Yu and Ren, Zhixiang and Yang, Yuedong},
116
+ journal = {Briefings in Bioinformatics},
117
+ volume = {25},
118
+ number = {3},
119
+ pages = {bbae163},
120
+ year = {2024},
121
+ doi = {10.1093/bib/bbae163}
122
+ }
123
+ ```
124
+
125
+ ## Credits
126
+
127
+ Original model and code by Chen et al. Source:
128
+ [GitHub](https://github.com/biomed-AI/SpliceBERT).
129
+ The HF conversion code was authored primarily by [Claude Code](https://claude.ai/code)
130
+ and reviewed manually by Taykhoom Dalal.
131
+
132
+ ## License
133
+
134
+ The checkpoint weights are distributed under
135
+ [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) by the upstream
136
+ [Zenodo record](https://doi.org/10.5281/zenodo.7995778). The original
137
+ SpliceBERT source code is BSD 3-Clause licensed.
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "Taykhoom/SpliceBERT-human-510nt",
3
+ "architectures": [
4
+ "BertForMaskedLM"
5
+ ],
6
+ "model_type": "bert_updated",
7
+ "auto_map": {
8
+ "AutoConfig": "Taykhoom/BERT-updated--configuration_bert_updated.BertUpdatedConfig",
9
+ "AutoModel": "Taykhoom/BERT-updated--modeling_bert.BertModel",
10
+ "AutoModelForMaskedLM": "Taykhoom/BERT-updated--modeling_bert.BertForMaskedLM"
11
+ },
12
+ "vocab_size": 10,
13
+ "hidden_size": 512,
14
+ "num_hidden_layers": 6,
15
+ "num_attention_heads": 16,
16
+ "intermediate_size": 2048,
17
+ "hidden_act": "gelu",
18
+ "hidden_dropout_prob": 0.1,
19
+ "attention_probs_dropout_prob": 0.1,
20
+ "max_position_embeddings": 512,
21
+ "type_vocab_size": 2,
22
+ "initializer_range": 0.02,
23
+ "layer_norm_eps": 1e-12,
24
+ "pad_token_id": 0,
25
+ "model_max_length": 510,
26
+ "transformers_version": "4.57.6"
27
+ }
configuration_bert_updated.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class BertUpdatedConfig(PretrainedConfig):
5
+ model_type = "bert_updated"
6
+
7
+ auto_map = {
8
+ "AutoConfig": "configuration_bert_updated.BertUpdatedConfig",
9
+ "AutoModel": "modeling_bert.BertModel",
10
+ "AutoModelForMaskedLM": "modeling_bert.BertForMaskedLM",
11
+ }
12
+
13
+ def __init__(
14
+ self,
15
+ vocab_size=30522,
16
+ hidden_size=768,
17
+ num_hidden_layers=12,
18
+ num_attention_heads=12,
19
+ intermediate_size=3072,
20
+ hidden_act="gelu",
21
+ hidden_dropout_prob=0.1,
22
+ attention_probs_dropout_prob=0.1,
23
+ max_position_embeddings=512,
24
+ type_vocab_size=2,
25
+ initializer_range=0.02,
26
+ layer_norm_eps=1e-12,
27
+ **kwargs,
28
+ ):
29
+ super().__init__(**kwargs)
30
+ self.vocab_size = vocab_size
31
+ self.hidden_size = hidden_size
32
+ self.num_hidden_layers = num_hidden_layers
33
+ self.num_attention_heads = num_attention_heads
34
+ self.intermediate_size = intermediate_size
35
+ self.hidden_act = hidden_act
36
+ self.hidden_dropout_prob = hidden_dropout_prob
37
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
38
+ self.max_position_embeddings = max_position_embeddings
39
+ self.type_vocab_size = type_vocab_size
40
+ self.initializer_range = initializer_range
41
+ self.layer_norm_eps = layer_norm_eps
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6e5465d8e1c0e827d36b88b9fd9ad4f84397760adc90d924391c2442da2f7b30
3
+ size 77826008
modeling_bert.py ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Optional, Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers import PreTrainedModel, PretrainedConfig
8
+ from transformers.modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
9
+
10
+ from .configuration_bert_updated import BertUpdatedConfig
11
+
12
+
13
+ class BertSelfAttention(nn.Module):
14
+
15
+ def __init__(self, config):
16
+ super().__init__()
17
+ self.num_attention_heads = config.num_attention_heads
18
+ self.attention_head_size = config.hidden_size // config.num_attention_heads
19
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
20
+
21
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
22
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
23
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
24
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
25
+
26
+ def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
27
+ B, T, _ = x.shape
28
+ return x.view(B, T, self.num_attention_heads, self.attention_head_size).permute(0, 2, 1, 3)
29
+
30
+ def forward(
31
+ self,
32
+ hidden_states: torch.Tensor,
33
+ key_padding_mask: Optional[torch.Tensor] = None,
34
+ output_attentions: bool = False,
35
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
36
+ q = self._split_heads(self.query(hidden_states))
37
+ k = self._split_heads(self.key(hidden_states))
38
+ v = self._split_heads(self.value(hidden_states))
39
+
40
+ scale = math.sqrt(self.attention_head_size)
41
+ scores = torch.matmul(q, k.transpose(-1, -2)) / scale
42
+ if key_padding_mask is not None:
43
+ scores = scores.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
44
+ probs = F.softmax(scores, dim=-1)
45
+ probs = self.dropout(probs)
46
+ context = torch.matmul(probs, v)
47
+
48
+ B, _, T, _ = context.shape
49
+ context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
50
+
51
+ if output_attentions:
52
+ return context, probs
53
+ return context, None
54
+
55
+
56
+ class BertSdpaSelfAttention(BertSelfAttention):
57
+
58
+ def forward(
59
+ self,
60
+ hidden_states: torch.Tensor,
61
+ key_padding_mask: Optional[torch.Tensor] = None,
62
+ output_attentions: bool = False,
63
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
64
+ if output_attentions:
65
+ return super().forward(hidden_states, key_padding_mask, output_attentions=True)
66
+
67
+ B, T, _ = hidden_states.shape
68
+ q = self._split_heads(self.query(hidden_states))
69
+ k = self._split_heads(self.key(hidden_states))
70
+ v = self._split_heads(self.value(hidden_states))
71
+
72
+ attn_mask = None
73
+ if key_padding_mask is not None:
74
+ attn_mask = torch.zeros(B, 1, 1, T, dtype=q.dtype, device=q.device)
75
+ attn_mask = attn_mask.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
76
+
77
+ context = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
78
+ context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
79
+ return context, None
80
+
81
+
82
+ class BertFlashSelfAttention(BertSelfAttention):
83
+
84
+ def forward(
85
+ self,
86
+ hidden_states: torch.Tensor,
87
+ key_padding_mask: Optional[torch.Tensor] = None,
88
+ output_attentions: bool = False,
89
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
90
+ if output_attentions:
91
+ return super().forward(hidden_states, key_padding_mask, output_attentions=True)
92
+
93
+ try:
94
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
95
+ from flash_attn.bert_padding import pad_input, unpad_input
96
+ except ImportError as e:
97
+ raise ImportError(
98
+ "flash_attn is required for attn_implementation='flash_attention_2'. "
99
+ "Install with: pip install flash-attn --no-build-isolation"
100
+ ) from e
101
+
102
+ B, T, _ = hidden_states.shape
103
+ q = self._split_heads(self.query(hidden_states)).permute(0, 2, 1, 3)
104
+ k = self._split_heads(self.key(hidden_states)).permute(0, 2, 1, 3)
105
+ v = self._split_heads(self.value(hidden_states)).permute(0, 2, 1, 3)
106
+
107
+ orig_dtype = q.dtype
108
+ if orig_dtype not in (torch.float16, torch.bfloat16):
109
+ q, k, v = q.to(torch.bfloat16), k.to(torch.bfloat16), v.to(torch.bfloat16)
110
+
111
+ if key_padding_mask is not None and key_padding_mask.any():
112
+ attend = ~key_padding_mask
113
+ q_u, indices, cu_seqlens, max_seqlen, _ = unpad_input(q, attend)
114
+ k_u, _, _, _, _ = unpad_input(k, attend)
115
+ v_u, _, _, _, _ = unpad_input(v, attend)
116
+ out_u = flash_attn_varlen_func(
117
+ q_u, k_u, v_u,
118
+ cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens,
119
+ max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen,
120
+ causal=False,
121
+ )
122
+ out = pad_input(out_u, indices, B, T)
123
+ else:
124
+ out = flash_attn_func(q, k, v, causal=False)
125
+
126
+ out = out.to(orig_dtype).reshape(B, T, self.all_head_size)
127
+ return out, None
128
+
129
+
130
+ BERT_SELF_ATTENTION_CLASSES = {
131
+ "eager": BertSelfAttention,
132
+ "sdpa": BertSdpaSelfAttention,
133
+ "flash_attention_2": BertFlashSelfAttention,
134
+ }
135
+
136
+
137
+ class BertSelfOutput(nn.Module):
138
+ def __init__(self, config):
139
+ super().__init__()
140
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
141
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
142
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
143
+
144
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
145
+ hidden_states = self.dropout(self.dense(hidden_states))
146
+ return self.LayerNorm(hidden_states + input_tensor)
147
+
148
+
149
+ class BertAttention(nn.Module):
150
+ def __init__(self, config):
151
+ super().__init__()
152
+ attn_cls = BERT_SELF_ATTENTION_CLASSES[getattr(config, "_attn_implementation", "eager")]
153
+ self.self = attn_cls(config)
154
+ self.output = BertSelfOutput(config)
155
+
156
+ def forward(
157
+ self,
158
+ hidden_states: torch.Tensor,
159
+ key_padding_mask: Optional[torch.Tensor],
160
+ output_attentions: bool = False,
161
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
162
+ self_out, attn_weights = self.self(hidden_states, key_padding_mask, output_attentions)
163
+ return self.output(self_out, hidden_states), attn_weights
164
+
165
+
166
+ class BertIntermediate(nn.Module):
167
+ def __init__(self, config):
168
+ super().__init__()
169
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
170
+
171
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
172
+ return F.gelu(self.dense(hidden_states))
173
+
174
+
175
+ class BertOutput(nn.Module):
176
+ def __init__(self, config):
177
+ super().__init__()
178
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
179
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
180
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
181
+
182
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
183
+ hidden_states = self.dropout(self.dense(hidden_states))
184
+ return self.LayerNorm(hidden_states + input_tensor)
185
+
186
+
187
+ class BertLayer(nn.Module):
188
+ def __init__(self, config):
189
+ super().__init__()
190
+ self.attention = BertAttention(config)
191
+ self.intermediate = BertIntermediate(config)
192
+ self.output = BertOutput(config)
193
+
194
+ def forward(
195
+ self,
196
+ hidden_states: torch.Tensor,
197
+ key_padding_mask: Optional[torch.Tensor],
198
+ output_attentions: bool = False,
199
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
200
+ attn_out, attn_weights = self.attention(hidden_states, key_padding_mask, output_attentions)
201
+ return self.output(self.intermediate(attn_out), attn_out), attn_weights
202
+
203
+
204
+ class BertEncoder(nn.Module):
205
+ def __init__(self, config):
206
+ super().__init__()
207
+ self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
208
+
209
+ def forward(
210
+ self,
211
+ hidden_states: torch.Tensor,
212
+ key_padding_mask: Optional[torch.Tensor],
213
+ output_hidden_states: bool = False,
214
+ output_attentions: bool = False,
215
+ ) -> Tuple:
216
+ all_hidden_states = (hidden_states,) if output_hidden_states else None
217
+ all_attentions = () if output_attentions else None
218
+
219
+ for layer in self.layer:
220
+ hidden_states, attn_weights = layer(hidden_states, key_padding_mask, output_attentions)
221
+ if output_hidden_states:
222
+ all_hidden_states = all_hidden_states + (hidden_states,)
223
+ if output_attentions:
224
+ all_attentions = all_attentions + (attn_weights,)
225
+
226
+ return hidden_states, all_hidden_states, all_attentions
227
+
228
+
229
+ class BertEmbeddings(nn.Module):
230
+ def __init__(self, config):
231
+ super().__init__()
232
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
233
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
234
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
235
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
236
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
237
+ self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
238
+
239
+ def forward(self, input_ids: torch.LongTensor, token_type_ids: Optional[torch.LongTensor] = None) -> torch.Tensor:
240
+ B, T = input_ids.shape
241
+ if token_type_ids is None:
242
+ token_type_ids = torch.zeros_like(input_ids)
243
+ x = self.word_embeddings(input_ids)
244
+ x = x + self.position_embeddings(self.position_ids[:, :T])
245
+ x = x + self.token_type_embeddings(token_type_ids)
246
+ return self.dropout(self.LayerNorm(x))
247
+
248
+
249
+ class BertPooler(nn.Module):
250
+ def __init__(self, config):
251
+ super().__init__()
252
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
253
+ self.activation = nn.Tanh()
254
+
255
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
256
+ return self.activation(self.dense(hidden_states[:, 0]))
257
+
258
+
259
+ class BertPredictionHeadTransform(nn.Module):
260
+ def __init__(self, config):
261
+ super().__init__()
262
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
263
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
264
+
265
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
266
+ return self.LayerNorm(F.gelu(self.dense(hidden_states)))
267
+
268
+
269
+ class BertModel(PreTrainedModel):
270
+ config_class = BertUpdatedConfig
271
+ base_model_prefix = "bert"
272
+ _supports_sdpa = True
273
+ _supports_flash_attn_2 = True
274
+
275
+ def __init__(self, config):
276
+ super().__init__(config)
277
+ self.embeddings = BertEmbeddings(config)
278
+ self.encoder = BertEncoder(config)
279
+ self.pooler = BertPooler(config)
280
+ self.post_init()
281
+
282
+ def get_input_embeddings(self):
283
+ return self.embeddings.word_embeddings
284
+
285
+ def set_input_embeddings(self, value):
286
+ self.embeddings.word_embeddings = value
287
+
288
+ def forward(
289
+ self,
290
+ input_ids: torch.LongTensor,
291
+ attention_mask: Optional[torch.Tensor] = None,
292
+ token_type_ids: Optional[torch.LongTensor] = None,
293
+ output_hidden_states: Optional[bool] = None,
294
+ output_attentions: Optional[bool] = None,
295
+ return_dict: Optional[bool] = None,
296
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
297
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
298
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
299
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
300
+
301
+ if attention_mask is None:
302
+ attention_mask = torch.ones_like(input_ids)
303
+ key_padding_mask = attention_mask.eq(0)
304
+ if not key_padding_mask.any():
305
+ key_padding_mask = None
306
+
307
+ x = self.embeddings(input_ids, token_type_ids)
308
+ last_hidden_state, all_hidden_states, all_attentions = self.encoder(
309
+ x, key_padding_mask,
310
+ output_hidden_states=output_hidden_states,
311
+ output_attentions=output_attentions,
312
+ )
313
+ pooled = self.pooler(last_hidden_state)
314
+
315
+ if not return_dict:
316
+ return tuple(v for v in [last_hidden_state, pooled, all_hidden_states, all_attentions] if v is not None)
317
+
318
+ return BaseModelOutputWithPooling(
319
+ last_hidden_state=last_hidden_state,
320
+ pooler_output=pooled,
321
+ hidden_states=all_hidden_states,
322
+ attentions=all_attentions,
323
+ )
324
+
325
+
326
+ class BertForMaskedLM(PreTrainedModel):
327
+ config_class = BertUpdatedConfig
328
+ base_model_prefix = "bert"
329
+ _supports_sdpa = True
330
+ _supports_flash_attn_2 = True
331
+
332
+ def __init__(self, config):
333
+ super().__init__(config)
334
+ self.bert = BertModel(config)
335
+ self.transform = BertPredictionHeadTransform(config)
336
+ self.cls = nn.Linear(config.hidden_size, config.vocab_size)
337
+ self.post_init()
338
+
339
+ def get_input_embeddings(self):
340
+ return self.bert.embeddings.word_embeddings
341
+
342
+ def forward(
343
+ self,
344
+ input_ids: torch.LongTensor,
345
+ attention_mask: Optional[torch.Tensor] = None,
346
+ token_type_ids: Optional[torch.LongTensor] = None,
347
+ labels: Optional[torch.LongTensor] = None,
348
+ output_hidden_states: Optional[bool] = None,
349
+ output_attentions: Optional[bool] = None,
350
+ return_dict: Optional[bool] = None,
351
+ ) -> Union[Tuple, MaskedLMOutput]:
352
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
353
+
354
+ outputs = self.bert(
355
+ input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids,
356
+ output_hidden_states=output_hidden_states, output_attentions=output_attentions,
357
+ return_dict=True,
358
+ )
359
+ logits = self.cls(self.transform(outputs.last_hidden_state))
360
+
361
+ loss = None
362
+ if labels is not None:
363
+ loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100)
364
+
365
+ if not return_dict:
366
+ output = (logits,) + outputs[2:]
367
+ return (loss,) + output if loss is not None else output
368
+
369
+ return MaskedLMOutput(
370
+ loss=loss, logits=logits,
371
+ hidden_states=outputs.hidden_states, attentions=outputs.attentions,
372
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "sep_token": "[SEP]",
4
+ "pad_token": "[PAD]",
5
+ "mask_token": "[MASK]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenization_splicebert.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from transformers import PreTrainedTokenizer
4
+
5
+ _DEFAULT_VOCAB = {
6
+ "[PAD]": 0,
7
+ "[UNK]": 1,
8
+ "[CLS]": 2,
9
+ "[SEP]": 3,
10
+ "[MASK]": 4,
11
+ "N": 5,
12
+ "A": 6,
13
+ "C": 7,
14
+ "G": 8,
15
+ "T": 9,
16
+ }
17
+
18
+
19
+ class SpliceBERTTokenizer(PreTrainedTokenizer):
20
+ """Single-nucleotide tokenizer for SpliceBERT.
21
+
22
+ Automatically converts U->T and adds [CLS]/[SEP] special tokens.
23
+ Raw sequences (not pre-spaced) are accepted.
24
+ """
25
+
26
+ vocab_files_names = {"vocab_file": "vocab.json"}
27
+ model_input_names = ["input_ids", "attention_mask"]
28
+
29
+ def __init__(
30
+ self,
31
+ vocab_file=None,
32
+ cls_token="[CLS]",
33
+ sep_token="[SEP]",
34
+ pad_token="[PAD]",
35
+ mask_token="[MASK]",
36
+ unk_token="[UNK]",
37
+ **kwargs,
38
+ ):
39
+ self._vocab = dict(_DEFAULT_VOCAB)
40
+ if vocab_file and os.path.isfile(vocab_file):
41
+ with open(vocab_file) as f:
42
+ self._vocab = json.load(f)
43
+ self._ids_to_tokens = {v: k for k, v in self._vocab.items()}
44
+ super().__init__(
45
+ cls_token=cls_token,
46
+ sep_token=sep_token,
47
+ pad_token=pad_token,
48
+ mask_token=mask_token,
49
+ unk_token=unk_token,
50
+ **kwargs,
51
+ )
52
+
53
+ @property
54
+ def vocab_size(self):
55
+ return len(self._vocab)
56
+
57
+ def get_vocab(self):
58
+ return dict(self._vocab)
59
+
60
+ def _tokenize(self, text):
61
+ return list(text.upper().replace("U", "T").replace(" ", ""))
62
+
63
+ def _convert_token_to_id(self, token):
64
+ return self._vocab.get(token, self._vocab["[UNK]"])
65
+
66
+ def _convert_id_to_token(self, index):
67
+ return self._ids_to_tokens.get(index, "[UNK]")
68
+
69
+ def save_vocabulary(self, save_directory, filename_prefix=None):
70
+ os.makedirs(save_directory, exist_ok=True)
71
+ fname = (filename_prefix + "-" if filename_prefix else "") + "vocab.json"
72
+ path = os.path.join(save_directory, fname)
73
+ with open(path, "w") as f:
74
+ json.dump(self._vocab, f, indent=2)
75
+ return (path,)
76
+
77
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
78
+ cls = [self.cls_token_id]
79
+ sep = [self.sep_token_id]
80
+ if token_ids_1 is None:
81
+ return cls + token_ids_0 + sep
82
+ return cls + token_ids_0 + sep + cls + token_ids_1 + sep
83
+
84
+ def get_special_tokens_mask(self, token_ids_0, token_ids_1=None,
85
+ already_has_special_tokens=False):
86
+ if already_has_special_tokens:
87
+ return super().get_special_tokens_mask(
88
+ token_ids_0, token_ids_1, already_has_special_tokens=True
89
+ )
90
+ mask = [1] + [0] * len(token_ids_0) + [1]
91
+ if token_ids_1 is not None:
92
+ mask += [1] + [0] * len(token_ids_1) + [1]
93
+ return mask
94
+
95
+ def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
96
+ if token_ids_1 is None:
97
+ return [0] + token_ids_0 + [0]
98
+ return [0] + token_ids_0 + [0, 0] + token_ids_1 + [0]
tokenizer_config.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenization_splicebert.SpliceBERTTokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "model_max_length": 510,
9
+ "tokenizer_class": "SpliceBERTTokenizer",
10
+ "cls_token": "[CLS]",
11
+ "sep_token": "[SEP]",
12
+ "eos_token": "[SEP]",
13
+ "pad_token": "[PAD]",
14
+ "mask_token": "[MASK]",
15
+ "unk_token": "[UNK]"
16
+ }
vocab.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "[PAD]": 0,
3
+ "[UNK]": 1,
4
+ "[CLS]": 2,
5
+ "[SEP]": 3,
6
+ "[MASK]": 4,
7
+ "N": 5,
8
+ "A": 6,
9
+ "C": 7,
10
+ "G": 8,
11
+ "T": 9
12
+ }