ccdv commited on
Commit
77e20b1
1 Parent(s): 80aca6d
README.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ tags:
5
+ - summarization
6
+ datasets:
7
+ - scientific_papers
8
+ metrics:
9
+ - rouge
10
+ model-index:
11
+ - name: ccdv/lsg-bart-base-16384-arxiv
12
+ results: []
13
+ ---
14
+
15
+ <!-- This model card has been generated automatically according to the information the Trainer had access to. You
16
+ should probably proofread and complete it, then remove this comment. -->
17
+
18
+ # ccdv/lsg-bart-base-16384-arxiv
19
+
20
+ This model is a fine-tuned version of [ccdv/lsg-bart-base-4096-arxiv](https://huggingface.co/ccdv/lsg-bart-base-4096-arxiv) on the scientific_papers arxiv dataset. \
21
+ It achieves the following results on the test set:
22
+
23
+ | Length | Global tokens | Sparse Type | Block Size | Sparsity | Connexions | R1 | R2 | RL | RLsum |
24
+ | 16384 | 64 | - | 256 | 0 | 768 | 48.55 | 20.76 | 28.39 | 44.03 |
25
+
26
+
27
+ ## Model description
28
+
29
+ The model has about ~145 millions parameters (6 encoder layers - 6 decoder layers). \
30
+ The model is warm started from BART-base, converted to handle long sequences (encoder only) and fine tuned.
31
+
32
+ ## Intended uses & limitations
33
+
34
+ More information needed
35
+
36
+ ## Training and evaluation data
37
+
38
+ More information needed
39
+
40
+ ## Training procedure
41
+
42
+ ### Training hyperparameters
43
+
44
+ The following hyperparameters were used during training:
45
+ - learning_rate: 8e-05
46
+ - train_batch_size: 1
47
+ - seed: 42
48
+ - gradient_accumulation_steps: 32
49
+ - total_train_batch_size: 32
50
+ - optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
51
+ - lr_scheduler_type: linear
52
+ - num_epochs: 1.0
53
+
54
+ ### Generate hyperparameters
55
+
56
+ The following hyperparameters were used during generation:
57
+ - dataset_name: scientific_papers
58
+ - dataset_config_name: arxiv
59
+ - eval_batch_size: 2
60
+ - early_stopping: True
61
+ - ignore_pad_token_for_loss: True
62
+ - length_penalty: 2.0
63
+ - max_length: 320
64
+ - min_length: 64
65
+ - num_beams: 5
66
+ - num_samples: None
67
+ - no_repeat_ngram_size: None
68
+ - seed: 123
69
+
70
+ ### Framework versions
71
+
72
+ - Transformers 4.18.0
73
+ - Pytorch 1.10.1+cu102
74
+ - Datasets 2.1.0
75
+ - Tokenizers 0.11.6
all_results.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eval_gen_len": 218.5635,
3
+ "eval_loss": 1.7079483270645142,
4
+ "eval_rouge1": 48.5477,
5
+ "eval_rouge2": 20.7579,
6
+ "eval_rougeL": 28.3878,
7
+ "eval_rougeLsum": 44.0302,
8
+ "eval_runtime": 21593.137,
9
+ "eval_samples": 6440,
10
+ "eval_samples_per_second": 0.298,
11
+ "eval_steps_per_second": 0.149
12
+ }
config.json ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/data/ccondevaux/lsg/text-summarization/tmp/arxiv/lsg_local_large_lr_16384_full_trained",
3
+ "activation_dropout": 0.1,
4
+ "activation_function": "gelu",
5
+ "adaptive": true,
6
+ "add_bias_logits": false,
7
+ "add_final_layer_norm": false,
8
+ "architectures": [
9
+ "LSGBartForConditionalGeneration"
10
+ ],
11
+ "attention_dropout": 0.1,
12
+ "auto_map": {
13
+ "AutoConfig": "modeling_lsg_bart.LSGBartConfig",
14
+ "AutoModel": "modeling_lsg_bart.LSGBartModel",
15
+ "AutoModelForCausalLM": "modeling_lsg_bart.LSGBartForCausalLM",
16
+ "AutoModelForQuestionAnswering": "modeling_lsg_bart.LSGBartForQuestionAnswering",
17
+ "AutoModelForSeq2SeqLM": "modeling_lsg_bart.LSGBartForConditionalGeneration",
18
+ "AutoModelForSequenceClassification": "modeling_lsg_bart.LSGBartForSequenceClassification"
19
+ },
20
+ "base_model_prefix": "lsg",
21
+ "block_size": 256,
22
+ "bos_token_id": 0,
23
+ "classif_dropout": 0.1,
24
+ "classifier_dropout": 0.0,
25
+ "d_model": 768,
26
+ "decoder_attention_heads": 12,
27
+ "decoder_ffn_dim": 3072,
28
+ "decoder_layerdrop": 0.0,
29
+ "decoder_layers": 6,
30
+ "decoder_start_token_id": 2,
31
+ "dropout": 0.1,
32
+ "early_stopping": true,
33
+ "encoder_attention_heads": 12,
34
+ "encoder_ffn_dim": 3072,
35
+ "encoder_layerdrop": 0.0,
36
+ "encoder_layers": 6,
37
+ "eos_token_id": 2,
38
+ "forced_bos_token_id": 0,
39
+ "forced_eos_token_id": 2,
40
+ "gradient_checkpointing": false,
41
+ "id2label": {
42
+ "0": "LABEL_0",
43
+ "1": "LABEL_1",
44
+ "2": "LABEL_2"
45
+ },
46
+ "init_std": 0.02,
47
+ "is_encoder_decoder": true,
48
+ "label2id": {
49
+ "LABEL_0": 0,
50
+ "LABEL_1": 1,
51
+ "LABEL_2": 2
52
+ },
53
+ "length_penalty": 2.0,
54
+ "lsh_num_pre_rounds": 1,
55
+ "max_length": 320,
56
+ "max_position_embeddings": 16384,
57
+ "min_length": 64,
58
+ "model_type": "bart",
59
+ "no_repeat_ngram_size": null,
60
+ "normalize_before": false,
61
+ "normalize_embedding": true,
62
+ "num_beams": 5,
63
+ "num_global_tokens": 64,
64
+ "num_hidden_layers": 6,
65
+ "pad_token_id": 1,
66
+ "pass_global_tokens_to_decoder": true,
67
+ "pool_with_global": true,
68
+ "scale_embedding": false,
69
+ "sparse_block_size": 0,
70
+ "sparsity_factor": 4,
71
+ "sparsity_type": "norm",
72
+ "task_specific_params": {
73
+ "summarization": {
74
+ "length_penalty": 1.0,
75
+ "max_length": 128,
76
+ "min_length": 12,
77
+ "num_beams": 4
78
+ },
79
+ "summarization_cnn": {
80
+ "length_penalty": 2.0,
81
+ "max_length": 142,
82
+ "min_length": 56,
83
+ "num_beams": 4
84
+ },
85
+ "summarization_xsum": {
86
+ "length_penalty": 1.0,
87
+ "max_length": 62,
88
+ "min_length": 11,
89
+ "num_beams": 6
90
+ }
91
+ },
92
+ "torch_dtype": "float32",
93
+ "transformers_version": "4.18.0",
94
+ "use_cache": true,
95
+ "vocab_size": 50265
96
+ }
eval_results.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "eval_gen_len": 218.5635,
3
+ "eval_loss": 1.7079483270645142,
4
+ "eval_rouge1": 48.5477,
5
+ "eval_rouge2": 20.7579,
6
+ "eval_rougeL": 28.3878,
7
+ "eval_rougeLsum": 44.0302,
8
+ "eval_runtime": 21593.137,
9
+ "eval_samples": 6440,
10
+ "eval_samples_per_second": 0.298,
11
+ "eval_steps_per_second": 0.149
12
+ }
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
modeling_lsg_bart.py ADDED
@@ -0,0 +1,2157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import warn
2
+ import torch
3
+ from transformers.models.bart.modeling_bart import *
4
+ from transformers.models.bart.modeling_bart import _expand_mask
5
+ import torch.nn as nn
6
+ from torch.nn import BCEWithLogitsLoss
7
+ import sys
8
+
9
+ AUTO_MAP = {
10
+ "AutoModel": "modeling_lsg_bart.LSGBartModel",
11
+ "AutoModelForCausalLM": "modeling_lsg_bart.LSGBartForCausalLM",
12
+ "AutoModelForQuestionAnswering": "modeling_lsg_bart.LSGBartForQuestionAnswering",
13
+ "AutoModelForSequenceClassification": "modeling_lsg_bart.LSGBartForSequenceClassification",
14
+ "AutoModelForSeq2SeqLM": "modeling_lsg_bart.LSGBartForConditionalGeneration"
15
+ }
16
+
17
+ class LSGBartConfig(BartConfig):
18
+ """
19
+ This class overrides :class:`~transformers.RobertaConfig`. Please check the superclass for the appropriate
20
+ documentation alongside usage examples.
21
+ """
22
+
23
+ base_model_prefix = "lsg"
24
+ model_type = "bart"
25
+ keys_to_ignore_at_inference = ["past_key_values"]
26
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
27
+
28
+ def __init__(
29
+ self,
30
+ adaptive=True,
31
+ base_model_prefix="lsg",
32
+ block_size=128,
33
+ lsh_num_pre_rounds=1,
34
+ num_global_tokens=1,
35
+ pass_global_tokens_to_decoder=True,
36
+ pool_with_global=True,
37
+ sparse_block_size=128,
38
+ sparsity_factor=2,
39
+ sparsity_type="norm",
40
+ **kwargs
41
+ ):
42
+ """Constructs LSGConfig."""
43
+ super().__init__(**kwargs)
44
+
45
+ self.adaptive = adaptive
46
+ self.auto_map = AUTO_MAP
47
+ self.base_model_prefix = base_model_prefix
48
+ self.block_size = block_size
49
+ self.lsh_num_pre_rounds = lsh_num_pre_rounds
50
+ self.num_global_tokens = num_global_tokens
51
+ self.pass_global_tokens_to_decoder = pass_global_tokens_to_decoder
52
+ self.pool_with_global = pool_with_global
53
+ self.sparse_block_size = sparse_block_size
54
+ self.sparsity_factor = sparsity_factor
55
+ self.sparsity_type = sparsity_type
56
+
57
+ if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride"]:
58
+ logger.warning(
59
+ "[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride'], setting sparsity_type=None, computation will skip sparse attention")
60
+ self.sparsity_type = None
61
+
62
+ if self.sparsity_type == "stride":
63
+ if self.sparsity_factor > self.encoder_attention_heads:
64
+ logger.warning(
65
+ "[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride sparsity"
66
+ )
67
+
68
+
69
+ def shift_tokens_right(input_ids, pad_token_id, decoder_start_token_id):
70
+ """
71
+ Shift input ids one token to the right.
72
+ """
73
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
74
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
75
+ shifted_input_ids[:, 0] = decoder_start_token_id
76
+
77
+ if pad_token_id is None:
78
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
79
+ # replace possible -100 values in labels by `pad_token_id`
80
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
81
+
82
+ return shifted_input_ids
83
+
84
+
85
+ def _make_causal_mask(input_ids_shape, dtype, past_key_values_length=0):
86
+ """
87
+ Make causal mask used for bi-directional self-attention.
88
+ """
89
+ bsz, tgt_len = input_ids_shape
90
+ mask = torch.full((tgt_len, tgt_len), float("-inf"))
91
+ mask_cond = torch.arange(mask.size(-1))
92
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
93
+ mask = mask.to(dtype)
94
+
95
+ if past_key_values_length > 0:
96
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
97
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
98
+
99
+
100
+ def _expand_mask(mask, dtype, tgt_len=None):
101
+ """
102
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
103
+ """
104
+ bsz, src_len = mask.size()
105
+ tgt_len = tgt_len if tgt_len is not None else src_len
106
+
107
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
108
+
109
+ inverted_mask = 1.0 - expanded_mask
110
+
111
+ return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
112
+
113
+
114
+ class BaseSelfAttention(nn.Module):
115
+
116
+ def __init__(
117
+ self,
118
+ embed_dim,
119
+ num_heads,
120
+ dropout=0.0,
121
+ is_decoder=False,
122
+ bias=True,
123
+ ):
124
+
125
+ super().__init__()
126
+ self.embed_dim = embed_dim
127
+ self.num_heads = num_heads
128
+ self.dropout = dropout
129
+ self.head_dim = embed_dim // num_heads
130
+
131
+ if (self.head_dim * num_heads) != self.embed_dim:
132
+ raise ValueError(
133
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
134
+ f" and `num_heads`: {num_heads})."
135
+ )
136
+ self.scaling = self.head_dim ** -0.5
137
+ self.is_decoder = is_decoder
138
+
139
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
140
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
141
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
142
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
143
+
144
+ def transpose_for_scores(self, x):
145
+ new_x_shape = x.size()[:-1] + (
146
+ self.num_heads,
147
+ self.head_dim,
148
+ )
149
+ x = x.view(*new_x_shape)
150
+ return x.permute(0, 2, 1, 3)
151
+
152
+ def reshape_output(self, context_layer):
153
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
154
+ new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
155
+ return context_layer.view(*new_context_layer_shape)
156
+
157
+ def project_QKV(self, hidden_states):
158
+
159
+ query_layer = self.transpose_for_scores(self.q_proj(hidden_states))
160
+ key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
161
+ value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
162
+ return query_layer, key_layer, value_layer
163
+
164
+
165
+ class BaseAttentionProduct(nn.Module):
166
+
167
+ def __init__(self, config):
168
+ """
169
+ Compute attention: softmax(Q @ K.T) @ V
170
+ """
171
+ super().__init__()
172
+ self.dropout = nn.Dropout(config.attention_dropout)
173
+
174
+ def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
175
+
176
+ d = query_layer.shape[-1]
177
+
178
+ # Take the dot product between "query" and "key" to get the raw attention scores.
179
+ attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
180
+
181
+ del query_layer
182
+ del key_layer
183
+
184
+ if attention_mask is not None:
185
+ # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
186
+ attention_scores = attention_scores + attention_mask
187
+ del attention_mask
188
+
189
+ # Normalize the attention scores to probabilities.
190
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
191
+
192
+ # This is actually dropping out entire tokens to attend to, which might
193
+ # seem a bit unusual, but is taken from the original Transformer paper.
194
+ context_layer = self.dropout(attention_probs) @ value_layer
195
+
196
+ return context_layer
197
+
198
+
199
+ class LSGAttentionProduct(nn.Module):
200
+
201
+ def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4):
202
+ """
203
+ Compute block or overlapping blocks attention products
204
+ """
205
+ super().__init__()
206
+
207
+ self.block_size = block_size
208
+ self.sparse_block_size = sparse_block_size
209
+ self.sparsity_factor = sparsity_factor
210
+
211
+ if self.block_size is None:
212
+ self.block_size = config.block_size
213
+
214
+ if self.sparse_block_size is None:
215
+ self.sparse_block_size = config.sparse_block_size
216
+
217
+ # Shape of blocks
218
+ self.local_shapes = (self.block_size*3, self.block_size)
219
+ if self.sparse_block_size and self.sparsity_factor > 0:
220
+ assert self.block_size % self.sparsity_factor == 0, "block_size must be divisible by sparsity_factor"
221
+ assert self.block_size//self.sparsity_factor >= 1, "Config is wrong, make sure block_size >= sparsity_factor"
222
+ self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
223
+
224
+ self.attention = BaseAttentionProduct(config)
225
+
226
+ def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
227
+
228
+ # Build local tokens
229
+ local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
230
+ del hidden_states
231
+
232
+ # Build sparse tokens
233
+ if sparse_hidden_states is not None:
234
+ sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
235
+
236
+ return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
237
+
238
+ def forward(
239
+ self,
240
+ query_layer,
241
+ key_layer,
242
+ value_layer,
243
+ attention_mask=None,
244
+ sparse_key=None,
245
+ sparse_value=None,
246
+ sparse_mask=None,
247
+ global_key=None,
248
+ global_value=None,
249
+ global_mask=None
250
+ ):
251
+
252
+ # Input batch, heads, length, hidden_size
253
+ n, h, t, d = query_layer.size()
254
+ n_blocks = t // self.block_size
255
+ assert t % self.block_size == 0
256
+
257
+ key_layer = self.build_lsg_inputs(
258
+ key_layer,
259
+ sparse_key,
260
+ global_key
261
+ )
262
+ del sparse_key
263
+ del global_key
264
+
265
+ value_layer = self.build_lsg_inputs(
266
+ value_layer,
267
+ sparse_value,
268
+ global_value
269
+ )
270
+ del sparse_value
271
+ del global_value
272
+
273
+ attention_mask = self.build_lsg_inputs(
274
+ attention_mask,
275
+ sparse_mask,
276
+ global_mask.transpose(-1, -2),
277
+ is_attn_mask=True
278
+ ).transpose(-1, -2)
279
+ del sparse_mask
280
+ del global_mask
281
+
282
+ # expect (..., t, d) shape
283
+ # Compute attention
284
+ context_layer = self.attention(
285
+ query_layer=self.chunk(query_layer, n_blocks),
286
+ key_layer=key_layer,
287
+ value_layer=value_layer,
288
+ attention_mask=attention_mask
289
+ )
290
+
291
+ return context_layer.reshape(n, h, -1, d)
292
+
293
+ def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
294
+
295
+ size, step = self.local_shapes
296
+ s = (size - step) // 2
297
+
298
+ # Pad before block reshaping
299
+ if is_attn_mask:
300
+ pad_value = -10000
301
+ hidden_states = hidden_states.transpose(-1, -2)
302
+ else:
303
+ pad_value = 0
304
+
305
+ hidden_states = torch.nn.functional.pad(
306
+ hidden_states.transpose(-1, -2),
307
+ pad=(s, s),
308
+ value=pad_value
309
+ ).transpose(-1, -2)
310
+
311
+ # Make blocks
312
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
313
+
314
+ return hidden_states
315
+
316
+ def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
317
+
318
+ size, step = self.sparse_shapes
319
+
320
+ # In case of odd case
321
+ odd_offset = (step % 2)
322
+
323
+ # n, h, t, d*2 + 1
324
+ size = size*2
325
+ s = (size - step) // 2 + odd_offset
326
+
327
+ # Pad before block reshaping
328
+ if is_attn_mask:
329
+ pad_value = -10000
330
+ hidden_states = hidden_states.transpose(-1, -2)
331
+ else:
332
+ pad_value = 0
333
+
334
+ hidden_states = torch.nn.functional.pad(
335
+ hidden_states.transpose(-1, -2),
336
+ pad=(s, s),
337
+ value=pad_value
338
+ ).transpose(-1, -2)
339
+
340
+ # Make blocks
341
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
342
+
343
+ # Fix case where block_size == sparsify_factor
344
+ if odd_offset:
345
+ hidden_states = hidden_states[..., :-1, :, :]
346
+
347
+ # Indexes for selection
348
+ u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
349
+ s = self.sparse_block_size
350
+
351
+ u_ = u + odd_offset
352
+ return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
353
+
354
+ def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
355
+
356
+ n, h, b, t, d = x_local.size()
357
+ x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
358
+ if x_sparse is not None:
359
+ return torch.cat([x_global, x_sparse, x_local], dim=dim)
360
+ return torch.cat([x_global, x_local], dim=dim)
361
+
362
+ def chunk(self, x, n_blocks):
363
+
364
+ t, d = x.size()[-2:]
365
+ return x.reshape(*x.size()[:-2], n_blocks, -1, d)
366
+
367
+
368
+ class LSGBartEncoderAttention(BaseSelfAttention):
369
+ '''
370
+ Compute local attention with overlapping blocs
371
+ Use global attention for tokens with highest norm
372
+ '''
373
+ def __init__(
374
+ self,
375
+ config,
376
+ embed_dim,
377
+ num_heads,
378
+ dropout
379
+ ):
380
+
381
+ super().__init__(embed_dim, num_heads, dropout)
382
+
383
+ self.block_size = config.block_size
384
+ self.sparse_block_size = config.sparse_block_size
385
+ self.num_global_tokens = config.num_global_tokens
386
+ self.sparsity_factor = config.sparsity_factor
387
+
388
+ self.attention = LSGAttentionProduct(
389
+ config,
390
+ block_size=config.block_size,
391
+ sparse_block_size=config.sparse_block_size,
392
+ sparsity_factor=self.sparsity_factor,
393
+ )
394
+
395
+ self.full_attention = BaseAttentionProduct(config)
396
+
397
+ sparse_functions = {
398
+ "norm": self.get_sparse_tokens_with_norm,
399
+ "pooling": self.get_sparse_tokens_with_pooling,
400
+ "lsh": self.get_sparse_tokens_with_lsh,
401
+ "stride": self.get_sparse_tokens_with_stride,
402
+ }
403
+
404
+ self.sparsity_type = config.sparsity_type
405
+ self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda x, y, z: (None, None, None))
406
+
407
+ if config.sparsity_type == "lsh":
408
+ self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
409
+
410
+ def get_sparse_tokens_with_norm(self, keys, values, mask):
411
+
412
+ if self.sparsity_factor == 1:
413
+ return keys, values, mask
414
+
415
+ with torch.no_grad():
416
+
417
+ block_size = min(self.block_size, self.sparse_block_size)
418
+ key_norm = keys.detach().norm(dim=-1, keepdim=True)
419
+ key_norm = key_norm * ~mask.transpose(-1, -2).bool()
420
+ key_norm = self.chunk(key_norm, block_size)
421
+
422
+ n, h, b, t, d = key_norm.size()
423
+
424
+ idx = key_norm.argsort(dim=-2)
425
+ del key_norm
426
+ idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
427
+
428
+ split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
429
+ sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
430
+
431
+ d = keys.size()[-1]
432
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
433
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
434
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
435
+
436
+ return keys, values, mask
437
+
438
+ def get_sparse_tokens_with_pooling(self, keys, values, mask):
439
+
440
+ if self.sparsity_factor == 1:
441
+ return keys, values, mask
442
+
443
+ keys = self.chunk(keys, self.sparsity_factor)
444
+ values = self.chunk(values, self.sparsity_factor)
445
+
446
+ n, h, b, t, d = keys.size()
447
+ mask = mask.reshape(n, 1, b, 1, t)
448
+ mask = ~mask.transpose(-1, -2).bool()
449
+
450
+ keys = keys * mask
451
+ values = values * mask
452
+
453
+ mask = mask.sum(dim=-2)
454
+ keys = keys.sum(dim=-2) / (mask + 1e-6)
455
+ values = values.sum(dim=-2) / (mask + 1e-6)
456
+
457
+ mask = - (1. - mask.clamp(0, 1)) * 1e4
458
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
459
+
460
+ def get_sparse_tokens_with_stride(self, keys, values, mask):
461
+
462
+ if self.sparsity_factor == 1:
463
+ return keys, values, mask
464
+
465
+ n, h, t, d = keys.size()
466
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
467
+ sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
468
+ sparse_idx = sparse_idx.expand(n, h, -1, 1)
469
+
470
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
471
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
472
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
473
+
474
+ return keys, values, mask
475
+
476
+ def get_sparse_tokens_with_lsh(self, keys, values, mask):
477
+
478
+ if self.sparsity_factor == 1:
479
+ return keys, values, mask
480
+
481
+ block_size = min(self.block_size, self.sparse_block_size)
482
+ keys = self.chunk(keys, block_size)
483
+ values = self.chunk(values, block_size)
484
+
485
+ n, h, b, t, d = keys.size()
486
+ mask = mask.reshape(n, 1, b, 1, t)
487
+ mask = ~mask.transpose(-1, -2).bool()
488
+
489
+ keys = keys * mask
490
+ values = values * mask
491
+ mask = mask.expand(-1, h, -1, -1, -1).float()
492
+
493
+ extra_factor = 1
494
+
495
+ for _ in range(self.lsh_num_pre_rounds):
496
+ keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
497
+
498
+ keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
499
+ keys /= mask + 1e-8
500
+ values /= mask + 1e-8
501
+
502
+ mask = -10000 * (1. - mask.clamp(0, 1))
503
+
504
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
505
+
506
+ def lsh_round(self, keys, values, mask, output_size):
507
+
508
+ with torch.no_grad():
509
+
510
+ n_hashes = output_size // 2
511
+ n, h, b, t, d = keys.size()
512
+ binary_mask = mask.clamp(0, 1)
513
+
514
+ indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
515
+ indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
516
+
517
+ n, h, b, t, d = keys.size()
518
+
519
+ x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
520
+ mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
521
+ keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
522
+ values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
523
+ mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
524
+
525
+ return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
526
+
527
+ def forward(
528
+ self,
529
+ hidden_states,
530
+ attention_mask=None,
531
+ layer_head_mask=None,
532
+ output_attentions=False
533
+ ):
534
+
535
+ query_layer, key_layer, value_layer = self.project_QKV(hidden_states)
536
+ outputs = self.not_causal_forward(
537
+ query_layer,
538
+ key_layer,
539
+ value_layer,
540
+ attention_mask=attention_mask[:, :, :1, :],
541
+ head_mask=layer_head_mask,
542
+ output_attentions=output_attentions
543
+ )
544
+
545
+ return self.out_proj(outputs), None, None
546
+
547
+ def not_causal_forward(
548
+ self,
549
+ query_layer,
550
+ key_layer,
551
+ value_layer,
552
+ attention_mask=None,
553
+ head_mask=None,
554
+ output_attentions=False,
555
+ ):
556
+
557
+ n, h, t, d = query_layer.size()
558
+
559
+ # Cat global mask
560
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
561
+
562
+ # Use normal attention if local attention covers every tokens
563
+ if t <= 2 * self.block_size + self.num_global_tokens:
564
+ context_layer = self.full_attention(
565
+ query_layer=query_layer,
566
+ key_layer=key_layer,
567
+ value_layer=value_layer,
568
+ attention_mask=attention_mask
569
+ )
570
+
571
+ if head_mask is not None:
572
+ context_layer = context_layer * head_mask[:, :, :1, :1]
573
+ return self.reshape_output(context_layer)
574
+
575
+ # Split input into global tokens and other tokens
576
+ split = (self.num_global_tokens, t - self.num_global_tokens)
577
+ global_query, query_layer = query_layer.split(split, dim=-2)
578
+
579
+ # Get global_attention
580
+ bos = self.full_attention(
581
+ query_layer=global_query,
582
+ key_layer=key_layer,
583
+ value_layer=value_layer,
584
+ attention_mask=attention_mask
585
+ )
586
+
587
+ # Split K Q M on global and non global
588
+ global_key, key_layer = key_layer.split(split, dim=-2)
589
+ global_value, value_layer = value_layer.split(split, dim=-2)
590
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
591
+
592
+ n, h, t, d = key_layer.size()
593
+
594
+ # Get sparse idx
595
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
596
+
597
+ if self.sparse_block_size and self.sparsity_factor > 0:
598
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
599
+
600
+ # Expand masks on heads
601
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
602
+ global_mask = global_mask.expand(-1, h, -1, -1)
603
+
604
+ # Compute dot product attention
605
+ context_layer = self.attention(
606
+ query_layer,
607
+ key_layer,
608
+ value_layer,
609
+ attention_mask,
610
+ sparse_key=sparse_key,
611
+ sparse_value=sparse_value,
612
+ sparse_mask=sparse_mask,
613
+ global_key=global_key,
614
+ global_value=global_value,
615
+ global_mask=global_mask
616
+ )
617
+
618
+ # Merge global and local-sparse tokens
619
+ context_layer = torch.cat([bos, context_layer], dim=-2)
620
+ if head_mask is not None:
621
+ context_layer = context_layer * head_mask[:, :, :1, :1]
622
+ context_layer = self.reshape_output(context_layer)
623
+
624
+ return context_layer
625
+
626
+ def chunk(self, x, chunk_size):
627
+
628
+ n, h, t, d = x.size()
629
+ return x.reshape(n, h, -1, chunk_size, d)
630
+
631
+
632
+ class LSGBartDecoderAttention(nn.Module):
633
+
634
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
635
+
636
+ def __init__(
637
+ self,
638
+ embed_dim,
639
+ num_heads,
640
+ dropout=0.0,
641
+ is_decoder=False,
642
+ bias=True,
643
+ ):
644
+
645
+ super().__init__()
646
+ self.embed_dim = embed_dim
647
+ self.num_heads = num_heads
648
+ self.dropout = dropout
649
+ self.head_dim = embed_dim // num_heads
650
+
651
+ if (self.head_dim * num_heads) != self.embed_dim:
652
+ raise ValueError(
653
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
654
+ f" and `num_heads`: {num_heads})."
655
+ )
656
+ self.scaling = self.head_dim ** -0.5
657
+ self.is_decoder = is_decoder
658
+
659
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
660
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
661
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
662
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
663
+
664
+ def _shape(self, tensor, seq_len, bsz):
665
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
666
+
667
+ def forward(
668
+ self,
669
+ hidden_states,
670
+ key_value_states=None,
671
+ past_key_value=None,
672
+ attention_mask=None,
673
+ layer_head_mask=None,
674
+ output_attentions=False,
675
+ ):
676
+
677
+ # if key_value_states are provided this layer is used as a cross-attention layer
678
+ # for the decoder
679
+ is_cross_attention = key_value_states is not None
680
+
681
+ bsz, tgt_len, _ = hidden_states.size()
682
+
683
+ # get query proj
684
+ query_states = self.q_proj(hidden_states) * self.scaling
685
+ # get key, value proj
686
+ if is_cross_attention and past_key_value is not None:
687
+ # reuse k,v, cross_attentions
688
+ key_states = past_key_value[0]
689
+ value_states = past_key_value[1]
690
+ elif is_cross_attention:
691
+ # cross_attentions
692
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
693
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
694
+ elif past_key_value is not None:
695
+ # reuse k, v, self_attention
696
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
697
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
698
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
699
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
700
+ else:
701
+ # self_attention
702
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
703
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
704
+
705
+ if self.is_decoder:
706
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
707
+ # Further calls to cross_attention layer can then reuse all cross-attention
708
+ # key/value_states (first "if" case)
709
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
710
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
711
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
712
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
713
+ past_key_value = (key_states, value_states)
714
+
715
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
716
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
717
+ key_states = key_states.view(*proj_shape)
718
+ value_states = value_states.view(*proj_shape)
719
+
720
+ src_len = key_states.size(1)
721
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
722
+
723
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
724
+ raise ValueError(
725
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
726
+ )
727
+
728
+ if attention_mask is not None:
729
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
730
+ raise ValueError(
731
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
732
+ )
733
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
734
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
735
+
736
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
737
+
738
+ if layer_head_mask is not None:
739
+ if layer_head_mask.size() != (self.num_heads,):
740
+ raise ValueError(
741
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
742
+ )
743
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
744
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
745
+
746
+ if output_attentions:
747
+ # this operation is a bit awkward, but it's required to
748
+ # make sure that attn_weights keeps its gradient.
749
+ # In order to do so, attn_weights have to be reshaped
750
+ # twice and have to be reused in the following
751
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
752
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
753
+ else:
754
+ attn_weights_reshaped = None
755
+
756
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
757
+
758
+ attn_output = torch.bmm(attn_probs, value_states)
759
+
760
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
761
+ raise ValueError(
762
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}"
763
+ )
764
+
765
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
766
+ attn_output = attn_output.transpose(1, 2)
767
+
768
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
769
+ # partitioned aross GPUs when using tensor-parallelism.
770
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
771
+
772
+ attn_output = self.out_proj(attn_output)
773
+
774
+ return attn_output, attn_weights_reshaped, past_key_value
775
+
776
+
777
+ class LSGBartLearnedPositionalEmbedding(nn.Embedding):
778
+ """
779
+ This module learns positional embeddings up to a fixed maximum size.
780
+ """
781
+
782
+ def __init__(self, num_embeddings, embedding_dim):
783
+ # Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
784
+ # and adjust num_embeddings appropriately. Other models don't have this hack
785
+ self.offset = 2
786
+ super().__init__(num_embeddings + self.offset, embedding_dim)
787
+
788
+ def forward(self, input_ids_shape, past_key_values_length=0):
789
+
790
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
791
+ bsz, seq_len = input_ids_shape[:2]
792
+ positions = torch.arange(
793
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
794
+ )
795
+ return super().forward(positions + self.offset)
796
+
797
+
798
+ class LSGBartEncoderLayer(nn.Module):
799
+
800
+ def __init__(self, config):
801
+
802
+ super().__init__()
803
+ self.embed_dim = config.d_model
804
+ self.self_attn = LSGBartEncoderAttention(
805
+ config=config,
806
+ embed_dim=self.embed_dim,
807
+ num_heads=config.encoder_attention_heads,
808
+ dropout=config.attention_dropout,
809
+ )
810
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
811
+ self.dropout = config.dropout
812
+ self.activation_fn = ACT2FN[config.activation_function]
813
+ self.activation_dropout = config.activation_dropout
814
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
815
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
816
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
817
+
818
+ def forward(
819
+ self,
820
+ hidden_states,
821
+ attention_mask,
822
+ layer_head_mask,
823
+ output_attentions=False,
824
+ ):
825
+ """
826
+ Args:
827
+ hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
828
+ attention_mask (:obj:`torch.FloatTensor`): attention mask of size
829
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
830
+ layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size
831
+ `(encoder_attention_heads,)`.
832
+ output_attentions (:obj:`bool`, `optional`):
833
+ Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under
834
+ returned tensors for more detail.
835
+ """
836
+ residual = hidden_states
837
+ hidden_states, attn_weights, _ = self.self_attn(
838
+ hidden_states=hidden_states,
839
+ attention_mask=attention_mask,
840
+ layer_head_mask=layer_head_mask,
841
+ output_attentions=output_attentions,
842
+ )
843
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
844
+ hidden_states = residual + hidden_states
845
+ hidden_states = self.self_attn_layer_norm(hidden_states)
846
+
847
+ residual = hidden_states
848
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
849
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
850
+ hidden_states = self.fc2(hidden_states)
851
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
852
+ hidden_states = residual + hidden_states
853
+ hidden_states = self.final_layer_norm(hidden_states)
854
+
855
+ if hidden_states.dtype == torch.float16 and (
856
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
857
+ ):
858
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
859
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
860
+
861
+ outputs = (hidden_states,)
862
+
863
+ if output_attentions:
864
+ outputs += (attn_weights,)
865
+
866
+ return outputs
867
+
868
+
869
+ class LSGBartDecoderLayer(nn.Module):
870
+
871
+ def __init__(self, config):
872
+
873
+ super().__init__()
874
+ self.embed_dim = config.d_model
875
+
876
+ self.self_attn = LSGBartDecoderAttention(
877
+ embed_dim=self.embed_dim,
878
+ num_heads=config.decoder_attention_heads,
879
+ dropout=config.attention_dropout,
880
+ is_decoder=True,
881
+ )
882
+ self.dropout = config.dropout
883
+ self.activation_fn = ACT2FN[config.activation_function]
884
+ self.activation_dropout = config.activation_dropout
885
+
886
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
887
+ self.encoder_attn = LSGBartDecoderAttention(
888
+ self.embed_dim,
889
+ config.decoder_attention_heads,
890
+ dropout=config.attention_dropout,
891
+ is_decoder=True,
892
+ )
893
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
894
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
895
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
896
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
897
+
898
+ def forward(
899
+ self,
900
+ hidden_states,
901
+ attention_mask=None,
902
+ encoder_hidden_states=None,
903
+ encoder_attention_mask=None,
904
+ layer_head_mask=None,
905
+ cross_attn_layer_head_mask=None,
906
+ past_key_value=None,
907
+ output_attentions=False,
908
+ use_cache=True,
909
+ ):
910
+ """
911
+ Args:
912
+ hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
913
+ attention_mask (:obj:`torch.FloatTensor`): attention mask of size
914
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
915
+ encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
916
+ encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size
917
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
918
+ layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size
919
+ `(encoder_attention_heads,)`.
920
+ cross_attn_layer_head_mask (:obj:`torch.FloatTensor`): mask for cross-attention heads in a given layer of
921
+ size `(decoder_attention_heads,)`.
922
+ past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states
923
+ output_attentions (:obj:`bool`, `optional`):
924
+ Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under
925
+ returned tensors for more detail.
926
+ """
927
+ residual = hidden_states
928
+
929
+ # Self Attention
930
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
931
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
932
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
933
+
934
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
935
+ hidden_states=hidden_states,
936
+ past_key_value=self_attn_past_key_value,
937
+ attention_mask=attention_mask,
938
+ layer_head_mask=layer_head_mask,
939
+ output_attentions=output_attentions,
940
+ )
941
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
942
+ hidden_states = residual + hidden_states
943
+ hidden_states = self.self_attn_layer_norm(hidden_states)
944
+
945
+ # Cross-Attention Block
946
+ cross_attn_present_key_value = None
947
+ cross_attn_weights = None
948
+ if encoder_hidden_states is not None:
949
+ residual = hidden_states
950
+
951
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
952
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
953
+
954
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
955
+ hidden_states=hidden_states,
956
+ key_value_states=encoder_hidden_states,
957
+ attention_mask=encoder_attention_mask,
958
+ layer_head_mask=cross_attn_layer_head_mask,
959
+ past_key_value=cross_attn_past_key_value,
960
+ output_attentions=output_attentions,
961
+ )
962
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
963
+ hidden_states = residual + hidden_states
964
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
965
+
966
+ # add cross-attn to positions 3,4 of present_key_value tuple
967
+ present_key_value = present_key_value + cross_attn_present_key_value
968
+
969
+ # Fully Connected
970
+ residual = hidden_states
971
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
972
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
973
+ hidden_states = self.fc2(hidden_states)
974
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
975
+ hidden_states = residual + hidden_states
976
+ hidden_states = self.final_layer_norm(hidden_states)
977
+
978
+ outputs = (hidden_states,)
979
+
980
+ if output_attentions:
981
+ outputs += (self_attn_weights, cross_attn_weights)
982
+
983
+ if use_cache:
984
+ outputs += (present_key_value,)
985
+
986
+ return outputs
987
+
988
+
989
+ class LSGBartClassificationHead(nn.Module):
990
+ """Head for sentence-level classification tasks."""
991
+
992
+ def __init__(
993
+ self,
994
+ input_dim,
995
+ inner_dim,
996
+ num_classes,
997
+ pooler_dropout,
998
+ ):
999
+
1000
+ super().__init__()
1001
+ self.dense = nn.Linear(input_dim, inner_dim)
1002
+ self.dropout = nn.Dropout(p=pooler_dropout)
1003
+ self.out_proj = nn.Linear(inner_dim, num_classes)
1004
+
1005
+ def forward(self, hidden_states):
1006
+
1007
+ hidden_states = self.dropout(hidden_states)
1008
+ hidden_states = self.dense(hidden_states)
1009
+ hidden_states = torch.tanh(hidden_states)
1010
+ hidden_states = self.dropout(hidden_states)
1011
+ hidden_states = self.out_proj(hidden_states)
1012
+ return hidden_states
1013
+
1014
+
1015
+ class LSGBartPretrainedModel(PreTrainedModel):
1016
+
1017
+ config_class = LSGBartConfig
1018
+ base_model_prefix = "model"
1019
+ supports_gradient_checkpointing = True
1020
+ _keys_to_ignore_on_load_unexpected = [r"encoder\.version", r"decoder\.version"]
1021
+
1022
+ def _init_weights(self, module):
1023
+
1024
+ std = self.config.init_std
1025
+ if isinstance(module, nn.Linear):
1026
+ module.weight.data.normal_(mean=0.0, std=std)
1027
+ if module.bias is not None:
1028
+ module.bias.data.zero_()
1029
+ elif isinstance(module, nn.Embedding):
1030
+ module.weight.data.normal_(mean=0.0, std=std)
1031
+ if module.padding_idx is not None:
1032
+ module.weight.data[module.padding_idx].zero_()
1033
+
1034
+ def _set_gradient_checkpointing(self, module, value=False):
1035
+
1036
+ if isinstance(module, (LSGBartDecoder, LSGBartEncoder)):
1037
+ module.gradient_checkpointing = value
1038
+
1039
+ @property
1040
+ def dummy_inputs(self):
1041
+ pad_token = self.config.pad_token_id
1042
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
1043
+ dummy_inputs = {
1044
+ "attention_mask": input_ids.ne(pad_token),
1045
+ "input_ids": input_ids,
1046
+ }
1047
+ return dummy_inputs
1048
+
1049
+
1050
+ class PretrainedLSGBartModel(LSGBartPretrainedModel):
1051
+
1052
+ def __init_subclass__(self):
1053
+ warnings.warn(
1054
+ "The class `PretrainedBartModel` has been depreciated, please use `LSGBartPretrainedModel` instead.",
1055
+ FutureWarning,
1056
+ )
1057
+
1058
+
1059
+ class LSGBartEncoder(LSGBartPretrainedModel):
1060
+ """
1061
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
1062
+ :class:`BartEncoderLayer`.
1063
+ Args:
1064
+ config: BartConfig
1065
+ embed_tokens (nn.Embedding): output embedding
1066
+ """
1067
+
1068
+ def __init__(self, config, embed_tokens=None):
1069
+
1070
+ super().__init__(config)
1071
+ self.dropout = config.dropout
1072
+ self.layerdrop = config.encoder_layerdrop
1073
+
1074
+ embed_dim = config.d_model
1075
+ self.padding_idx = config.pad_token_id
1076
+ self.max_source_positions = config.max_position_embeddings
1077
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
1078
+
1079
+ if embed_tokens is not None:
1080
+ self.embed_tokens = embed_tokens
1081
+ else:
1082
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
1083
+
1084
+ self.embed_positions = LSGBartLearnedPositionalEmbedding(
1085
+ config.max_position_embeddings,
1086
+ embed_dim,
1087
+ )
1088
+ self.layers = nn.ModuleList([LSGBartEncoderLayer(config) for _ in range(config.encoder_layers)])
1089
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
1090
+
1091
+ #
1092
+ assert hasattr(config, "num_global_tokens")
1093
+ self.num_global_tokens = config.num_global_tokens
1094
+ self.pad_idx = config.pad_token_id
1095
+
1096
+ assert hasattr(config, "block_size") and hasattr(config, "adaptive")
1097
+ self.block_size = config.block_size
1098
+ self.adaptive = config.adaptive
1099
+ self.pool_with_global = config.pool_with_global
1100
+ self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
1101
+
1102
+ self.global_embeddings = nn.Embedding(512, embedding_dim=config.d_model)
1103
+
1104
+ self.gradient_checkpointing = False
1105
+
1106
+ # Initialize weights and apply final processing
1107
+ self.post_init()
1108
+
1109
+ def get_input_embeddings(self):
1110
+ return self.embed_tokens
1111
+
1112
+ def set_input_embeddings(self, value):
1113
+ self.embed_tokens = value
1114
+
1115
+ def forward(self,
1116
+ input_ids=None,
1117
+ attention_mask=None,
1118
+ head_mask=None,
1119
+ inputs_embeds=None,
1120
+ output_attentions=None,
1121
+ output_hidden_states=None,
1122
+ return_dict=None
1123
+ ):
1124
+
1125
+
1126
+ inputs_ = input_ids if input_ids is not None else inputs_embeds
1127
+ n, t = inputs_.size()[:2]
1128
+
1129
+ if attention_mask is None:
1130
+ attention_mask = torch.ones(n, t, device=inputs_.device)
1131
+
1132
+ b = self.block_size * 2
1133
+ pad = t % self.block_size
1134
+
1135
+ # Check if t is multiple of block_size and pad
1136
+ if t > b and pad > 0:
1137
+ pad_length = self.block_size - pad
1138
+ if input_ids is not None:
1139
+ input_ids = torch.nn.functional.pad(input_ids, (0, pad_length), value=self.pad_idx)
1140
+ else:
1141
+ inputs_embeds = torch.nn.functional.pad(inputs_embeds.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
1142
+ attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=0)
1143
+
1144
+ # else adaptive sequence length
1145
+ elif self.adaptive:
1146
+ # Get last non zero mask index
1147
+ s = int(attention_mask.cumsum(dim=-1).argmax(dim=-1).max()) + 1
1148
+ if s < t and self.block_size is not None:
1149
+ s = max(2, s // self.block_size + 1) * self.block_size if s > b else s
1150
+ if input_ids is not None:
1151
+ input_ids = input_ids[:, :s]
1152
+ else:
1153
+ inputs_embeds = inputs_embeds[:, :s]
1154
+ attention_mask = attention_mask[:, :s]
1155
+
1156
+ n, t_ = attention_mask.size()
1157
+
1158
+ encoder_outputs = self.forward_with_adaptive(
1159
+ input_ids=input_ids,
1160
+ attention_mask=attention_mask,
1161
+ head_mask=head_mask,
1162
+ inputs_embeds=inputs_embeds,
1163
+ output_attentions=output_attentions,
1164
+ output_hidden_states=output_hidden_states,
1165
+ return_dict=return_dict,
1166
+ )
1167
+
1168
+ context = encoder_outputs[0]
1169
+ diff = t - t_
1170
+
1171
+ if self.pass_global_tokens_to_decoder:
1172
+ offset = self.num_global_tokens
1173
+ else:
1174
+ if self.pool_with_global:
1175
+ context[:, self.num_global_tokens] = context[:, 0]
1176
+ context = context[..., self.num_global_tokens:, :]
1177
+ offset = 0
1178
+
1179
+ # Adapt sequence to initial shape
1180
+ if diff > 0:
1181
+ context = torch.nn.functional.pad(context.transpose(-1, -2), pad=(0, diff), value=0).transpose(-1, -2)
1182
+ elif diff < 0:
1183
+ context = context[:, :t + offset]
1184
+
1185
+ if return_dict:
1186
+ encoder_outputs.last_hidden_state = context
1187
+ else:
1188
+ encoder_outputs = (context, ) + encoder_outputs[1:]
1189
+
1190
+ return encoder_outputs
1191
+
1192
+ def forward_with_adaptive(
1193
+ self,
1194
+ input_ids=None,
1195
+ attention_mask=None,
1196
+ head_mask=None,
1197
+ inputs_embeds=None,
1198
+ output_attentions=None,
1199
+ output_hidden_states=None,
1200
+ return_dict=None,
1201
+ ):
1202
+
1203
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1204
+ output_hidden_states = (
1205
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1206
+ )
1207
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1208
+
1209
+ # retrieve input_ids and inputs_embeds
1210
+ if input_ids is not None and inputs_embeds is not None:
1211
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1212
+ elif input_ids is not None:
1213
+ input_shape = input_ids.size()
1214
+ input_ids = input_ids.view(-1, input_shape[-1])
1215
+ elif inputs_embeds is not None:
1216
+ input_shape = inputs_embeds.size()[:-1]
1217
+ else:
1218
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1219
+
1220
+ if inputs_embeds is None:
1221
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1222
+
1223
+ embed_pos = self.embed_positions(input_shape)
1224
+ hidden_states = inputs_embeds + embed_pos
1225
+
1226
+ # Add global tokens
1227
+ n, t, d = hidden_states.size()
1228
+ global_idx = torch.arange(self.num_global_tokens, device=hidden_states.device).reshape(1, -1)
1229
+ hidden_states = torch.cat([self.global_embeddings(global_idx).expand(n, -1, -1), hidden_states], dim=-2)
1230
+
1231
+ hidden_states = self.layernorm_embedding(hidden_states)
1232
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1233
+
1234
+ # expand attention_mask
1235
+ if attention_mask is not None:
1236
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1237
+ attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
1238
+
1239
+ encoder_states = () if output_hidden_states else None
1240
+ all_attentions = () if output_attentions else None
1241
+
1242
+ # check if head_mask has a correct number of layers specified if desired
1243
+ if head_mask is not None:
1244
+ if head_mask.size()[0] != (len(self.layers)):
1245
+ raise ValueError(
1246
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
1247
+ )
1248
+
1249
+ for idx, encoder_layer in enumerate(self.layers):
1250
+ if output_hidden_states:
1251
+ encoder_states = encoder_states + (hidden_states,)
1252
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1253
+ dropout_probability = random.uniform(0, 1)
1254
+ if self.training and (dropout_probability < self.layerdrop): # skip the layer
1255
+ layer_outputs = (None, None)
1256
+ else:
1257
+ if self.gradient_checkpointing and self.training:
1258
+
1259
+ def create_custom_forward(module):
1260
+ def custom_forward(*inputs):
1261
+ return module(*inputs, output_attentions)
1262
+
1263
+ return custom_forward
1264
+
1265
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1266
+ create_custom_forward(encoder_layer),
1267
+ hidden_states,
1268
+ attention_mask,
1269
+ (head_mask[idx] if head_mask is not None else None),
1270
+ )
1271
+ else:
1272
+ layer_outputs = encoder_layer(
1273
+ hidden_states,
1274
+ attention_mask,
1275
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1276
+ output_attentions=output_attentions,
1277
+ )
1278
+
1279
+ hidden_states = layer_outputs[0]
1280
+
1281
+ if output_attentions:
1282
+ all_attentions = all_attentions + (layer_outputs[1],)
1283
+
1284
+ if output_hidden_states:
1285
+ encoder_states = encoder_states + (hidden_states,)
1286
+
1287
+ if not return_dict:
1288
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
1289
+ return BaseModelOutput(
1290
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
1291
+ )
1292
+
1293
+
1294
+ class LSGBartDecoder(LSGBartPretrainedModel):
1295
+ """
1296
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a :class:`LSGBartDecoderLayer`
1297
+ Args:
1298
+ config: BartConfig
1299
+ embed_tokens (nn.Embedding): output embedding
1300
+ """
1301
+
1302
+ def __init__(self, config, embed_tokens=None):
1303
+
1304
+ super().__init__(config)
1305
+ self.dropout = config.dropout
1306
+ self.layerdrop = config.decoder_layerdrop
1307
+ self.padding_idx = config.pad_token_id
1308
+ self.max_target_positions = config.max_position_embeddings
1309
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
1310
+
1311
+ if embed_tokens is not None:
1312
+ self.embed_tokens = embed_tokens
1313
+ else:
1314
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
1315
+
1316
+ self.embed_positions = LSGBartLearnedPositionalEmbedding(
1317
+ config.max_position_embeddings,
1318
+ config.d_model,
1319
+ )
1320
+ self.layers = nn.ModuleList([LSGBartDecoderLayer(config) for _ in range(config.decoder_layers)])
1321
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
1322
+
1323
+ self.gradient_checkpointing = False
1324
+
1325
+ # Initialize weights and apply final processing
1326
+ self.post_init()
1327
+
1328
+ def get_input_embeddings(self):
1329
+ return self.embed_tokens
1330
+
1331
+ def set_input_embeddings(self, value):
1332
+ self.embed_tokens = value
1333
+
1334
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
1335
+ # create causal mask
1336
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1337
+ combined_attention_mask = None
1338
+ if input_shape[-1] > 1:
1339
+ combined_attention_mask = _make_causal_mask(
1340
+ input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length
1341
+ ).to(self.device)
1342
+
1343
+ if attention_mask is not None:
1344
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1345
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
1346
+ combined_attention_mask = (
1347
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
1348
+ )
1349
+
1350
+ return combined_attention_mask
1351
+
1352
+ def forward(
1353
+ self,
1354
+ input_ids=None,
1355
+ attention_mask=None,
1356
+ encoder_hidden_states=None,
1357
+ encoder_attention_mask=None,
1358
+ head_mask=None,
1359
+ cross_attn_head_mask=None,
1360
+ past_key_values=None,
1361
+ inputs_embeds=None,
1362
+ use_cache=None,
1363
+ output_attentions=None,
1364
+ output_hidden_states=None,
1365
+ return_dict=None,
1366
+ ):
1367
+
1368
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1369
+ output_hidden_states = (
1370
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1371
+ )
1372
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1373
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1374
+
1375
+ # retrieve input_ids and inputs_embeds
1376
+ if input_ids is not None and inputs_embeds is not None:
1377
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1378
+ elif input_ids is not None:
1379
+ input_shape = input_ids.size()
1380
+ input_ids = input_ids.view(-1, input_shape[-1])
1381
+ elif inputs_embeds is not None:
1382
+ input_shape = inputs_embeds.size()[:-1]
1383
+ else:
1384
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1385
+
1386
+ # past_key_values_length
1387
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
1388
+
1389
+ if inputs_embeds is None:
1390
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1391
+
1392
+ # Cut
1393
+ if attention_mask is not None:
1394
+ max_len = int(attention_mask.sum(dim=-1).max())
1395
+ inputs_embeds = inputs_embeds[:, :max_len]
1396
+ attention_mask = attention_mask[..., :max_len]
1397
+ input_shape = inputs_embeds.size()[:-1]
1398
+
1399
+ attention_mask = self._prepare_decoder_attention_mask(
1400
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1401
+ )
1402
+
1403
+ # expand encoder attention mask
1404
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1405
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1406
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
1407
+
1408
+ # embed positions
1409
+ positions = self.embed_positions(input_shape, past_key_values_length)
1410
+
1411
+ hidden_states = inputs_embeds + positions
1412
+ hidden_states = self.layernorm_embedding(hidden_states)
1413
+
1414
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
1415
+
1416
+ # decoder layers
1417
+ all_hidden_states = () if output_hidden_states else None
1418
+ all_self_attns = () if output_attentions else None
1419
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
1420
+ next_decoder_cache = () if use_cache else None
1421
+
1422
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1423
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
1424
+ if attn_mask is not None:
1425
+ if attn_mask.size()[0] != (len(self.layers)):
1426
+ raise ValueError(
1427
+ "The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
1428
+ )
1429
+
1430
+ for idx, decoder_layer in enumerate(self.layers):
1431
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1432
+ if output_hidden_states:
1433
+ all_hidden_states += (hidden_states,)
1434
+ dropout_probability = random.uniform(0, 1)
1435
+ if self.training and (dropout_probability < self.layerdrop):
1436
+ continue
1437
+
1438
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1439
+
1440
+ if self.gradient_checkpointing and self.training:
1441
+
1442
+ if use_cache:
1443
+ logger.warning(
1444
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1445
+ )
1446
+ use_cache = False
1447
+
1448
+ def create_custom_forward(module):
1449
+ def custom_forward(*inputs):
1450
+ # None for past_key_value
1451
+ return module(*inputs, output_attentions, use_cache)
1452
+
1453
+ return custom_forward
1454
+
1455
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1456
+ create_custom_forward(decoder_layer),
1457
+ hidden_states,
1458
+ attention_mask,
1459
+ encoder_hidden_states,
1460
+ encoder_attention_mask,
1461
+ head_mask[idx] if head_mask is not None else None,
1462
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1463
+ None,
1464
+ )
1465
+ else:
1466
+
1467
+ layer_outputs = decoder_layer(
1468
+ hidden_states,
1469
+ attention_mask=attention_mask,
1470
+ encoder_hidden_states=encoder_hidden_states,
1471
+ encoder_attention_mask=encoder_attention_mask,
1472
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
1473
+ cross_attn_layer_head_mask=(
1474
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
1475
+ ),
1476
+ past_key_value=past_key_value,
1477
+ output_attentions=output_attentions,
1478
+ use_cache=use_cache,
1479
+ )
1480
+ hidden_states = layer_outputs[0]
1481
+
1482
+ if use_cache:
1483
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1484
+
1485
+ if output_attentions:
1486
+ all_self_attns += (layer_outputs[1],)
1487
+
1488
+ if encoder_hidden_states is not None:
1489
+ all_cross_attentions += (layer_outputs[2],)
1490
+
1491
+ # add hidden states from the last decoder layer
1492
+ if output_hidden_states:
1493
+ all_hidden_states += (hidden_states,)
1494
+
1495
+ next_cache = next_decoder_cache if use_cache else None
1496
+ if not return_dict:
1497
+ return tuple(
1498
+ v
1499
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1500
+ if v is not None
1501
+ )
1502
+ return BaseModelOutputWithPastAndCrossAttentions(
1503
+ last_hidden_state=hidden_states,
1504
+ past_key_values=next_cache,
1505
+ hidden_states=all_hidden_states,
1506
+ attentions=all_self_attns,
1507
+ cross_attentions=all_cross_attentions,
1508
+ )
1509
+
1510
+
1511
+ class LSGBartModel(LSGBartPretrainedModel):
1512
+
1513
+ def __init__(self, config):
1514
+
1515
+ super().__init__(config)
1516
+
1517
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1518
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1519
+ self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
1520
+ self.num_global_tokens = config.num_global_tokens
1521
+ self.encoder = LSGBartEncoder(config, self.shared)
1522
+ self.decoder = LSGBartDecoder(config, self.shared)
1523
+
1524
+ # Initialize weights and apply final processing
1525
+ self.post_init()
1526
+
1527
+ def get_input_embeddings(self):
1528
+ return self.shared
1529
+
1530
+ def set_input_embeddings(self, value):
1531
+ self.shared = value
1532
+ self.encoder.embed_tokens = self.shared
1533
+ self.decoder.embed_tokens = self.shared
1534
+
1535
+ def get_encoder(self):
1536
+ return self.encoder
1537
+
1538
+ def get_decoder(self):
1539
+ return self.decoder
1540
+
1541
+ def forward(
1542
+ self,
1543
+ input_ids=None,
1544
+ attention_mask=None,
1545
+ decoder_input_ids=None,
1546
+ decoder_attention_mask=None,
1547
+ head_mask=None,
1548
+ decoder_head_mask=None,
1549
+ cross_attn_head_mask=None,
1550
+ encoder_outputs=None,
1551
+ past_key_values=None,
1552
+ inputs_embeds=None,
1553
+ decoder_inputs_embeds=None,
1554
+ use_cache=None,
1555
+ output_attentions=None,
1556
+ output_hidden_states=None,
1557
+ return_dict=None,
1558
+ ):
1559
+
1560
+ # different to other models, Bart automatically creates decoder_input_ids from
1561
+ # input_ids if no decoder_input_ids are provided
1562
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1563
+ decoder_input_ids = shift_tokens_right(
1564
+ input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
1565
+ )
1566
+
1567
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1568
+ output_hidden_states = (
1569
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1570
+ )
1571
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1572
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1573
+
1574
+ if encoder_outputs is None:
1575
+ encoder_outputs = self.encoder(
1576
+ input_ids=input_ids,
1577
+ attention_mask=attention_mask,
1578
+ head_mask=head_mask,
1579
+ inputs_embeds=inputs_embeds,
1580
+ output_attentions=output_attentions,
1581
+ output_hidden_states=output_hidden_states,
1582
+ return_dict=return_dict,
1583
+ )
1584
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1585
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1586
+ encoder_outputs = BaseModelOutput(
1587
+ last_hidden_state=encoder_outputs[0],
1588
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1589
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1590
+ )
1591
+
1592
+ # Pad mask for global tokens
1593
+ if self.pass_global_tokens_to_decoder:
1594
+ attention_mask = torch.nn.functional.pad(attention_mask, pad=(self.num_global_tokens, 0), value=1)
1595
+
1596
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1597
+ decoder_outputs = self.decoder(
1598
+ input_ids=decoder_input_ids,
1599
+ attention_mask=decoder_attention_mask,
1600
+ encoder_hidden_states=encoder_outputs[0],
1601
+ encoder_attention_mask=attention_mask,
1602
+ head_mask=decoder_head_mask,
1603
+ cross_attn_head_mask=cross_attn_head_mask,
1604
+ past_key_values=past_key_values,
1605
+ inputs_embeds=decoder_inputs_embeds,
1606
+ use_cache=use_cache,
1607
+ output_attentions=output_attentions,
1608
+ output_hidden_states=output_hidden_states,
1609
+ return_dict=return_dict,
1610
+ )
1611
+
1612
+ if not return_dict:
1613
+ return decoder_outputs + encoder_outputs
1614
+
1615
+ return Seq2SeqModelOutput(
1616
+ last_hidden_state=decoder_outputs.last_hidden_state,
1617
+ past_key_values=decoder_outputs.past_key_values,
1618
+ decoder_hidden_states=decoder_outputs.hidden_states,
1619
+ decoder_attentions=decoder_outputs.attentions,
1620
+ cross_attentions=decoder_outputs.cross_attentions,
1621
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1622
+ encoder_hidden_states=encoder_outputs.hidden_states,
1623
+ encoder_attentions=encoder_outputs.attentions,
1624
+ )
1625
+
1626
+
1627
+ class LSGBartForConditionalGeneration(LSGBartPretrainedModel):
1628
+
1629
+ base_model_prefix = "model"
1630
+ _keys_to_ignore_on_load_missing = [r"final_logits_bias", r"lm_head\.weight"]
1631
+
1632
+ def __init__(self, config):
1633
+
1634
+ super().__init__(config)
1635
+ self.model = LSGBartModel(config)
1636
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1637
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1638
+
1639
+ # Initialize weights and apply final processing
1640
+ self.post_init()
1641
+
1642
+ def get_encoder(self):
1643
+ return self.model.get_encoder()
1644
+
1645
+ def get_decoder(self):
1646
+ return self.model.get_decoder()
1647
+
1648
+ def resize_token_embeddings(self, new_num_tokens):
1649
+ new_embeddings = super().resize_token_embeddings(new_num_tokens)
1650
+ self._resize_final_logits_bias(new_num_tokens)
1651
+ return new_embeddings
1652
+
1653
+ def _resize_final_logits_bias(self, new_num_tokens):
1654
+ old_num_tokens = self.final_logits_bias.shape[-1]
1655
+ if new_num_tokens <= old_num_tokens:
1656
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1657
+ else:
1658
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1659
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1660
+ self.register_buffer("final_logits_bias", new_bias)
1661
+
1662
+ def get_output_embeddings(self):
1663
+ return self.lm_head
1664
+
1665
+ def set_output_embeddings(self, new_embeddings):
1666
+ self.lm_head = new_embeddings
1667
+
1668
+ def forward(
1669
+ self,
1670
+ input_ids=None,
1671
+ attention_mask=None,
1672
+ decoder_input_ids=None,
1673
+ decoder_attention_mask=None,
1674
+ head_mask=None,
1675
+ decoder_head_mask=None,
1676
+ cross_attn_head_mask=None,
1677
+ encoder_outputs=None,
1678
+ past_key_values=None,
1679
+ inputs_embeds=None,
1680
+ decoder_inputs_embeds=None,
1681
+ labels=None,
1682
+ use_cache=None,
1683
+ output_attentions=None,
1684
+ output_hidden_states=None,
1685
+ return_dict=None,
1686
+ ):
1687
+
1688
+ r"""
1689
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1690
+ Labels for computing the masked language modeling loss. Indices should either be in ``[0, ...,
1691
+ config.vocab_size]`` or -100 (see ``input_ids`` docstring). Tokens with indices set to ``-100`` are ignored
1692
+ (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``.
1693
+ Returns:
1694
+ """
1695
+
1696
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1697
+
1698
+ if labels is not None:
1699
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1700
+ decoder_input_ids = shift_tokens_right(
1701
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1702
+ )
1703
+
1704
+ outputs = self.model(
1705
+ input_ids,
1706
+ attention_mask=attention_mask,
1707
+ decoder_input_ids=decoder_input_ids,
1708
+ encoder_outputs=encoder_outputs,
1709
+ decoder_attention_mask=decoder_attention_mask,
1710
+ head_mask=head_mask,
1711
+ decoder_head_mask=decoder_head_mask,
1712
+ cross_attn_head_mask=cross_attn_head_mask,
1713
+ past_key_values=past_key_values,
1714
+ inputs_embeds=inputs_embeds,
1715
+ decoder_inputs_embeds=decoder_inputs_embeds,
1716
+ use_cache=use_cache,
1717
+ output_attentions=output_attentions,
1718
+ output_hidden_states=output_hidden_states,
1719
+ return_dict=return_dict,
1720
+ )
1721
+
1722
+
1723
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1724
+
1725
+ masked_lm_loss = None
1726
+ if labels is not None:
1727
+ loss_fct = CrossEntropyLoss()
1728
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1729
+
1730
+ if not return_dict:
1731
+ output = (lm_logits,) + outputs[1:]
1732
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1733
+
1734
+ return Seq2SeqLMOutput(
1735
+ loss=masked_lm_loss,
1736
+ logits=lm_logits,
1737
+ past_key_values=outputs.past_key_values,
1738
+ decoder_hidden_states=outputs.decoder_hidden_states,
1739
+ decoder_attentions=outputs.decoder_attentions,
1740
+ cross_attentions=outputs.cross_attentions,
1741
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1742
+ encoder_hidden_states=outputs.encoder_hidden_states,
1743
+ encoder_attentions=outputs.encoder_attentions,
1744
+ )
1745
+
1746
+ def prepare_inputs_for_generation(
1747
+ self,
1748
+ decoder_input_ids,
1749
+ past=None,
1750
+ attention_mask=None,
1751
+ head_mask=None,
1752
+ decoder_head_mask=None,
1753
+ cross_attn_head_mask=None,
1754
+ use_cache=None,
1755
+ encoder_outputs=None,
1756
+ **kwargs
1757
+ ):
1758
+ # cut decoder_input_ids if past is used
1759
+ if past is not None:
1760
+ decoder_input_ids = decoder_input_ids[:, -1:]
1761
+
1762
+ return {
1763
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1764
+ "encoder_outputs": encoder_outputs,
1765
+ "past_key_values": past,
1766
+ "decoder_input_ids": decoder_input_ids,
1767
+ "attention_mask": attention_mask,
1768
+ "head_mask": head_mask,
1769
+ "decoder_head_mask": decoder_head_mask,
1770
+ "cross_attn_head_mask": cross_attn_head_mask,
1771
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1772
+ }
1773
+
1774
+ def prepare_decoder_input_ids_from_labels(self, labels):
1775
+ return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
1776
+
1777
+ @staticmethod
1778
+ def _reorder_cache(past, beam_idx):
1779
+ reordered_past = ()
1780
+ for layer_past in past:
1781
+ # cached cross_attention states don't have to be reordered -> they are always the same
1782
+ reordered_past += (
1783
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],
1784
+ )
1785
+ return reordered_past
1786
+
1787
+
1788
+ class LSGBartForSequenceClassification(LSGBartPretrainedModel):
1789
+
1790
+ def __init__(self, config, **kwargs):
1791
+
1792
+ super().__init__(config, **kwargs)
1793
+ self.model = LSGBartModel(config)
1794
+ self.classification_head = LSGBartClassificationHead(
1795
+ config.d_model,
1796
+ config.d_model,
1797
+ config.num_labels,
1798
+ config.classifier_dropout,
1799
+ )
1800
+ self.model._init_weights(self.classification_head.dense)
1801
+ self.model._init_weights(self.classification_head.out_proj)
1802
+
1803
+ def forward(
1804
+ self,
1805
+ input_ids=None,
1806
+ attention_mask=None,
1807
+ decoder_input_ids=None,
1808
+ decoder_attention_mask=None,
1809
+ head_mask=None,
1810
+ decoder_head_mask=None,
1811
+ cross_attn_head_mask=None,
1812
+ encoder_outputs=None,
1813
+ inputs_embeds=None,
1814
+ decoder_inputs_embeds=None,
1815
+ labels=None,
1816
+ use_cache=None,
1817
+ output_attentions=None,
1818
+ output_hidden_states=None,
1819
+ return_dict=None,
1820
+ ):
1821
+
1822
+ r"""
1823
+ labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
1824
+ Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
1825
+ config.num_labels - 1]`. If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1826
+ """
1827
+
1828
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1829
+ if labels is not None:
1830
+ use_cache = False
1831
+
1832
+ if input_ids is None and inputs_embeds is not None:
1833
+ raise NotImplementedError(
1834
+ f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
1835
+ )
1836
+
1837
+ outputs = self.model(
1838
+ input_ids,
1839
+ attention_mask=attention_mask,
1840
+ decoder_input_ids=decoder_input_ids,
1841
+ decoder_attention_mask=decoder_attention_mask,
1842
+ head_mask=head_mask,
1843
+ decoder_head_mask=decoder_head_mask,
1844
+ cross_attn_head_mask=cross_attn_head_mask,
1845
+ encoder_outputs=encoder_outputs,
1846
+ inputs_embeds=inputs_embeds,
1847
+ decoder_inputs_embeds=decoder_inputs_embeds,
1848
+ use_cache=use_cache,
1849
+ output_attentions=output_attentions,
1850
+ output_hidden_states=output_hidden_states,
1851
+ return_dict=return_dict,
1852
+ )
1853
+ hidden_states = outputs[0] # last hidden state
1854
+
1855
+ eos_mask = input_ids.eq(self.config.eos_token_id)
1856
+
1857
+ t, t_ = eos_mask.size()[-1], hidden_states.size()[-2]
1858
+ if t > t_:
1859
+ eos_mask = eos_mask[:, :t_]
1860
+
1861
+ if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
1862
+ raise ValueError("All examples must have the same number of <eos> tokens.")
1863
+ sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
1864
+ :, -1, :
1865
+ ]
1866
+ logits = self.classification_head(sentence_representation)
1867
+
1868
+ loss = None
1869
+ if labels is not None:
1870
+ if self.config.problem_type is None:
1871
+ if self.config.num_labels == 1:
1872
+ self.config.problem_type = "regression"
1873
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1874
+ self.config.problem_type = "single_label_classification"
1875
+ else:
1876
+ self.config.problem_type = "multi_label_classification"
1877
+
1878
+ if self.config.problem_type == "regression":
1879
+ loss_fct = MSELoss()
1880
+ if self.config.num_labels == 1:
1881
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
1882
+ else:
1883
+ loss = loss_fct(logits, labels)
1884
+ elif self.config.problem_type == "single_label_classification":
1885
+ loss_fct = CrossEntropyLoss()
1886
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
1887
+ elif self.config.problem_type == "multi_label_classification":
1888
+ loss_fct = BCEWithLogitsLoss()
1889
+ loss = loss_fct(logits, labels)
1890
+ if not return_dict:
1891
+ output = (logits,) + outputs[1:]
1892
+ return ((loss,) + output) if loss is not None else output
1893
+
1894
+ return Seq2SeqSequenceClassifierOutput(
1895
+ loss=loss,
1896
+ logits=logits,
1897
+ past_key_values=outputs.past_key_values,
1898
+ decoder_hidden_states=outputs.decoder_hidden_states,
1899
+ decoder_attentions=outputs.decoder_attentions,
1900
+ cross_attentions=outputs.cross_attentions,
1901
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1902
+ encoder_hidden_states=outputs.encoder_hidden_states,
1903
+ encoder_attentions=outputs.encoder_attentions,
1904
+ )
1905
+
1906
+
1907
+ class LSGBartForQuestionAnswering(LSGBartPretrainedModel):
1908
+
1909
+ def __init__(self, config):
1910
+
1911
+ super().__init__(config)
1912
+
1913
+ config.num_labels = 2
1914
+ self.num_labels = config.num_labels
1915
+
1916
+ self.model = LSGBartModel(config)
1917
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1918
+
1919
+ self.model._init_weights(self.qa_outputs)
1920
+
1921
+ def forward(
1922
+ self,
1923
+ input_ids=None,
1924
+ attention_mask=None,
1925
+ decoder_input_ids=None,
1926
+ decoder_attention_mask=None,
1927
+ head_mask=None,
1928
+ decoder_head_mask=None,
1929
+ cross_attn_head_mask=None,
1930
+ encoder_outputs=None,
1931
+ start_positions=None,
1932
+ end_positions=None,
1933
+ inputs_embeds=None,
1934
+ decoder_inputs_embeds=None,
1935
+ use_cache=None,
1936
+ output_attentions=None,
1937
+ output_hidden_states=None,
1938
+ return_dict=None,
1939
+ ):
1940
+
1941
+ r"""
1942
+ start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
1943
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1944
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1945
+ are not taken into account for computing the loss.
1946
+ end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
1947
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1948
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1949
+ are not taken into account for computing the loss.
1950
+ """
1951
+
1952
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1953
+ if start_positions is not None and end_positions is not None:
1954
+ use_cache = False
1955
+
1956
+ outputs = self.model(
1957
+ input_ids,
1958
+ attention_mask=attention_mask,
1959
+ decoder_input_ids=decoder_input_ids,
1960
+ decoder_attention_mask=decoder_attention_mask,
1961
+ head_mask=head_mask,
1962
+ decoder_head_mask=decoder_head_mask,
1963
+ cross_attn_head_mask=cross_attn_head_mask,
1964
+ encoder_outputs=encoder_outputs,
1965
+ inputs_embeds=inputs_embeds,
1966
+ decoder_inputs_embeds=decoder_inputs_embeds,
1967
+ use_cache=use_cache,
1968
+ output_attentions=output_attentions,
1969
+ output_hidden_states=output_hidden_states,
1970
+ return_dict=return_dict,
1971
+ )
1972
+
1973
+ sequence_output = outputs[0]
1974
+
1975
+ logits = self.qa_outputs(sequence_output)
1976
+ start_logits, end_logits = logits.split(1, dim=-1)
1977
+ start_logits = start_logits.squeeze(-1).contiguous()
1978
+ end_logits = end_logits.squeeze(-1).contiguous()
1979
+
1980
+ total_loss = None
1981
+ if start_positions is not None and end_positions is not None:
1982
+ # If we are on multi-GPU, split add a dimension
1983
+ if len(start_positions.size()) > 1:
1984
+ start_positions = start_positions.squeeze(-1)
1985
+ if len(end_positions.size()) > 1:
1986
+ end_positions = end_positions.squeeze(-1)
1987
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1988
+ ignored_index = start_logits.size(1)
1989
+ start_positions = start_positions.clamp(0, ignored_index)
1990
+ end_positions = end_positions.clamp(0, ignored_index)
1991
+
1992
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1993
+ start_loss = loss_fct(start_logits, start_positions)
1994
+ end_loss = loss_fct(end_logits, end_positions)
1995
+ total_loss = (start_loss + end_loss) / 2
1996
+
1997
+ if not return_dict:
1998
+ output = (
1999
+ start_logits,
2000
+ end_logits,
2001
+ ) + outputs[1:]
2002
+ return ((total_loss,) + output) if total_loss is not None else output
2003
+
2004
+ return Seq2SeqQuestionAnsweringModelOutput(
2005
+ loss=total_loss,
2006
+ start_logits=start_logits,
2007
+ end_logits=end_logits,
2008
+ past_key_values=outputs.past_key_values,
2009
+ decoder_hidden_states=outputs.decoder_hidden_states,
2010
+ decoder_attentions=outputs.decoder_attentions,
2011
+ cross_attentions=outputs.cross_attentions,
2012
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
2013
+ encoder_hidden_states=outputs.encoder_hidden_states,
2014
+ encoder_attentions=outputs.encoder_attentions,
2015
+ )
2016
+
2017
+
2018
+ class LSGBartDecoderWrapper(LSGBartPretrainedModel):
2019
+ """
2020
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
2021
+ used in combination with the :class:`~transformers.EncoderDecoderModel` framework.
2022
+ """
2023
+
2024
+ def __init__(self, config):
2025
+ super().__init__(config)
2026
+ self.decoder = LSGBartDecoder(config)
2027
+
2028
+ def forward(self, *args, **kwargs):
2029
+ return self.decoder(*args, **kwargs)
2030
+
2031
+
2032
+ class LSGBartForCausalLM(LSGBartPretrainedModel):
2033
+
2034
+ def __init__(self, config):
2035
+
2036
+ super().__init__(config)
2037
+ config = copy.deepcopy(config)
2038
+ config.is_decoder = True
2039
+ config.is_encoder_decoder = False
2040
+ self.model = LSGBartDecoderWrapper(config)
2041
+
2042
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
2043
+
2044
+ # Initialize weights and apply final processing
2045
+ self.post_init()
2046
+
2047
+ def get_input_embeddings(self):
2048
+ return self.model.decoder.embed_tokens
2049
+
2050
+ def set_input_embeddings(self, value):
2051
+ self.model.decoder.embed_tokens = value
2052
+
2053
+ def get_output_embeddings(self):
2054
+ return self.lm_head
2055
+
2056
+ def set_output_embeddings(self, new_embeddings):
2057
+ self.lm_head = new_embeddings
2058
+
2059
+ def set_decoder(self, decoder):
2060
+ self.model.decoder = decoder
2061
+
2062
+ def get_decoder(self):
2063
+ return self.model.decoder
2064
+
2065
+ def forward(
2066
+ self,
2067
+ input_ids=None,
2068
+ attention_mask=None,
2069
+ encoder_hidden_states=None,
2070
+ encoder_attention_mask=None,
2071
+ head_mask=None,
2072
+ cross_attn_head_mask=None,
2073
+ past_key_values=None,
2074
+ inputs_embeds=None,
2075
+ labels=None,
2076
+ use_cache=None,
2077
+ output_attentions=None,
2078
+ output_hidden_states=None,
2079
+ return_dict=None,
2080
+ ):
2081
+
2082
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
2083
+ output_hidden_states = (
2084
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
2085
+ )
2086
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
2087
+
2088
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
2089
+ outputs = self.model.decoder(
2090
+ input_ids=input_ids,
2091
+ attention_mask=attention_mask,
2092
+ encoder_hidden_states=encoder_hidden_states,
2093
+ encoder_attention_mask=encoder_attention_mask,
2094
+ head_mask=head_mask,
2095
+ cross_attn_head_mask=cross_attn_head_mask,
2096
+ past_key_values=past_key_values,
2097
+ inputs_embeds=inputs_embeds,
2098
+ use_cache=use_cache,
2099
+ output_attentions=output_attentions,
2100
+ output_hidden_states=output_hidden_states,
2101
+ return_dict=return_dict,
2102
+ )
2103
+
2104
+ logits = self.lm_head(outputs[0])
2105
+
2106
+ loss = None
2107
+ if labels is not None:
2108
+ loss_fct = CrossEntropyLoss()
2109
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
2110
+
2111
+ if not return_dict:
2112
+ output = (logits,) + outputs[1:]
2113
+ return (loss,) + output if loss is not None else output
2114
+
2115
+ return CausalLMOutputWithCrossAttentions(
2116
+ loss=loss,
2117
+ logits=logits,
2118
+ past_key_values=outputs.past_key_values,
2119
+ hidden_states=outputs.hidden_states,
2120
+ attentions=outputs.attentions,
2121
+ cross_attentions=outputs.cross_attentions,
2122
+ )
2123
+
2124
+ def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, use_cache=None, **kwargs):
2125
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
2126
+ if attention_mask is None:
2127
+ attention_mask = input_ids.new_ones(input_ids.shape)
2128
+
2129
+ if past:
2130
+ input_ids = input_ids[:, -1:]
2131
+ # first step, decoder_cached_states are empty
2132
+ return {
2133
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
2134
+ "attention_mask": attention_mask,
2135
+ "past_key_values": past,
2136
+ "use_cache": use_cache,
2137
+ }
2138
+
2139
+ @staticmethod
2140
+ def _reorder_cache(past, beam_idx):
2141
+ reordered_past = ()
2142
+ for layer_past in past:
2143
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
2144
+ return reordered_past
2145
+
2146
+
2147
+ def str_to_class(classname):
2148
+ return getattr(sys.modules[__name__], classname)
2149
+
2150
+ # Register model in Auto API
2151
+ try:
2152
+ LSGBartConfig.register_for_auto_class()
2153
+ for key, value in AUTO_MAP.items():
2154
+ str_to_class(value.split(".")[-1]).register_for_auto_class(key)
2155
+ except:
2156
+ warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
2157
+ warn("Update to transformers >= 4.17.0 to fix.")
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aaa7c2f67804eb3b01d0b555a6e9600fa80b188a9506560aa88ab19008a2e4b7
3
+ size 653914167
special_tokens_map.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": false}}
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"errors": "replace", "bos_token": "<s>", "eos_token": "</s>", "sep_token": "</s>", "cls_token": "<s>", "unk_token": "<unk>", "pad_token": "<pad>", "mask_token": "<mask>", "add_prefix_space": false, "trim_offsets": true, "model_max_length": 16384, "special_tokens_map_file": null, "name_or_path": "/data/ccondevaux/lsg/text-summarization/tmp/arxiv/lsg_local_large_lr_16384_full_trained", "tokenizer_class": "BartTokenizer"}
vocab.json ADDED
The diff for this file is too large to render. See raw diff