Taykhoom commited on
Commit
ac7f7ab
·
verified ·
1 Parent(s): acde8cc

Upload folder using huggingface_hub

Browse files
README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags:
4
+ - bert
5
+ - language-model
6
+ license: apache-2.0
7
+ ---
8
+
9
+ # BERT-updated
10
+
11
+ Standard BERT architecture with `flash_attention_2` and `sdpa` support added.
12
+
13
+ This is a **shared code repository** — it contains no pretrained weights. It is used
14
+ as the code backend for biological sequence models that share the vanilla BERT
15
+ architecture (post-LN transformer, learned absolute position embeddings) but have
16
+ model-specific vocabularies and hyperparameters:
17
+
18
+ - [Taykhoom/RNABERT](https://huggingface.co/Taykhoom/RNABERT)
19
+ - [Taykhoom/UTRBERT-3mer](https://huggingface.co/Taykhoom/UTRBERT-3mer), [4mer](https://huggingface.co/Taykhoom/UTRBERT-4mer), [5mer](https://huggingface.co/Taykhoom/UTRBERT-5mer), [6mer](https://huggingface.co/Taykhoom/UTRBERT-6mer)
20
+ - [Taykhoom/DNABERT-3mer](https://huggingface.co/Taykhoom/DNABERT-3mer), [4mer](https://huggingface.co/Taykhoom/DNABERT-4mer), [5mer](https://huggingface.co/Taykhoom/DNABERT-5mer), [6mer](https://huggingface.co/Taykhoom/DNABERT-6mer)
21
+
22
+ Each of those repos stores weights, tokenizer, and config; their `auto_map` in
23
+ `config.json` points here for the modeling code.
24
+
25
+ ## What was changed from stock `transformers.BertModel`
26
+
27
+ The standard HF `BertModel` (transformers 4.57.6) supports `sdpa` but not
28
+ `flash_attention_2`. This repo adds a complete `attn_implementation` dispatch:
29
+
30
+ | Backend | Class | Notes |
31
+ |---|---|---|
32
+ | `eager` | `BertSelfAttention` | Standard scaled dot-product, identical to original BERT |
33
+ | `sdpa` | `BertSdpaSelfAttention` | `F.scaled_dot_product_attention`, bool mask -> additive float mask |
34
+ | `flash_attention_2` | `BertFlashSelfAttention` | `flash_attn_varlen_func` for padded inputs, `flash_attn_func` for unpadded |
35
+
36
+ The rest of the architecture (embeddings, FFN, pooler, weight layout) is unchanged.
37
+
38
+ ## Usage
39
+
40
+ Do not load this repo directly. Load one of the model repos listed above:
41
+
42
+ ```python
43
+ from transformers import AutoTokenizer, AutoModel
44
+
45
+ tokenizer = AutoTokenizer.from_pretrained("Taykhoom/RNABERT", trust_remote_code=True)
46
+ model = AutoModel.from_pretrained("Taykhoom/RNABERT", trust_remote_code=True)
47
+
48
+ # Flash Attention 2
49
+ model = AutoModel.from_pretrained("Taykhoom/UTRBERT-3mer", trust_remote_code=True,
50
+ attn_implementation="flash_attention_2")
51
+ ```
52
+
53
+ ## Credits
54
+
55
+ Modeling code authored primarily by [Claude Code](https://claude.ai/code) and reviewed
56
+ manually by Taykhoom Dalal.
57
+
58
+ ## License
59
+
60
+ Apache 2.0.
__pycache__/configuration_bert_updated.cpython-39.pyc ADDED
Binary file (1.35 kB). View file
 
__pycache__/modeling_bert.cpython-39.pyc ADDED
Binary file (13 kB). View file
 
config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "bert_updated",
3
+ "architectures": ["BertModel"],
4
+ "auto_map": {
5
+ "AutoConfig": "configuration_bert_updated.BertUpdatedConfig",
6
+ "AutoModel": "modeling_bert.BertModel",
7
+ "AutoModelForMaskedLM": "modeling_bert.BertForMaskedLM"
8
+ },
9
+ "vocab_size": 30522,
10
+ "hidden_size": 768,
11
+ "num_hidden_layers": 12,
12
+ "num_attention_heads": 12,
13
+ "intermediate_size": 3072,
14
+ "hidden_act": "gelu",
15
+ "hidden_dropout_prob": 0.1,
16
+ "attention_probs_dropout_prob": 0.1,
17
+ "max_position_embeddings": 512,
18
+ "type_vocab_size": 2,
19
+ "initializer_range": 0.02,
20
+ "layer_norm_eps": 1e-12,
21
+ "pad_token_id": 0
22
+ }
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
modeling_bert.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 BertModel(PreTrainedModel):
260
+ config_class = BertUpdatedConfig
261
+ _supports_sdpa = True
262
+ _supports_flash_attn_2 = True
263
+
264
+ def __init__(self, config):
265
+ super().__init__(config)
266
+ self.embeddings = BertEmbeddings(config)
267
+ self.encoder = BertEncoder(config)
268
+ self.pooler = BertPooler(config)
269
+ self.post_init()
270
+
271
+ def get_input_embeddings(self):
272
+ return self.embeddings.word_embeddings
273
+
274
+ def set_input_embeddings(self, value):
275
+ self.embeddings.word_embeddings = value
276
+
277
+ def forward(
278
+ self,
279
+ input_ids: torch.LongTensor,
280
+ attention_mask: Optional[torch.Tensor] = None,
281
+ token_type_ids: Optional[torch.LongTensor] = None,
282
+ output_hidden_states: Optional[bool] = None,
283
+ output_attentions: Optional[bool] = None,
284
+ return_dict: Optional[bool] = None,
285
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
286
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
287
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
288
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
289
+
290
+ if attention_mask is None:
291
+ attention_mask = torch.ones_like(input_ids)
292
+ key_padding_mask = attention_mask.eq(0)
293
+ if not key_padding_mask.any():
294
+ key_padding_mask = None
295
+
296
+ x = self.embeddings(input_ids, token_type_ids)
297
+ last_hidden_state, all_hidden_states, all_attentions = self.encoder(
298
+ x, key_padding_mask,
299
+ output_hidden_states=output_hidden_states,
300
+ output_attentions=output_attentions,
301
+ )
302
+ pooled = self.pooler(last_hidden_state)
303
+
304
+ if not return_dict:
305
+ return tuple(v for v in [last_hidden_state, pooled, all_hidden_states, all_attentions] if v is not None)
306
+
307
+ return BaseModelOutputWithPooling(
308
+ last_hidden_state=last_hidden_state,
309
+ pooler_output=pooled,
310
+ hidden_states=all_hidden_states,
311
+ attentions=all_attentions,
312
+ )
313
+
314
+
315
+ class BertForMaskedLM(PreTrainedModel):
316
+ config_class = BertUpdatedConfig
317
+ _supports_sdpa = True
318
+ _supports_flash_attn_2 = True
319
+
320
+ def __init__(self, config):
321
+ super().__init__(config)
322
+ self.bert = BertModel(config)
323
+ self.cls = nn.Linear(config.hidden_size, config.vocab_size)
324
+ self.post_init()
325
+
326
+ def get_input_embeddings(self):
327
+ return self.bert.embeddings.word_embeddings
328
+
329
+ def forward(
330
+ self,
331
+ input_ids: torch.LongTensor,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ token_type_ids: Optional[torch.LongTensor] = None,
334
+ labels: Optional[torch.LongTensor] = None,
335
+ output_hidden_states: Optional[bool] = None,
336
+ output_attentions: Optional[bool] = None,
337
+ return_dict: Optional[bool] = None,
338
+ ) -> Union[Tuple, MaskedLMOutput]:
339
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
340
+
341
+ outputs = self.bert(
342
+ input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids,
343
+ output_hidden_states=output_hidden_states, output_attentions=output_attentions,
344
+ return_dict=True,
345
+ )
346
+ logits = self.cls(outputs.last_hidden_state)
347
+
348
+ loss = None
349
+ if labels is not None:
350
+ loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100)
351
+
352
+ if not return_dict:
353
+ output = (logits,) + outputs[2:]
354
+ return (loss,) + output if loss is not None else output
355
+
356
+ return MaskedLMOutput(
357
+ loss=loss, logits=logits,
358
+ hidden_states=outputs.hidden_states, attentions=outputs.attentions,
359
+ )