weicaijaden commited on
Commit
0154361
·
verified ·
1 Parent(s): 861ddf4

Upload 6 files

Browse files
Files changed (6) hide show
  1. config.json +27 -0
  2. modeling_mutbert.py +1263 -0
  3. pytorch_model.bin +3 -0
  4. tokenizer.json +153 -0
  5. tokenizer_config.json +1 -0
  6. vocab.txt +9 -0
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ { "_name_or_path": "JadenLong/pig-mutbert-ref",
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
+ }
modeling_mutbert.py ADDED
@@ -0,0 +1,1263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 RoPEBertPooler(nn.Module):
618
+ # def __init__(self, config):
619
+ # self.pooler_type = config.pooler_type
620
+ # super().__init__()
621
+ #
622
+ # def forward(self, hidden_states: torch.Tensor, attention_mask: torch.LongTensor) -> torch.Tensor:
623
+ # pass
624
+
625
+
626
+ class RoPEBertMeanTokensPooler(nn.Module):
627
+ def __init__(self, config):
628
+ super().__init__()
629
+
630
+ def forward(self, hidden_states: torch.Tensor, attention_mask: torch.LongTensor) -> torch.Tensor:
631
+ input_mask_expanded = attention_mask.unsqueeze(-1).expand(hidden_states.size()).float()
632
+ pooled_output = torch.sum(hidden_states * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
633
+
634
+ return pooled_output
635
+
636
+
637
+ class RoPEBertCLSTokenTransformPooler(nn.Module):
638
+ def __init__(self, config):
639
+ super().__init__()
640
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
641
+ self.activation = nn.Tanh()
642
+
643
+ def forward(self, hidden_states: torch.Tensor, attention_mask: torch.LongTensor) -> torch.Tensor:
644
+
645
+ first_token_tensor = hidden_states[:, 0]
646
+ pooled_output = self.dense(first_token_tensor)
647
+ pooled_output = self.activation(pooled_output)
648
+
649
+ return pooled_output
650
+
651
+
652
+ ROPEBERT_POOLER_CLASSES = {
653
+ "mean": RoPEBertMeanTokensPooler,
654
+ "first_token_transform": RoPEBertCLSTokenTransformPooler,
655
+ }
656
+
657
+
658
+ class RoPEBertPredictionHeadTransform(nn.Module):
659
+ def __init__(self, config):
660
+ super().__init__()
661
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
662
+ if isinstance(config.hidden_act, str):
663
+ self.transform_act_fn = ACT2FN[config.hidden_act]
664
+ else:
665
+ self.transform_act_fn = config.hidden_act
666
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
667
+
668
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
669
+ hidden_states = self.dense(hidden_states)
670
+ hidden_states = self.transform_act_fn(hidden_states)
671
+ hidden_states = self.LayerNorm(hidden_states)
672
+ return hidden_states
673
+
674
+
675
+ class RoPEBertLMPredictionHead(nn.Module):
676
+ def __init__(self, config):
677
+ super().__init__()
678
+ self.transform = RoPEBertPredictionHeadTransform(config)
679
+
680
+ # The output weights are the same as the input embeddings, but there is
681
+ # an output-only bias for each token.
682
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
683
+
684
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
685
+
686
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
687
+ self.decoder.bias = self.bias
688
+
689
+ def forward(self, hidden_states):
690
+ hidden_states = self.transform(hidden_states)
691
+ hidden_states = self.decoder(hidden_states)
692
+ return hidden_states
693
+
694
+
695
+ class RoPEBertOnlyMLMHead(nn.Module):
696
+ def __init__(self, config):
697
+ super().__init__()
698
+ self.predictions = RoPEBertLMPredictionHead(config)
699
+
700
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
701
+ prediction_scores = self.predictions(sequence_output)
702
+ return prediction_scores
703
+
704
+
705
+ class RoPEBertOnlyNSPHead(nn.Module):
706
+ def __init__(self, config):
707
+ super().__init__()
708
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
709
+
710
+ def forward(self, pooled_output):
711
+ seq_relationship_score = self.seq_relationship(pooled_output)
712
+ return seq_relationship_score
713
+
714
+
715
+ class RoPEBertPreTrainingHeads(nn.Module):
716
+ def __init__(self, config):
717
+ super().__init__()
718
+ self.predictions = RoPEBertLMPredictionHead(config)
719
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
720
+
721
+ def forward(self, sequence_output, pooled_output):
722
+ prediction_scores = self.predictions(sequence_output)
723
+ seq_relationship_score = self.seq_relationship(pooled_output)
724
+ return prediction_scores, seq_relationship_score
725
+
726
+
727
+ class RoPEBertPreTrainedModel(PreTrainedModel):
728
+ """
729
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
730
+ models.
731
+ """
732
+
733
+ config_class = RoPEBertConfig
734
+ base_model_prefix = "bert"
735
+ supports_gradient_checkpointing = True
736
+ _supports_sdpa = True
737
+
738
+ def _init_weights(self, module):
739
+ """Initialize the weights"""
740
+ if isinstance(module, nn.Linear):
741
+ # Slightly different from the TF version which uses truncated_normal for initialization
742
+ # cf https://github.com/pytorch/pytorch/pull/5617
743
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
744
+ if module.bias is not None:
745
+ module.bias.data.zero_()
746
+ elif isinstance(module, nn.Embedding):
747
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
748
+ if module.padding_idx is not None:
749
+ module.weight.data[module.padding_idx].zero_()
750
+ elif isinstance(module, nn.LayerNorm):
751
+ module.bias.data.zero_()
752
+ module.weight.data.fill_(1.0)
753
+
754
+
755
+ @dataclass
756
+ class RoPEBertForPreTrainingOutput(ModelOutput):
757
+
758
+ loss: Optional[torch.FloatTensor] = None
759
+ prediction_logits: torch.FloatTensor = None
760
+ seq_relationship_logits: torch.FloatTensor = None
761
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
762
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
763
+
764
+
765
+ class RoPEBertModel(RoPEBertPreTrainedModel):
766
+
767
+ def __init__(self, config, add_pooling_layer=True):
768
+ super().__init__(config)
769
+ self.config = config
770
+
771
+ self.embeddings = RoPEBertEmbeddings(config)
772
+ self.encoder = RoPEBertEncoder(config)
773
+
774
+ self.pooler = ROPEBERT_POOLER_CLASSES[config.pooler_type](config=config) if add_pooling_layer else None
775
+
776
+ # Initialize weights and apply final processing
777
+ self.post_init()
778
+
779
+ def get_input_embeddings(self):
780
+ return self.embeddings.word_embeddings
781
+
782
+ def set_input_embeddings(self, value):
783
+ self.embeddings.word_embeddings = value
784
+
785
+ def _prune_heads(self, heads_to_prune):
786
+ """
787
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
788
+ class PreTrainedModel
789
+ """
790
+ for layer, heads in heads_to_prune.items():
791
+ self.encoder.layer[layer].attention.prune_heads(heads)
792
+
793
+ def forward(
794
+ self,
795
+ input_ids: Optional[torch.Tensor] = None,
796
+ attention_mask: Optional[torch.Tensor] = None,
797
+ token_type_ids: Optional[torch.Tensor] = None,
798
+ position_ids: Optional[torch.Tensor] = None,
799
+ head_mask: Optional[torch.Tensor] = None,
800
+ inputs_embeds: Optional[torch.Tensor] = None,
801
+ output_attentions: Optional[bool] = None,
802
+ output_hidden_states: Optional[bool] = None,
803
+ return_dict: Optional[bool] = None,
804
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPooling]:
805
+
806
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
807
+ output_hidden_states = (
808
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
809
+ )
810
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
811
+
812
+ if input_ids is not None and inputs_embeds is not None:
813
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
814
+ elif input_ids is not None:
815
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
816
+ input_shape = input_ids.size()[:-1] # modified
817
+ elif inputs_embeds is not None:
818
+ input_shape = inputs_embeds.size()[:-1]
819
+ else:
820
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
821
+
822
+ if output_attentions and self.config.attn_implementation == 'sdpa':
823
+ logger.warning("Cant use output_attentions with sdpa attention, turning off")
824
+ output_attentions = False
825
+
826
+ batch_size, seq_length = input_shape
827
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
828
+
829
+ if attention_mask is None:
830
+ attention_mask = torch.ones((batch_size, seq_length), device=device)
831
+
832
+ if position_ids is None:
833
+ position_ids = torch.arange(
834
+ 0, seq_length, dtype=torch.long, device=device
835
+ )
836
+ position_ids = position_ids.unsqueeze(0)
837
+
838
+ if token_type_ids is None:
839
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
840
+
841
+ # We can provide a self-attention mask of dimensions [batch_size, 1, from_seq_length, to_seq_length]
842
+ # ourselves in which case we just need to make it broadcastable to all heads.
843
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
844
+
845
+ # Prepare head mask if needed
846
+ # 1.0 in head_mask indicate we keep the head
847
+ # attention_probs has shape bsz x n_heads x N x N
848
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
849
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
850
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
851
+
852
+ embedding_output = self.embeddings(
853
+ input_ids=input_ids,
854
+ token_type_ids=token_type_ids,
855
+ inputs_embeds=inputs_embeds
856
+ )
857
+ encoder_outputs = self.encoder(
858
+ embedding_output,
859
+ attention_mask=extended_attention_mask,
860
+ head_mask=head_mask,
861
+ position_ids=position_ids,
862
+ output_attentions=output_attentions,
863
+ output_hidden_states=output_hidden_states,
864
+ return_dict=return_dict,
865
+ )
866
+ sequence_output = encoder_outputs[0]
867
+ pooled_output = self.pooler(sequence_output, attention_mask) if self.pooler is not None else None
868
+
869
+ if not return_dict:
870
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
871
+
872
+ return BaseModelOutputWithPooling(
873
+ last_hidden_state=sequence_output,
874
+ pooler_output=pooled_output,
875
+ hidden_states=encoder_outputs.hidden_states,
876
+ attentions=encoder_outputs.attentions,
877
+ )
878
+
879
+
880
+ class RoPEBertForPreTraining(RoPEBertPreTrainedModel):
881
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
882
+
883
+ def __init__(self, config):
884
+ super().__init__(config)
885
+
886
+ self.bert = RoPEBertModel(config)
887
+ self.cls = RoPEBertPreTrainingHeads(config)
888
+
889
+ # Initialize weights and apply final processing
890
+ self.post_init()
891
+
892
+ def get_output_embeddings(self):
893
+ return self.cls.predictions.decoder
894
+
895
+ def set_output_embeddings(self, new_embeddings):
896
+ self.cls.predictions.decoder = new_embeddings
897
+
898
+ def forward(
899
+ self,
900
+ input_ids: Optional[torch.Tensor] = None,
901
+ attention_mask: Optional[torch.Tensor] = None,
902
+ token_type_ids: Optional[torch.Tensor] = None,
903
+ position_ids: Optional[torch.Tensor] = None,
904
+ head_mask: Optional[torch.Tensor] = None,
905
+ inputs_embeds: Optional[torch.Tensor] = None,
906
+ labels: Optional[torch.Tensor] = None,
907
+ next_sentence_label: Optional[torch.Tensor] = None,
908
+ output_attentions: Optional[bool] = None,
909
+ output_hidden_states: Optional[bool] = None,
910
+ return_dict: Optional[bool] = None,
911
+ ) -> Union[Tuple[torch.Tensor], RoPEBertForPreTrainingOutput]:
912
+
913
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
914
+
915
+ outputs = self.bert(
916
+ input_ids,
917
+ attention_mask=attention_mask,
918
+ token_type_ids=token_type_ids,
919
+ position_ids=position_ids,
920
+ head_mask=head_mask,
921
+ inputs_embeds=inputs_embeds,
922
+ output_attentions=output_attentions,
923
+ output_hidden_states=output_hidden_states,
924
+ return_dict=return_dict,
925
+ )
926
+
927
+ sequence_output, pooled_output = outputs[:2]
928
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
929
+
930
+ total_loss = None
931
+ if labels is not None and next_sentence_label is not None:
932
+ loss_fct = CrossEntropyLoss()
933
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
934
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
935
+ total_loss = masked_lm_loss + next_sentence_loss
936
+
937
+ if not return_dict:
938
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
939
+ return ((total_loss,) + output) if total_loss is not None else output
940
+
941
+ return RoPEBertForPreTrainingOutput(
942
+ loss=total_loss,
943
+ prediction_logits=prediction_scores,
944
+ seq_relationship_logits=seq_relationship_score,
945
+ hidden_states=outputs.hidden_states,
946
+ attentions=outputs.attentions,
947
+ )
948
+
949
+
950
+ class DNACrossEntropy(nn.Module):
951
+ def __init__(self, *args, **kwargs) -> None:
952
+ super().__init__(*args, **kwargs)
953
+
954
+ def forward(self, predictions, labels):
955
+ # labels: (n_mask, vocab_size)
956
+ # predicts: (n_mask, vocab_size)
957
+ log_probs = F.log_softmax(predictions, dim=-1)
958
+ loss = -(labels * log_probs).sum(dim=-1).mean()
959
+
960
+ return loss
961
+
962
+
963
+ class RoPEBertForMaskedLM(RoPEBertPreTrainedModel):
964
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
965
+
966
+ def __init__(self, config):
967
+ super().__init__(config)
968
+
969
+ if config.is_decoder:
970
+ logger.warning(
971
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
972
+ "bi-directional self-attention."
973
+ )
974
+
975
+ self.bert = RoPEBertModel(config, add_pooling_layer=False)
976
+ self.cls = RoPEBertOnlyMLMHead(config)
977
+
978
+ # Initialize weights and apply final processing
979
+ self.post_init()
980
+
981
+ def get_output_embeddings(self):
982
+ return self.cls.predictions.decoder
983
+
984
+ def set_output_embeddings(self, new_embeddings):
985
+ self.cls.predictions.decoder = new_embeddings
986
+
987
+ def forward(
988
+ self,
989
+ input_ids: Optional[torch.Tensor] = None,
990
+ attention_mask: Optional[torch.Tensor] = None,
991
+ token_type_ids: Optional[torch.Tensor] = None,
992
+ position_ids: Optional[torch.Tensor] = None,
993
+ head_mask: Optional[torch.Tensor] = None,
994
+ inputs_embeds: Optional[torch.Tensor] = None,
995
+ labels: Optional[torch.Tensor] = None,
996
+ masked_indices: Optional[torch.Tensor] = None,
997
+ output_attentions: Optional[bool] = None,
998
+ output_hidden_states: Optional[bool] = None,
999
+ return_dict: Optional[bool] = None,
1000
+ ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
1001
+ r"""
1002
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1003
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1004
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1005
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1006
+ """
1007
+
1008
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1009
+
1010
+ outputs = self.bert(
1011
+ input_ids=input_ids,
1012
+ attention_mask=attention_mask,
1013
+ token_type_ids=token_type_ids,
1014
+ position_ids=position_ids,
1015
+ head_mask=head_mask,
1016
+ inputs_embeds=inputs_embeds,
1017
+ output_attentions=output_attentions,
1018
+ output_hidden_states=output_hidden_states,
1019
+ return_dict=return_dict,
1020
+ )
1021
+
1022
+ sequence_output = outputs[0]
1023
+ prediction_scores = self.cls(sequence_output)
1024
+
1025
+ masked_lm_loss = None
1026
+ if labels is not None:
1027
+ # CrossEntropyLoss() # -100 index = padding token
1028
+ loss_fct = DNACrossEntropy()
1029
+ masked_lm_loss = loss_fct(prediction_scores[masked_indices].view(-1, self.config.vocab_size),
1030
+ labels[masked_indices].view(-1, self.config.vocab_size))
1031
+
1032
+ if not return_dict:
1033
+ output = (prediction_scores,) + outputs[2:]
1034
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1035
+
1036
+ return MaskedLMOutput(
1037
+ loss=masked_lm_loss,
1038
+ logits=prediction_scores,
1039
+ hidden_states=outputs.hidden_states,
1040
+ attentions=outputs.attentions,
1041
+ )
1042
+
1043
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1044
+ input_shape = input_ids.shape
1045
+ effective_batch_size = input_shape[0]
1046
+
1047
+ # add a dummy token
1048
+ if self.config.pad_token_id is None:
1049
+ raise ValueError("The PAD token should be defined for generation")
1050
+
1051
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1052
+ dummy_token = torch.full(
1053
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1054
+ )
1055
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1056
+
1057
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1058
+
1059
+
1060
+ class RoPEBertForSequenceClassification(RoPEBertPreTrainedModel):
1061
+ def __init__(self, config):
1062
+ super().__init__(config)
1063
+ self.num_labels = config.num_labels
1064
+ self.config = config
1065
+
1066
+ self.bert = RoPEBertModel(config)
1067
+ classifier_dropout = (
1068
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1069
+ )
1070
+ self.dropout = nn.Dropout(classifier_dropout)
1071
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1072
+
1073
+ # Initialize weights and apply final processing
1074
+ self.post_init()
1075
+
1076
+ def forward(
1077
+ self,
1078
+ input_ids: Optional[torch.Tensor] = None,
1079
+ attention_mask: Optional[torch.Tensor] = None,
1080
+ token_type_ids: Optional[torch.Tensor] = None,
1081
+ position_ids: Optional[torch.Tensor] = None,
1082
+ head_mask: Optional[torch.Tensor] = None,
1083
+ inputs_embeds: Optional[torch.Tensor] = None,
1084
+ labels: Optional[torch.Tensor] = None,
1085
+ output_attentions: Optional[bool] = None,
1086
+ output_hidden_states: Optional[bool] = None,
1087
+ return_dict: Optional[bool] = None,
1088
+ ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
1089
+ r"""
1090
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1091
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1092
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1093
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1094
+ """
1095
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1096
+
1097
+ outputs = self.bert(
1098
+ input_ids,
1099
+ attention_mask=attention_mask,
1100
+ token_type_ids=token_type_ids,
1101
+ position_ids=position_ids,
1102
+ head_mask=head_mask,
1103
+ inputs_embeds=inputs_embeds,
1104
+ output_attentions=output_attentions,
1105
+ output_hidden_states=output_hidden_states,
1106
+ return_dict=return_dict,
1107
+ )
1108
+
1109
+ pooled_output = outputs[1]
1110
+
1111
+ pooled_output = self.dropout(pooled_output)
1112
+ logits = self.classifier(pooled_output)
1113
+
1114
+ loss = None
1115
+ if labels is not None:
1116
+ if self.config.problem_type is None:
1117
+ if self.num_labels == 1:
1118
+ self.config.problem_type = "regression"
1119
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1120
+ self.config.problem_type = "single_label_classification"
1121
+ else:
1122
+ self.config.problem_type = "multi_label_classification"
1123
+
1124
+ if self.config.problem_type == "regression":
1125
+ loss_fct = MSELoss()
1126
+ if self.num_labels == 1:
1127
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1128
+ else:
1129
+ loss = loss_fct(logits, labels)
1130
+ elif self.config.problem_type == "single_label_classification":
1131
+ loss_fct = CrossEntropyLoss()
1132
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1133
+ elif self.config.problem_type == "multi_label_classification":
1134
+ loss_fct = BCEWithLogitsLoss()
1135
+ loss = loss_fct(logits, labels)
1136
+ if not return_dict:
1137
+ output = (logits,) + outputs[2:]
1138
+ return ((loss,) + output) if loss is not None else output
1139
+
1140
+ return SequenceClassifierOutput(
1141
+ loss=loss,
1142
+ logits=logits,
1143
+ hidden_states=outputs.hidden_states,
1144
+ attentions=outputs.attentions,
1145
+ )
1146
+
1147
+
1148
+ def test_rope_bert():
1149
+ # Configuration Parameters
1150
+ config = RoPEBertConfig(
1151
+ vocab_size=30522, # Typical BERT vocab size
1152
+ hidden_size=768,
1153
+ num_hidden_layers=12,
1154
+ num_attention_heads=12,
1155
+ intermediate_size=3072,
1156
+ max_position_embeddings=512,
1157
+ type_vocab_size=2,
1158
+ pooler_type="mean", # or "first_token_transform"
1159
+ rope_theta=10000.0,
1160
+ rope_scaling=None, # or specify a scaling dict
1161
+ )
1162
+
1163
+ # Initialize the Model
1164
+ model = RoPEBertForPreTraining(config)
1165
+ model.eval() # Set to evaluation mode
1166
+
1167
+ # Generate Random Inputs
1168
+ B, L = 2, 10 # Batch size and sequence length
1169
+ input_ids = torch.randint(0, config.vocab_size, (B, L))
1170
+ attention_mask = torch.ones((B, L), dtype=torch.long)
1171
+
1172
+ # Forward Pass
1173
+ with torch.no_grad():
1174
+ outputs = model(input_ids=input_ids, attention_mask=attention_mask)
1175
+
1176
+ # Unpack Outputs
1177
+ loss = outputs.loss
1178
+ prediction_logits = outputs.prediction_logits
1179
+ seq_relationship_logits = outputs.seq_relationship_logits
1180
+
1181
+ # Print Output Shapes
1182
+ print(f"Input IDs Shape: {input_ids.shape}") # Expected: (B, L)
1183
+ print(f"Attention Mask Shape: {attention_mask.shape}") # Expected: (B, L)")
1184
+ print(f"Prediction Logits Shape: {prediction_logits.shape}") # Expected: (B, L, vocab_size)
1185
+ print(f"Seq Relationship Logits Shape: {seq_relationship_logits.shape}") # Expected: (B, 2)
1186
+
1187
+ # Additionally, test RoPEBertForSequenceClassification
1188
+ classification_model = RoPEBertForSequenceClassification(config)
1189
+ classification_model.eval()
1190
+
1191
+ labels = torch.randint(0, config.num_labels if hasattr(config, 'num_labels') else 2, (B,))
1192
+ with torch.no_grad():
1193
+ cls_outputs = classification_model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
1194
+
1195
+ logits = cls_outputs.logits
1196
+ print(f"Classification Logits Shape: {logits.shape}") # Expected: (B, num_labels)
1197
+
1198
+
1199
+ def test_rope_bert_for_masked_lm():
1200
+ # Configuration Parameters
1201
+ config = RoPEBertConfig(
1202
+ vocab_size=30522, # Typical BERT vocab size
1203
+ hidden_size=768,
1204
+ num_hidden_layers=12,
1205
+ num_attention_heads=12,
1206
+ intermediate_size=3072,
1207
+ max_position_embeddings=512,
1208
+ type_vocab_size=2,
1209
+ pooler_type="mean", # or "first_token_transform"
1210
+ rope_theta=10000.0,
1211
+ rope_scaling=None, # or specify a scaling dict
1212
+ )
1213
+
1214
+ # Initialize the Model
1215
+ model = RoPEBertForMaskedLM(config)
1216
+ model.eval() # Set to evaluation mode
1217
+
1218
+ # Generate Random Inputs
1219
+ B, L = 2, 10 # Batch size and sequence length
1220
+ input_ids = torch.randint(0, config.vocab_size, (B, L))
1221
+ attention_mask = torch.ones((B, L), dtype=torch.long)
1222
+
1223
+ # Generate Random Labels
1224
+ # For MLM, labels should have the same shape as input_ids
1225
+ # Typically, some tokens are masked, and others are set to -100 to be ignored
1226
+ # For testing, we'll randomly set some labels to -100
1227
+ labels = torch.randint(0, config.vocab_size, (B, L))
1228
+ # Randomly select 15% of the tokens to mask (as per BERT's original masking strategy)
1229
+ probability_matrix = torch.full(labels.shape, 0.15)
1230
+ masked_indices = torch.bernoulli(probability_matrix).bool()
1231
+ labels[~masked_indices] = -100 # Only compute loss on masked tokens
1232
+
1233
+ # Forward Pass
1234
+ with torch.no_grad():
1235
+ outputs = model(
1236
+ input_ids=input_ids,
1237
+ attention_mask=attention_mask,
1238
+ labels=labels
1239
+ )
1240
+
1241
+ # Unpack Outputs
1242
+ loss = outputs.loss
1243
+ prediction_logits = outputs.logits
1244
+
1245
+ # Print Output Shapes
1246
+ print(f"Input IDs Shape: {input_ids.shape}") # Expected: (B, L)
1247
+ print(f"Attention Mask Shape: {attention_mask.shape}") # Expected: (B, L)
1248
+ print(f"Labels Shape: {labels.shape}") # Expected: (B, L)
1249
+ print(f"Loss: {loss.item()}") # Scalar loss value
1250
+ print(f"Prediction Logits Shape: {prediction_logits.shape}") # Expected: (B, L, vocab_size)")
1251
+
1252
+ # Verify the logits shape
1253
+ assert prediction_logits.shape == (B, L, config.vocab_size), \
1254
+ f"Expected logits shape {(B, L, config.vocab_size)}, but got {prediction_logits.shape}"
1255
+
1256
+ print("RoPEBertForMaskedLM test passed successfully.")
1257
+
1258
+
1259
+ if __name__ == "__main__":
1260
+ # test_rope_bert()
1261
+ test_rope_bert_for_masked_lm()
1262
+
1263
+
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:470df259a46294c1800d3112ddd6583dfc0a2e29a499d6fb6ed13f36cc56e46e
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