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, dtype="auto") - Notebooks
- Google Colab
- Kaggle
Upload folder using huggingface_hub
Browse files- config.json +1 -1
- configuration_bert_updated.py +41 -0
- model.safetensors +2 -2
- modeling_bert.py +372 -0
config.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
{
|
| 2 |
"_name_or_path": "Taykhoom/SpliceBERT-1024nt",
|
| 3 |
"architectures": [
|
| 4 |
-
"
|
| 5 |
],
|
| 6 |
"model_type": "bert_updated",
|
| 7 |
"auto_map": {
|
|
|
|
| 1 |
{
|
| 2 |
"_name_or_path": "Taykhoom/SpliceBERT-1024nt",
|
| 3 |
"architectures": [
|
| 4 |
+
"BertForMaskedLM"
|
| 5 |
],
|
| 6 |
"model_type": "bert_updated",
|
| 7 |
"auto_map": {
|
configuration_bert_updated.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BertUpdatedConfig(PretrainedConfig):
|
| 5 |
+
model_type = "bert_updated"
|
| 6 |
+
|
| 7 |
+
auto_map = {
|
| 8 |
+
"AutoConfig": "configuration_bert_updated.BertUpdatedConfig",
|
| 9 |
+
"AutoModel": "modeling_bert.BertModel",
|
| 10 |
+
"AutoModelForMaskedLM": "modeling_bert.BertForMaskedLM",
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
vocab_size=30522,
|
| 16 |
+
hidden_size=768,
|
| 17 |
+
num_hidden_layers=12,
|
| 18 |
+
num_attention_heads=12,
|
| 19 |
+
intermediate_size=3072,
|
| 20 |
+
hidden_act="gelu",
|
| 21 |
+
hidden_dropout_prob=0.1,
|
| 22 |
+
attention_probs_dropout_prob=0.1,
|
| 23 |
+
max_position_embeddings=512,
|
| 24 |
+
type_vocab_size=2,
|
| 25 |
+
initializer_range=0.02,
|
| 26 |
+
layer_norm_eps=1e-12,
|
| 27 |
+
**kwargs,
|
| 28 |
+
):
|
| 29 |
+
super().__init__(**kwargs)
|
| 30 |
+
self.vocab_size = vocab_size
|
| 31 |
+
self.hidden_size = hidden_size
|
| 32 |
+
self.num_hidden_layers = num_hidden_layers
|
| 33 |
+
self.num_attention_heads = num_attention_heads
|
| 34 |
+
self.intermediate_size = intermediate_size
|
| 35 |
+
self.hidden_act = hidden_act
|
| 36 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 37 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 38 |
+
self.max_position_embeddings = max_position_embeddings
|
| 39 |
+
self.type_vocab_size = type_vocab_size
|
| 40 |
+
self.initializer_range = initializer_range
|
| 41 |
+
self.layer_norm_eps = layer_norm_eps
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3785342bb2a4d6e602fcbda35e1c3f1659f78f82ed9b3bd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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from typing import Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
| 8 |
+
from transformers.modeling_outputs import BaseModelOutputWithPooling, MaskedLMOutput
|
| 9 |
+
|
| 10 |
+
from .configuration_bert_updated import BertUpdatedConfig
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class BertSelfAttention(nn.Module):
|
| 14 |
+
|
| 15 |
+
def __init__(self, config):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.num_attention_heads = config.num_attention_heads
|
| 18 |
+
self.attention_head_size = config.hidden_size // config.num_attention_heads
|
| 19 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 20 |
+
|
| 21 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 22 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 23 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 24 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 25 |
+
|
| 26 |
+
def _split_heads(self, x: torch.Tensor) -> torch.Tensor:
|
| 27 |
+
B, T, _ = x.shape
|
| 28 |
+
return x.view(B, T, self.num_attention_heads, self.attention_head_size).permute(0, 2, 1, 3)
|
| 29 |
+
|
| 30 |
+
def forward(
|
| 31 |
+
self,
|
| 32 |
+
hidden_states: torch.Tensor,
|
| 33 |
+
key_padding_mask: Optional[torch.Tensor] = None,
|
| 34 |
+
output_attentions: bool = False,
|
| 35 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 36 |
+
q = self._split_heads(self.query(hidden_states))
|
| 37 |
+
k = self._split_heads(self.key(hidden_states))
|
| 38 |
+
v = self._split_heads(self.value(hidden_states))
|
| 39 |
+
|
| 40 |
+
scale = math.sqrt(self.attention_head_size)
|
| 41 |
+
scores = torch.matmul(q, k.transpose(-1, -2)) / scale
|
| 42 |
+
if key_padding_mask is not None:
|
| 43 |
+
scores = scores.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
|
| 44 |
+
probs = F.softmax(scores, dim=-1)
|
| 45 |
+
probs = self.dropout(probs)
|
| 46 |
+
context = torch.matmul(probs, v)
|
| 47 |
+
|
| 48 |
+
B, _, T, _ = context.shape
|
| 49 |
+
context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
|
| 50 |
+
|
| 51 |
+
if output_attentions:
|
| 52 |
+
return context, probs
|
| 53 |
+
return context, None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class BertSdpaSelfAttention(BertSelfAttention):
|
| 57 |
+
|
| 58 |
+
def forward(
|
| 59 |
+
self,
|
| 60 |
+
hidden_states: torch.Tensor,
|
| 61 |
+
key_padding_mask: Optional[torch.Tensor] = None,
|
| 62 |
+
output_attentions: bool = False,
|
| 63 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 64 |
+
if output_attentions:
|
| 65 |
+
return super().forward(hidden_states, key_padding_mask, output_attentions=True)
|
| 66 |
+
|
| 67 |
+
B, T, _ = hidden_states.shape
|
| 68 |
+
q = self._split_heads(self.query(hidden_states))
|
| 69 |
+
k = self._split_heads(self.key(hidden_states))
|
| 70 |
+
v = self._split_heads(self.value(hidden_states))
|
| 71 |
+
|
| 72 |
+
attn_mask = None
|
| 73 |
+
if key_padding_mask is not None:
|
| 74 |
+
attn_mask = torch.zeros(B, 1, 1, T, dtype=q.dtype, device=q.device)
|
| 75 |
+
attn_mask = attn_mask.masked_fill(key_padding_mask[:, None, None, :], float("-inf"))
|
| 76 |
+
|
| 77 |
+
context = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
|
| 78 |
+
context = context.permute(0, 2, 1, 3).contiguous().view(B, T, self.all_head_size)
|
| 79 |
+
return context, None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class BertFlashSelfAttention(BertSelfAttention):
|
| 83 |
+
|
| 84 |
+
def forward(
|
| 85 |
+
self,
|
| 86 |
+
hidden_states: torch.Tensor,
|
| 87 |
+
key_padding_mask: Optional[torch.Tensor] = None,
|
| 88 |
+
output_attentions: bool = False,
|
| 89 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 90 |
+
if output_attentions:
|
| 91 |
+
return super().forward(hidden_states, key_padding_mask, output_attentions=True)
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
from flash_attn import flash_attn_func, flash_attn_varlen_func
|
| 95 |
+
from flash_attn.bert_padding import pad_input, unpad_input
|
| 96 |
+
except ImportError as e:
|
| 97 |
+
raise ImportError(
|
| 98 |
+
"flash_attn is required for attn_implementation='flash_attention_2'. "
|
| 99 |
+
"Install with: pip install flash-attn --no-build-isolation"
|
| 100 |
+
) from e
|
| 101 |
+
|
| 102 |
+
B, T, _ = hidden_states.shape
|
| 103 |
+
q = self._split_heads(self.query(hidden_states)).permute(0, 2, 1, 3)
|
| 104 |
+
k = self._split_heads(self.key(hidden_states)).permute(0, 2, 1, 3)
|
| 105 |
+
v = self._split_heads(self.value(hidden_states)).permute(0, 2, 1, 3)
|
| 106 |
+
|
| 107 |
+
orig_dtype = q.dtype
|
| 108 |
+
if orig_dtype not in (torch.float16, torch.bfloat16):
|
| 109 |
+
q, k, v = q.to(torch.bfloat16), k.to(torch.bfloat16), v.to(torch.bfloat16)
|
| 110 |
+
|
| 111 |
+
if key_padding_mask is not None and key_padding_mask.any():
|
| 112 |
+
attend = ~key_padding_mask
|
| 113 |
+
q_u, indices, cu_seqlens, max_seqlen, _ = unpad_input(q, attend)
|
| 114 |
+
k_u, _, _, _, _ = unpad_input(k, attend)
|
| 115 |
+
v_u, _, _, _, _ = unpad_input(v, attend)
|
| 116 |
+
out_u = flash_attn_varlen_func(
|
| 117 |
+
q_u, k_u, v_u,
|
| 118 |
+
cu_seqlens_q=cu_seqlens, cu_seqlens_k=cu_seqlens,
|
| 119 |
+
max_seqlen_q=max_seqlen, max_seqlen_k=max_seqlen,
|
| 120 |
+
causal=False,
|
| 121 |
+
)
|
| 122 |
+
out = pad_input(out_u, indices, B, T)
|
| 123 |
+
else:
|
| 124 |
+
out = flash_attn_func(q, k, v, causal=False)
|
| 125 |
+
|
| 126 |
+
out = out.to(orig_dtype).reshape(B, T, self.all_head_size)
|
| 127 |
+
return out, None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
BERT_SELF_ATTENTION_CLASSES = {
|
| 131 |
+
"eager": BertSelfAttention,
|
| 132 |
+
"sdpa": BertSdpaSelfAttention,
|
| 133 |
+
"flash_attention_2": BertFlashSelfAttention,
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class BertSelfOutput(nn.Module):
|
| 138 |
+
def __init__(self, config):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 141 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 142 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 143 |
+
|
| 144 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 145 |
+
hidden_states = self.dropout(self.dense(hidden_states))
|
| 146 |
+
return self.LayerNorm(hidden_states + input_tensor)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class BertAttention(nn.Module):
|
| 150 |
+
def __init__(self, config):
|
| 151 |
+
super().__init__()
|
| 152 |
+
attn_cls = BERT_SELF_ATTENTION_CLASSES[getattr(config, "_attn_implementation", "eager")]
|
| 153 |
+
self.self = attn_cls(config)
|
| 154 |
+
self.output = BertSelfOutput(config)
|
| 155 |
+
|
| 156 |
+
def forward(
|
| 157 |
+
self,
|
| 158 |
+
hidden_states: torch.Tensor,
|
| 159 |
+
key_padding_mask: Optional[torch.Tensor],
|
| 160 |
+
output_attentions: bool = False,
|
| 161 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 162 |
+
self_out, attn_weights = self.self(hidden_states, key_padding_mask, output_attentions)
|
| 163 |
+
return self.output(self_out, hidden_states), attn_weights
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class BertIntermediate(nn.Module):
|
| 167 |
+
def __init__(self, config):
|
| 168 |
+
super().__init__()
|
| 169 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
| 170 |
+
|
| 171 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 172 |
+
return F.gelu(self.dense(hidden_states))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class BertOutput(nn.Module):
|
| 176 |
+
def __init__(self, config):
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
| 179 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 180 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 181 |
+
|
| 182 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 183 |
+
hidden_states = self.dropout(self.dense(hidden_states))
|
| 184 |
+
return self.LayerNorm(hidden_states + input_tensor)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class BertLayer(nn.Module):
|
| 188 |
+
def __init__(self, config):
|
| 189 |
+
super().__init__()
|
| 190 |
+
self.attention = BertAttention(config)
|
| 191 |
+
self.intermediate = BertIntermediate(config)
|
| 192 |
+
self.output = BertOutput(config)
|
| 193 |
+
|
| 194 |
+
def forward(
|
| 195 |
+
self,
|
| 196 |
+
hidden_states: torch.Tensor,
|
| 197 |
+
key_padding_mask: Optional[torch.Tensor],
|
| 198 |
+
output_attentions: bool = False,
|
| 199 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 200 |
+
attn_out, attn_weights = self.attention(hidden_states, key_padding_mask, output_attentions)
|
| 201 |
+
return self.output(self.intermediate(attn_out), attn_out), attn_weights
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class BertEncoder(nn.Module):
|
| 205 |
+
def __init__(self, config):
|
| 206 |
+
super().__init__()
|
| 207 |
+
self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])
|
| 208 |
+
|
| 209 |
+
def forward(
|
| 210 |
+
self,
|
| 211 |
+
hidden_states: torch.Tensor,
|
| 212 |
+
key_padding_mask: Optional[torch.Tensor],
|
| 213 |
+
output_hidden_states: bool = False,
|
| 214 |
+
output_attentions: bool = False,
|
| 215 |
+
) -> Tuple:
|
| 216 |
+
all_hidden_states = (hidden_states,) if output_hidden_states else None
|
| 217 |
+
all_attentions = () if output_attentions else None
|
| 218 |
+
|
| 219 |
+
for layer in self.layer:
|
| 220 |
+
hidden_states, attn_weights = layer(hidden_states, key_padding_mask, output_attentions)
|
| 221 |
+
if output_hidden_states:
|
| 222 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 223 |
+
if output_attentions:
|
| 224 |
+
all_attentions = all_attentions + (attn_weights,)
|
| 225 |
+
|
| 226 |
+
return hidden_states, all_hidden_states, all_attentions
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class BertEmbeddings(nn.Module):
|
| 230 |
+
def __init__(self, config):
|
| 231 |
+
super().__init__()
|
| 232 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
| 233 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
| 234 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
| 235 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 236 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 237 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
| 238 |
+
|
| 239 |
+
def forward(self, input_ids: torch.LongTensor, token_type_ids: Optional[torch.LongTensor] = None) -> torch.Tensor:
|
| 240 |
+
B, T = input_ids.shape
|
| 241 |
+
if token_type_ids is None:
|
| 242 |
+
token_type_ids = torch.zeros_like(input_ids)
|
| 243 |
+
x = self.word_embeddings(input_ids)
|
| 244 |
+
x = x + self.position_embeddings(self.position_ids[:, :T])
|
| 245 |
+
x = x + self.token_type_embeddings(token_type_ids)
|
| 246 |
+
return self.dropout(self.LayerNorm(x))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class BertPooler(nn.Module):
|
| 250 |
+
def __init__(self, config):
|
| 251 |
+
super().__init__()
|
| 252 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 253 |
+
self.activation = nn.Tanh()
|
| 254 |
+
|
| 255 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 256 |
+
return self.activation(self.dense(hidden_states[:, 0]))
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
class BertPredictionHeadTransform(nn.Module):
|
| 260 |
+
def __init__(self, config):
|
| 261 |
+
super().__init__()
|
| 262 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 263 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 264 |
+
|
| 265 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 266 |
+
return self.LayerNorm(F.gelu(self.dense(hidden_states)))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class BertModel(PreTrainedModel):
|
| 270 |
+
config_class = BertUpdatedConfig
|
| 271 |
+
base_model_prefix = "bert"
|
| 272 |
+
_supports_sdpa = True
|
| 273 |
+
_supports_flash_attn_2 = True
|
| 274 |
+
|
| 275 |
+
def __init__(self, config):
|
| 276 |
+
super().__init__(config)
|
| 277 |
+
self.embeddings = BertEmbeddings(config)
|
| 278 |
+
self.encoder = BertEncoder(config)
|
| 279 |
+
self.pooler = BertPooler(config)
|
| 280 |
+
self.post_init()
|
| 281 |
+
|
| 282 |
+
def get_input_embeddings(self):
|
| 283 |
+
return self.embeddings.word_embeddings
|
| 284 |
+
|
| 285 |
+
def set_input_embeddings(self, value):
|
| 286 |
+
self.embeddings.word_embeddings = value
|
| 287 |
+
|
| 288 |
+
def forward(
|
| 289 |
+
self,
|
| 290 |
+
input_ids: torch.LongTensor,
|
| 291 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 292 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 293 |
+
output_hidden_states: Optional[bool] = None,
|
| 294 |
+
output_attentions: Optional[bool] = None,
|
| 295 |
+
return_dict: Optional[bool] = None,
|
| 296 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 297 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 298 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 299 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 300 |
+
|
| 301 |
+
if attention_mask is None:
|
| 302 |
+
attention_mask = torch.ones_like(input_ids)
|
| 303 |
+
key_padding_mask = attention_mask.eq(0)
|
| 304 |
+
if not key_padding_mask.any():
|
| 305 |
+
key_padding_mask = None
|
| 306 |
+
|
| 307 |
+
x = self.embeddings(input_ids, token_type_ids)
|
| 308 |
+
last_hidden_state, all_hidden_states, all_attentions = self.encoder(
|
| 309 |
+
x, key_padding_mask,
|
| 310 |
+
output_hidden_states=output_hidden_states,
|
| 311 |
+
output_attentions=output_attentions,
|
| 312 |
+
)
|
| 313 |
+
pooled = self.pooler(last_hidden_state)
|
| 314 |
+
|
| 315 |
+
if not return_dict:
|
| 316 |
+
return tuple(v for v in [last_hidden_state, pooled, all_hidden_states, all_attentions] if v is not None)
|
| 317 |
+
|
| 318 |
+
return BaseModelOutputWithPooling(
|
| 319 |
+
last_hidden_state=last_hidden_state,
|
| 320 |
+
pooler_output=pooled,
|
| 321 |
+
hidden_states=all_hidden_states,
|
| 322 |
+
attentions=all_attentions,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
class BertForMaskedLM(PreTrainedModel):
|
| 327 |
+
config_class = BertUpdatedConfig
|
| 328 |
+
base_model_prefix = "bert"
|
| 329 |
+
_supports_sdpa = True
|
| 330 |
+
_supports_flash_attn_2 = True
|
| 331 |
+
|
| 332 |
+
def __init__(self, config):
|
| 333 |
+
super().__init__(config)
|
| 334 |
+
self.bert = BertModel(config)
|
| 335 |
+
self.transform = BertPredictionHeadTransform(config)
|
| 336 |
+
self.cls = nn.Linear(config.hidden_size, config.vocab_size)
|
| 337 |
+
self.post_init()
|
| 338 |
+
|
| 339 |
+
def get_input_embeddings(self):
|
| 340 |
+
return self.bert.embeddings.word_embeddings
|
| 341 |
+
|
| 342 |
+
def forward(
|
| 343 |
+
self,
|
| 344 |
+
input_ids: torch.LongTensor,
|
| 345 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 346 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
| 347 |
+
labels: Optional[torch.LongTensor] = None,
|
| 348 |
+
output_hidden_states: Optional[bool] = None,
|
| 349 |
+
output_attentions: Optional[bool] = None,
|
| 350 |
+
return_dict: Optional[bool] = None,
|
| 351 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
| 352 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 353 |
+
|
| 354 |
+
outputs = self.bert(
|
| 355 |
+
input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids,
|
| 356 |
+
output_hidden_states=output_hidden_states, output_attentions=output_attentions,
|
| 357 |
+
return_dict=True,
|
| 358 |
+
)
|
| 359 |
+
logits = self.cls(self.transform(outputs.last_hidden_state))
|
| 360 |
+
|
| 361 |
+
loss = None
|
| 362 |
+
if labels is not None:
|
| 363 |
+
loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100)
|
| 364 |
+
|
| 365 |
+
if not return_dict:
|
| 366 |
+
output = (logits,) + outputs[2:]
|
| 367 |
+
return (loss,) + output if loss is not None else output
|
| 368 |
+
|
| 369 |
+
return MaskedLMOutput(
|
| 370 |
+
loss=loss, logits=logits,
|
| 371 |
+
hidden_states=outputs.hidden_states, attentions=outputs.attentions,
|
| 372 |
+
)
|