weicaijaden commited on
Commit
672f4f2
·
verified ·
1 Parent(s): 6fc875e

Upload 8 files

Browse files
Files changed (8) hide show
  1. README.md +95 -3
  2. config.json +27 -0
  3. gitattributes +35 -0
  4. modeling_mutbert.py +1136 -0
  5. pytorch_model.bin +3 -0
  6. tokenizer.json +153 -0
  7. tokenizer_config.json +1 -0
  8. vocab.txt +9 -0
README.md CHANGED
@@ -1,3 +1,95 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ tags:
4
+ - biology
5
+ - transformers
6
+ - Feature Extraction
7
+ - bioRxiv 2025.01.23.634452
8
+ ---
9
+
10
+ **This is repository for MutBERT (pretrained with mutation data in human genome)**.
11
+
12
+ **You can find all MutBERT variants at [here](https://huggingface.co/JadenLong).**
13
+
14
+ ## Introduction
15
+
16
+ This is the official pre-trained model introduced in MutBERT: Probabilistic Genome Representation Improves Genomics Foundation Models.
17
+
18
+ We sincerely appreciate the Tochka-Al team for the ruRoPEBert implementation, which serves as the base of MutBERT development.
19
+
20
+ MutBERT is a transformer-based genome foundation model trained only on Human genome.
21
+
22
+ ## Model Source
23
+
24
+ - Repository: [MutBERT](https://github.com/ai4nucleome/mutBERT)
25
+ - Paper: [MutBERT: Probabilistic Genome Representation Improves Genomics Foundation Models](https://www.biorxiv.org/content/10.1101/2025.01.23.634452v1)
26
+
27
+ ## Usage
28
+
29
+ ### Load tokenizer and model
30
+
31
+ ```python
32
+ from transformers import AutoTokenizer, AutoModel
33
+
34
+ model_name = "JadenLong/MutBERT"
35
+ # Optional: JadenLong/MutBERT-Huamn-Ref, JadenLong/MutBERT-Multi
36
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
37
+ model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
38
+ ```
39
+
40
+ The default attention is flash attention("sdpa"). If you want use basic attention, you can replace it with "eager". Please refer to [here](https://huggingface.co/JadenLong/MutBERT/blob/main/modeling_mutbert.py#L438).
41
+
42
+ ### Get embeddings
43
+
44
+ ```python
45
+ import torch
46
+ import torch.nn.functional as F
47
+
48
+ from transformers import AutoTokenizer, AutoModel
49
+
50
+ model_name = "JadenLong/MutBERT"
51
+ # Optional: JadenLong/MutBERT-Huamn-Ref, JadenLong/MutBERT-Multi
52
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
53
+ model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
54
+
55
+ dna = "ATCGGGGCCCATTA"
56
+ inputs = tokenizer(dna, return_tensors='pt')["input_ids"]
57
+
58
+ mut_inputs = F.one_hot(inputs, num_classes=len(tokenizer)).float().to("cpu") # len(tokenizer) is vocab size
59
+ last_hidden_state = model(mut_inputs).last_hidden_state # [1, sequence_length, 768]
60
+ # or: last_hidden_state = model(mut_inputs)[0] # [1, sequence_length, 768]
61
+
62
+ # embedding with mean pooling
63
+ embedding_mean = torch.mean(last_hidden_state[0], dim=0)
64
+ print(embedding_mean.shape) # expect to be 768
65
+
66
+ # embedding with max pooling
67
+ embedding_max = torch.max(last_hidden_state[0], dim=0)[0]
68
+ print(embedding_max.shape) # expect to be 768
69
+ ```
70
+
71
+ ### Using as a Classifier
72
+
73
+ ```python
74
+ from transformers import AutoModelForSequenceClassification
75
+
76
+ model_name = "JadenLong/MutBERT"
77
+ # Optional: JadenLong/MutBERT-Huamn-Ref, JadenLong/MutBERT-Multi
78
+ model = AutoModelForSequenceClassification.from_pretrained(model_name, trust_remote_code=True, num_labels=2)
79
+ ```
80
+
81
+ ### With RoPE scaling
82
+
83
+ Allowed types for RoPE scaling are: `linear` and `dynamic`. To extend the model's context window you need to add rope_scaling parameter.
84
+
85
+ If you want to scale your model context by 2x:
86
+
87
+ ```python
88
+ model_name = "JadenLong/MutBERT"
89
+ # Optional: JadenLong/MutBERT-Huamn-Ref, JadenLong/MutBERT-Multi
90
+ model = AutoModel.from_pretrained(model_name,
91
+ trust_remote_code=True,
92
+ rope_scaling={'type': 'dynamic','factor': 2.0}
93
+ ) # 2.0 for x2 scaling, 4.0 for x4, etc..
94
+ ```
95
+
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ { "_name_or_path": "JadenLong/MutBERT",
2
+ "auto_map": {
3
+ "AutoConfig": "modeling_mutbert.RoPEBertConfig",
4
+ "AutoModel": "modeling_mutbert.RoPEBertModel",
5
+ "AutoModelForMaskedLM": "modeling_mutbert.RoPEBertForMaskedLM",
6
+ "AutoModelForSequenceClassification": "modeling_mutbert.RoPEBertForSequenceClassification"
7
+ },
8
+ "attention_probs_dropout_prob": 0.1,
9
+ "classifier_dropout": null,
10
+ "hidden_act": "gelu",
11
+ "hidden_dropout_prob": 0.1,
12
+ "hidden_size": 768,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 3072,
15
+ "layer_norm_eps": 1e-12,
16
+ "max_position_embeddings": 512,
17
+ "model_type": "bert",
18
+ "num_attention_heads": 12,
19
+ "num_hidden_layers": 12,
20
+ "pad_token_id": 3,
21
+ "pooler_type": "mean",
22
+ "rope_scaling": null,
23
+ "rope_theta": 10000.0,
24
+ "transformers_version": "4.45.2",
25
+ "type_vocab_size": 2,
26
+ "vocab_size": 9
27
+ }
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
modeling_mutbert.py ADDED
@@ -0,0 +1,1136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch BERT model with ROPE."""
17
+
18
+
19
+ import math
20
+ from dataclasses import dataclass
21
+ from typing import Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ import torch.nn.functional as F
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+ from transformers import PretrainedConfig
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (
31
+ BaseModelOutputWithPooling,
32
+ MaskedLMOutput,
33
+ SequenceClassifierOutput,
34
+ )
35
+ from transformers.modeling_utils import PreTrainedModel
36
+ from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
37
+ from transformers.utils import (
38
+ ModelOutput,
39
+ logging,
40
+ )
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class RoPEBertConfig(PretrainedConfig):
46
+
47
+ model_type = "bert"
48
+
49
+ def __init__(
50
+ self,
51
+ vocab_size=9,
52
+ hidden_size=768,
53
+ num_hidden_layers=12,
54
+ num_attention_heads=12,
55
+ intermediate_size=3072,
56
+ hidden_act="gelu",
57
+ pooler_type="mean", # first_token_transform
58
+ hidden_dropout_prob=0.1,
59
+ attention_probs_dropout_prob=0.1,
60
+ max_position_embeddings=512,
61
+ type_vocab_size=2,
62
+ initializer_range=0.02,
63
+ layer_norm_eps=1e-12,
64
+ pad_token_id=0,
65
+ classifier_dropout=None,
66
+ rope_theta=10000.0,
67
+ rope_scaling=None,
68
+ **kwargs,
69
+ ):
70
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
71
+
72
+ self.vocab_size = vocab_size
73
+ self.hidden_size = hidden_size
74
+ self.num_hidden_layers = num_hidden_layers
75
+ self.num_attention_heads = num_attention_heads
76
+ self.hidden_act = hidden_act
77
+ self.intermediate_size = intermediate_size
78
+ self.hidden_dropout_prob = hidden_dropout_prob
79
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
80
+ self.max_position_embeddings = max_position_embeddings
81
+ self.type_vocab_size = type_vocab_size
82
+ self.initializer_range = initializer_range
83
+ self.layer_norm_eps = layer_norm_eps
84
+ self.classifier_dropout = classifier_dropout
85
+ self.rope_theta = rope_theta
86
+ self.rope_scaling = rope_scaling
87
+ self.pooler_type = pooler_type
88
+
89
+ self._pooler_type_validation()
90
+ self._rope_scaling_validation()
91
+
92
+ def _pooler_type_validation(self):
93
+ if self.pooler_type not in ['first_token_transform', 'mean']:
94
+ raise ValueError(
95
+ f"`pooler_type` must be one of `first_token_transform` or `mean`, got {self.pooler_type}"
96
+ )
97
+
98
+ def _rope_scaling_validation(self):
99
+ """
100
+ Validate the `rope_scaling` configuration.
101
+ """
102
+ if self.rope_scaling is None:
103
+ return
104
+
105
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
106
+ raise ValueError(
107
+ "`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
108
+ f"got {self.rope_scaling}"
109
+ )
110
+ rope_scaling_type = self.rope_scaling.get("type", None)
111
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
112
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
113
+ raise ValueError(
114
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
115
+ )
116
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
117
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
118
+
119
+
120
+ class RoPEBertEmbeddings(nn.Module):
121
+ """Construct the embeddings from word, token_type embeddings."""
122
+
123
+ def __init__(self, config):
124
+ super().__init__()
125
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
126
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
127
+
128
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
129
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
130
+
131
+ def forward(
132
+ self,
133
+ input_ids: Optional[torch.FloatTensor] = None,
134
+ token_type_ids: Optional[torch.LongTensor] = None,
135
+ inputs_embeds: Optional[torch.FloatTensor] = None,
136
+ ) -> torch.Tensor:
137
+ if inputs_embeds is None:
138
+ # input_ids: b, l, v
139
+ inputs_embeds = torch.matmul(input_ids, self.word_embeddings.weight)
140
+ # self.word_embeddings(input_ids)
141
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
142
+
143
+ embeddings = inputs_embeds + token_type_embeddings
144
+
145
+ embeddings = self.LayerNorm(embeddings)
146
+ embeddings = self.dropout(embeddings)
147
+ return embeddings
148
+
149
+
150
+ class BertRotaryEmbedding(nn.Module):
151
+ def __init__(self, dim, max_position_embeddings=512, base=10000, device=None):
152
+ super().__init__()
153
+
154
+ self.dim = dim
155
+ self.max_position_embeddings = max_position_embeddings
156
+ self.base = base
157
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
158
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
159
+
160
+ # Build here to make `torch.jit.trace` work.
161
+ self._set_cos_sin_cache(
162
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
163
+ )
164
+
165
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
166
+ self.max_seq_len_cached = seq_len
167
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
168
+
169
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq) # equal to torch.outer(t, inv_freq)
170
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
+ emb = torch.cat((freqs, freqs), dim=-1)
172
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
173
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
174
+
175
+ def forward(self, x, seq_len=None):
176
+ # x: [bs, num_attention_heads, seq_len, head_size]
177
+ if seq_len > self.max_seq_len_cached:
178
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
179
+
180
+ return (
181
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
182
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
183
+ )
184
+
185
+
186
+ class BertLinearScalingRotaryEmbedding(BertRotaryEmbedding):
187
+ """BertRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
188
+
189
+ def __init__(self, dim, max_position_embeddings=512, base=10000, device=None, scaling_factor=1.0):
190
+ self.scaling_factor = scaling_factor
191
+ super().__init__(dim, max_position_embeddings, base, device)
192
+
193
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
194
+ self.max_seq_len_cached = seq_len
195
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
196
+ t = t / self.scaling_factor
197
+
198
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
199
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
200
+ emb = torch.cat((freqs, freqs), dim=-1)
201
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
202
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
203
+
204
+
205
+ class BertDynamicNTKScalingRotaryEmbedding(BertRotaryEmbedding):
206
+ """BertRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
207
+
208
+ def __init__(self, dim, max_position_embeddings=512, base=10000, device=None, scaling_factor=1.0):
209
+ self.scaling_factor = scaling_factor
210
+ super().__init__(dim, max_position_embeddings, base, device)
211
+
212
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
213
+ self.max_seq_len_cached = seq_len
214
+
215
+ if seq_len > self.max_position_embeddings:
216
+ base = self.base * (
217
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
218
+ ) ** (self.dim / (self.dim - 2))
219
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
220
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
221
+
222
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
223
+
224
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
225
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
226
+ emb = torch.cat((freqs, freqs), dim=-1)
227
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
228
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
229
+
230
+
231
+ def rotate_half(x):
232
+ """Rotates half the hidden dims of the input."""
233
+ x1 = x[..., : x.shape[-1] // 2]
234
+ x2 = x[..., x.shape[-1] // 2 :]
235
+ return torch.cat((-x2, x1), dim=-1)
236
+
237
+
238
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
239
+ """Applies Rotary Position Embedding to the query and key tensors.
240
+ Args:
241
+ q (`torch.Tensor`): The query tensor.
242
+ k (`torch.Tensor`): The key tensor.
243
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
244
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
245
+ position_ids (`torch.Tensor`):
246
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
247
+ used to pass offsetted position ids when working with a KV-cache.
248
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
249
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
250
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
251
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
252
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
253
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
254
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
255
+ Returns:
256
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
257
+ """
258
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
259
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
260
+ q_embed = (q * cos) + (rotate_half(q) * sin)
261
+ k_embed = (k * cos) + (rotate_half(k) * sin)
262
+ return q_embed, k_embed
263
+
264
+
265
+ class RoPEBertSelfAttention(nn.Module):
266
+
267
+ def __init__(self, config: RoPEBertConfig):
268
+ super().__init__()
269
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
270
+ raise ValueError(
271
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
272
+ f"heads ({config.num_attention_heads})"
273
+ )
274
+
275
+ self.num_attention_heads = config.num_attention_heads
276
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
277
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
278
+
279
+ self.max_position_embeddings = config.max_position_embeddings
280
+ self.rope_theta = config.rope_theta
281
+
282
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
283
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
284
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
285
+
286
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
287
+
288
+ self.config = config
289
+
290
+ self._init_rope()
291
+
292
+ def _init_rope(self):
293
+ if self.config.rope_scaling is None:
294
+ self.rotary_emb = BertRotaryEmbedding(
295
+ self.attention_head_size,
296
+ max_position_embeddings=self.max_position_embeddings,
297
+ base=self.rope_theta,
298
+ )
299
+ else:
300
+ scaling_type = self.config.rope_scaling["type"]
301
+ scaling_factor = self.config.rope_scaling["factor"]
302
+ if scaling_type == "linear":
303
+ self.rotary_emb = BertLinearScalingRotaryEmbedding(
304
+ self.attention_head_size,
305
+ max_position_embeddings=self.max_position_embeddings,
306
+ scaling_factor=scaling_factor,
307
+ base=self.rope_theta,
308
+ )
309
+ elif scaling_type == "dynamic":
310
+ self.rotary_emb = BertDynamicNTKScalingRotaryEmbedding(
311
+ self.attention_head_size,
312
+ max_position_embeddings=self.max_position_embeddings,
313
+ scaling_factor=scaling_factor,
314
+ base=self.rope_theta,
315
+ )
316
+ else:
317
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
318
+
319
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
320
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
321
+ x = x.view(new_x_shape)
322
+ return x.permute(0, 2, 1, 3)
323
+
324
+ def forward(
325
+ self,
326
+ hidden_states: torch.Tensor,
327
+ attention_mask: Optional[torch.FloatTensor] = None,
328
+ head_mask: Optional[torch.FloatTensor] = None,
329
+ position_ids: Optional[torch.LongTensor] = None,
330
+ output_attentions: Optional[bool] = False,
331
+ ) -> Tuple[torch.Tensor]:
332
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
333
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
334
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
335
+
336
+ kv_seq_len = key_layer.shape[-2]
337
+ cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
338
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
339
+
340
+ # Take the dot product between "query" and "key" to get the raw attention scores.
341
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
342
+
343
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
344
+ if attention_mask is not None:
345
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
346
+ attention_scores = attention_scores + attention_mask
347
+
348
+ # Normalize the attention scores to probabilities.
349
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
350
+
351
+ # This is actually dropping out entire tokens to attend to, which might
352
+ # seem a bit unusual, but is taken from the original Transformer paper.
353
+ attention_probs = self.dropout(attention_probs)
354
+
355
+ # Mask heads if we want to
356
+ if head_mask is not None:
357
+ attention_probs = attention_probs * head_mask
358
+
359
+ context_layer = torch.matmul(attention_probs, value_layer)
360
+
361
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
362
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
363
+ context_layer = context_layer.view(new_context_layer_shape)
364
+
365
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
366
+
367
+ return outputs
368
+
369
+
370
+ class RoPEBertSdpaAttention(RoPEBertSelfAttention):
371
+
372
+ def forward(
373
+ self,
374
+ hidden_states: torch.Tensor,
375
+ attention_mask: Optional[torch.FloatTensor] = None,
376
+ head_mask: Optional[torch.FloatTensor] = None,
377
+ position_ids: Optional[torch.LongTensor] = None,
378
+ output_attentions: Optional[bool] = False,
379
+ ) -> Tuple[torch.Tensor]:
380
+
381
+ bsz, q_len, _ = hidden_states.size()
382
+
383
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
384
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
385
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
386
+
387
+ kv_seq_len = key_layer.shape[-2]
388
+ cos, sin = self.rotary_emb(value_layer, seq_len=kv_seq_len)
389
+ query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin, position_ids)
390
+
391
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
392
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
393
+ if query_layer.device.type == "cuda" and attention_mask is not None:
394
+ query_layer = query_layer.contiguous()
395
+ key_layer = key_layer.contiguous()
396
+ value_layer = value_layer.contiguous()
397
+
398
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
399
+ query_layer,
400
+ key_layer,
401
+ value_layer,
402
+ attn_mask=attention_mask,
403
+ dropout_p=self.config.attention_probs_dropout_prob if self.training else 0.0,
404
+ is_causal=False
405
+ )
406
+
407
+ context_layer = context_layer.transpose(1, 2).contiguous()
408
+ context_layer = context_layer.reshape(bsz, q_len, self.all_head_size)
409
+
410
+ outputs = (context_layer,)
411
+
412
+ return outputs
413
+
414
+
415
+ ROPEBERT_ATTENTION_CLASSES = {
416
+ "eager": RoPEBertSelfAttention,
417
+ "sdpa": RoPEBertSdpaAttention,
418
+ }
419
+
420
+
421
+ class RoPEBertSelfOutput(nn.Module):
422
+ def __init__(self, config):
423
+ super().__init__()
424
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
425
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
426
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
427
+
428
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
429
+ hidden_states = self.dense(hidden_states)
430
+ hidden_states = self.dropout(hidden_states)
431
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
432
+ return hidden_states
433
+
434
+
435
+ class RoPEBertAttention(nn.Module):
436
+ def __init__(self, config):
437
+ super().__init__()
438
+ self.self = ROPEBERT_ATTENTION_CLASSES["sdpa"](config=config)
439
+ self.output = RoPEBertSelfOutput(config)
440
+ self.pruned_heads = set()
441
+
442
+ def prune_heads(self, heads):
443
+ if len(heads) == 0:
444
+ return
445
+ heads, index = find_pruneable_heads_and_indices(
446
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
447
+ )
448
+
449
+ # Prune linear layers
450
+ self.self.query = prune_linear_layer(self.self.query, index)
451
+ self.self.key = prune_linear_layer(self.self.key, index)
452
+ self.self.value = prune_linear_layer(self.self.value, index)
453
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
454
+
455
+ # Update hyper params and store pruned heads
456
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
457
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
458
+ self.pruned_heads = self.pruned_heads.union(heads)
459
+
460
+ def forward(
461
+ self,
462
+ hidden_states: torch.Tensor,
463
+ attention_mask: Optional[torch.FloatTensor] = None,
464
+ head_mask: Optional[torch.FloatTensor] = None,
465
+ position_ids: Optional[torch.LongTensor] = None,
466
+ output_attentions: Optional[bool] = False,
467
+ ) -> Tuple[torch.Tensor]:
468
+ self_outputs = self.self(
469
+ hidden_states,
470
+ attention_mask,
471
+ head_mask,
472
+ position_ids,
473
+ output_attentions
474
+ )
475
+ attention_output = self.output(self_outputs[0], hidden_states)
476
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
477
+ return outputs
478
+
479
+
480
+ class RoPEBertIntermediate(nn.Module):
481
+ def __init__(self, config):
482
+ super().__init__()
483
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
484
+ if isinstance(config.hidden_act, str):
485
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
486
+ else:
487
+ self.intermediate_act_fn = config.hidden_act
488
+
489
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
490
+ hidden_states = self.dense(hidden_states)
491
+ hidden_states = self.intermediate_act_fn(hidden_states)
492
+ return hidden_states
493
+
494
+
495
+ class RoPEBertOutput(nn.Module):
496
+ def __init__(self, config):
497
+ super().__init__()
498
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
499
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
500
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
501
+
502
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
503
+ hidden_states = self.dense(hidden_states)
504
+ hidden_states = self.dropout(hidden_states)
505
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
506
+ return hidden_states
507
+
508
+
509
+ class RoPEBertLayer(nn.Module):
510
+ def __init__(self, config):
511
+ super().__init__()
512
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
513
+ self.seq_len_dim = 1
514
+ self.attention = RoPEBertAttention(config)
515
+ self.intermediate = RoPEBertIntermediate(config)
516
+ self.output = RoPEBertOutput(config)
517
+
518
+ def forward(
519
+ self,
520
+ hidden_states: torch.Tensor,
521
+ attention_mask: Optional[torch.FloatTensor] = None,
522
+ head_mask: Optional[torch.FloatTensor] = None,
523
+ position_ids: Optional[torch.LongTensor] = None,
524
+ output_attentions: Optional[bool] = False,
525
+ ) -> Tuple[torch.Tensor]:
526
+ self_attention_outputs = self.attention(
527
+ hidden_states,
528
+ attention_mask,
529
+ head_mask,
530
+ position_ids,
531
+ output_attentions=output_attentions
532
+ )
533
+ attention_output = self_attention_outputs[0]
534
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
535
+
536
+ layer_output = apply_chunking_to_forward(
537
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
538
+ )
539
+ outputs = (layer_output,) + outputs
540
+
541
+ return outputs
542
+
543
+ def feed_forward_chunk(self, attention_output):
544
+ intermediate_output = self.intermediate(attention_output)
545
+ layer_output = self.output(intermediate_output, attention_output)
546
+ return layer_output
547
+
548
+
549
+ class RoPEBertEncoder(nn.Module):
550
+ def __init__(self, config):
551
+ super().__init__()
552
+ self.config = config
553
+ self.layer = nn.ModuleList([RoPEBertLayer(config) for _ in range(config.num_hidden_layers)])
554
+ self.gradient_checkpointing = False
555
+
556
+ def forward(
557
+ self,
558
+ hidden_states: torch.Tensor,
559
+ attention_mask: Optional[torch.FloatTensor] = None,
560
+ head_mask: Optional[torch.FloatTensor] = None,
561
+ position_ids: Optional[torch.LongTensor] = None,
562
+ output_attentions: Optional[bool] = False,
563
+ output_hidden_states: Optional[bool] = False,
564
+ return_dict: Optional[bool] = True,
565
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPooling]:
566
+ all_hidden_states = () if output_hidden_states else None
567
+ all_self_attentions = () if output_attentions else None
568
+
569
+ for i, layer_module in enumerate(self.layer):
570
+ if output_hidden_states:
571
+ all_hidden_states = all_hidden_states + (hidden_states,)
572
+
573
+ layer_head_mask = head_mask[i] if head_mask is not None else None
574
+
575
+ if self.gradient_checkpointing and self.training:
576
+ layer_outputs = self._gradient_checkpointing_func(
577
+ layer_module.__call__,
578
+ hidden_states,
579
+ attention_mask,
580
+ layer_head_mask,
581
+ position_ids,
582
+ output_attentions
583
+ )
584
+ else:
585
+ layer_outputs = layer_module(
586
+ hidden_states,
587
+ attention_mask,
588
+ layer_head_mask,
589
+ position_ids,
590
+ output_attentions
591
+ )
592
+
593
+ hidden_states = layer_outputs[0]
594
+ if output_attentions:
595
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
596
+
597
+ if output_hidden_states:
598
+ all_hidden_states = all_hidden_states + (hidden_states,)
599
+
600
+ if not return_dict:
601
+ return tuple(
602
+ v
603
+ for v in [
604
+ hidden_states,
605
+ all_hidden_states,
606
+ all_self_attentions,
607
+ ]
608
+ if v is not None
609
+ )
610
+ return BaseModelOutputWithPooling(
611
+ last_hidden_state=hidden_states,
612
+ hidden_states=all_hidden_states,
613
+ attentions=all_self_attentions,
614
+ )
615
+
616
+
617
+ class RoPEBertMeanTokensPooler(nn.Module):
618
+ def __init__(self, config):
619
+ super().__init__()
620
+
621
+ def forward(self, hidden_states: torch.Tensor, attention_mask: torch.LongTensor) -> torch.Tensor:
622
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(hidden_states.size()).float()
623
+ pooled_output = torch.sum(hidden_states * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
624
+
625
+ return pooled_output
626
+
627
+
628
+ class RoPEBertCLSTokenTransformPooler(nn.Module):
629
+ def __init__(self, config):
630
+ super().__init__()
631
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
632
+ self.activation = nn.Tanh()
633
+
634
+ def forward(self, hidden_states: torch.Tensor, attention_mask: torch.LongTensor) -> torch.Tensor:
635
+
636
+ first_token_tensor = hidden_states[:, 0]
637
+ pooled_output = self.dense(first_token_tensor)
638
+ pooled_output = self.activation(pooled_output)
639
+
640
+ return pooled_output
641
+
642
+
643
+ ROPEBERT_POOLER_CLASSES = {
644
+ "mean": RoPEBertMeanTokensPooler,
645
+ "first_token_transform": RoPEBertCLSTokenTransformPooler,
646
+ }
647
+
648
+
649
+ class RoPEBertPredictionHeadTransform(nn.Module):
650
+ def __init__(self, config):
651
+ super().__init__()
652
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
653
+ if isinstance(config.hidden_act, str):
654
+ self.transform_act_fn = ACT2FN[config.hidden_act]
655
+ else:
656
+ self.transform_act_fn = config.hidden_act
657
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
658
+
659
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
660
+ hidden_states = self.dense(hidden_states)
661
+ hidden_states = self.transform_act_fn(hidden_states)
662
+ hidden_states = self.LayerNorm(hidden_states)
663
+ return hidden_states
664
+
665
+
666
+ class RoPEBertLMPredictionHead(nn.Module):
667
+ def __init__(self, config):
668
+ super().__init__()
669
+ self.transform = RoPEBertPredictionHeadTransform(config)
670
+
671
+ # The output weights are the same as the input embeddings, but there is
672
+ # an output-only bias for each token.
673
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
674
+
675
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
676
+
677
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
678
+ self.decoder.bias = self.bias
679
+
680
+ def forward(self, hidden_states):
681
+ hidden_states = self.transform(hidden_states)
682
+ hidden_states = self.decoder(hidden_states)
683
+ return hidden_states
684
+
685
+
686
+ class RoPEBertOnlyMLMHead(nn.Module):
687
+ def __init__(self, config):
688
+ super().__init__()
689
+ self.predictions = RoPEBertLMPredictionHead(config)
690
+
691
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
692
+ prediction_scores = self.predictions(sequence_output)
693
+ return prediction_scores
694
+
695
+
696
+ class RoPEBertOnlyNSPHead(nn.Module):
697
+ def __init__(self, config):
698
+ super().__init__()
699
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
700
+
701
+ def forward(self, pooled_output):
702
+ seq_relationship_score = self.seq_relationship(pooled_output)
703
+ return seq_relationship_score
704
+
705
+
706
+ class RoPEBertPreTrainingHeads(nn.Module):
707
+ def __init__(self, config):
708
+ super().__init__()
709
+ self.predictions = RoPEBertLMPredictionHead(config)
710
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
711
+
712
+ def forward(self, sequence_output, pooled_output):
713
+ prediction_scores = self.predictions(sequence_output)
714
+ seq_relationship_score = self.seq_relationship(pooled_output)
715
+ return prediction_scores, seq_relationship_score
716
+
717
+
718
+ class RoPEBertPreTrainedModel(PreTrainedModel):
719
+ """
720
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
721
+ models.
722
+ """
723
+
724
+ config_class = RoPEBertConfig
725
+ base_model_prefix = "bert"
726
+ supports_gradient_checkpointing = True
727
+ _supports_sdpa = True
728
+
729
+ def _init_weights(self, module):
730
+ """Initialize the weights"""
731
+ if isinstance(module, nn.Linear):
732
+ # Slightly different from the TF version which uses truncated_normal for initialization
733
+ # cf https://github.com/pytorch/pytorch/pull/5617
734
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
735
+ if module.bias is not None:
736
+ module.bias.data.zero_()
737
+ elif isinstance(module, nn.Embedding):
738
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
739
+ if module.padding_idx is not None:
740
+ module.weight.data[module.padding_idx].zero_()
741
+ elif isinstance(module, nn.LayerNorm):
742
+ module.bias.data.zero_()
743
+ module.weight.data.fill_(1.0)
744
+
745
+
746
+ @dataclass
747
+ class RoPEBertForPreTrainingOutput(ModelOutput):
748
+
749
+ loss: Optional[torch.FloatTensor] = None
750
+ prediction_logits: torch.FloatTensor = None
751
+ seq_relationship_logits: torch.FloatTensor = None
752
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
753
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
754
+
755
+
756
+ class RoPEBertModel(RoPEBertPreTrainedModel):
757
+
758
+ def __init__(self, config, add_pooling_layer=True):
759
+ super().__init__(config)
760
+ self.config = config
761
+
762
+ self.embeddings = RoPEBertEmbeddings(config)
763
+ self.encoder = RoPEBertEncoder(config)
764
+
765
+ self.pooler = ROPEBERT_POOLER_CLASSES[config.pooler_type](config=config) if add_pooling_layer else None
766
+
767
+ # Initialize weights and apply final processing
768
+ self.post_init()
769
+
770
+ def get_input_embeddings(self):
771
+ return self.embeddings.word_embeddings
772
+
773
+ def set_input_embeddings(self, value):
774
+ self.embeddings.word_embeddings = value
775
+
776
+ def _prune_heads(self, heads_to_prune):
777
+ """
778
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
779
+ class PreTrainedModel
780
+ """
781
+ for layer, heads in heads_to_prune.items():
782
+ self.encoder.layer[layer].attention.prune_heads(heads)
783
+
784
+ def forward(
785
+ self,
786
+ input_ids: Optional[torch.Tensor] = None,
787
+ attention_mask: Optional[torch.Tensor] = None,
788
+ token_type_ids: Optional[torch.Tensor] = None,
789
+ position_ids: Optional[torch.Tensor] = None,
790
+ head_mask: Optional[torch.Tensor] = None,
791
+ inputs_embeds: Optional[torch.Tensor] = None,
792
+ output_attentions: Optional[bool] = None,
793
+ output_hidden_states: Optional[bool] = None,
794
+ return_dict: Optional[bool] = None,
795
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPooling]:
796
+
797
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
798
+ output_hidden_states = (
799
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
800
+ )
801
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
802
+
803
+ if input_ids is not None and inputs_embeds is not None:
804
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
805
+ elif input_ids is not None:
806
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
807
+ input_shape = input_ids.size()[:-1] # modified
808
+ elif inputs_embeds is not None:
809
+ input_shape = inputs_embeds.size()[:-1]
810
+ else:
811
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
812
+
813
+ if output_attentions and self.config.attn_implementation == 'sdpa':
814
+ logger.warning("Cant use output_attentions with sdpa attention, turning off")
815
+ output_attentions = False
816
+
817
+ batch_size, seq_length = input_shape
818
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
819
+
820
+ if attention_mask is None:
821
+ attention_mask = torch.ones((batch_size, seq_length), device=device)
822
+
823
+ if position_ids is None:
824
+ position_ids = torch.arange(
825
+ 0, seq_length, dtype=torch.long, device=device
826
+ )
827
+ position_ids = position_ids.unsqueeze(0)
828
+
829
+ if token_type_ids is None:
830
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
831
+
832
+ # We can provide a self-attention mask of dimensions [batch_size, 1, from_seq_length, to_seq_length]
833
+ # ourselves in which case we just need to make it broadcastable to all heads.
834
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
835
+
836
+ # Prepare head mask if needed
837
+ # 1.0 in head_mask indicate we keep the head
838
+ # attention_probs has shape bsz x n_heads x N x N
839
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
840
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
841
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
842
+
843
+ embedding_output = self.embeddings(
844
+ input_ids=input_ids,
845
+ token_type_ids=token_type_ids,
846
+ inputs_embeds=inputs_embeds
847
+ )
848
+ encoder_outputs = self.encoder(
849
+ embedding_output,
850
+ attention_mask=extended_attention_mask,
851
+ head_mask=head_mask,
852
+ position_ids=position_ids,
853
+ output_attentions=output_attentions,
854
+ output_hidden_states=output_hidden_states,
855
+ return_dict=return_dict,
856
+ )
857
+ sequence_output = encoder_outputs[0]
858
+ pooled_output = self.pooler(sequence_output, attention_mask) if self.pooler is not None else None
859
+
860
+ if not return_dict:
861
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
862
+
863
+ return BaseModelOutputWithPooling(
864
+ last_hidden_state=sequence_output,
865
+ pooler_output=pooled_output,
866
+ hidden_states=encoder_outputs.hidden_states,
867
+ attentions=encoder_outputs.attentions,
868
+ )
869
+
870
+
871
+ class RoPEBertForPreTraining(RoPEBertPreTrainedModel):
872
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
873
+
874
+ def __init__(self, config):
875
+ super().__init__(config)
876
+
877
+ self.bert = RoPEBertModel(config)
878
+ self.cls = RoPEBertPreTrainingHeads(config)
879
+
880
+ # Initialize weights and apply final processing
881
+ self.post_init()
882
+
883
+ def get_output_embeddings(self):
884
+ return self.cls.predictions.decoder
885
+
886
+ def set_output_embeddings(self, new_embeddings):
887
+ self.cls.predictions.decoder = new_embeddings
888
+
889
+ def forward(
890
+ self,
891
+ input_ids: Optional[torch.Tensor] = None,
892
+ attention_mask: Optional[torch.Tensor] = None,
893
+ token_type_ids: Optional[torch.Tensor] = None,
894
+ position_ids: Optional[torch.Tensor] = None,
895
+ head_mask: Optional[torch.Tensor] = None,
896
+ inputs_embeds: Optional[torch.Tensor] = None,
897
+ labels: Optional[torch.Tensor] = None,
898
+ next_sentence_label: Optional[torch.Tensor] = None,
899
+ output_attentions: Optional[bool] = None,
900
+ output_hidden_states: Optional[bool] = None,
901
+ return_dict: Optional[bool] = None,
902
+ ) -> Union[Tuple[torch.Tensor], RoPEBertForPreTrainingOutput]:
903
+
904
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
905
+
906
+ outputs = self.bert(
907
+ input_ids,
908
+ attention_mask=attention_mask,
909
+ token_type_ids=token_type_ids,
910
+ position_ids=position_ids,
911
+ head_mask=head_mask,
912
+ inputs_embeds=inputs_embeds,
913
+ output_attentions=output_attentions,
914
+ output_hidden_states=output_hidden_states,
915
+ return_dict=return_dict,
916
+ )
917
+
918
+ sequence_output, pooled_output = outputs[:2]
919
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
920
+
921
+ total_loss = None
922
+ if labels is not None and next_sentence_label is not None:
923
+ loss_fct = CrossEntropyLoss()
924
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
925
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
926
+ total_loss = masked_lm_loss + next_sentence_loss
927
+
928
+ if not return_dict:
929
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
930
+ return ((total_loss,) + output) if total_loss is not None else output
931
+
932
+ return RoPEBertForPreTrainingOutput(
933
+ loss=total_loss,
934
+ prediction_logits=prediction_scores,
935
+ seq_relationship_logits=seq_relationship_score,
936
+ hidden_states=outputs.hidden_states,
937
+ attentions=outputs.attentions,
938
+ )
939
+
940
+
941
+ class DNACrossEntropy(nn.Module):
942
+ def __init__(self, *args, **kwargs) -> None:
943
+ super().__init__(*args, **kwargs)
944
+
945
+ def forward(self, predictions, labels):
946
+ # labels: (n_mask, vocab_size)
947
+ # predicts: (n_mask, vocab_size)
948
+ log_probs = F.log_softmax(predictions, dim=-1)
949
+ loss = -(labels * log_probs).sum(dim=-1).mean()
950
+
951
+ return loss
952
+
953
+
954
+ class RoPEBertForMaskedLM(RoPEBertPreTrainedModel):
955
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
956
+
957
+ def __init__(self, config):
958
+ super().__init__(config)
959
+
960
+ if config.is_decoder:
961
+ logger.warning(
962
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
963
+ "bi-directional self-attention."
964
+ )
965
+
966
+ self.bert = RoPEBertModel(config, add_pooling_layer=False)
967
+ self.cls = RoPEBertOnlyMLMHead(config)
968
+
969
+ # Initialize weights and apply final processing
970
+ self.post_init()
971
+
972
+ def get_output_embeddings(self):
973
+ return self.cls.predictions.decoder
974
+
975
+ def set_output_embeddings(self, new_embeddings):
976
+ self.cls.predictions.decoder = new_embeddings
977
+
978
+ def forward(
979
+ self,
980
+ input_ids: Optional[torch.Tensor] = None,
981
+ attention_mask: Optional[torch.Tensor] = None,
982
+ token_type_ids: Optional[torch.Tensor] = None,
983
+ position_ids: Optional[torch.Tensor] = None,
984
+ head_mask: Optional[torch.Tensor] = None,
985
+ inputs_embeds: Optional[torch.Tensor] = None,
986
+ labels: Optional[torch.Tensor] = None,
987
+ masked_indices: Optional[torch.Tensor] = None,
988
+ output_attentions: Optional[bool] = None,
989
+ output_hidden_states: Optional[bool] = None,
990
+ return_dict: Optional[bool] = None,
991
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
992
+ r"""
993
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
994
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
995
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
996
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
997
+ """
998
+
999
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1000
+
1001
+ outputs = self.bert(
1002
+ input_ids=input_ids,
1003
+ attention_mask=attention_mask,
1004
+ token_type_ids=token_type_ids,
1005
+ position_ids=position_ids,
1006
+ head_mask=head_mask,
1007
+ inputs_embeds=inputs_embeds,
1008
+ output_attentions=output_attentions,
1009
+ output_hidden_states=output_hidden_states,
1010
+ return_dict=return_dict,
1011
+ )
1012
+
1013
+ sequence_output = outputs[0]
1014
+ prediction_scores = self.cls(sequence_output)
1015
+
1016
+ masked_lm_loss = None
1017
+ if labels is not None:
1018
+ # CrossEntropyLoss() # -100 index = padding token
1019
+ loss_fct = DNACrossEntropy()
1020
+ masked_lm_loss = loss_fct(prediction_scores[masked_indices].view(-1, self.config.vocab_size),
1021
+ labels[masked_indices].view(-1, self.config.vocab_size))
1022
+
1023
+ if not return_dict:
1024
+ output = (prediction_scores,) + outputs[2:]
1025
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1026
+
1027
+ return MaskedLMOutput(
1028
+ loss=masked_lm_loss,
1029
+ logits=prediction_scores,
1030
+ hidden_states=outputs.hidden_states,
1031
+ attentions=outputs.attentions,
1032
+ )
1033
+
1034
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1035
+ input_shape = input_ids.shape
1036
+ effective_batch_size = input_shape[0]
1037
+
1038
+ # add a dummy token
1039
+ if self.config.pad_token_id is None:
1040
+ raise ValueError("The PAD token should be defined for generation")
1041
+
1042
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1043
+ dummy_token = torch.full(
1044
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1045
+ )
1046
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1047
+
1048
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1049
+
1050
+
1051
+ class RoPEBertForSequenceClassification(RoPEBertPreTrainedModel):
1052
+ def __init__(self, config):
1053
+ super().__init__(config)
1054
+ self.num_labels = config.num_labels
1055
+ self.config = config
1056
+
1057
+ self.bert = RoPEBertModel(config)
1058
+ classifier_dropout = (
1059
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1060
+ )
1061
+ self.dropout = nn.Dropout(classifier_dropout)
1062
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1063
+
1064
+ # Initialize weights and apply final processing
1065
+ self.post_init()
1066
+
1067
+ def forward(
1068
+ self,
1069
+ input_ids: Optional[torch.Tensor] = None,
1070
+ attention_mask: Optional[torch.Tensor] = None,
1071
+ token_type_ids: Optional[torch.Tensor] = None,
1072
+ position_ids: Optional[torch.Tensor] = None,
1073
+ head_mask: Optional[torch.Tensor] = None,
1074
+ inputs_embeds: Optional[torch.Tensor] = None,
1075
+ labels: Optional[torch.Tensor] = None,
1076
+ output_attentions: Optional[bool] = None,
1077
+ output_hidden_states: Optional[bool] = None,
1078
+ return_dict: Optional[bool] = None,
1079
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1080
+ r"""
1081
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1082
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1083
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1084
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1085
+ """
1086
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1087
+
1088
+ outputs = self.bert(
1089
+ input_ids,
1090
+ attention_mask=attention_mask,
1091
+ token_type_ids=token_type_ids,
1092
+ position_ids=position_ids,
1093
+ head_mask=head_mask,
1094
+ inputs_embeds=inputs_embeds,
1095
+ output_attentions=output_attentions,
1096
+ output_hidden_states=output_hidden_states,
1097
+ return_dict=return_dict,
1098
+ )
1099
+
1100
+ pooled_output = outputs[1]
1101
+
1102
+ pooled_output = self.dropout(pooled_output)
1103
+ logits = self.classifier(pooled_output)
1104
+
1105
+ loss = None
1106
+ if labels is not None:
1107
+ if self.config.problem_type is None:
1108
+ if self.num_labels == 1:
1109
+ self.config.problem_type = "regression"
1110
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1111
+ self.config.problem_type = "single_label_classification"
1112
+ else:
1113
+ self.config.problem_type = "multi_label_classification"
1114
+
1115
+ if self.config.problem_type == "regression":
1116
+ loss_fct = MSELoss()
1117
+ if self.num_labels == 1:
1118
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1119
+ else:
1120
+ loss = loss_fct(logits, labels)
1121
+ elif self.config.problem_type == "single_label_classification":
1122
+ loss_fct = CrossEntropyLoss()
1123
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1124
+ elif self.config.problem_type == "multi_label_classification":
1125
+ loss_fct = BCEWithLogitsLoss()
1126
+ loss = loss_fct(logits, labels)
1127
+ if not return_dict:
1128
+ output = (logits,) + outputs[2:]
1129
+ return ((loss,) + output) if loss is not None else output
1130
+
1131
+ return SequenceClassifierOutput(
1132
+ loss=loss,
1133
+ logits=logits,
1134
+ hidden_states=outputs.hidden_states,
1135
+ attentions=outputs.attentions,
1136
+ )
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73a10975b93bed0f259698985f8420b86c7c5dedcf8b992053643085dd9d1140
3
+ size 342710382
tokenizer.json ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "1.0",
3
+ "truncation": null,
4
+ "padding": null,
5
+ "added_tokens": [
6
+ {
7
+ "id": 0,
8
+ "special": true,
9
+ "content": "[UNK]",
10
+ "single_word": false,
11
+ "lstrip": false,
12
+ "rstrip": false,
13
+ "normalized": false
14
+ },
15
+ {
16
+ "id": 1,
17
+ "special": true,
18
+ "content": "[CLS]",
19
+ "single_word": false,
20
+ "lstrip": false,
21
+ "rstrip": false,
22
+ "normalized": false
23
+ },
24
+ {
25
+ "id": 2,
26
+ "special": true,
27
+ "content": "[SEP]",
28
+ "single_word": false,
29
+ "lstrip": false,
30
+ "rstrip": false,
31
+ "normalized": false
32
+ },
33
+ {
34
+ "id": 3,
35
+ "special": true,
36
+ "content": "[PAD]",
37
+ "single_word": false,
38
+ "lstrip": false,
39
+ "rstrip": false,
40
+ "normalized": false
41
+ },
42
+ {
43
+ "id": 4,
44
+ "special": true,
45
+ "content": "[MASK]",
46
+ "single_word": false,
47
+ "lstrip": false,
48
+ "rstrip": false,
49
+ "normalized": false
50
+ }
51
+ ],
52
+ "normalizer": null,
53
+ "pre_tokenizer": {
54
+ "type": "Whitespace"
55
+ },
56
+ "post_processor": {
57
+ "type": "TemplateProcessing",
58
+ "single": [
59
+ {
60
+ "SpecialToken": {
61
+ "id": "[CLS]",
62
+ "type_id": 0
63
+ }
64
+ },
65
+ {
66
+ "Sequence": {
67
+ "id": "A",
68
+ "type_id": 0
69
+ }
70
+ },
71
+ {
72
+ "SpecialToken": {
73
+ "id": "[SEP]",
74
+ "type_id": 0
75
+ }
76
+ }
77
+ ],
78
+ "pair": [
79
+ {
80
+ "SpecialToken": {
81
+ "id": "[CLS]",
82
+ "type_id": 0
83
+ }
84
+ },
85
+ {
86
+ "Sequence": {
87
+ "id": "A",
88
+ "type_id": 0
89
+ }
90
+ },
91
+ {
92
+ "SpecialToken": {
93
+ "id": "[SEP]",
94
+ "type_id": 0
95
+ }
96
+ },
97
+ {
98
+ "Sequence": {
99
+ "id": "B",
100
+ "type_id": 1
101
+ }
102
+ },
103
+ {
104
+ "SpecialToken": {
105
+ "id": "[SEP]",
106
+ "type_id": 1
107
+ }
108
+ }
109
+ ],
110
+ "special_tokens": {
111
+ "[CLS]": {
112
+ "id": "[CLS]",
113
+ "ids": [
114
+ 1
115
+ ],
116
+ "tokens": [
117
+ "[CLS]"
118
+ ]
119
+ },
120
+ "[SEP]": {
121
+ "id": "[SEP]",
122
+ "ids": [
123
+ 2
124
+ ],
125
+ "tokens": [
126
+ "[SEP]"
127
+ ]
128
+ }
129
+ }
130
+ },
131
+ "decoder": null,
132
+ "model": {
133
+ "type": "BPE",
134
+ "dropout": null,
135
+ "unk_token": "[UNK]",
136
+ "continuing_subword_prefix": null,
137
+ "end_of_word_suffix": null,
138
+ "fuse_unk": false,
139
+ "vocab": {
140
+ "[UNK]": 0,
141
+ "[CLS]": 1,
142
+ "[SEP]": 2,
143
+ "[PAD]": 3,
144
+ "[MASK]": 4,
145
+ "A": 5,
146
+ "C": 6,
147
+ "G": 7,
148
+ "T": 8
149
+ },
150
+ "merges": [
151
+ ]
152
+ }
153
+ }
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"tokenizer_class": "PreTrainedTokenizerFast", "unk_token": "[UNK]", "cls_token": "[CLS]", "sep_token": "[SEP]", "pad_token": "[PAD]", "mask_token": "[MASK]"}
vocab.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [PAD]
2
+ [UNK]
3
+ [CLS]
4
+ [SEP]
5
+ [MASK]
6
+ A
7
+ T
8
+ C
9
+ G