hamingsi commited on
Commit
d3dd5dd
·
verified ·
1 Parent(s): 943574e

Upload SpikingLM checkpoint and code

Browse files
README.md ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ pipeline_tag: fill-mask
4
+ tags:
5
+ - bert
6
+ - spiking-neural-network
7
+ - masked-language-modeling
8
+ - pytorch
9
+ license: apache-2.0
10
+ ---
11
+
12
+ # SpikingLM
13
+
14
+ SpikingLM is a BERT-base style masked-language model with spiking attention blocks.
15
+
16
+ This checkpoint uses:
17
+
18
+ - temporal Spiking BERT with `T=4`
19
+ - learnable Q/K/V scaling parameters initialized from `7`
20
+ - LIF nodes for projection, Q, K, V, attention output, and MLP blocks
21
+ - `FP16OptimizedExp2Softmax` through `self.learnmax(attention_scores)` for attention normalization
22
+
23
+ ## Files
24
+
25
+ ```text
26
+ config.json
27
+ model.safetensors
28
+ tokenizer.json
29
+ tokenizer_config.json
30
+ special_tokens_map.json
31
+ vocab.txt
32
+ spiking_bert/modeling_spiking_bert.py
33
+ scripts/finetune_glue.py
34
+ requirements.txt
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ```python
40
+ from safetensors.torch import load_file
41
+ from transformers import AutoConfig, AutoTokenizer
42
+ from spiking_bert import BertForMaskedLM
43
+
44
+ repo_or_path = "YOUR_USERNAME/SpikingLM"
45
+
46
+ config = AutoConfig.from_pretrained(repo_or_path)
47
+ config.T = 4
48
+ config._attn_implementation = "eager"
49
+
50
+ tokenizer = AutoTokenizer.from_pretrained(repo_or_path)
51
+ model = BertForMaskedLM(config)
52
+
53
+ state = load_file("model.safetensors")
54
+ model.load_state_dict(state)
55
+ ```
56
+
57
+ If you clone the repository locally, replace `repo_or_path` with the local clone path and load `model.safetensors` from that directory.
58
+
59
+ ## Results
60
+
61
+ Masked-language-model evaluation stored with the checkpoint:
62
+
63
+ ```json
64
+ {"perplexity": 57.81198691730261}
65
+ ```
66
+
67
+ ## Notes
68
+
69
+ Large binary weights are stored as `model.safetensors`. The model code requires `torch`, `transformers`, `safetensors`, and `spikingjelly`.
all_results.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"perplexity": 57.81198691730261}
config.json ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "T": 4,
3
+ "architectures": [
4
+ "BertForMaskedLM"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "classifier_dropout": null,
8
+ "dtype": "float32",
9
+ "gradient_checkpointing": false,
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": 0,
21
+ "position_embedding_type": "absolute",
22
+ "transformers_version": "4.57.0",
23
+ "type_vocab_size": 2,
24
+ "use_cache": true,
25
+ "vocab_size": 30522
26
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5a591db6049da28c2356ca56b61ffb6ee5bd5a8fe5ce3d4d2f3b3722a81373b7
3
+ size 438197096
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate>=0.28.0
2
+ datasets>=2.14.0
3
+ evaluate>=0.4.0
4
+ huggingface-hub>=0.20.0
5
+ numpy
6
+ safetensors
7
+ scikit-learn
8
+ spikingjelly
9
+ torch
10
+ tqdm
11
+ transformers>=4.57.0
scripts/finetune_glue.py ADDED
@@ -0,0 +1,689 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # 添加从预训练checkpoint加载的功能
3
+
4
+ import argparse
5
+ import json
6
+ import logging
7
+ import math
8
+ import os
9
+ import random
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14
+
15
+ import datasets
16
+ import evaluate
17
+ import torch
18
+ from accelerate import Accelerator
19
+ from accelerate.logging import get_logger
20
+ from accelerate.utils import set_seed
21
+ from datasets import load_dataset
22
+ from huggingface_hub import HfApi
23
+ from torch.utils.data import DataLoader
24
+ from tqdm.auto import tqdm
25
+ from safetensors.torch import load_file # 添加这个导入
26
+
27
+ import transformers
28
+ from transformers import (
29
+ AutoConfig,
30
+ AutoModelForSequenceClassification,
31
+ AutoTokenizer,
32
+ DataCollatorWithPadding,
33
+ PretrainedConfig,
34
+ SchedulerType,
35
+ default_data_collator,
36
+ get_scheduler,
37
+ )
38
+ from transformers.utils import check_min_version
39
+
40
+ from spikingjelly.activation_based import functional
41
+ check_min_version("4.57.0")
42
+ logger = get_logger(__name__)
43
+
44
+ task_to_keys = {
45
+ "cola": ("sentence", None),
46
+ "mnli": ("premise", "hypothesis"),
47
+ "mrpc": ("sentence1", "sentence2"),
48
+ "qnli": ("question", "sentence"),
49
+ "qqp": ("question1", "question2"),
50
+ "rte": ("sentence1", "sentence2"),
51
+ "sst2": ("sentence", None),
52
+ "stsb": ("sentence1", "sentence2"),
53
+ "wnli": ("sentence1", "sentence2"),
54
+ }
55
+
56
+
57
+ def parse_args():
58
+ parser = argparse.ArgumentParser(description="Finetune a transformers model on a text classification task")
59
+ parser.add_argument(
60
+ "--task_name",
61
+ type=str,
62
+ default=None,
63
+ help="The name of the glue task to train on.",
64
+ choices=list(task_to_keys.keys()),
65
+ )
66
+ parser.add_argument(
67
+ "--train_file", type=str, default=None, help="A csv or a json file containing the training data."
68
+ )
69
+ parser.add_argument(
70
+ "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
71
+ )
72
+ parser.add_argument(
73
+ "--max_length",
74
+ type=int,
75
+ default=128,
76
+ help="The maximum total input sequence length after tokenization.",
77
+ )
78
+ parser.add_argument(
79
+ "--pad_to_max_length",
80
+ action="store_true",
81
+ help="If passed, pad all samples to `max_length`. Otherwise, dynamic padding is used.",
82
+ )
83
+ parser.add_argument(
84
+ "--model_name_or_path",
85
+ type=str,
86
+ help="Path to pretrained model or model identifier from huggingface.co/models.",
87
+ required=True,
88
+ )
89
+ parser.add_argument(
90
+ "--pretrained_checkpoint",
91
+ type=str,
92
+ default=None,
93
+ help="Path to pretrained checkpoint directory containing model.safetensors (e.g., step_10000)",
94
+ )
95
+ parser.add_argument(
96
+ "--dataset_cache_dir",
97
+ type=str,
98
+ default=None,
99
+ help="Optional Hugging Face datasets cache directory.",
100
+ )
101
+ parser.add_argument(
102
+ "--use_slow_tokenizer",
103
+ action="store_true",
104
+ help="If passed, will use a slow tokenizer.",
105
+ )
106
+ parser.add_argument(
107
+ "--per_device_train_batch_size",
108
+ type=int,
109
+ default=8,
110
+ help="Batch size (per device) for the training dataloader.",
111
+ )
112
+ parser.add_argument(
113
+ "--per_device_eval_batch_size",
114
+ type=int,
115
+ default=8,
116
+ help="Batch size (per device) for the evaluation dataloader.",
117
+ )
118
+ parser.add_argument(
119
+ "--learning_rate",
120
+ type=float,
121
+ default=5e-5,
122
+ help="Initial learning rate to use.",
123
+ )
124
+ parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
125
+ parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
126
+ parser.add_argument(
127
+ "--max_train_steps",
128
+ type=int,
129
+ default=None,
130
+ help="Total number of training steps to perform.",
131
+ )
132
+ parser.add_argument(
133
+ "--gradient_accumulation_steps",
134
+ type=int,
135
+ default=1,
136
+ help="Number of updates steps to accumulate before performing a backward/update pass.",
137
+ )
138
+ parser.add_argument(
139
+ "--lr_scheduler_type",
140
+ type=SchedulerType,
141
+ default="linear",
142
+ help="The scheduler type to use.",
143
+ choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
144
+ )
145
+ parser.add_argument(
146
+ "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
147
+ )
148
+ parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
149
+ parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
150
+ parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
151
+ parser.add_argument(
152
+ "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
153
+ )
154
+ parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
155
+ parser.add_argument(
156
+ "--trust_remote_code",
157
+ type=bool,
158
+ default=False,
159
+ help="Whether or not to allow for custom models defined on the Hub.",
160
+ )
161
+ parser.add_argument(
162
+ "--checkpointing_steps",
163
+ type=str,
164
+ default=None,
165
+ help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
166
+ )
167
+ parser.add_argument(
168
+ "--resume_from_checkpoint",
169
+ type=str,
170
+ default=None,
171
+ help="If the training should continue from a checkpoint folder.",
172
+ )
173
+ parser.add_argument(
174
+ "--with_tracking",
175
+ action="store_true",
176
+ help="Whether to enable experiment trackers for logging.",
177
+ )
178
+ parser.add_argument(
179
+ "--report_to",
180
+ type=str,
181
+ default="all",
182
+ help='The integration to report the results and logs to.',
183
+ )
184
+ parser.add_argument(
185
+ "--ignore_mismatched_sizes",
186
+ action="store_true",
187
+ help="Whether or not to enable to load a pretrained model whose head dimensions are different.",
188
+ )
189
+ parser.add_argument(
190
+ "--T",
191
+ type=int,
192
+ default=4,
193
+ )
194
+ args = parser.parse_args()
195
+
196
+ # Sanity checks
197
+ if args.task_name is None and args.train_file is None and args.validation_file is None:
198
+ raise ValueError("Need either a task name or a training/validation file.")
199
+ else:
200
+ if args.train_file is not None:
201
+ extension = args.train_file.split(".")[-1]
202
+ assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
203
+ if args.validation_file is not None:
204
+ extension = args.validation_file.split(".")[-1]
205
+ assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
206
+
207
+ if args.push_to_hub:
208
+ assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
209
+
210
+ return args
211
+
212
+
213
+ def load_model_from_checkpoint(checkpoint_path, config, num_labels):
214
+ """
215
+ 从包含model.safetensors的checkpoint目录加载模型
216
+
217
+ Args:
218
+ checkpoint_path: checkpoint目录路径(如 step_10000)
219
+ config: 模型配置
220
+ num_labels: 分类任务的标签数量
221
+
222
+ Returns:
223
+ 加载了预训练权重的模型
224
+ """
225
+ from spiking_bert.modeling_spiking_bert import BertForSequenceClassification
226
+
227
+ # 检查safetensors文件是否存在
228
+ safetensors_path = os.path.join(checkpoint_path, "model.safetensors")
229
+ if not os.path.exists(safetensors_path):
230
+ raise FileNotFoundError(f"Cannot find model.safetensors in {checkpoint_path}")
231
+
232
+ logger.info(f"Loading pretrained weights from {safetensors_path}")
233
+
234
+ # 修改config以适应分类任务
235
+ config.num_labels = num_labels
236
+
237
+ # 创建分类模型(会初始化新的分类头)
238
+ model = BertForSequenceClassification(config)
239
+
240
+ # 加载预训练的权重
241
+ pretrained_state_dict = load_file(safetensors_path)
242
+
243
+ # 获取当前模型的state_dict
244
+ model_state_dict = model.state_dict()
245
+
246
+ # 只加载匹配的权重(跳过分类头)
247
+ matched_keys = []
248
+ mismatched_keys = []
249
+
250
+ for key in pretrained_state_dict.keys():
251
+ if key in model_state_dict:
252
+ if pretrained_state_dict[key].shape == model_state_dict[key].shape:
253
+ model_state_dict[key] = pretrained_state_dict[key]
254
+ matched_keys.append(key)
255
+ else:
256
+ mismatched_keys.append(key)
257
+ logger.warning(f"Shape mismatch for {key}: pretrained {pretrained_state_dict[key].shape} vs model {model_state_dict[key].shape}")
258
+ else:
259
+ logger.info(f"Key {key} not found in model, skipping...")
260
+
261
+ # 加载权重
262
+ model.load_state_dict(model_state_dict)
263
+
264
+ logger.info(f"Loaded {len(matched_keys)} matching weights from checkpoint")
265
+ logger.info(f"Skipped {len(mismatched_keys)} mismatched weights")
266
+ logger.info(f"Classifier head will be trained from scratch")
267
+
268
+ return model
269
+
270
+
271
+ def main():
272
+ args = parse_args()
273
+
274
+ # Initialize the accelerator
275
+ accelerator = (
276
+ Accelerator(log_with=args.report_to, project_dir=args.output_dir) if args.with_tracking else Accelerator()
277
+ )
278
+
279
+ # Make one log on every process with the configuration for debugging.
280
+ logging.basicConfig(
281
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
282
+ datefmt="%m/%d/%Y %H:%M:%S",
283
+ level=logging.INFO,
284
+ )
285
+ logger.info(accelerator.state, main_process_only=False)
286
+ if accelerator.is_local_main_process:
287
+ datasets.utils.logging.set_verbosity_warning()
288
+ transformers.utils.logging.set_verbosity_info()
289
+ else:
290
+ datasets.utils.logging.set_verbosity_error()
291
+ transformers.utils.logging.set_verbosity_error()
292
+
293
+ # Set seed
294
+ if args.seed is not None:
295
+ set_seed(args.seed)
296
+
297
+ # Handle the repository creation
298
+ if accelerator.is_main_process:
299
+ if args.push_to_hub:
300
+ repo_name = args.hub_model_id
301
+ if repo_name is None:
302
+ repo_name = Path(args.output_dir).absolute().name
303
+ api = HfApi()
304
+ repo_id = api.create_repo(repo_name, exist_ok=True, token=args.hub_token).repo_id
305
+
306
+ with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
307
+ if "step_*" not in gitignore:
308
+ gitignore.write("step_*\n")
309
+ if "epoch_*" not in gitignore:
310
+ gitignore.write("epoch_*\n")
311
+ elif args.output_dir is not None:
312
+ os.makedirs(args.output_dir, exist_ok=True)
313
+ accelerator.wait_for_everyone()
314
+
315
+ # Load datasets
316
+ if args.task_name is not None:
317
+ raw_datasets = load_dataset("nyu-mll/glue", args.task_name, cache_dir=args.dataset_cache_dir)
318
+ else:
319
+ data_files = {}
320
+ if args.train_file is not None:
321
+ data_files["train"] = args.train_file
322
+ if args.validation_file is not None:
323
+ data_files["validation"] = args.validation_file
324
+ extension = (args.train_file if args.train_file is not None else args.validation_file).split(".")[-1]
325
+ raw_datasets = load_dataset(extension, data_files=data_files)
326
+
327
+ # Labels
328
+ if args.task_name is not None:
329
+ is_regression = args.task_name == "stsb"
330
+ if not is_regression:
331
+ label_list = raw_datasets["train"].features["label"].names
332
+ num_labels = len(label_list)
333
+ else:
334
+ num_labels = 1
335
+ else:
336
+ is_regression = raw_datasets["train"].features["label"].dtype in ["float32", "float64"]
337
+ if is_regression:
338
+ num_labels = 1
339
+ else:
340
+ label_list = raw_datasets["train"].unique("label")
341
+ label_list.sort()
342
+ num_labels = len(label_list)
343
+
344
+ # Load config and tokenizer
345
+ config = AutoConfig.from_pretrained(
346
+ args.model_name_or_path,
347
+ num_labels=num_labels,
348
+ finetuning_task=args.task_name,
349
+ trust_remote_code=args.trust_remote_code,
350
+ )
351
+ tokenizer = AutoTokenizer.from_pretrained(
352
+ args.model_name_or_path, use_fast=not args.use_slow_tokenizer, trust_remote_code=args.trust_remote_code
353
+ )
354
+ if tokenizer.pad_token is None:
355
+ tokenizer.pad_token = tokenizer.eos_token
356
+ config.pad_token_id = tokenizer.pad_token_id
357
+ config.T = args.T
358
+ config._attn_implementation = 'eager'
359
+
360
+ if args.pretrained_checkpoint is not None:
361
+ logger.info(f"Loading model from pretrained checkpoint: {args.pretrained_checkpoint}")
362
+ model = load_model_from_checkpoint(args.pretrained_checkpoint, config, num_labels)
363
+ else:
364
+ logger.info(f"Loading model from: {args.model_name_or_path}")
365
+ model = AutoModelForSequenceClassification.from_pretrained(
366
+ args.model_name_or_path,
367
+ from_tf=bool(".ckpt" in args.model_name_or_path),
368
+ config=config,
369
+ ignore_mismatched_sizes=args.ignore_mismatched_sizes,
370
+ trust_remote_code=args.trust_remote_code,
371
+ )
372
+
373
+ logger.info(model)
374
+
375
+ # Preprocessing the datasets
376
+ if args.task_name is not None:
377
+ sentence1_key, sentence2_key = task_to_keys[args.task_name]
378
+ else:
379
+ non_label_column_names = [name for name in raw_datasets["train"].column_names if name != "label"]
380
+ if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names:
381
+ sentence1_key, sentence2_key = "sentence1", "sentence2"
382
+ else:
383
+ if len(non_label_column_names) >= 2:
384
+ sentence1_key, sentence2_key = non_label_column_names[:2]
385
+ else:
386
+ sentence1_key, sentence2_key = non_label_column_names[0], None
387
+
388
+ # Label mapping
389
+ label_to_id = None
390
+ if (
391
+ model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id
392
+ and args.task_name is not None
393
+ and not is_regression
394
+ ):
395
+ label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()}
396
+ if sorted(label_name_to_id.keys()) == sorted(label_list):
397
+ logger.info(f"Using label correspondence: {label_name_to_id}")
398
+ label_to_id = {i: label_name_to_id[label_list[i]] for i in range(num_labels)}
399
+ else:
400
+ logger.warning("Model labels don't match dataset labels, ignoring model labels.")
401
+ elif args.task_name is None and not is_regression:
402
+ label_to_id = {v: i for i, v in enumerate(label_list)}
403
+
404
+ if label_to_id is not None:
405
+ model.config.label2id = label_to_id
406
+ model.config.id2label = {id: label for label, id in config.label2id.items()}
407
+ elif args.task_name is not None and not is_regression:
408
+ model.config.label2id = {l: i for i, l in enumerate(label_list)}
409
+ model.config.id2label = {id: label for label, id in config.label2id.items()}
410
+
411
+ padding = "max_length" if args.pad_to_max_length else False
412
+
413
+ def preprocess_function(examples):
414
+ texts = (
415
+ (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key])
416
+ )
417
+ result = tokenizer(*texts, padding=padding, max_length=args.max_length, truncation=True)
418
+
419
+ if "label" in examples:
420
+ if label_to_id is not None:
421
+ result["labels"] = [label_to_id[l] for l in examples["label"]]
422
+ else:
423
+ result["labels"] = examples["label"]
424
+ return result
425
+
426
+ with accelerator.main_process_first():
427
+ processed_datasets = raw_datasets.map(
428
+ preprocess_function,
429
+ batched=True,
430
+ remove_columns=raw_datasets["train"].column_names,
431
+ desc="Running tokenizer on dataset",
432
+ )
433
+
434
+ train_dataset = processed_datasets["train"]
435
+ eval_dataset = processed_datasets["validation_matched" if args.task_name == "mnli" else "validation"]
436
+
437
+ # Log a few random samples
438
+ for index in random.sample(range(len(train_dataset)), 3):
439
+ logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
440
+
441
+ # DataLoaders creation
442
+ if args.pad_to_max_length:
443
+ data_collator = default_data_collator
444
+ else:
445
+ if accelerator.mixed_precision == "fp8":
446
+ pad_to_multiple_of = 16
447
+ elif accelerator.mixed_precision != "no":
448
+ pad_to_multiple_of = 8
449
+ else:
450
+ pad_to_multiple_of = None
451
+ data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=pad_to_multiple_of)
452
+
453
+ train_dataloader = DataLoader(
454
+ train_dataset, shuffle=True, collate_fn=data_collator, batch_size=args.per_device_train_batch_size
455
+ )
456
+ eval_dataloader = DataLoader(eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size)
457
+
458
+ # Optimizer
459
+ no_decay = ["bias", "LayerNorm.weight"]
460
+ optimizer_grouped_parameters = [
461
+ {
462
+ "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
463
+ "weight_decay": args.weight_decay,
464
+ },
465
+ {
466
+ "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
467
+ "weight_decay": 0.0,
468
+ },
469
+ ]
470
+ optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
471
+
472
+ # Scheduler
473
+ overrode_max_train_steps = False
474
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
475
+ if args.max_train_steps is None:
476
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
477
+ overrode_max_train_steps = True
478
+
479
+ lr_scheduler = get_scheduler(
480
+ name=args.lr_scheduler_type,
481
+ optimizer=optimizer,
482
+ num_warmup_steps=args.num_warmup_steps,
483
+ num_training_steps=args.max_train_steps,
484
+ )
485
+
486
+ # Prepare with accelerator
487
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
488
+ model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
489
+ )
490
+
491
+ # Recalculate training steps
492
+ num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
493
+ if overrode_max_train_steps:
494
+ args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
495
+ args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
496
+
497
+ checkpointing_steps = args.checkpointing_steps
498
+ if checkpointing_steps is not None and checkpointing_steps.isdigit():
499
+ checkpointing_steps = int(checkpointing_steps)
500
+
501
+ # Initialize trackers
502
+ if args.with_tracking:
503
+ experiment_config = vars(args)
504
+ experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
505
+ accelerator.init_trackers("glue_no_trainer", experiment_config)
506
+ # Get metric
507
+ if args.task_name is not None:
508
+ metric = evaluate.load("glue", args.task_name)
509
+ else:
510
+ metric = evaluate.load("accuracy")
511
+
512
+ # Train!
513
+ total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
514
+
515
+ logger.info("***** Running training *****")
516
+ logger.info(f" Num examples = {len(train_dataset)}")
517
+ logger.info(f" Num Epochs = {args.num_train_epochs}")
518
+ logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
519
+ logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
520
+ logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
521
+ logger.info(f" Total optimization steps = {args.max_train_steps}")
522
+
523
+ progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
524
+ completed_steps = 0
525
+ starting_epoch = 0
526
+
527
+ # Resume from checkpoint if specified
528
+ if args.resume_from_checkpoint:
529
+ if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
530
+ checkpoint_path = args.resume_from_checkpoint
531
+ path = os.path.basename(args.resume_from_checkpoint)
532
+ else:
533
+ dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
534
+ dirs.sort(key=os.path.getctime)
535
+ path = dirs[-1]
536
+ checkpoint_path = path
537
+ path = os.path.basename(checkpoint_path)
538
+
539
+ accelerator.print(f"Resumed from checkpoint: {checkpoint_path}")
540
+ accelerator.load_state(checkpoint_path)
541
+ training_difference = os.path.splitext(path)[0]
542
+
543
+ if "epoch" in training_difference:
544
+ starting_epoch = int(training_difference.replace("epoch_", "")) + 1
545
+ resume_step = None
546
+ completed_steps = starting_epoch * num_update_steps_per_epoch
547
+ else:
548
+ resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps
549
+ starting_epoch = resume_step // len(train_dataloader)
550
+ completed_steps = resume_step // args.gradient_accumulation_steps
551
+ resume_step -= starting_epoch * len(train_dataloader)
552
+
553
+ progress_bar.update(completed_steps)
554
+
555
+ for epoch in range(starting_epoch, args.num_train_epochs):
556
+ model.train()
557
+ if args.with_tracking:
558
+ total_loss = 0
559
+ if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
560
+ active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
561
+ else:
562
+ active_dataloader = train_dataloader
563
+
564
+ for step, batch in enumerate(active_dataloader):
565
+ outputs = model(**batch)
566
+ loss = outputs.loss
567
+ if args.with_tracking:
568
+ total_loss += loss.detach().float()
569
+ loss = loss / args.gradient_accumulation_steps
570
+ accelerator.backward(loss)
571
+ if step % args.gradient_accumulation_steps == 0 or step == len(train_dataloader) - 1:
572
+ optimizer.step()
573
+ lr_scheduler.step()
574
+ optimizer.zero_grad()
575
+ progress_bar.update(1)
576
+ completed_steps += 1
577
+ functional.reset_net(model)
578
+ if isinstance(checkpointing_steps, int):
579
+ if completed_steps % checkpointing_steps == 0 and accelerator.sync_gradients:
580
+ output_dir = f"step_{completed_steps}"
581
+ if args.output_dir is not None:
582
+ output_dir = os.path.join(args.output_dir, output_dir)
583
+ accelerator.save_state(output_dir)
584
+
585
+ if completed_steps >= args.max_train_steps:
586
+ break
587
+
588
+ model.eval()
589
+ samples_seen = 0
590
+ for step, batch in enumerate(eval_dataloader):
591
+ with torch.no_grad():
592
+ outputs = model(**batch)
593
+ predictions = outputs.logits.argmax(dim=-1) if not is_regression else outputs.logits.squeeze()
594
+ predictions, references = accelerator.gather((predictions, batch["labels"]))
595
+ if accelerator.num_processes > 1:
596
+ if step == len(eval_dataloader) - 1:
597
+ predictions = predictions[: len(eval_dataloader.dataset) - samples_seen]
598
+ references = references[: len(eval_dataloader.dataset) - samples_seen]
599
+ else:
600
+ samples_seen += references.shape[0]
601
+ metric.add_batch(
602
+ predictions=predictions,
603
+ references=references,
604
+ )
605
+ functional.reset_net(model)
606
+
607
+ eval_metric = metric.compute()
608
+ logger.info(f"epoch {epoch}: {eval_metric}")
609
+
610
+ if args.with_tracking:
611
+ accelerator.log(
612
+ {
613
+ "accuracy" if args.task_name is not None else "glue": eval_metric,
614
+ "train_loss": total_loss.item() / len(train_dataloader),
615
+ "epoch": epoch,
616
+ "step": completed_steps,
617
+ },
618
+ step=completed_steps,
619
+ )
620
+
621
+ if args.push_to_hub and epoch < args.num_train_epochs - 1:
622
+ accelerator.wait_for_everyone()
623
+ unwrapped_model = accelerator.unwrap_model(model)
624
+ unwrapped_model.save_pretrained(
625
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
626
+ )
627
+ if accelerator.is_main_process:
628
+ tokenizer.save_pretrained(args.output_dir)
629
+ api.upload_folder(
630
+ commit_message=f"Training in progress epoch {epoch}",
631
+ folder_path=args.output_dir,
632
+ repo_id=repo_id,
633
+ repo_type="model",
634
+ token=args.hub_token,
635
+ )
636
+
637
+ if args.checkpointing_steps == "epoch":
638
+ output_dir = f"epoch_{epoch}"
639
+ if args.output_dir is not None:
640
+ output_dir = os.path.join(args.output_dir, output_dir)
641
+ accelerator.save_state(output_dir)
642
+
643
+ if args.output_dir is not None:
644
+ accelerator.wait_for_everyone()
645
+ unwrapped_model = accelerator.unwrap_model(model)
646
+ unwrapped_model.save_pretrained(
647
+ args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save
648
+ )
649
+ if accelerator.is_main_process:
650
+ tokenizer.save_pretrained(args.output_dir)
651
+ if args.push_to_hub:
652
+ api.upload_folder(
653
+ commit_message="End of training",
654
+ folder_path=args.output_dir,
655
+ repo_id=repo_id,
656
+ repo_type="model",
657
+ token=args.hub_token,
658
+ )
659
+
660
+ if args.task_name == "mnli":
661
+ eval_dataset = processed_datasets["validation_mismatched"]
662
+ eval_dataloader = DataLoader(
663
+ eval_dataset, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
664
+ )
665
+ eval_dataloader = accelerator.prepare(eval_dataloader)
666
+
667
+ model.eval()
668
+ for step, batch in enumerate(eval_dataloader):
669
+ outputs = model(**batch)
670
+ predictions = outputs.logits.argmax(dim=-1)
671
+ metric.add_batch(
672
+ predictions=accelerator.gather(predictions),
673
+ references=accelerator.gather(batch["labels"]),
674
+ )
675
+ functional.reset_net(model)
676
+ eval_metric = metric.compute()
677
+ logger.info(f"mnli-mm: {eval_metric}")
678
+
679
+ if args.output_dir is not None:
680
+ all_results = {f"eval_{k}": v for k, v in eval_metric.items()}
681
+ with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
682
+ json.dump(all_results, f)
683
+
684
+ accelerator.wait_for_everyone()
685
+ accelerator.end_training()
686
+
687
+
688
+ if __name__ == "__main__":
689
+ main()
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
spiking_bert/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .modeling_spiking_bert import (
2
+ BertForMaskedLM,
3
+ BertForSequenceClassification,
4
+ BertModel,
5
+ BertPreTrainedModel,
6
+ )
7
+
8
+ __all__ = [
9
+ "BertForMaskedLM",
10
+ "BertForSequenceClassification",
11
+ "BertModel",
12
+ "BertPreTrainedModel",
13
+ ]
spiking_bert/modeling_spiking_bert.py ADDED
@@ -0,0 +1,1882 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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."""
17
+
18
+ import math
19
+ import os
20
+ import warnings
21
+ from dataclasses import dataclass
22
+ from typing import Optional, Union
23
+
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, EncoderDecoderCache
30
+ from transformers.generation import GenerationMixin
31
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
32
+ from transformers.modeling_layers import GradientCheckpointingLayer
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPastAndCrossAttentions,
35
+ BaseModelOutputWithPoolingAndCrossAttentions,
36
+ CausalLMOutputWithCrossAttentions,
37
+ MaskedLMOutput,
38
+ MultipleChoiceModelOutput,
39
+ NextSentencePredictorOutput,
40
+ QuestionAnsweringModelOutput,
41
+ SequenceClassifierOutput,
42
+ TokenClassifierOutput,
43
+ )
44
+ from transformers.modeling_utils import PreTrainedModel
45
+ from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
46
+ from transformers.utils import ModelOutput, auto_docstring, logging
47
+ from transformers.utils.deprecation import deprecate_kwarg
48
+ from transformers.models.bert.configuration_bert import BertConfig
49
+ from spikingjelly.activation_based import neuron
50
+
51
+
52
+ logger = logging.get_logger(__name__)
53
+
54
+
55
+ def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
56
+ """Load tf checkpoints in a pytorch model."""
57
+ try:
58
+ import re
59
+
60
+ import numpy as np
61
+ import tensorflow as tf
62
+ except ImportError:
63
+ logger.error(
64
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
65
+ "https://www.tensorflow.org/install/ for installation instructions."
66
+ )
67
+ raise
68
+ tf_path = os.path.abspath(tf_checkpoint_path)
69
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
70
+ # Load weights from TF model
71
+ init_vars = tf.train.list_variables(tf_path)
72
+ names = []
73
+ arrays = []
74
+ for name, shape in init_vars:
75
+ logger.info(f"Loading TF weight {name} with shape {shape}")
76
+ array = tf.train.load_variable(tf_path, name)
77
+ names.append(name)
78
+ arrays.append(array)
79
+
80
+ for name, array in zip(names, arrays):
81
+ name = name.split("/")
82
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
83
+ # which are not required for using pretrained model
84
+ if any(
85
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
86
+ for n in name
87
+ ):
88
+ logger.info(f"Skipping {'/'.join(name)}")
89
+ continue
90
+ pointer = model
91
+ for m_name in name:
92
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
93
+ scope_names = re.split(r"_(\d+)", m_name)
94
+ else:
95
+ scope_names = [m_name]
96
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
97
+ pointer = getattr(pointer, "weight")
98
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
99
+ pointer = getattr(pointer, "bias")
100
+ elif scope_names[0] == "output_weights":
101
+ pointer = getattr(pointer, "weight")
102
+ elif scope_names[0] == "squad":
103
+ pointer = getattr(pointer, "classifier")
104
+ else:
105
+ try:
106
+ pointer = getattr(pointer, scope_names[0])
107
+ except AttributeError:
108
+ logger.info(f"Skipping {'/'.join(name)}")
109
+ continue
110
+ if len(scope_names) >= 2:
111
+ num = int(scope_names[1])
112
+ pointer = pointer[num]
113
+ if m_name[-11:] == "_embeddings":
114
+ pointer = getattr(pointer, "weight")
115
+ elif m_name == "kernel":
116
+ array = np.transpose(array)
117
+ try:
118
+ if pointer.shape != array.shape:
119
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
120
+ except ValueError as e:
121
+ e.args += (pointer.shape, array.shape)
122
+ raise
123
+ logger.info(f"Initialize PyTorch weight {name}")
124
+ pointer.data = torch.from_numpy(array)
125
+ return model
126
+
127
+
128
+ class BertEmbeddings(nn.Module):
129
+ """Construct the embeddings from word, position and token_type embeddings."""
130
+
131
+ def __init__(self, config):
132
+ super().__init__()
133
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
134
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
135
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
136
+
137
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
138
+ # any TensorFlow checkpoint file
139
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
140
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
141
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
142
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
143
+ self.register_buffer(
144
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
145
+ )
146
+ self.register_buffer(
147
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
148
+ )
149
+
150
+ def forward(
151
+ self,
152
+ input_ids: Optional[torch.LongTensor] = None,
153
+ token_type_ids: Optional[torch.LongTensor] = None,
154
+ position_ids: Optional[torch.LongTensor] = None,
155
+ inputs_embeds: Optional[torch.FloatTensor] = None,
156
+ past_key_values_length: int = 0,
157
+ ) -> torch.Tensor:
158
+ if input_ids is not None:
159
+ input_shape = input_ids.size()
160
+ else:
161
+ input_shape = inputs_embeds.size()[:-1]
162
+
163
+ seq_length = input_shape[1]
164
+
165
+ if position_ids is None:
166
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
167
+
168
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
169
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
170
+ # issue #5664
171
+ if token_type_ids is None:
172
+ if hasattr(self, "token_type_ids"):
173
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
174
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
175
+ token_type_ids = buffered_token_type_ids_expanded
176
+ else:
177
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
178
+
179
+ if inputs_embeds is None:
180
+ inputs_embeds = self.word_embeddings(input_ids)
181
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
182
+
183
+ embeddings = inputs_embeds + token_type_embeddings
184
+ if self.position_embedding_type == "absolute":
185
+ position_embeddings = self.position_embeddings(position_ids)
186
+ embeddings += position_embeddings
187
+ embeddings = self.LayerNorm(embeddings)
188
+ embeddings = self.dropout(embeddings)
189
+ return embeddings
190
+
191
+ class FP16OptimizedExp2Softmax(nn.Module):
192
+ def __init__(self, T, init_value=1.0):
193
+ """
194
+ Args:
195
+ T: Temporal dimension size
196
+ head_size: Number of attention heads
197
+ init_value: Initial value for scale parameter
198
+ """
199
+ super().__init__()
200
+ # 注册为可学习参数,维度 [T, head_size]
201
+ self.scale = nn.Parameter(torch.full((T,), init_value))
202
+
203
+ def forward(self, tensor, k=1.0):
204
+ """
205
+ Args:
206
+ tensor: Input tensor of shape [T, B, head_size, seq_len, seq_len]
207
+ k: Temperature parameter
208
+ Returns:
209
+ Scaled softmax output
210
+ """
211
+ tensor = tensor - tensor.max(dim=-1, keepdim=True)[0] - 1
212
+ tensor.clamp_(min=-30.0, max=30.0)
213
+ tensor = torch.exp2(tensor)
214
+ # tensor = tensor / (tensor.sum(dim=-1, keepdim=True) + 1e-6)
215
+
216
+ # scale: [T, head_size] -> [T, 1, head_size, 1, 1] for broadcasting
217
+ scale = self.scale[:, None, None, None, None]
218
+ tensor = tensor * scale
219
+ return tensor
220
+
221
+ class BertSelfAttention(nn.Module):
222
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
223
+ super().__init__()
224
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
225
+ raise ValueError(
226
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
227
+ f"heads ({config.num_attention_heads})"
228
+ )
229
+
230
+ self.num_attention_heads = config.num_attention_heads
231
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
232
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
233
+
234
+ self.proj_lif = neuron.LIFNode(tau=2.0, detach_reset=True, backend='cupy', step_mode='m')
235
+ self.q_lif = neuron.LIFNode(tau=2.0, detach_reset=True, backend='cupy', step_mode='m')
236
+ self.k_lif = neuron.LIFNode(tau=2.0, detach_reset=True, backend='cupy', step_mode='m')
237
+ self.v_lif = neuron.LIFNode(tau=2.0, detach_reset=True, backend='cupy', step_mode='m')
238
+
239
+ self.scale = 0.125
240
+
241
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
242
+ self.q_lam = nn.Parameter(torch.ones(self.all_head_size)*7)
243
+ # self.q_norm = nn.RMSNorm(config.hidden_size)
244
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
245
+ self.k_lam = nn.Parameter(torch.ones(self.all_head_size)*7)
246
+ # self.k_norm = nn.RMSNorm(config.hidden_size)
247
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
248
+ self.v_lam = nn.Parameter(torch.ones(self.all_head_size)*7)
249
+ # self.v_norm = nn.RMSNorm(config.hidden_size)
250
+ self.learnmax = FP16OptimizedExp2Softmax(T=config.T)
251
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
252
+ self.position_embedding_type = position_embedding_type or getattr(
253
+ config, "position_embedding_type", "absolute"
254
+ )
255
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
256
+ self.max_position_embeddings = config.max_position_embeddings
257
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
258
+
259
+ self.is_decoder = config.is_decoder
260
+ self.layer_idx = layer_idx
261
+ # True 时不做 q_lam/k_lam/v_lam 缩放(等价于恒等,便于与启用 lamb 的实验对比)
262
+ self.disable_qkv_lamb = bool(getattr(config, "disable_qkv_lamb", False))
263
+
264
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
265
+ def forward(
266
+ self,
267
+ hidden_states: torch.Tensor,
268
+ attention_mask: Optional[torch.FloatTensor] = None,
269
+ head_mask: Optional[torch.FloatTensor] = None,
270
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
271
+ past_key_values: Optional[Cache] = None,
272
+ output_attentions: Optional[bool] = False,
273
+ cache_position: Optional[torch.Tensor] = None,
274
+ ) -> tuple[torch.Tensor]:
275
+ T, batch_size, seq_length, _ = hidden_states.shape
276
+ hidden_states = self.proj_lif(hidden_states)
277
+ query_layer = self.query(hidden_states)
278
+ # query_layer = self.q_norm(query_layer.reshape(T*batch_size, seq_length, -1)).reshape(T, batch_size, seq_length, -1)
279
+ if not self.disable_qkv_lamb:
280
+ query_layer = self.q_lam * query_layer
281
+ query_layer = self.q_lif(query_layer)
282
+ query_layer = query_layer.view(T, batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
283
+ 2, 3
284
+ )
285
+
286
+ is_updated = False
287
+ is_cross_attention = encoder_hidden_states is not None
288
+ if past_key_values is not None:
289
+ if isinstance(past_key_values, EncoderDecoderCache):
290
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
291
+ if is_cross_attention:
292
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
293
+ curr_past_key_value = past_key_values.cross_attention_cache
294
+ else:
295
+ curr_past_key_value = past_key_values.self_attention_cache
296
+ else:
297
+ curr_past_key_value = past_key_values
298
+
299
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
300
+ if is_cross_attention and past_key_values is not None and is_updated:
301
+ # reuse k,v, cross_attentions
302
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
303
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
304
+ else:
305
+ key_layer = self.key(current_states)
306
+ # key_layer = self.k_norm(key_layer.reshape(T*batch_size, seq_length, -1)).reshape(T, batch_size, seq_length, -1)
307
+ if not self.disable_qkv_lamb:
308
+ key_layer = self.k_lam * key_layer
309
+ key_layer = self.k_lif(key_layer)
310
+ key_layer = key_layer.view(T, batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
311
+ 2, 3
312
+ )
313
+ value_layer = self.value(current_states)
314
+ # value_layer = self.v_norm(value_layer.reshape(T*batch_size, seq_length, -1)).reshape(T, batch_size, seq_length, -1)
315
+ if not self.disable_qkv_lamb:
316
+ value_layer = self.v_lam * value_layer
317
+ value_layer = self.v_lif(value_layer)
318
+ value_layer = value_layer.view(
319
+ T, batch_size, -1, self.num_attention_heads, self.attention_head_size
320
+ ).transpose(2, 3)
321
+
322
+ if past_key_values is not None:
323
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
324
+ cache_position = cache_position if not is_cross_attention else None
325
+ key_layer, value_layer = curr_past_key_value.update(
326
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
327
+ )
328
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
329
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
330
+ past_key_values.is_updated[self.layer_idx] = True
331
+
332
+ # Take the dot product between "query" and "key" to get the raw attention scores.
333
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
334
+
335
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
336
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
337
+ if past_key_values is not None:
338
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
339
+ -1, 1
340
+ )
341
+ else:
342
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
343
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
344
+ distance = position_ids_l - position_ids_r
345
+
346
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
347
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
348
+
349
+ if self.position_embedding_type == "relative_key":
350
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
351
+ attention_scores = attention_scores + relative_position_scores.unsqueeze(0)
352
+ elif self.position_embedding_type == "relative_key_query":
353
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
354
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
355
+ attention_scores = attention_scores + relative_position_scores_query.unsqueeze(0) + relative_position_scores_key.unsqueeze(0)
356
+
357
+ # attention_scores = attention_scores / math.sqrt(self.attention_head_size)
358
+ # print(attention_mask)
359
+ if attention_mask is not None:
360
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
361
+ attention_scores = attention_scores + attention_mask
362
+
363
+ # # # Normalize the attention scores to probabilities.
364
+ attention_probs = self.learnmax(attention_scores)
365
+ # attention_probs = nn.functional.softmax(attention_scores, dim=-1)
366
+
367
+ # # This is actually dropping out entire tokens to attend to, which might
368
+ # # seem a bit unusual, but is taken from the original Transformer paper.
369
+ # attention_probs = self.dropout(attention_probs)
370
+ # if attention_mask is not None:
371
+ # attention_scores = attention_scores * attention_mask.unsqueeze(0)
372
+
373
+ # attention_probs = attention_scores * self.scale
374
+
375
+ # Mask heads if we want to
376
+ # if head_mask is not None:
377
+ # attention_probs = attention_probs * head_mask
378
+
379
+ context_layer = torch.matmul(attention_probs, value_layer) # t,b,h,l,d -> t,b,l,h,d
380
+
381
+ context_layer = context_layer.permute(0, 1, 3, 2, 4).contiguous()
382
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
383
+ context_layer = context_layer.view(new_context_layer_shape)
384
+
385
+ return context_layer, attention_probs
386
+
387
+
388
+ class BertSdpaSelfAttention(BertSelfAttention):
389
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
390
+ super().__init__(config, position_embedding_type=position_embedding_type, layer_idx=layer_idx)
391
+ self.dropout_prob = config.attention_probs_dropout_prob
392
+
393
+ # Adapted from BertSelfAttention
394
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
395
+ def forward(
396
+ self,
397
+ hidden_states: torch.Tensor,
398
+ attention_mask: Optional[torch.Tensor] = None,
399
+ head_mask: Optional[torch.FloatTensor] = None,
400
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
401
+ past_key_values: Optional[Cache] = None,
402
+ output_attentions: Optional[bool] = False,
403
+ cache_position: Optional[torch.Tensor] = None,
404
+ ) -> tuple[torch.Tensor]:
405
+ if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
406
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
407
+ logger.warning_once(
408
+ "BertSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
409
+ "non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
410
+ "the manual attention implementation, but specifying the manual implementation will be required from "
411
+ "Transformers version v5.0.0 onwards. This warning can be removed using the argument "
412
+ '`attn_implementation="eager"` when loading the model.'
413
+ )
414
+ return super().forward(
415
+ hidden_states,
416
+ attention_mask,
417
+ head_mask,
418
+ encoder_hidden_states,
419
+ past_key_values,
420
+ output_attentions,
421
+ cache_position,
422
+ )
423
+
424
+ T, bsz, tgt_len, _ = hidden_states.size()
425
+
426
+ query_layer = (
427
+ self.query(hidden_states).view(bsz, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
428
+ )
429
+
430
+ is_updated = False
431
+ is_cross_attention = encoder_hidden_states is not None
432
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
433
+ if past_key_values is not None:
434
+ if isinstance(past_key_values, EncoderDecoderCache):
435
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
436
+ if is_cross_attention:
437
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
438
+ curr_past_key_value = past_key_values.cross_attention_cache
439
+ else:
440
+ curr_past_key_value = past_key_values.self_attention_cache
441
+ else:
442
+ curr_past_key_value = past_key_values
443
+
444
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
445
+ if is_cross_attention and past_key_values is not None and is_updated:
446
+ # reuse k,v, cross_attentions
447
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
448
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
449
+ else:
450
+ key_layer = (
451
+ self.key(current_states)
452
+ .view(bsz, -1, self.num_attention_heads, self.attention_head_size)
453
+ .transpose(1, 2)
454
+ )
455
+ value_layer = (
456
+ self.value(current_states)
457
+ .view(bsz, -1, self.num_attention_heads, self.attention_head_size)
458
+ .transpose(1, 2)
459
+ )
460
+
461
+ if past_key_values is not None:
462
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
463
+ cache_position = cache_position if not is_cross_attention else None
464
+ key_layer, value_layer = curr_past_key_value.update(
465
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
466
+ )
467
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
468
+ if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
469
+ past_key_values.is_updated[self.layer_idx] = True
470
+
471
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
472
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
473
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
474
+ # a causal mask in case tgt_len == 1.
475
+ is_causal = self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1
476
+
477
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
478
+ query_layer,
479
+ key_layer,
480
+ value_layer,
481
+ attn_mask=attention_mask,
482
+ dropout_p=self.dropout_prob if self.training else 0.0,
483
+ is_causal=is_causal,
484
+ )
485
+
486
+ attn_output = attn_output.transpose(1, 2)
487
+ attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
488
+
489
+ return attn_output, None
490
+
491
+
492
+ class BertSelfOutput(nn.Module):
493
+ def __init__(self, config):
494
+ super().__init__()
495
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
496
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
497
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
498
+
499
+ self.attn_lif = neuron.LIFNode(tau=2.0, v_threshold=0.5, detach_reset=True, backend='cupy', step_mode='m')
500
+
501
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
502
+ hidden_states = self.attn_lif(hidden_states)
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
+ BERT_SELF_ATTENTION_CLASSES = {
510
+ "eager": BertSelfAttention,
511
+ "sdpa": BertSdpaSelfAttention,
512
+ }
513
+
514
+
515
+ class BertAttention(nn.Module):
516
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
517
+ super().__init__()
518
+ self.self = BERT_SELF_ATTENTION_CLASSES[config._attn_implementation](
519
+ config,
520
+ position_embedding_type=position_embedding_type,
521
+ layer_idx=layer_idx,
522
+ )
523
+ self.output = BertSelfOutput(config)
524
+ self.pruned_heads = set()
525
+
526
+ def prune_heads(self, heads):
527
+ if len(heads) == 0:
528
+ return
529
+ heads, index = find_pruneable_heads_and_indices(
530
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
531
+ )
532
+
533
+ # Prune linear layers
534
+ self.self.query = prune_linear_layer(self.self.query, index)
535
+ self.self.key = prune_linear_layer(self.self.key, index)
536
+ self.self.value = prune_linear_layer(self.self.value, index)
537
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
538
+
539
+ # Update hyper params and store pruned heads
540
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
541
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
542
+ self.pruned_heads = self.pruned_heads.union(heads)
543
+
544
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
545
+ def forward(
546
+ self,
547
+ hidden_states: torch.Tensor,
548
+ attention_mask: Optional[torch.FloatTensor] = None,
549
+ head_mask: Optional[torch.FloatTensor] = None,
550
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
551
+ past_key_values: Optional[Cache] = None,
552
+ output_attentions: Optional[bool] = False,
553
+ cache_position: Optional[torch.Tensor] = None,
554
+ ) -> tuple[torch.Tensor]:
555
+ self_outputs = self.self(
556
+ hidden_states,
557
+ attention_mask=attention_mask,
558
+ head_mask=head_mask,
559
+ encoder_hidden_states=encoder_hidden_states,
560
+ past_key_values=past_key_values,
561
+ output_attentions=output_attentions,
562
+ cache_position=cache_position,
563
+ )
564
+ attention_output = self.output(self_outputs[0], hidden_states)
565
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
566
+ return outputs
567
+
568
+
569
+ class BertIntermediate(nn.Module):
570
+ def __init__(self, config):
571
+ super().__init__()
572
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
573
+ if isinstance(config.hidden_act, str):
574
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
575
+ else:
576
+ self.intermediate_act_fn = config.hidden_act
577
+
578
+ self.mlp1_lif = neuron.LIFNode(tau=2.0, detach_reset=True, backend='cupy', step_mode='m')
579
+
580
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
581
+ hidden_states = self.mlp1_lif(hidden_states)
582
+ hidden_states = self.dense(hidden_states)
583
+ # hidden_states = self.intermediate_act_fn(hidden_states)
584
+ return hidden_states
585
+
586
+
587
+ class BertOutput(nn.Module):
588
+ def __init__(self, config):
589
+ super().__init__()
590
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
591
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
592
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
593
+
594
+ self.mlp2_lif = neuron.LIFNode(tau=2.0, detach_reset=True, backend='cupy', step_mode='m')
595
+
596
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
597
+ hidden_states = self.mlp2_lif(hidden_states)
598
+ hidden_states = self.dense(hidden_states)
599
+ hidden_states = self.dropout(hidden_states)
600
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
601
+ return hidden_states
602
+
603
+
604
+ class BertLayer(GradientCheckpointingLayer):
605
+ def __init__(self, config, layer_idx=None):
606
+ super().__init__()
607
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
608
+ self.seq_len_dim = 1
609
+ self.attention = BertAttention(config, layer_idx=layer_idx)
610
+ self.is_decoder = config.is_decoder
611
+ self.add_cross_attention = config.add_cross_attention
612
+ if self.add_cross_attention:
613
+ if not self.is_decoder:
614
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
615
+ self.crossattention = BertAttention(config, position_embedding_type="absolute", layer_idx=layer_idx)
616
+ self.intermediate = BertIntermediate(config)
617
+ self.output = BertOutput(config)
618
+
619
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
620
+ def forward(
621
+ self,
622
+ hidden_states: torch.Tensor,
623
+ attention_mask: Optional[torch.FloatTensor] = None,
624
+ head_mask: Optional[torch.FloatTensor] = None,
625
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
626
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
627
+ past_key_values: Optional[Cache] = None,
628
+ output_attentions: Optional[bool] = False,
629
+ cache_position: Optional[torch.Tensor] = None,
630
+ ) -> tuple[torch.Tensor]:
631
+ self_attention_outputs = self.attention(
632
+ hidden_states,
633
+ attention_mask=attention_mask,
634
+ head_mask=head_mask,
635
+ output_attentions=output_attentions,
636
+ past_key_values=past_key_values,
637
+ cache_position=cache_position,
638
+ )
639
+ attention_output = self_attention_outputs[0]
640
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
641
+
642
+ if self.is_decoder and encoder_hidden_states is not None:
643
+ if not hasattr(self, "crossattention"):
644
+ raise ValueError(
645
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
646
+ " by setting `config.add_cross_attention=True`"
647
+ )
648
+
649
+ cross_attention_outputs = self.crossattention(
650
+ attention_output,
651
+ attention_mask=encoder_attention_mask,
652
+ head_mask=head_mask,
653
+ encoder_hidden_states=encoder_hidden_states,
654
+ past_key_values=past_key_values,
655
+ output_attentions=output_attentions,
656
+ cache_position=cache_position,
657
+ )
658
+ attention_output = cross_attention_outputs[0]
659
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
660
+
661
+ layer_output = apply_chunking_to_forward(
662
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
663
+ )
664
+ outputs = (layer_output,) + outputs
665
+
666
+ return outputs
667
+
668
+ def feed_forward_chunk(self, attention_output):
669
+ intermediate_output = self.intermediate(attention_output)
670
+ layer_output = self.output(intermediate_output, attention_output)
671
+ return layer_output
672
+
673
+
674
+ class BertEncoder(nn.Module):
675
+ def __init__(self, config, layer_idx=None):
676
+ super().__init__()
677
+ self.config = config
678
+ self.layer = nn.ModuleList([BertLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
679
+ self.gradient_checkpointing = False
680
+
681
+ self.T = config.T
682
+
683
+ def forward(
684
+ self,
685
+ hidden_states: torch.Tensor,
686
+ attention_mask: Optional[torch.FloatTensor] = None,
687
+ head_mask: Optional[torch.FloatTensor] = None,
688
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
689
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
690
+ past_key_values: Optional[Cache] = None,
691
+ use_cache: Optional[bool] = None,
692
+ output_attentions: Optional[bool] = False,
693
+ output_hidden_states: Optional[bool] = False,
694
+ return_dict: Optional[bool] = True,
695
+ cache_position: Optional[torch.Tensor] = None,
696
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
697
+ all_hidden_states = () if output_hidden_states else None
698
+ all_self_attentions = () if output_attentions else None
699
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
700
+
701
+ if self.gradient_checkpointing and self.training:
702
+ if use_cache:
703
+ logger.warning_once(
704
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
705
+ )
706
+ use_cache = False
707
+
708
+ if use_cache and self.config.is_decoder and past_key_values is None:
709
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
710
+
711
+ if use_cache and self.config.is_decoder and isinstance(past_key_values, tuple):
712
+ logger.warning_once(
713
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
714
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
715
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
716
+ )
717
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
718
+
719
+ hidden_states = hidden_states.repeat(tuple([self.T] + torch.ones(len(hidden_states.size()), dtype=int).tolist())) # T B L D
720
+
721
+ for i, layer_module in enumerate(self.layer):
722
+ if output_hidden_states:
723
+ all_hidden_states = all_hidden_states + (hidden_states,)
724
+
725
+ layer_head_mask = head_mask[i] if head_mask is not None else None
726
+
727
+ layer_outputs = layer_module(
728
+ hidden_states,
729
+ attention_mask,
730
+ layer_head_mask,
731
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
732
+ encoder_attention_mask=encoder_attention_mask,
733
+ past_key_values=past_key_values,
734
+ output_attentions=output_attentions,
735
+ cache_position=cache_position,
736
+ )
737
+
738
+ hidden_states = layer_outputs[0]
739
+ if output_attentions:
740
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
741
+ if self.config.add_cross_attention:
742
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
743
+
744
+ if output_hidden_states:
745
+ all_hidden_states = all_hidden_states + (hidden_states.mean(0),)
746
+
747
+ hidden_states = hidden_states.mean(0)
748
+
749
+ if not return_dict:
750
+ return tuple(
751
+ v
752
+ for v in [
753
+ hidden_states,
754
+ past_key_values,
755
+ all_hidden_states,
756
+ all_self_attentions,
757
+ all_cross_attentions,
758
+ ]
759
+ if v is not None
760
+ )
761
+ return BaseModelOutputWithPastAndCrossAttentions(
762
+ last_hidden_state=hidden_states,
763
+ past_key_values=past_key_values,
764
+ hidden_states=all_hidden_states,
765
+ attentions=all_self_attentions,
766
+ cross_attentions=all_cross_attentions,
767
+ )
768
+
769
+
770
+ class BertPooler(nn.Module):
771
+ def __init__(self, config):
772
+ super().__init__()
773
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
774
+ self.activation = nn.Tanh()
775
+
776
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
777
+ # We "pool" the model by simply taking the hidden state corresponding
778
+ # to the first token.
779
+ first_token_tensor = hidden_states[:, 0]
780
+ pooled_output = self.dense(first_token_tensor)
781
+ pooled_output = self.activation(pooled_output)
782
+ return pooled_output
783
+
784
+
785
+ class BertPredictionHeadTransform(nn.Module):
786
+ def __init__(self, config):
787
+ super().__init__()
788
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
789
+ if isinstance(config.hidden_act, str):
790
+ self.transform_act_fn = ACT2FN[config.hidden_act]
791
+ else:
792
+ self.transform_act_fn = config.hidden_act
793
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
794
+
795
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
796
+ hidden_states = self.dense(hidden_states)
797
+ hidden_states = self.transform_act_fn(hidden_states)
798
+ hidden_states = self.LayerNorm(hidden_states)
799
+ return hidden_states
800
+
801
+
802
+ class BertLMPredictionHead(nn.Module):
803
+ def __init__(self, config):
804
+ super().__init__()
805
+ self.transform = BertPredictionHeadTransform(config)
806
+
807
+ # The output weights are the same as the input embeddings, but there is
808
+ # an output-only bias for each token.
809
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
810
+
811
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
812
+
813
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
814
+ self.decoder.bias = self.bias
815
+
816
+ def _tie_weights(self):
817
+ self.decoder.bias = self.bias
818
+
819
+ def forward(self, hidden_states):
820
+ hidden_states = self.transform(hidden_states)
821
+ hidden_states = self.decoder(hidden_states)
822
+ return hidden_states
823
+
824
+
825
+ class BertOnlyMLMHead(nn.Module):
826
+ def __init__(self, config):
827
+ super().__init__()
828
+ self.predictions = BertLMPredictionHead(config)
829
+
830
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
831
+ prediction_scores = self.predictions(sequence_output)
832
+ return prediction_scores
833
+
834
+
835
+ class BertOnlyNSPHead(nn.Module):
836
+ def __init__(self, config):
837
+ super().__init__()
838
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
839
+
840
+ def forward(self, pooled_output):
841
+ seq_relationship_score = self.seq_relationship(pooled_output)
842
+ return seq_relationship_score
843
+
844
+
845
+ class BertPreTrainingHeads(nn.Module):
846
+ def __init__(self, config):
847
+ super().__init__()
848
+ self.predictions = BertLMPredictionHead(config)
849
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
850
+
851
+ def forward(self, sequence_output, pooled_output):
852
+ prediction_scores = self.predictions(sequence_output)
853
+ seq_relationship_score = self.seq_relationship(pooled_output)
854
+ return prediction_scores, seq_relationship_score
855
+
856
+
857
+ @auto_docstring
858
+ class BertPreTrainedModel(PreTrainedModel):
859
+ config: BertConfig
860
+ load_tf_weights = load_tf_weights_in_bert
861
+ base_model_prefix = "bert"
862
+ supports_gradient_checkpointing = True
863
+ _supports_sdpa = True
864
+
865
+ def _init_weights(self, module):
866
+ """Initialize the weights"""
867
+ if isinstance(module, nn.Linear):
868
+ # Slightly different from the TF version which uses truncated_normal for initialization
869
+ # cf https://github.com/pytorch/pytorch/pull/5617
870
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
871
+ if module.bias is not None:
872
+ module.bias.data.zero_()
873
+ elif isinstance(module, nn.Embedding):
874
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
875
+ if module.padding_idx is not None:
876
+ module.weight.data[module.padding_idx].zero_()
877
+ elif isinstance(module, nn.LayerNorm):
878
+ module.bias.data.zero_()
879
+ module.weight.data.fill_(1.0)
880
+ elif isinstance(module, BertLMPredictionHead):
881
+ module.bias.data.zero_()
882
+
883
+
884
+ @dataclass
885
+ @auto_docstring(
886
+ custom_intro="""
887
+ Output type of [`BertForPreTraining`].
888
+ """
889
+ )
890
+ class BertForPreTrainingOutput(ModelOutput):
891
+ r"""
892
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
893
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
894
+ (classification) loss.
895
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
896
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
897
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
898
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
899
+ before SoftMax).
900
+ """
901
+
902
+ loss: Optional[torch.FloatTensor] = None
903
+ prediction_logits: Optional[torch.FloatTensor] = None
904
+ seq_relationship_logits: Optional[torch.FloatTensor] = None
905
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
906
+ attentions: Optional[tuple[torch.FloatTensor]] = None
907
+
908
+
909
+ @auto_docstring(
910
+ custom_intro="""
911
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
912
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
913
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
914
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
915
+
916
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
917
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
918
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
919
+ """
920
+ )
921
+ class BertModel(BertPreTrainedModel):
922
+ _no_split_modules = ["BertEmbeddings", "BertLayer"]
923
+
924
+ def __init__(self, config, add_pooling_layer=True):
925
+ r"""
926
+ add_pooling_layer (bool, *optional*, defaults to `True`):
927
+ Whether to add a pooling layer
928
+ """
929
+ super().__init__(config)
930
+ self.config = config
931
+
932
+ self.embeddings = BertEmbeddings(config)
933
+ self.encoder = BertEncoder(config)
934
+
935
+ self.pooler = BertPooler(config) if add_pooling_layer else None
936
+
937
+ self.attn_implementation = config._attn_implementation
938
+ self.position_embedding_type = config.position_embedding_type
939
+
940
+ # Initialize weights and apply final processing
941
+ self.post_init()
942
+
943
+ def get_input_embeddings(self):
944
+ return self.embeddings.word_embeddings
945
+
946
+ def set_input_embeddings(self, value):
947
+ self.embeddings.word_embeddings = value
948
+
949
+ def _prune_heads(self, heads_to_prune):
950
+ """
951
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
952
+ class PreTrainedModel
953
+ """
954
+ for layer, heads in heads_to_prune.items():
955
+ self.encoder.layer[layer].attention.prune_heads(heads)
956
+
957
+ @auto_docstring
958
+ def forward(
959
+ self,
960
+ input_ids: Optional[torch.Tensor] = None,
961
+ attention_mask: Optional[torch.Tensor] = None,
962
+ token_type_ids: Optional[torch.Tensor] = None,
963
+ position_ids: Optional[torch.Tensor] = None,
964
+ head_mask: Optional[torch.Tensor] = None,
965
+ inputs_embeds: Optional[torch.Tensor] = None,
966
+ encoder_hidden_states: Optional[torch.Tensor] = None,
967
+ encoder_attention_mask: Optional[torch.Tensor] = None,
968
+ past_key_values: Optional[Cache] = None,
969
+ use_cache: Optional[bool] = None,
970
+ output_attentions: Optional[bool] = None,
971
+ output_hidden_states: Optional[bool] = None,
972
+ return_dict: Optional[bool] = None,
973
+ cache_position: Optional[torch.Tensor] = None,
974
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
975
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
976
+ output_hidden_states = (
977
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
978
+ )
979
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
980
+
981
+ if self.config.is_decoder:
982
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
983
+ else:
984
+ use_cache = False
985
+
986
+ if input_ids is not None and inputs_embeds is not None:
987
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
988
+ elif input_ids is not None:
989
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
990
+ input_shape = input_ids.size()
991
+ elif inputs_embeds is not None:
992
+ input_shape = inputs_embeds.size()[:-1]
993
+ else:
994
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
995
+
996
+ batch_size, seq_length = input_shape
997
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
998
+
999
+ past_key_values_length = 0
1000
+ if past_key_values is not None:
1001
+ past_key_values_length = (
1002
+ past_key_values[0][0].shape[-2]
1003
+ if not isinstance(past_key_values, Cache)
1004
+ else past_key_values.get_seq_length()
1005
+ )
1006
+
1007
+ if token_type_ids is None:
1008
+ if hasattr(self.embeddings, "token_type_ids"):
1009
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
1010
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
1011
+ token_type_ids = buffered_token_type_ids_expanded
1012
+ else:
1013
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
1014
+
1015
+ embedding_output = self.embeddings(
1016
+ input_ids=input_ids,
1017
+ position_ids=position_ids,
1018
+ token_type_ids=token_type_ids,
1019
+ inputs_embeds=inputs_embeds,
1020
+ past_key_values_length=past_key_values_length,
1021
+ )
1022
+
1023
+ if attention_mask is None:
1024
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
1025
+
1026
+ use_sdpa_attention_masks = (
1027
+ self.attn_implementation == "sdpa"
1028
+ and self.position_embedding_type == "absolute"
1029
+ and head_mask is None
1030
+ and not output_attentions
1031
+ )
1032
+
1033
+ # Expand the attention mask
1034
+ if use_sdpa_attention_masks and attention_mask.dim() == 2:
1035
+ # Expand the attention mask for SDPA.
1036
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
1037
+ if self.config.is_decoder:
1038
+ extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1039
+ attention_mask,
1040
+ input_shape,
1041
+ embedding_output,
1042
+ past_key_values_length,
1043
+ )
1044
+ else:
1045
+ extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1046
+ attention_mask, embedding_output.dtype, tgt_len=seq_length
1047
+ )
1048
+ else:
1049
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
1050
+ # ourselves in which case we just need to make it broadcastable to all heads.
1051
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
1052
+
1053
+ # If a 2D or 3D attention mask is provided for the cross-attention
1054
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
1055
+ if self.config.is_decoder and encoder_hidden_states is not None:
1056
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
1057
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
1058
+ if encoder_attention_mask is None:
1059
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
1060
+
1061
+ if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
1062
+ # Expand the attention mask for SDPA.
1063
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
1064
+ encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1065
+ encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
1066
+ )
1067
+ else:
1068
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
1069
+ else:
1070
+ encoder_extended_attention_mask = None
1071
+
1072
+ # Prepare head mask if needed
1073
+ # 1.0 in head_mask indicate we keep the head
1074
+ # attention_probs has shape bsz x n_heads x N x N
1075
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
1076
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
1077
+
1078
+ ### update extended_attention_mask during training here!!!
1079
+ # extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
1080
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
1081
+ encoder_outputs = self.encoder(
1082
+ embedding_output,
1083
+ attention_mask=extended_attention_mask,
1084
+ head_mask=head_mask,
1085
+ encoder_hidden_states=encoder_hidden_states,
1086
+ encoder_attention_mask=encoder_extended_attention_mask,
1087
+ past_key_values=past_key_values,
1088
+ use_cache=use_cache,
1089
+ output_attentions=output_attentions,
1090
+ output_hidden_states=output_hidden_states,
1091
+ return_dict=return_dict,
1092
+ cache_position=cache_position,
1093
+ )
1094
+ sequence_output = encoder_outputs[0]
1095
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1096
+
1097
+ if not return_dict:
1098
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1099
+
1100
+ return BaseModelOutputWithPoolingAndCrossAttentions(
1101
+ last_hidden_state=sequence_output,
1102
+ pooler_output=pooled_output,
1103
+ past_key_values=encoder_outputs.past_key_values,
1104
+ hidden_states=encoder_outputs.hidden_states,
1105
+ attentions=encoder_outputs.attentions,
1106
+ cross_attentions=encoder_outputs.cross_attentions,
1107
+ )
1108
+
1109
+
1110
+ @auto_docstring(
1111
+ custom_intro="""
1112
+ Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
1113
+ sentence prediction (classification)` head.
1114
+ """
1115
+ )
1116
+ class BertForPreTraining(BertPreTrainedModel):
1117
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1118
+
1119
+ def __init__(self, config):
1120
+ super().__init__(config)
1121
+
1122
+ self.bert = BertModel(config)
1123
+ self.cls = BertPreTrainingHeads(config)
1124
+
1125
+ # Initialize weights and apply final processing
1126
+ self.post_init()
1127
+
1128
+ def get_output_embeddings(self):
1129
+ return self.cls.predictions.decoder
1130
+
1131
+ def set_output_embeddings(self, new_embeddings):
1132
+ self.cls.predictions.decoder = new_embeddings
1133
+ self.cls.predictions.bias = new_embeddings.bias
1134
+
1135
+ @auto_docstring
1136
+ def forward(
1137
+ self,
1138
+ input_ids: Optional[torch.Tensor] = None,
1139
+ attention_mask: Optional[torch.Tensor] = None,
1140
+ token_type_ids: Optional[torch.Tensor] = None,
1141
+ position_ids: Optional[torch.Tensor] = None,
1142
+ head_mask: Optional[torch.Tensor] = None,
1143
+ inputs_embeds: Optional[torch.Tensor] = None,
1144
+ labels: Optional[torch.Tensor] = None,
1145
+ next_sentence_label: Optional[torch.Tensor] = None,
1146
+ output_attentions: Optional[bool] = None,
1147
+ output_hidden_states: Optional[bool] = None,
1148
+ return_dict: Optional[bool] = None,
1149
+ ) -> Union[tuple[torch.Tensor], BertForPreTrainingOutput]:
1150
+ r"""
1151
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1152
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1153
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
1154
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1155
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1156
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
1157
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
1158
+
1159
+ - 0 indicates sequence B is a continuation of sequence A,
1160
+ - 1 indicates sequence B is a random sequence.
1161
+
1162
+ Example:
1163
+
1164
+ ```python
1165
+ >>> from transformers import AutoTokenizer, BertForPreTraining
1166
+ >>> import torch
1167
+
1168
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1169
+ >>> model = BertForPreTraining.from_pretrained("google-bert/bert-base-uncased")
1170
+
1171
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1172
+ >>> outputs = model(**inputs)
1173
+
1174
+ >>> prediction_logits = outputs.prediction_logits
1175
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
1176
+ ```
1177
+ """
1178
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1179
+
1180
+ outputs = self.bert(
1181
+ input_ids,
1182
+ attention_mask=attention_mask,
1183
+ token_type_ids=token_type_ids,
1184
+ position_ids=position_ids,
1185
+ head_mask=head_mask,
1186
+ inputs_embeds=inputs_embeds,
1187
+ output_attentions=output_attentions,
1188
+ output_hidden_states=output_hidden_states,
1189
+ return_dict=return_dict,
1190
+ )
1191
+
1192
+ sequence_output, pooled_output = outputs[:2]
1193
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
1194
+
1195
+ total_loss = None
1196
+ if labels is not None and next_sentence_label is not None:
1197
+ loss_fct = CrossEntropyLoss()
1198
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1199
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
1200
+ total_loss = masked_lm_loss + next_sentence_loss
1201
+
1202
+ if not return_dict:
1203
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
1204
+ return ((total_loss,) + output) if total_loss is not None else output
1205
+
1206
+ return BertForPreTrainingOutput(
1207
+ loss=total_loss,
1208
+ prediction_logits=prediction_scores,
1209
+ seq_relationship_logits=seq_relationship_score,
1210
+ hidden_states=outputs.hidden_states,
1211
+ attentions=outputs.attentions,
1212
+ )
1213
+
1214
+
1215
+ @auto_docstring(
1216
+ custom_intro="""
1217
+ Bert Model with a `language modeling` head on top for CLM fine-tuning.
1218
+ """
1219
+ )
1220
+ class BertLMHeadModel(BertPreTrainedModel, GenerationMixin):
1221
+ _tied_weights_keys = ["cls.predictions.decoder.bias", "cls.predictions.decoder.weight"]
1222
+
1223
+ def __init__(self, config):
1224
+ super().__init__(config)
1225
+
1226
+ if not config.is_decoder:
1227
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
1228
+
1229
+ self.bert = BertModel(config, add_pooling_layer=False)
1230
+ self.cls = BertOnlyMLMHead(config)
1231
+
1232
+ # Initialize weights and apply final processing
1233
+ self.post_init()
1234
+
1235
+ def get_output_embeddings(self):
1236
+ return self.cls.predictions.decoder
1237
+
1238
+ def set_output_embeddings(self, new_embeddings):
1239
+ self.cls.predictions.decoder = new_embeddings
1240
+ self.cls.predictions.bias = new_embeddings.bias
1241
+
1242
+ @auto_docstring
1243
+ def forward(
1244
+ self,
1245
+ input_ids: Optional[torch.Tensor] = None,
1246
+ attention_mask: Optional[torch.Tensor] = None,
1247
+ token_type_ids: Optional[torch.Tensor] = None,
1248
+ position_ids: Optional[torch.Tensor] = None,
1249
+ head_mask: Optional[torch.Tensor] = None,
1250
+ inputs_embeds: Optional[torch.Tensor] = None,
1251
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1252
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1253
+ labels: Optional[torch.Tensor] = None,
1254
+ past_key_values: Optional[Cache] = None,
1255
+ use_cache: Optional[bool] = None,
1256
+ output_attentions: Optional[bool] = None,
1257
+ output_hidden_states: Optional[bool] = None,
1258
+ return_dict: Optional[bool] = None,
1259
+ cache_position: Optional[torch.Tensor] = None,
1260
+ **loss_kwargs,
1261
+ ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
1262
+ r"""
1263
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1264
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
1265
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
1266
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
1267
+ """
1268
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1269
+ if labels is not None:
1270
+ use_cache = False
1271
+
1272
+ outputs = self.bert(
1273
+ input_ids,
1274
+ attention_mask=attention_mask,
1275
+ token_type_ids=token_type_ids,
1276
+ position_ids=position_ids,
1277
+ head_mask=head_mask,
1278
+ inputs_embeds=inputs_embeds,
1279
+ encoder_hidden_states=encoder_hidden_states,
1280
+ encoder_attention_mask=encoder_attention_mask,
1281
+ past_key_values=past_key_values,
1282
+ use_cache=use_cache,
1283
+ output_attentions=output_attentions,
1284
+ output_hidden_states=output_hidden_states,
1285
+ return_dict=return_dict,
1286
+ cache_position=cache_position,
1287
+ )
1288
+
1289
+ sequence_output = outputs[0]
1290
+ prediction_scores = self.cls(sequence_output)
1291
+
1292
+ lm_loss = None
1293
+ if labels is not None:
1294
+ lm_loss = self.loss_function(prediction_scores, labels, self.config.vocab_size, **loss_kwargs)
1295
+
1296
+ if not return_dict:
1297
+ output = (prediction_scores,) + outputs[2:]
1298
+ return ((lm_loss,) + output) if lm_loss is not None else output
1299
+
1300
+ return CausalLMOutputWithCrossAttentions(
1301
+ loss=lm_loss,
1302
+ logits=prediction_scores,
1303
+ past_key_values=outputs.past_key_values,
1304
+ hidden_states=outputs.hidden_states,
1305
+ attentions=outputs.attentions,
1306
+ cross_attentions=outputs.cross_attentions,
1307
+ )
1308
+
1309
+
1310
+ @auto_docstring
1311
+ class BertForMaskedLM(BertPreTrainedModel):
1312
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1313
+
1314
+ def __init__(self, config):
1315
+ super().__init__(config)
1316
+
1317
+ if config.is_decoder:
1318
+ logger.warning(
1319
+ "If you want to use `BertForMaskedLM` make sure `config.is_decoder=False` for "
1320
+ "bi-directional self-attention."
1321
+ )
1322
+
1323
+ self.bert = BertModel(config, add_pooling_layer=False)
1324
+ self.cls = BertOnlyMLMHead(config)
1325
+
1326
+ # Initialize weights and apply final processing
1327
+ self.post_init()
1328
+
1329
+ def get_output_embeddings(self):
1330
+ return self.cls.predictions.decoder
1331
+
1332
+ def set_output_embeddings(self, new_embeddings):
1333
+ self.cls.predictions.decoder = new_embeddings
1334
+ self.cls.predictions.bias = new_embeddings.bias
1335
+
1336
+ @auto_docstring
1337
+ def forward(
1338
+ self,
1339
+ input_ids: Optional[torch.Tensor] = None,
1340
+ attention_mask: Optional[torch.Tensor] = None,
1341
+ token_type_ids: Optional[torch.Tensor] = None,
1342
+ position_ids: Optional[torch.Tensor] = None,
1343
+ head_mask: Optional[torch.Tensor] = None,
1344
+ inputs_embeds: Optional[torch.Tensor] = None,
1345
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1346
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1347
+ labels: Optional[torch.Tensor] = None,
1348
+ output_attentions: Optional[bool] = None,
1349
+ output_hidden_states: Optional[bool] = None,
1350
+ return_dict: Optional[bool] = None,
1351
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
1352
+ r"""
1353
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1354
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
1355
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
1356
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
1357
+ """
1358
+
1359
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1360
+
1361
+ outputs = self.bert(
1362
+ input_ids,
1363
+ attention_mask=attention_mask,
1364
+ token_type_ids=token_type_ids,
1365
+ position_ids=position_ids,
1366
+ head_mask=head_mask,
1367
+ inputs_embeds=inputs_embeds,
1368
+ encoder_hidden_states=encoder_hidden_states,
1369
+ encoder_attention_mask=encoder_attention_mask,
1370
+ output_attentions=output_attentions,
1371
+ output_hidden_states=output_hidden_states,
1372
+ return_dict=return_dict,
1373
+ )
1374
+
1375
+ sequence_output = outputs[0]
1376
+ prediction_scores = self.cls(sequence_output)
1377
+
1378
+ masked_lm_loss = None
1379
+ if labels is not None:
1380
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
1381
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
1382
+
1383
+ if not return_dict:
1384
+ output = (prediction_scores,) + outputs[2:]
1385
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1386
+
1387
+ return MaskedLMOutput(
1388
+ loss=masked_lm_loss,
1389
+ logits=prediction_scores,
1390
+ hidden_states=outputs.hidden_states,
1391
+ attentions=outputs.attentions,
1392
+ )
1393
+
1394
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
1395
+ input_shape = input_ids.shape
1396
+ effective_batch_size = input_shape[0]
1397
+
1398
+ # add a dummy token
1399
+ if self.config.pad_token_id is None:
1400
+ raise ValueError("The PAD token should be defined for generation")
1401
+
1402
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
1403
+ dummy_token = torch.full(
1404
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
1405
+ )
1406
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
1407
+
1408
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
1409
+
1410
+ @classmethod
1411
+ def can_generate(cls) -> bool:
1412
+ """
1413
+ Legacy correction: BertForMaskedLM can't call `generate()` from `GenerationMixin`, even though it has a
1414
+ `prepare_inputs_for_generation` method.
1415
+ """
1416
+ return False
1417
+
1418
+
1419
+ @auto_docstring(
1420
+ custom_intro="""
1421
+ Bert Model with a `next sentence prediction (classification)` head on top.
1422
+ """
1423
+ )
1424
+ class BertForNextSentencePrediction(BertPreTrainedModel):
1425
+ def __init__(self, config):
1426
+ super().__init__(config)
1427
+
1428
+ self.bert = BertModel(config)
1429
+ self.cls = BertOnlyNSPHead(config)
1430
+
1431
+ # Initialize weights and apply final processing
1432
+ self.post_init()
1433
+
1434
+ @auto_docstring
1435
+ def forward(
1436
+ self,
1437
+ input_ids: Optional[torch.Tensor] = None,
1438
+ attention_mask: Optional[torch.Tensor] = None,
1439
+ token_type_ids: Optional[torch.Tensor] = None,
1440
+ position_ids: Optional[torch.Tensor] = None,
1441
+ head_mask: Optional[torch.Tensor] = None,
1442
+ inputs_embeds: Optional[torch.Tensor] = None,
1443
+ labels: Optional[torch.Tensor] = None,
1444
+ output_attentions: Optional[bool] = None,
1445
+ output_hidden_states: Optional[bool] = None,
1446
+ return_dict: Optional[bool] = None,
1447
+ **kwargs,
1448
+ ) -> Union[tuple[torch.Tensor], NextSentencePredictorOutput]:
1449
+ r"""
1450
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1451
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
1452
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
1453
+
1454
+ - 0 indicates sequence B is a continuation of sequence A,
1455
+ - 1 indicates sequence B is a random sequence.
1456
+
1457
+ Example:
1458
+
1459
+ ```python
1460
+ >>> from transformers import AutoTokenizer, BertForNextSentencePrediction
1461
+ >>> import torch
1462
+
1463
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
1464
+ >>> model = BertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
1465
+
1466
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
1467
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
1468
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
1469
+
1470
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
1471
+ >>> logits = outputs.logits
1472
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
1473
+ ```
1474
+ """
1475
+
1476
+ if "next_sentence_label" in kwargs:
1477
+ warnings.warn(
1478
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
1479
+ " `labels` instead.",
1480
+ FutureWarning,
1481
+ )
1482
+ labels = kwargs.pop("next_sentence_label")
1483
+
1484
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1485
+
1486
+ outputs = self.bert(
1487
+ input_ids,
1488
+ attention_mask=attention_mask,
1489
+ token_type_ids=token_type_ids,
1490
+ position_ids=position_ids,
1491
+ head_mask=head_mask,
1492
+ inputs_embeds=inputs_embeds,
1493
+ output_attentions=output_attentions,
1494
+ output_hidden_states=output_hidden_states,
1495
+ return_dict=return_dict,
1496
+ )
1497
+
1498
+ pooled_output = outputs[1]
1499
+
1500
+ seq_relationship_scores = self.cls(pooled_output)
1501
+
1502
+ next_sentence_loss = None
1503
+ if labels is not None:
1504
+ loss_fct = CrossEntropyLoss()
1505
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
1506
+
1507
+ if not return_dict:
1508
+ output = (seq_relationship_scores,) + outputs[2:]
1509
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
1510
+
1511
+ return NextSentencePredictorOutput(
1512
+ loss=next_sentence_loss,
1513
+ logits=seq_relationship_scores,
1514
+ hidden_states=outputs.hidden_states,
1515
+ attentions=outputs.attentions,
1516
+ )
1517
+
1518
+
1519
+ @auto_docstring(
1520
+ custom_intro="""
1521
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
1522
+ output) e.g. for GLUE tasks.
1523
+ """
1524
+ )
1525
+ class BertForSequenceClassification(BertPreTrainedModel):
1526
+ def __init__(self, config):
1527
+ super().__init__(config)
1528
+ self.num_labels = config.num_labels
1529
+ self.config = config
1530
+
1531
+ self.bert = BertModel(config)
1532
+ classifier_dropout = (
1533
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1534
+ )
1535
+ self.dropout = nn.Dropout(classifier_dropout)
1536
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1537
+
1538
+ # Initialize weights and apply final processing
1539
+ self.post_init()
1540
+
1541
+ @auto_docstring
1542
+ def forward(
1543
+ self,
1544
+ input_ids: Optional[torch.Tensor] = None,
1545
+ attention_mask: Optional[torch.Tensor] = None,
1546
+ token_type_ids: Optional[torch.Tensor] = None,
1547
+ position_ids: Optional[torch.Tensor] = None,
1548
+ head_mask: Optional[torch.Tensor] = None,
1549
+ inputs_embeds: Optional[torch.Tensor] = None,
1550
+ labels: Optional[torch.Tensor] = None,
1551
+ output_attentions: Optional[bool] = None,
1552
+ output_hidden_states: Optional[bool] = None,
1553
+ return_dict: Optional[bool] = None,
1554
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
1555
+ r"""
1556
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1557
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1558
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1559
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1560
+ """
1561
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1562
+
1563
+ outputs = self.bert(
1564
+ input_ids,
1565
+ attention_mask=attention_mask,
1566
+ token_type_ids=token_type_ids,
1567
+ position_ids=position_ids,
1568
+ head_mask=head_mask,
1569
+ inputs_embeds=inputs_embeds,
1570
+ output_attentions=output_attentions,
1571
+ output_hidden_states=output_hidden_states,
1572
+ return_dict=return_dict,
1573
+ )
1574
+
1575
+ pooled_output = outputs[1]
1576
+
1577
+ pooled_output = self.dropout(pooled_output)
1578
+ logits = self.classifier(pooled_output)
1579
+
1580
+ loss = None
1581
+ if labels is not None:
1582
+ if self.config.problem_type is None:
1583
+ if self.num_labels == 1:
1584
+ self.config.problem_type = "regression"
1585
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1586
+ self.config.problem_type = "single_label_classification"
1587
+ else:
1588
+ self.config.problem_type = "multi_label_classification"
1589
+
1590
+ if self.config.problem_type == "regression":
1591
+ loss_fct = MSELoss()
1592
+ if self.num_labels == 1:
1593
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1594
+ else:
1595
+ loss = loss_fct(logits, labels)
1596
+ elif self.config.problem_type == "single_label_classification":
1597
+ loss_fct = CrossEntropyLoss()
1598
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1599
+ elif self.config.problem_type == "multi_label_classification":
1600
+ loss_fct = BCEWithLogitsLoss()
1601
+ loss = loss_fct(logits, labels)
1602
+ if not return_dict:
1603
+ output = (logits,) + outputs[2:]
1604
+ return ((loss,) + output) if loss is not None else output
1605
+
1606
+ return SequenceClassifierOutput(
1607
+ loss=loss,
1608
+ logits=logits,
1609
+ hidden_states=outputs.hidden_states,
1610
+ attentions=outputs.attentions,
1611
+ )
1612
+
1613
+
1614
+ @auto_docstring
1615
+ class BertForMultipleChoice(BertPreTrainedModel):
1616
+ def __init__(self, config):
1617
+ super().__init__(config)
1618
+
1619
+ self.bert = BertModel(config)
1620
+ classifier_dropout = (
1621
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1622
+ )
1623
+ self.dropout = nn.Dropout(classifier_dropout)
1624
+ self.classifier = nn.Linear(config.hidden_size, 1)
1625
+
1626
+ # Initialize weights and apply final processing
1627
+ self.post_init()
1628
+
1629
+ @auto_docstring
1630
+ def forward(
1631
+ self,
1632
+ input_ids: Optional[torch.Tensor] = None,
1633
+ attention_mask: Optional[torch.Tensor] = None,
1634
+ token_type_ids: Optional[torch.Tensor] = None,
1635
+ position_ids: Optional[torch.Tensor] = None,
1636
+ head_mask: Optional[torch.Tensor] = None,
1637
+ inputs_embeds: Optional[torch.Tensor] = None,
1638
+ labels: Optional[torch.Tensor] = None,
1639
+ output_attentions: Optional[bool] = None,
1640
+ output_hidden_states: Optional[bool] = None,
1641
+ return_dict: Optional[bool] = None,
1642
+ ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
1643
+ r"""
1644
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
1645
+ Indices of input sequence tokens in the vocabulary.
1646
+
1647
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1648
+ [`PreTrainedTokenizer.__call__`] for details.
1649
+
1650
+ [What are input IDs?](../glossary#input-ids)
1651
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1652
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
1653
+ 1]`:
1654
+
1655
+ - 0 corresponds to a *sentence A* token,
1656
+ - 1 corresponds to a *sentence B* token.
1657
+
1658
+ [What are token type IDs?](../glossary#token-type-ids)
1659
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
1660
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
1661
+ config.max_position_embeddings - 1]`.
1662
+
1663
+ [What are position IDs?](../glossary#position-ids)
1664
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
1665
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1666
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1667
+ model's internal embedding lookup matrix.
1668
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1669
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
1670
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
1671
+ `input_ids` above)
1672
+ """
1673
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1674
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
1675
+
1676
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
1677
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
1678
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
1679
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
1680
+ inputs_embeds = (
1681
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
1682
+ if inputs_embeds is not None
1683
+ else None
1684
+ )
1685
+
1686
+ outputs = self.bert(
1687
+ input_ids,
1688
+ attention_mask=attention_mask,
1689
+ token_type_ids=token_type_ids,
1690
+ position_ids=position_ids,
1691
+ head_mask=head_mask,
1692
+ inputs_embeds=inputs_embeds,
1693
+ output_attentions=output_attentions,
1694
+ output_hidden_states=output_hidden_states,
1695
+ return_dict=return_dict,
1696
+ )
1697
+
1698
+ pooled_output = outputs[1]
1699
+
1700
+ pooled_output = self.dropout(pooled_output)
1701
+ logits = self.classifier(pooled_output)
1702
+ reshaped_logits = logits.view(-1, num_choices)
1703
+
1704
+ loss = None
1705
+ if labels is not None:
1706
+ loss_fct = CrossEntropyLoss()
1707
+ loss = loss_fct(reshaped_logits, labels)
1708
+
1709
+ if not return_dict:
1710
+ output = (reshaped_logits,) + outputs[2:]
1711
+ return ((loss,) + output) if loss is not None else output
1712
+
1713
+ return MultipleChoiceModelOutput(
1714
+ loss=loss,
1715
+ logits=reshaped_logits,
1716
+ hidden_states=outputs.hidden_states,
1717
+ attentions=outputs.attentions,
1718
+ )
1719
+
1720
+
1721
+ @auto_docstring
1722
+ class BertForTokenClassification(BertPreTrainedModel):
1723
+ def __init__(self, config):
1724
+ super().__init__(config)
1725
+ self.num_labels = config.num_labels
1726
+
1727
+ self.bert = BertModel(config, add_pooling_layer=False)
1728
+ classifier_dropout = (
1729
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1730
+ )
1731
+ self.dropout = nn.Dropout(classifier_dropout)
1732
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1733
+
1734
+ # Initialize weights and apply final processing
1735
+ self.post_init()
1736
+
1737
+ @auto_docstring
1738
+ def forward(
1739
+ self,
1740
+ input_ids: Optional[torch.Tensor] = None,
1741
+ attention_mask: Optional[torch.Tensor] = None,
1742
+ token_type_ids: Optional[torch.Tensor] = None,
1743
+ position_ids: Optional[torch.Tensor] = None,
1744
+ head_mask: Optional[torch.Tensor] = None,
1745
+ inputs_embeds: Optional[torch.Tensor] = None,
1746
+ labels: Optional[torch.Tensor] = None,
1747
+ output_attentions: Optional[bool] = None,
1748
+ output_hidden_states: Optional[bool] = None,
1749
+ return_dict: Optional[bool] = None,
1750
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
1751
+ r"""
1752
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1753
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
1754
+ """
1755
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1756
+
1757
+ outputs = self.bert(
1758
+ input_ids,
1759
+ attention_mask=attention_mask,
1760
+ token_type_ids=token_type_ids,
1761
+ position_ids=position_ids,
1762
+ head_mask=head_mask,
1763
+ inputs_embeds=inputs_embeds,
1764
+ output_attentions=output_attentions,
1765
+ output_hidden_states=output_hidden_states,
1766
+ return_dict=return_dict,
1767
+ )
1768
+
1769
+ sequence_output = outputs[0]
1770
+
1771
+ sequence_output = self.dropout(sequence_output)
1772
+ logits = self.classifier(sequence_output)
1773
+
1774
+ loss = None
1775
+ if labels is not None:
1776
+ loss_fct = CrossEntropyLoss()
1777
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1778
+
1779
+ if not return_dict:
1780
+ output = (logits,) + outputs[2:]
1781
+ return ((loss,) + output) if loss is not None else output
1782
+
1783
+ return TokenClassifierOutput(
1784
+ loss=loss,
1785
+ logits=logits,
1786
+ hidden_states=outputs.hidden_states,
1787
+ attentions=outputs.attentions,
1788
+ )
1789
+
1790
+
1791
+ @auto_docstring
1792
+ class BertForQuestionAnswering(BertPreTrainedModel):
1793
+ def __init__(self, config):
1794
+ super().__init__(config)
1795
+ self.num_labels = config.num_labels
1796
+
1797
+ self.bert = BertModel(config, add_pooling_layer=False)
1798
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1799
+
1800
+ # Initialize weights and apply final processing
1801
+ self.post_init()
1802
+
1803
+ @auto_docstring
1804
+ def forward(
1805
+ self,
1806
+ input_ids: Optional[torch.Tensor] = None,
1807
+ attention_mask: Optional[torch.Tensor] = None,
1808
+ token_type_ids: Optional[torch.Tensor] = None,
1809
+ position_ids: Optional[torch.Tensor] = None,
1810
+ head_mask: Optional[torch.Tensor] = None,
1811
+ inputs_embeds: Optional[torch.Tensor] = None,
1812
+ start_positions: Optional[torch.Tensor] = None,
1813
+ end_positions: Optional[torch.Tensor] = None,
1814
+ output_attentions: Optional[bool] = None,
1815
+ output_hidden_states: Optional[bool] = None,
1816
+ return_dict: Optional[bool] = None,
1817
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1818
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1819
+
1820
+ outputs = self.bert(
1821
+ input_ids,
1822
+ attention_mask=attention_mask,
1823
+ token_type_ids=token_type_ids,
1824
+ position_ids=position_ids,
1825
+ head_mask=head_mask,
1826
+ inputs_embeds=inputs_embeds,
1827
+ output_attentions=output_attentions,
1828
+ output_hidden_states=output_hidden_states,
1829
+ return_dict=return_dict,
1830
+ )
1831
+
1832
+ sequence_output = outputs[0]
1833
+
1834
+ logits = self.qa_outputs(sequence_output)
1835
+ start_logits, end_logits = logits.split(1, dim=-1)
1836
+ start_logits = start_logits.squeeze(-1).contiguous()
1837
+ end_logits = end_logits.squeeze(-1).contiguous()
1838
+
1839
+ total_loss = None
1840
+ if start_positions is not None and end_positions is not None:
1841
+ # If we are on multi-GPU, split add a dimension
1842
+ if len(start_positions.size()) > 1:
1843
+ start_positions = start_positions.squeeze(-1)
1844
+ if len(end_positions.size()) > 1:
1845
+ end_positions = end_positions.squeeze(-1)
1846
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1847
+ ignored_index = start_logits.size(1)
1848
+ start_positions = start_positions.clamp(0, ignored_index)
1849
+ end_positions = end_positions.clamp(0, ignored_index)
1850
+
1851
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1852
+ start_loss = loss_fct(start_logits, start_positions)
1853
+ end_loss = loss_fct(end_logits, end_positions)
1854
+ total_loss = (start_loss + end_loss) / 2
1855
+
1856
+ if not return_dict:
1857
+ output = (start_logits, end_logits) + outputs[2:]
1858
+ return ((total_loss,) + output) if total_loss is not None else output
1859
+
1860
+ return QuestionAnsweringModelOutput(
1861
+ loss=total_loss,
1862
+ start_logits=start_logits,
1863
+ end_logits=end_logits,
1864
+ hidden_states=outputs.hidden_states,
1865
+ attentions=outputs.attentions,
1866
+ )
1867
+
1868
+
1869
+ __all__ = [
1870
+ "BertForMaskedLM",
1871
+ "BertForMultipleChoice",
1872
+ "BertForNextSentencePrediction",
1873
+ "BertForPreTraining",
1874
+ "BertForQuestionAnswering",
1875
+ "BertForSequenceClassification",
1876
+ "BertForTokenClassification",
1877
+ "BertLayer",
1878
+ "BertLMHeadModel",
1879
+ "BertModel",
1880
+ "BertPreTrainedModel",
1881
+ "load_tf_weights_in_bert",
1882
+ ]
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": false,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": true,
47
+ "extra_special_tokens": {},
48
+ "mask_token": "[MASK]",
49
+ "model_max_length": 512,
50
+ "pad_token": "[PAD]",
51
+ "sep_token": "[SEP]",
52
+ "strip_accents": null,
53
+ "tokenize_chinese_chars": true,
54
+ "tokenizer_class": "BertTokenizer",
55
+ "unk_token": "[UNK]"
56
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff