Instructions to use Taykhoom/SpliceBERT-1024nt with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Taykhoom/SpliceBERT-1024nt with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="Taykhoom/SpliceBERT-1024nt", trust_remote_code=True)# Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("Taykhoom/SpliceBERT-1024nt", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Fix model correctness and Hugging Face compatibility
Browse files- README.md +1 -2
- config.json +4 -4
- configuration_bert_updated.py +2 -0
- modeling_bert.py +212 -37
- tokenization_splicebert.py +7 -4
README.md
CHANGED
|
@@ -152,8 +152,7 @@ model = AutoModel.from_pretrained("Taykhoom/SpliceBERT-1024nt",
|
|
| 152 |
|
| 153 |
Original model and code by Chen et al. Source:
|
| 154 |
[GitHub](https://github.com/biomed-AI/SpliceBERT).
|
| 155 |
-
|
| 156 |
-
and reviewed manually by Taykhoom Dalal.
|
| 157 |
|
| 158 |
## License
|
| 159 |
|
|
|
|
| 152 |
|
| 153 |
Original model and code by Chen et al. Source:
|
| 154 |
[GitHub](https://github.com/biomed-AI/SpliceBERT).
|
| 155 |
+
Hugging Face port maintained by Taykhoom Dalal.
|
|
|
|
| 156 |
|
| 157 |
## License
|
| 158 |
|
config.json
CHANGED
|
@@ -5,9 +5,9 @@
|
|
| 5 |
],
|
| 6 |
"model_type": "bert_updated",
|
| 7 |
"auto_map": {
|
| 8 |
-
"AutoConfig": "
|
| 9 |
-
"AutoModel": "
|
| 10 |
-
"AutoModelForMaskedLM": "
|
| 11 |
},
|
| 12 |
"vocab_size": 10,
|
| 13 |
"hidden_size": 512,
|
|
@@ -24,4 +24,4 @@
|
|
| 24 |
"pad_token_id": 0,
|
| 25 |
"model_max_length": 1024,
|
| 26 |
"transformers_version": "4.57.6"
|
| 27 |
-
}
|
|
|
|
| 5 |
],
|
| 6 |
"model_type": "bert_updated",
|
| 7 |
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_bert_updated.BertUpdatedConfig",
|
| 9 |
+
"AutoModel": "modeling_bert.BertModel",
|
| 10 |
+
"AutoModelForMaskedLM": "modeling_bert.BertForMaskedLM"
|
| 11 |
},
|
| 12 |
"vocab_size": 10,
|
| 13 |
"hidden_size": 512,
|
|
|
|
| 24 |
"pad_token_id": 0,
|
| 25 |
"model_max_length": 1024,
|
| 26 |
"transformers_version": "4.57.6"
|
| 27 |
+
}
|
configuration_bert_updated.py
CHANGED
|
@@ -18,6 +18,7 @@ class BertUpdatedConfig(PretrainedConfig):
|
|
| 18 |
num_attention_heads=12,
|
| 19 |
intermediate_size=3072,
|
| 20 |
hidden_act="gelu",
|
|
|
|
| 21 |
hidden_dropout_prob=0.1,
|
| 22 |
attention_probs_dropout_prob=0.1,
|
| 23 |
max_position_embeddings=512,
|
|
@@ -33,6 +34,7 @@ class BertUpdatedConfig(PretrainedConfig):
|
|
| 33 |
self.num_attention_heads = num_attention_heads
|
| 34 |
self.intermediate_size = intermediate_size
|
| 35 |
self.hidden_act = hidden_act
|
|
|
|
| 36 |
self.hidden_dropout_prob = hidden_dropout_prob
|
| 37 |
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 38 |
self.max_position_embeddings = max_position_embeddings
|
|
|
|
| 18 |
num_attention_heads=12,
|
| 19 |
intermediate_size=3072,
|
| 20 |
hidden_act="gelu",
|
| 21 |
+
mlm_hidden_act=None,
|
| 22 |
hidden_dropout_prob=0.1,
|
| 23 |
attention_probs_dropout_prob=0.1,
|
| 24 |
max_position_embeddings=512,
|
|
|
|
| 34 |
self.num_attention_heads = num_attention_heads
|
| 35 |
self.intermediate_size = intermediate_size
|
| 36 |
self.hidden_act = hidden_act
|
| 37 |
+
self.mlm_hidden_act = mlm_hidden_act
|
| 38 |
self.hidden_dropout_prob = hidden_dropout_prob
|
| 39 |
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 40 |
self.max_position_embeddings = max_position_embeddings
|
modeling_bert.py
CHANGED
|
@@ -4,6 +4,8 @@ from typing import Optional, Tuple, Union
|
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
import torch.nn.functional as F
|
|
|
|
|
|
|
| 7 |
from transformers import PreTrainedModel, PretrainedConfig
|
| 8 |
from transformers.modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 9 |
|
|
@@ -32,6 +34,7 @@ class BertSelfAttention(nn.Module):
|
|
| 32 |
hidden_states: torch.Tensor,
|
| 33 |
key_padding_mask: Optional[torch.Tensor] = None,
|
| 34 |
output_attentions: bool = False,
|
|
|
|
| 35 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 36 |
q = self._split_heads(self.query(hidden_states))
|
| 37 |
k = self._split_heads(self.key(hidden_states))
|
|
@@ -41,9 +44,14 @@ class BertSelfAttention(nn.Module):
|
|
| 41 |
scores = torch.matmul(q, k.transpose(-1, -2)) / scale
|
| 42 |
if key_padding_mask is not None:
|
| 43 |
scores = scores.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
|
| 44 |
-
probs =
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
B, _, T, _ = context.shape
|
| 49 |
context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
|
|
@@ -60,9 +68,15 @@ class BertSdpaSelfAttention(BertSelfAttention):
|
|
| 60 |
hidden_states: torch.Tensor,
|
| 61 |
key_padding_mask: Optional[torch.Tensor] = None,
|
| 62 |
output_attentions: bool = False,
|
|
|
|
| 63 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 64 |
-
if output_attentions:
|
| 65 |
-
return super().forward(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
B, T, _ = hidden_states.shape
|
| 68 |
q = self._split_heads(self.query(hidden_states))
|
|
@@ -74,7 +88,13 @@ class BertSdpaSelfAttention(BertSelfAttention):
|
|
| 74 |
attn_mask = torch.zeros(B, 1, 1, T, dtype=q.dtype, device=q.device)
|
| 75 |
attn_mask = attn_mask.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
|
| 76 |
|
| 77 |
-
context = F.scaled_dot_product_attention(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
|
| 79 |
return context, None
|
| 80 |
|
|
@@ -86,9 +106,22 @@ class BertFlashSelfAttention(BertSelfAttention):
|
|
| 86 |
hidden_states: torch.Tensor,
|
| 87 |
key_padding_mask: Optional[torch.Tensor] = None,
|
| 88 |
output_attentions: bool = False,
|
|
|
|
| 89 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 90 |
-
if
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
try:
|
| 94 |
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
|
@@ -104,9 +137,11 @@ class BertFlashSelfAttention(BertSelfAttention):
|
|
| 104 |
k = self._split_heads(self.key(hidden_states)).permute(0, 2, 1, 3)
|
| 105 |
v = self._split_heads(self.value(hidden_states)).permute(0, 2, 1, 3)
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
| 110 |
|
| 111 |
if key_padding_mask is not None and key_padding_mask.any():
|
| 112 |
attend = ~key_padding_mask
|
|
@@ -117,13 +152,20 @@ class BertFlashSelfAttention(BertSelfAttention):
|
|
| 117 |
q_u, k_u, v_u,
|
| 118 |
cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens,
|
| 119 |
max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen,
|
|
|
|
| 120 |
causal=False,
|
| 121 |
)
|
| 122 |
out = pad_input(out_u, indices, B, T)
|
| 123 |
else:
|
| 124 |
-
out = flash_attn_func(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
out = out.
|
| 127 |
return out, None
|
| 128 |
|
| 129 |
|
|
@@ -158,8 +200,14 @@ class BertAttention(nn.Module):
|
|
| 158 |
hidden_states: torch.Tensor,
|
| 159 |
key_padding_mask: Optional[torch.Tensor],
|
| 160 |
output_attentions: bool = False,
|
|
|
|
| 161 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 162 |
-
self_out, attn_weights = self.self(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
return self.output(self_out, hidden_states), attn_weights
|
| 164 |
|
| 165 |
|
|
@@ -167,9 +215,15 @@ class BertIntermediate(nn.Module):
|
|
| 167 |
def __init__(self, config):
|
| 168 |
super().__init__()
|
| 169 |
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 172 |
-
return
|
| 173 |
|
| 174 |
|
| 175 |
class BertOutput(nn.Module):
|
|
@@ -196,8 +250,14 @@ class BertLayer(nn.Module):
|
|
| 196 |
hidden_states: torch.Tensor,
|
| 197 |
key_padding_mask: Optional[torch.Tensor],
|
| 198 |
output_attentions: bool = False,
|
|
|
|
| 199 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 200 |
-
attn_out, attn_weights = self.attention(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
return self.output(self.intermediate(attn_out), attn_out), attn_weights
|
| 202 |
|
| 203 |
|
|
@@ -205,6 +265,7 @@ class BertEncoder(nn.Module):
|
|
| 205 |
def __init__(self, config):
|
| 206 |
super().__init__()
|
| 207 |
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
|
|
|
| 208 |
|
| 209 |
def forward(
|
| 210 |
self,
|
|
@@ -212,12 +273,31 @@ class BertEncoder(nn.Module):
|
|
| 212 |
key_padding_mask: Optional[torch.Tensor],
|
| 213 |
output_hidden_states: bool = False,
|
| 214 |
output_attentions: bool = False,
|
|
|
|
| 215 |
) -> Tuple:
|
| 216 |
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 217 |
all_attentions = () if output_attentions else None
|
| 218 |
|
| 219 |
-
for layer in self.layer:
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
if output_hidden_states:
|
| 222 |
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 223 |
if output_attentions:
|
|
@@ -236,13 +316,39 @@ class BertEmbeddings(nn.Module):
|
|
| 236 |
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 237 |
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
| 238 |
|
| 239 |
-
def forward(
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
if token_type_ids is None:
|
| 242 |
-
token_type_ids = torch.
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
x = x + self.token_type_embeddings(token_type_ids)
|
|
|
|
| 246 |
return self.dropout(self.LayerNorm(x))
|
| 247 |
|
| 248 |
|
|
@@ -261,9 +367,20 @@ class BertPredictionHeadTransform(nn.Module):
|
|
| 261 |
super().__init__()
|
| 262 |
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 263 |
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 266 |
-
return self.LayerNorm(
|
| 267 |
|
| 268 |
|
| 269 |
class BertModel(PreTrainedModel):
|
|
@@ -271,12 +388,14 @@ class BertModel(PreTrainedModel):
|
|
| 271 |
base_model_prefix = "bert"
|
| 272 |
_supports_sdpa = True
|
| 273 |
_supports_flash_attn_2 = True
|
|
|
|
|
|
|
| 274 |
|
| 275 |
-
def __init__(self, config):
|
| 276 |
super().__init__(config)
|
| 277 |
self.embeddings = BertEmbeddings(config)
|
| 278 |
self.encoder = BertEncoder(config)
|
| 279 |
-
self.pooler = BertPooler(config)
|
| 280 |
self.post_init()
|
| 281 |
|
| 282 |
def get_input_embeddings(self):
|
|
@@ -287,9 +406,12 @@ class BertModel(PreTrainedModel):
|
|
| 287 |
|
| 288 |
def forward(
|
| 289 |
self,
|
| 290 |
-
input_ids: torch.LongTensor,
|
| 291 |
attention_mask: Optional[torch.Tensor] = None,
|
| 292 |
token_type_ids: Optional[torch.LongTensor] = None,
|
|
|
|
|
|
|
|
|
|
| 293 |
output_hidden_states: Optional[bool] = None,
|
| 294 |
output_attentions: Optional[bool] = None,
|
| 295 |
return_dict: Optional[bool] = None,
|
|
@@ -298,22 +420,51 @@ class BertModel(PreTrainedModel):
|
|
| 298 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 299 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 300 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
if attention_mask is None:
|
| 302 |
-
attention_mask = torch.
|
| 303 |
key_padding_mask = attention_mask.eq(0)
|
| 304 |
if not key_padding_mask.any():
|
| 305 |
key_padding_mask = None
|
| 306 |
-
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
last_hidden_state, all_hidden_states, all_attentions = self.encoder(
|
| 309 |
x, key_padding_mask,
|
| 310 |
output_hidden_states=output_hidden_states,
|
| 311 |
output_attentions=output_attentions,
|
|
|
|
| 312 |
)
|
| 313 |
-
pooled = self.pooler(last_hidden_state)
|
| 314 |
|
| 315 |
if not return_dict:
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
return BaseModelOutputWithPooling(
|
| 319 |
last_hidden_state=last_hidden_state,
|
|
@@ -328,10 +479,12 @@ class BertForMaskedLM(PreTrainedModel):
|
|
| 328 |
base_model_prefix = "bert"
|
| 329 |
_supports_sdpa = True
|
| 330 |
_supports_flash_attn_2 = True
|
|
|
|
|
|
|
| 331 |
|
| 332 |
def __init__(self, config):
|
| 333 |
super().__init__(config)
|
| 334 |
-
self.bert = BertModel(config)
|
| 335 |
self.transform = BertPredictionHeadTransform(config)
|
| 336 |
self.cls = nn.Linear(config.hidden_size, config.vocab_size)
|
| 337 |
self.post_init()
|
|
@@ -339,11 +492,23 @@ class BertForMaskedLM(PreTrainedModel):
|
|
| 339 |
def get_input_embeddings(self):
|
| 340 |
return self.bert.embeddings.word_embeddings
|
| 341 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 342 |
def forward(
|
| 343 |
self,
|
| 344 |
-
input_ids: torch.LongTensor,
|
| 345 |
attention_mask: Optional[torch.Tensor] = None,
|
| 346 |
token_type_ids: Optional[torch.LongTensor] = None,
|
|
|
|
|
|
|
|
|
|
| 347 |
labels: Optional[torch.LongTensor] = None,
|
| 348 |
output_hidden_states: Optional[bool] = None,
|
| 349 |
output_attentions: Optional[bool] = None,
|
|
@@ -352,8 +517,14 @@ class BertForMaskedLM(PreTrainedModel):
|
|
| 352 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 353 |
|
| 354 |
outputs = self.bert(
|
| 355 |
-
input_ids
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
return_dict=True,
|
| 358 |
)
|
| 359 |
logits = self.cls(self.transform(outputs.last_hidden_state))
|
|
@@ -363,7 +534,11 @@ class BertForMaskedLM(PreTrainedModel):
|
|
| 363 |
loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100)
|
| 364 |
|
| 365 |
if not return_dict:
|
| 366 |
-
output = (logits,)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
return (loss,) + output if loss is not None else output
|
| 368 |
|
| 369 |
return MaskedLMOutput(
|
|
|
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
import torch.nn.functional as F
|
| 7 |
+
import torch.utils.checkpoint
|
| 8 |
+
from transformers.activations import ACT2FN
|
| 9 |
from transformers import PreTrainedModel, PretrainedConfig
|
| 10 |
from transformers.modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 11 |
|
|
|
|
| 34 |
hidden_states: torch.Tensor,
|
| 35 |
key_padding_mask: Optional[torch.Tensor] = None,
|
| 36 |
output_attentions: bool = False,
|
| 37 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 38 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 39 |
q = self._split_heads(self.query(hidden_states))
|
| 40 |
k = self._split_heads(self.key(hidden_states))
|
|
|
|
| 44 |
scores = torch.matmul(q, k.transpose(-1, -2)) / scale
|
| 45 |
if key_padding_mask is not None:
|
| 46 |
scores = scores.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
|
| 47 |
+
probs = torch.nan_to_num(
|
| 48 |
+
F.softmax(scores.float(), dim=-1),
|
| 49 |
+
nan=0.0,
|
| 50 |
+
)
|
| 51 |
+
context_probs = self.dropout(probs)
|
| 52 |
+
if head_mask is not None:
|
| 53 |
+
context_probs = context_probs * head_mask
|
| 54 |
+
context = torch.matmul(context_probs.to(v.dtype), v)
|
| 55 |
|
| 56 |
B, _, T, _ = context.shape
|
| 57 |
context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
|
|
|
|
| 68 |
hidden_states: torch.Tensor,
|
| 69 |
key_padding_mask: Optional[torch.Tensor] = None,
|
| 70 |
output_attentions: bool = False,
|
| 71 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 72 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 73 |
+
if output_attentions or head_mask is not None:
|
| 74 |
+
return super().forward(
|
| 75 |
+
hidden_states,
|
| 76 |
+
key_padding_mask,
|
| 77 |
+
output_attentions=output_attentions,
|
| 78 |
+
head_mask=head_mask,
|
| 79 |
+
)
|
| 80 |
|
| 81 |
B, T, _ = hidden_states.shape
|
| 82 |
q = self._split_heads(self.query(hidden_states))
|
|
|
|
| 88 |
attn_mask = torch.zeros(B, 1, 1, T, dtype=q.dtype, device=q.device)
|
| 89 |
attn_mask = attn_mask.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
|
| 90 |
|
| 91 |
+
context = F.scaled_dot_product_attention(
|
| 92 |
+
q,
|
| 93 |
+
k,
|
| 94 |
+
v,
|
| 95 |
+
attn_mask=attn_mask,
|
| 96 |
+
dropout_p=self.dropout.p if self.training else 0.0,
|
| 97 |
+
)
|
| 98 |
context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
|
| 99 |
return context, None
|
| 100 |
|
|
|
|
| 106 |
hidden_states: torch.Tensor,
|
| 107 |
key_padding_mask: Optional[torch.Tensor] = None,
|
| 108 |
output_attentions: bool = False,
|
| 109 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 110 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 111 |
+
if (
|
| 112 |
+
output_attentions
|
| 113 |
+
or head_mask is not None
|
| 114 |
+
or (
|
| 115 |
+
key_padding_mask is not None
|
| 116 |
+
and (~key_padding_mask).sum(dim=-1).eq(0).any()
|
| 117 |
+
)
|
| 118 |
+
):
|
| 119 |
+
return super().forward(
|
| 120 |
+
hidden_states,
|
| 121 |
+
key_padding_mask,
|
| 122 |
+
output_attentions=output_attentions,
|
| 123 |
+
head_mask=head_mask,
|
| 124 |
+
)
|
| 125 |
|
| 126 |
try:
|
| 127 |
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
|
|
|
| 137 |
k = self._split_heads(self.key(hidden_states)).permute(0, 2, 1, 3)
|
| 138 |
v = self._split_heads(self.value(hidden_states)).permute(0, 2, 1, 3)
|
| 139 |
|
| 140 |
+
if q.dtype not in (torch.float16, torch.bfloat16):
|
| 141 |
+
raise ValueError(
|
| 142 |
+
"flash_attention_2 requires float16 or bfloat16 model weights. "
|
| 143 |
+
f"Received {q.dtype}."
|
| 144 |
+
)
|
| 145 |
|
| 146 |
if key_padding_mask is not None and key_padding_mask.any():
|
| 147 |
attend = ~key_padding_mask
|
|
|
|
| 152 |
q_u, k_u, v_u,
|
| 153 |
cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens,
|
| 154 |
max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen,
|
| 155 |
+
dropout_p=self.dropout.p if self.training else 0.0,
|
| 156 |
causal=False,
|
| 157 |
)
|
| 158 |
out = pad_input(out_u, indices, B, T)
|
| 159 |
else:
|
| 160 |
+
out = flash_attn_func(
|
| 161 |
+
q,
|
| 162 |
+
k,
|
| 163 |
+
v,
|
| 164 |
+
dropout_p=self.dropout.p if self.training else 0.0,
|
| 165 |
+
causal=False,
|
| 166 |
+
)
|
| 167 |
|
| 168 |
+
out = out.reshape(B, T, self.all_head_size)
|
| 169 |
return out, None
|
| 170 |
|
| 171 |
|
|
|
|
| 200 |
hidden_states: torch.Tensor,
|
| 201 |
key_padding_mask: Optional[torch.Tensor],
|
| 202 |
output_attentions: bool = False,
|
| 203 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 204 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 205 |
+
self_out, attn_weights = self.self(
|
| 206 |
+
hidden_states,
|
| 207 |
+
key_padding_mask,
|
| 208 |
+
output_attentions,
|
| 209 |
+
head_mask,
|
| 210 |
+
)
|
| 211 |
return self.output(self_out, hidden_states), attn_weights
|
| 212 |
|
| 213 |
|
|
|
|
| 215 |
def __init__(self, config):
|
| 216 |
super().__init__()
|
| 217 |
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 218 |
+
if config.hidden_act in (None, "identity", "linear"):
|
| 219 |
+
self.intermediate_act_fn = lambda value: value
|
| 220 |
+
elif isinstance(config.hidden_act, str):
|
| 221 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
| 222 |
+
else:
|
| 223 |
+
self.intermediate_act_fn = config.hidden_act
|
| 224 |
|
| 225 |
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 226 |
+
return self.intermediate_act_fn(self.dense(hidden_states))
|
| 227 |
|
| 228 |
|
| 229 |
class BertOutput(nn.Module):
|
|
|
|
| 250 |
hidden_states: torch.Tensor,
|
| 251 |
key_padding_mask: Optional[torch.Tensor],
|
| 252 |
output_attentions: bool = False,
|
| 253 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 254 |
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 255 |
+
attn_out, attn_weights = self.attention(
|
| 256 |
+
hidden_states,
|
| 257 |
+
key_padding_mask,
|
| 258 |
+
output_attentions,
|
| 259 |
+
head_mask,
|
| 260 |
+
)
|
| 261 |
return self.output(self.intermediate(attn_out), attn_out), attn_weights
|
| 262 |
|
| 263 |
|
|
|
|
| 265 |
def __init__(self, config):
|
| 266 |
super().__init__()
|
| 267 |
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
| 268 |
+
self.gradient_checkpointing = False
|
| 269 |
|
| 270 |
def forward(
|
| 271 |
self,
|
|
|
|
| 273 |
key_padding_mask: Optional[torch.Tensor],
|
| 274 |
output_hidden_states: bool = False,
|
| 275 |
output_attentions: bool = False,
|
| 276 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 277 |
) -> Tuple:
|
| 278 |
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 279 |
all_attentions = () if output_attentions else None
|
| 280 |
|
| 281 |
+
for layer_index, layer in enumerate(self.layer):
|
| 282 |
+
layer_head_mask = (
|
| 283 |
+
head_mask[layer_index] if head_mask is not None else None
|
| 284 |
+
)
|
| 285 |
+
if self.gradient_checkpointing and self.training:
|
| 286 |
+
hidden_states, attn_weights = torch.utils.checkpoint.checkpoint(
|
| 287 |
+
layer.__call__,
|
| 288 |
+
hidden_states,
|
| 289 |
+
key_padding_mask,
|
| 290 |
+
output_attentions,
|
| 291 |
+
layer_head_mask,
|
| 292 |
+
use_reentrant=False,
|
| 293 |
+
)
|
| 294 |
+
else:
|
| 295 |
+
hidden_states, attn_weights = layer(
|
| 296 |
+
hidden_states,
|
| 297 |
+
key_padding_mask,
|
| 298 |
+
output_attentions,
|
| 299 |
+
layer_head_mask,
|
| 300 |
+
)
|
| 301 |
if output_hidden_states:
|
| 302 |
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 303 |
if output_attentions:
|
|
|
|
| 316 |
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 317 |
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
| 318 |
|
| 319 |
+
def forward(
|
| 320 |
+
self,
|
| 321 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 322 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 323 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 324 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 325 |
+
) -> torch.Tensor:
|
| 326 |
+
if (input_ids is None) == (inputs_embeds is None):
|
| 327 |
+
raise ValueError("Specify exactly one of input_ids or inputs_embeds.")
|
| 328 |
+
B, T = (
|
| 329 |
+
input_ids.shape
|
| 330 |
+
if input_ids is not None
|
| 331 |
+
else inputs_embeds.shape[:2]
|
| 332 |
+
)
|
| 333 |
if token_type_ids is None:
|
| 334 |
+
token_type_ids = torch.zeros(
|
| 335 |
+
(B, T),
|
| 336 |
+
dtype=torch.long,
|
| 337 |
+
device=(
|
| 338 |
+
input_ids.device
|
| 339 |
+
if input_ids is not None
|
| 340 |
+
else inputs_embeds.device
|
| 341 |
+
),
|
| 342 |
+
)
|
| 343 |
+
if position_ids is None:
|
| 344 |
+
position_ids = self.position_ids[:, :T]
|
| 345 |
+
x = (
|
| 346 |
+
self.word_embeddings(input_ids)
|
| 347 |
+
if inputs_embeds is None
|
| 348 |
+
else inputs_embeds
|
| 349 |
+
)
|
| 350 |
x = x + self.token_type_embeddings(token_type_ids)
|
| 351 |
+
x = x + self.position_embeddings(position_ids)
|
| 352 |
return self.dropout(self.LayerNorm(x))
|
| 353 |
|
| 354 |
|
|
|
|
| 367 |
super().__init__()
|
| 368 |
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 369 |
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 370 |
+
hidden_act = (
|
| 371 |
+
config.mlm_hidden_act
|
| 372 |
+
if getattr(config, "mlm_hidden_act", None) is not None
|
| 373 |
+
else config.hidden_act
|
| 374 |
+
)
|
| 375 |
+
if hidden_act in (None, "identity", "linear"):
|
| 376 |
+
self.transform_act_fn = lambda value: value
|
| 377 |
+
elif isinstance(hidden_act, str):
|
| 378 |
+
self.transform_act_fn = ACT2FN[hidden_act]
|
| 379 |
+
else:
|
| 380 |
+
self.transform_act_fn = hidden_act
|
| 381 |
|
| 382 |
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 383 |
+
return self.LayerNorm(self.transform_act_fn(self.dense(hidden_states)))
|
| 384 |
|
| 385 |
|
| 386 |
class BertModel(PreTrainedModel):
|
|
|
|
| 388 |
base_model_prefix = "bert"
|
| 389 |
_supports_sdpa = True
|
| 390 |
_supports_flash_attn_2 = True
|
| 391 |
+
supports_gradient_checkpointing = True
|
| 392 |
+
_keys_to_ignore_on_load_missing = [r"pooler\."]
|
| 393 |
|
| 394 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 395 |
super().__init__(config)
|
| 396 |
self.embeddings = BertEmbeddings(config)
|
| 397 |
self.encoder = BertEncoder(config)
|
| 398 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
| 399 |
self.post_init()
|
| 400 |
|
| 401 |
def get_input_embeddings(self):
|
|
|
|
| 406 |
|
| 407 |
def forward(
|
| 408 |
self,
|
| 409 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 410 |
attention_mask: Optional[torch.Tensor] = None,
|
| 411 |
token_type_ids: Optional[torch.LongTensor] = None,
|
| 412 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 413 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 414 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 415 |
output_hidden_states: Optional[bool] = None,
|
| 416 |
output_attentions: Optional[bool] = None,
|
| 417 |
return_dict: Optional[bool] = None,
|
|
|
|
| 420 |
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 421 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 422 |
|
| 423 |
+
if (input_ids is None) == (inputs_embeds is None):
|
| 424 |
+
raise ValueError("Specify exactly one of input_ids or inputs_embeds.")
|
| 425 |
+
input_shape = (
|
| 426 |
+
input_ids.shape
|
| 427 |
+
if input_ids is not None
|
| 428 |
+
else inputs_embeds.shape[:2]
|
| 429 |
+
)
|
| 430 |
+
input_device = (
|
| 431 |
+
input_ids.device
|
| 432 |
+
if input_ids is not None
|
| 433 |
+
else inputs_embeds.device
|
| 434 |
+
)
|
| 435 |
if attention_mask is None:
|
| 436 |
+
attention_mask = torch.ones(input_shape, device=input_device)
|
| 437 |
key_padding_mask = attention_mask.eq(0)
|
| 438 |
if not key_padding_mask.any():
|
| 439 |
key_padding_mask = None
|
| 440 |
+
head_mask = self.get_head_mask(
|
| 441 |
+
head_mask,
|
| 442 |
+
self.config.num_hidden_layers,
|
| 443 |
+
)
|
| 444 |
+
if all(mask is None for mask in head_mask):
|
| 445 |
+
head_mask = None
|
| 446 |
+
|
| 447 |
+
x = self.embeddings(
|
| 448 |
+
input_ids=input_ids,
|
| 449 |
+
token_type_ids=token_type_ids,
|
| 450 |
+
position_ids=position_ids,
|
| 451 |
+
inputs_embeds=inputs_embeds,
|
| 452 |
+
)
|
| 453 |
last_hidden_state, all_hidden_states, all_attentions = self.encoder(
|
| 454 |
x, key_padding_mask,
|
| 455 |
output_hidden_states=output_hidden_states,
|
| 456 |
output_attentions=output_attentions,
|
| 457 |
+
head_mask=head_mask,
|
| 458 |
)
|
| 459 |
+
pooled = self.pooler(last_hidden_state) if self.pooler is not None else None
|
| 460 |
|
| 461 |
if not return_dict:
|
| 462 |
+
output = (last_hidden_state, pooled)
|
| 463 |
+
if output_hidden_states:
|
| 464 |
+
output += (all_hidden_states,)
|
| 465 |
+
if output_attentions:
|
| 466 |
+
output += (all_attentions,)
|
| 467 |
+
return output
|
| 468 |
|
| 469 |
return BaseModelOutputWithPooling(
|
| 470 |
last_hidden_state=last_hidden_state,
|
|
|
|
| 479 |
base_model_prefix = "bert"
|
| 480 |
_supports_sdpa = True
|
| 481 |
_supports_flash_attn_2 = True
|
| 482 |
+
supports_gradient_checkpointing = True
|
| 483 |
+
_keys_to_ignore_on_load_unexpected = [r"bert\.pooler\."]
|
| 484 |
|
| 485 |
def __init__(self, config):
|
| 486 |
super().__init__(config)
|
| 487 |
+
self.bert = BertModel(config, add_pooling_layer=False)
|
| 488 |
self.transform = BertPredictionHeadTransform(config)
|
| 489 |
self.cls = nn.Linear(config.hidden_size, config.vocab_size)
|
| 490 |
self.post_init()
|
|
|
|
| 492 |
def get_input_embeddings(self):
|
| 493 |
return self.bert.embeddings.word_embeddings
|
| 494 |
|
| 495 |
+
def set_input_embeddings(self, value):
|
| 496 |
+
self.bert.embeddings.word_embeddings = value
|
| 497 |
+
|
| 498 |
+
def get_output_embeddings(self):
|
| 499 |
+
return self.cls
|
| 500 |
+
|
| 501 |
+
def set_output_embeddings(self, value):
|
| 502 |
+
self.cls = value
|
| 503 |
+
|
| 504 |
def forward(
|
| 505 |
self,
|
| 506 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 507 |
attention_mask: Optional[torch.Tensor] = None,
|
| 508 |
token_type_ids: Optional[torch.LongTensor] = None,
|
| 509 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 510 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 511 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 512 |
labels: Optional[torch.LongTensor] = None,
|
| 513 |
output_hidden_states: Optional[bool] = None,
|
| 514 |
output_attentions: Optional[bool] = None,
|
|
|
|
| 517 |
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 518 |
|
| 519 |
outputs = self.bert(
|
| 520 |
+
input_ids=input_ids,
|
| 521 |
+
attention_mask=attention_mask,
|
| 522 |
+
token_type_ids=token_type_ids,
|
| 523 |
+
position_ids=position_ids,
|
| 524 |
+
head_mask=head_mask,
|
| 525 |
+
inputs_embeds=inputs_embeds,
|
| 526 |
+
output_hidden_states=output_hidden_states,
|
| 527 |
+
output_attentions=output_attentions,
|
| 528 |
return_dict=True,
|
| 529 |
)
|
| 530 |
logits = self.cls(self.transform(outputs.last_hidden_state))
|
|
|
|
| 534 |
loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100)
|
| 535 |
|
| 536 |
if not return_dict:
|
| 537 |
+
output = (logits,)
|
| 538 |
+
if output_hidden_states:
|
| 539 |
+
output += (outputs.hidden_states,)
|
| 540 |
+
if output_attentions:
|
| 541 |
+
output += (outputs.attentions,)
|
| 542 |
return (loss,) + output if loss is not None else output
|
| 543 |
|
| 544 |
return MaskedLMOutput(
|
tokenization_splicebert.py
CHANGED
|
@@ -79,7 +79,7 @@ class SpliceBERTTokenizer(PreTrainedTokenizer):
|
|
| 79 |
sep = [self.sep_token_id]
|
| 80 |
if token_ids_1 is None:
|
| 81 |
return cls + token_ids_0 + sep
|
| 82 |
-
return cls + token_ids_0 + sep +
|
| 83 |
|
| 84 |
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None,
|
| 85 |
already_has_special_tokens=False):
|
|
@@ -89,10 +89,13 @@ class SpliceBERTTokenizer(PreTrainedTokenizer):
|
|
| 89 |
)
|
| 90 |
mask = [1] + [0] * len(token_ids_0) + [1]
|
| 91 |
if token_ids_1 is not None:
|
| 92 |
-
mask += [
|
| 93 |
return mask
|
| 94 |
|
| 95 |
def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
|
| 96 |
if token_ids_1 is None:
|
| 97 |
-
return [0]
|
| 98 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
sep = [self.sep_token_id]
|
| 80 |
if token_ids_1 is None:
|
| 81 |
return cls + token_ids_0 + sep
|
| 82 |
+
return cls + token_ids_0 + sep + token_ids_1 + sep
|
| 83 |
|
| 84 |
def get_special_tokens_mask(self, token_ids_0, token_ids_1=None,
|
| 85 |
already_has_special_tokens=False):
|
|
|
|
| 89 |
)
|
| 90 |
mask = [1] + [0] * len(token_ids_0) + [1]
|
| 91 |
if token_ids_1 is not None:
|
| 92 |
+
mask += [0] * len(token_ids_1) + [1]
|
| 93 |
return mask
|
| 94 |
|
| 95 |
def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None):
|
| 96 |
if token_ids_1 is None:
|
| 97 |
+
return [0] * (len(token_ids_0) + 2)
|
| 98 |
+
return (
|
| 99 |
+
[0] * (len(token_ids_0) + 2)
|
| 100 |
+
+ [1] * (len(token_ids_1) + 1)
|
| 101 |
+
)
|