Auruncus commited on
Commit
d5e62a4
1 Parent(s): 36e2a49

Upload LSGMBartForConditionalGeneration

Browse files
Files changed (5) hide show
  1. README.md +201 -0
  2. config.json +78 -0
  3. generation_config.json +9 -0
  4. model.safetensors +3 -0
  5. modeling_lsg_mbart.py +1102 -0
README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
200
+
201
+
config.json ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "lsg-mbart-lsh-ru-128-4-4096-v2-1",
3
+ "_num_labels": 3,
4
+ "activation_dropout": 0.0,
5
+ "activation_function": "gelu",
6
+ "adaptive": true,
7
+ "add_bias_logits": false,
8
+ "add_final_layer_norm": true,
9
+ "architectures": [
10
+ "LSGMBartForConditionalGeneration"
11
+ ],
12
+ "attention_dropout": 0.0,
13
+ "auto_map": {
14
+ "AutoConfig": "modeling_lsg_mbart.LSGMBartConfig",
15
+ "AutoModel": "modeling_lsg_mbart.LSGMBartModel",
16
+ "AutoModelForCausalLM": "modeling_lsg_mbart.LSGMBartForCausalLM",
17
+ "AutoModelForQuestionAnswering": "modeling_lsg_mbart.LSGMBartForQuestionAnswering",
18
+ "AutoModelForSeq2SeqLM": "modeling_lsg_mbart.LSGMBartForConditionalGeneration",
19
+ "AutoModelForSequenceClassification": "modeling_lsg_mbart.LSGMBartForSequenceClassification"
20
+ },
21
+ "base_model_prefix": "lsg",
22
+ "block_size": 128,
23
+ "bos_token_id": 0,
24
+ "classif_dropout": 0.0,
25
+ "classifier_dropout": 0.0,
26
+ "d_model": 1024,
27
+ "decoder_attention_heads": 16,
28
+ "decoder_ffn_dim": 4096,
29
+ "decoder_layerdrop": 0.0,
30
+ "decoder_layers": 12,
31
+ "dropout": 0.1,
32
+ "encoder_attention_heads": 16,
33
+ "encoder_ffn_dim": 4096,
34
+ "encoder_layerdrop": 0.0,
35
+ "encoder_layers": 12,
36
+ "eos_token_id": 2,
37
+ "forced_eos_token_id": 2,
38
+ "id2label": {
39
+ "0": "LABEL_0",
40
+ "1": "LABEL_1",
41
+ "2": "LABEL_2"
42
+ },
43
+ "init_std": 0.02,
44
+ "is_encoder_decoder": true,
45
+ "label2id": {
46
+ "LABEL_0": 0,
47
+ "LABEL_1": 1,
48
+ "LABEL_2": 2
49
+ },
50
+ "lsh_num_pre_rounds": 1,
51
+ "mask_first_token": false,
52
+ "max_length": 1024,
53
+ "max_position_embeddings": 16384,
54
+ "model_type": "mbart",
55
+ "normalize_before": true,
56
+ "normalize_embedding": true,
57
+ "num_beams": 5,
58
+ "num_global_tokens": 24,
59
+ "num_hidden_layers": 12,
60
+ "output_past": true,
61
+ "pad_token_id": 1,
62
+ "pass_global_tokens_to_decoder": true,
63
+ "pool_with_global": true,
64
+ "scale_embedding": true,
65
+ "sparse_block_size": 128,
66
+ "sparsity_factor": 4,
67
+ "sparsity_type": "lsh",
68
+ "static_position_embeddings": false,
69
+ "task_specific_params": {
70
+ "translation_en_to_ro": {
71
+ "decoder_start_token_id": 250020
72
+ }
73
+ },
74
+ "torch_dtype": "float32",
75
+ "transformers_version": "4.38.2",
76
+ "use_cache": true,
77
+ "vocab_size": 25137
78
+ }
generation_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 0,
3
+ "eos_token_id": 2,
4
+ "forced_eos_token_id": 2,
5
+ "max_length": 1024,
6
+ "num_beams": 5,
7
+ "pad_token_id": 1,
8
+ "transformers_version": "4.38.2"
9
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0082665f62bb3a27ad8335a1bf5345dfda31929db24f72d41008538464e6992
3
+ size 1650345508
modeling_lsg_mbart.py ADDED
@@ -0,0 +1,1102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import warn
2
+ import torch
3
+ from transformers.models.mbart.modeling_mbart import *
4
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
5
+ import torch.nn as nn
6
+ import sys
7
+
8
+ AUTO_MAP = {
9
+ "AutoModel": "modeling_lsg_mbart.LSGMBartModel",
10
+ "AutoModelForCausalLM": "modeling_lsg_mbart.LSGMBartForCausalLM",
11
+ "AutoModelForQuestionAnswering": "modeling_lsg_mbart.LSGMBartForQuestionAnswering",
12
+ "AutoModelForSequenceClassification": "modeling_lsg_mbart.LSGMBartForSequenceClassification",
13
+ "AutoModelForSeq2SeqLM": "modeling_lsg_mbart.LSGMBartForConditionalGeneration"
14
+ }
15
+
16
+ class LSGMBartConfig(MBartConfig):
17
+ """
18
+ This class overrides :class:`~transformers.MBartConfig`. Please check the superclass for the appropriate
19
+ documentation alongside usage examples.
20
+ """
21
+
22
+ base_model_prefix = "lsg"
23
+ model_type = "mbart"
24
+ keys_to_ignore_at_inference = ["past_key_values"]
25
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
26
+
27
+ def __init__(
28
+ self,
29
+ adaptive=True,
30
+ base_model_prefix="lsg",
31
+ block_size=128,
32
+ lsh_num_pre_rounds=1,
33
+ mask_first_token=False,
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.mask_first_token = mask_first_token
51
+ self.num_global_tokens = num_global_tokens
52
+ self.pass_global_tokens_to_decoder = pass_global_tokens_to_decoder
53
+ self.pool_with_global = pool_with_global
54
+ self.sparse_block_size = sparse_block_size
55
+ self.sparsity_factor = sparsity_factor
56
+ self.sparsity_type = sparsity_type
57
+
58
+ if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride", "block_stride", "bos_pooling"]:
59
+ logger.warning(
60
+ "[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride', 'bos_pooling'], \
61
+ setting sparsity_type=None, computation will skip sparse attention")
62
+ self.sparsity_type = None
63
+
64
+ if self.sparsity_type in ["stride", "block_stride"]:
65
+ if self.sparsity_factor > self.encoder_attention_heads:
66
+ logger.warning(
67
+ "[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
68
+ )
69
+
70
+ if self.num_global_tokens < 1:
71
+ logger.warning(
72
+ "[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
73
+ )
74
+ self.num_global_tokens = 1
75
+ elif self.num_global_tokens > 512:
76
+ logger.warning(
77
+ "[WARNING CONFIG]: num_global_tokens > 512 is not allowed, setting num_global_tokens=512"
78
+ )
79
+ self.num_global_tokens = 512
80
+
81
+ if self.sparsity_factor > 0:
82
+ assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
83
+ assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
84
+
85
+ if self.mask_first_token and not pool_with_global:
86
+ logger.warning(
87
+ "[WARNING CONFIG]: pool_with_global==False is not compatible with mask_first_token==True. Setting pool_with_global to True.")
88
+ self.pool_with_global = True
89
+
90
+ if hasattr(self, "position_embedding_type"):
91
+ if self.position_embedding_type != "absolute":
92
+ logger.warning(
93
+ "[WARNING CONFIG]: LSG Attention is not compatible with relative positional embedding and will skip its computation. Set position_embedding_type='absolute' to remove this warning.")
94
+
95
+
96
+ class BaseSelfAttention(nn.Module):
97
+
98
+ def __init__(
99
+ self,
100
+ embed_dim,
101
+ num_heads,
102
+ dropout=0.0,
103
+ is_decoder=False,
104
+ bias=True,
105
+ ):
106
+
107
+ super().__init__()
108
+ self.embed_dim = embed_dim
109
+ self.num_heads = num_heads
110
+ self.dropout = dropout
111
+ self.head_dim = embed_dim // num_heads
112
+
113
+ if (self.head_dim * num_heads) != self.embed_dim:
114
+ raise ValueError(
115
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
116
+ f" and `num_heads`: {num_heads})."
117
+ )
118
+ self.scaling = self.head_dim ** -0.5
119
+ self.is_decoder = is_decoder
120
+
121
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
122
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
123
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
124
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
125
+
126
+ def transpose_for_scores(self, x):
127
+ new_x_shape = x.size()[:-1] + (
128
+ self.num_heads,
129
+ self.head_dim,
130
+ )
131
+ x = x.view(*new_x_shape)
132
+ return x.permute(0, 2, 1, 3)
133
+
134
+ def reshape_output(self, context_layer):
135
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
136
+ new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
137
+ return context_layer.view(*new_context_layer_shape)
138
+
139
+ def project_QKV(self, hidden_states):
140
+
141
+ query_layer = self.transpose_for_scores(self.q_proj(hidden_states))
142
+ key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
143
+ value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
144
+ return query_layer, key_layer, value_layer
145
+
146
+
147
+ class BaseAttentionProduct(nn.Module):
148
+
149
+ def __init__(self, config):
150
+ """
151
+ Compute attention: softmax(Q @ K.T) @ V
152
+ """
153
+ super().__init__()
154
+ self.dropout = nn.Dropout(config.attention_dropout)
155
+
156
+ def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
157
+
158
+ d = query_layer.shape[-1]
159
+
160
+ # Take the dot product between "query" and "key" to get the raw attention scores.
161
+ attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
162
+
163
+ del query_layer
164
+ del key_layer
165
+
166
+ if attention_mask is not None:
167
+ # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
168
+ attention_scores = attention_scores + attention_mask
169
+ del attention_mask
170
+
171
+ # Normalize the attention scores to probabilities.
172
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
173
+
174
+ # This is actually dropping out entire tokens to attend to, which might
175
+ # seem a bit unusual, but is taken from the original Transformer paper.
176
+ context_layer = self.dropout(attention_probs) @ value_layer
177
+
178
+ return context_layer
179
+
180
+
181
+ class LSGAttentionProduct(nn.Module):
182
+
183
+ def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4):
184
+ """
185
+ Compute block or overlapping blocks attention products
186
+ """
187
+ super().__init__()
188
+
189
+ self.block_size = block_size
190
+ self.sparse_block_size = sparse_block_size
191
+ self.sparsity_factor = sparsity_factor
192
+
193
+ if self.block_size is None:
194
+ self.block_size = config.block_size
195
+
196
+ if self.sparse_block_size is None:
197
+ self.sparse_block_size = config.sparse_block_size
198
+
199
+ # Shape of blocks
200
+ self.local_shapes = (self.block_size*3, self.block_size)
201
+ if self.sparse_block_size and self.sparsity_factor > 0:
202
+ self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
203
+
204
+ self.attention = BaseAttentionProduct(config)
205
+
206
+ def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
207
+
208
+ # Build local tokens
209
+ local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
210
+ del hidden_states
211
+
212
+ # Build sparse tokens
213
+ if sparse_hidden_states is not None:
214
+ sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
215
+
216
+ return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
217
+
218
+ def forward(
219
+ self,
220
+ query_layer,
221
+ key_layer,
222
+ value_layer,
223
+ attention_mask=None,
224
+ sparse_key=None,
225
+ sparse_value=None,
226
+ sparse_mask=None,
227
+ global_key=None,
228
+ global_value=None,
229
+ global_mask=None
230
+ ):
231
+
232
+ # Input batch, heads, length, hidden_size
233
+ n, h, t, d = query_layer.size()
234
+ n_blocks = t // self.block_size
235
+ assert t % self.block_size == 0
236
+
237
+ key_layer = self.build_lsg_inputs(
238
+ key_layer,
239
+ sparse_key,
240
+ global_key
241
+ )
242
+ del sparse_key
243
+ del global_key
244
+
245
+ value_layer = self.build_lsg_inputs(
246
+ value_layer,
247
+ sparse_value,
248
+ global_value
249
+ )
250
+ del sparse_value
251
+ del global_value
252
+
253
+ attention_mask = self.build_lsg_inputs(
254
+ attention_mask,
255
+ sparse_mask,
256
+ global_mask.transpose(-1, -2),
257
+ is_attn_mask=True
258
+ ).transpose(-1, -2)
259
+ del sparse_mask
260
+ del global_mask
261
+
262
+ # expect (..., t, d) shape
263
+ # Compute attention
264
+ context_layer = self.attention(
265
+ query_layer=self.chunk(query_layer, n_blocks),
266
+ key_layer=key_layer,
267
+ value_layer=value_layer,
268
+ attention_mask=attention_mask
269
+ )
270
+
271
+ return context_layer.reshape(n, h, -1, d)
272
+
273
+ def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
274
+
275
+ size, step = self.local_shapes
276
+ s = (size - step) // 2
277
+
278
+ # Pad before block reshaping
279
+ if is_attn_mask:
280
+ pad_value = torch.finfo(hidden_states.dtype).min
281
+ hidden_states = hidden_states.transpose(-1, -2)
282
+ else:
283
+ pad_value = 0
284
+
285
+ hidden_states = torch.nn.functional.pad(
286
+ hidden_states.transpose(-1, -2),
287
+ pad=(s, s),
288
+ value=pad_value
289
+ ).transpose(-1, -2)
290
+
291
+ # Make blocks
292
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
293
+
294
+ return hidden_states
295
+
296
+ def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
297
+
298
+ size, step = self.sparse_shapes
299
+
300
+ # In case of odd case
301
+ odd_offset = (step % 2)
302
+
303
+ # n, h, t, d*2 + 1
304
+ size = size*2
305
+ s = (size - step) // 2 + odd_offset
306
+
307
+ # Pad before block reshaping
308
+ if is_attn_mask:
309
+ pad_value = torch.finfo(hidden_states.dtype).min
310
+ hidden_states = hidden_states.transpose(-1, -2)
311
+ else:
312
+ pad_value = 0
313
+
314
+ hidden_states = torch.nn.functional.pad(
315
+ hidden_states.transpose(-1, -2),
316
+ pad=(s, s),
317
+ value=pad_value
318
+ ).transpose(-1, -2)
319
+
320
+ # Make blocks
321
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
322
+
323
+ # Fix case where block_size == sparsify_factor
324
+ if odd_offset:
325
+ hidden_states = hidden_states[..., :-1, :, :]
326
+
327
+ # Indexes for selection
328
+ u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
329
+ s = self.sparse_block_size
330
+
331
+ u_ = u + odd_offset
332
+ return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
333
+
334
+ def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
335
+
336
+ n, h, b, t, d = x_local.size()
337
+ x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
338
+ if x_sparse is not None:
339
+ return torch.cat([x_global, x_sparse, x_local], dim=dim)
340
+ return torch.cat([x_global, x_local], dim=dim)
341
+
342
+ def chunk(self, x, n_blocks):
343
+
344
+ t, d = x.size()[-2:]
345
+ return x.reshape(*x.size()[:-2], n_blocks, -1, d)
346
+
347
+
348
+ class LSGMBartEncoderSelfAttention(BaseSelfAttention):
349
+ '''
350
+ Compute local attention with overlapping blocs
351
+ Use global attention for tokens with highest norm
352
+ '''
353
+ def __init__(
354
+ self,
355
+ config,
356
+ embed_dim,
357
+ num_heads,
358
+ dropout
359
+ ):
360
+
361
+ super().__init__(embed_dim, num_heads, dropout)
362
+
363
+ self.block_size = config.block_size
364
+ self.sparse_block_size = config.sparse_block_size
365
+ self.num_global_tokens = config.num_global_tokens
366
+ self.sparsity_factor = config.sparsity_factor
367
+
368
+ self.attention = LSGAttentionProduct(
369
+ config,
370
+ block_size=config.block_size,
371
+ sparse_block_size=config.sparse_block_size,
372
+ sparsity_factor=self.sparsity_factor,
373
+ )
374
+
375
+ self.full_attention = BaseAttentionProduct(config)
376
+
377
+ sparse_functions = {
378
+ "norm": self.get_sparse_tokens_with_norm,
379
+ "pooling": self.get_sparse_tokens_with_pooling,
380
+ "lsh": self.get_sparse_tokens_with_lsh,
381
+ "stride": self.get_sparse_tokens_with_stride,
382
+ "block_stride": self.get_sparse_tokens_with_block_stride,
383
+ "bos_pooling": self.get_sparse_tokens_with_bos_pooling
384
+ }
385
+
386
+ self.sparsity_type = config.sparsity_type
387
+ self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda w, x, y, z: (None, None, None))
388
+
389
+ if config.sparsity_type == "lsh":
390
+ self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
391
+
392
+ def get_sparse_tokens_with_norm(self, queries, keys, values, mask):
393
+
394
+ if self.sparsity_factor == 1:
395
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
396
+
397
+ with torch.no_grad():
398
+
399
+ block_size = min(self.block_size, self.sparse_block_size)
400
+ key_norm = keys.detach().norm(dim=-1, keepdim=True)
401
+ key_norm = key_norm * ~mask.transpose(-1, -2).bool()
402
+ key_norm = self.chunk(key_norm, block_size)
403
+
404
+ n, h, b, t, d = key_norm.size()
405
+
406
+ idx = key_norm.argsort(dim=-2)
407
+ del key_norm
408
+ idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
409
+
410
+ split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
411
+ sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
412
+
413
+ d = keys.size()[-1]
414
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
415
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
416
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
417
+
418
+ return keys, values, mask
419
+
420
+ def get_sparse_tokens_with_pooling(self, queries, keys, values, mask):
421
+
422
+ if self.sparsity_factor == 1:
423
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
424
+
425
+ keys = self.chunk(keys, self.sparsity_factor)
426
+ values = self.chunk(values, self.sparsity_factor)
427
+
428
+ n, h, b, t, d = keys.size()
429
+ mask = mask.reshape(n, 1, b, 1, t)
430
+ mask = ~mask.transpose(-1, -2).bool()
431
+
432
+ keys = keys * mask
433
+ values = values * mask
434
+
435
+ mask = mask.sum(dim=-2)
436
+ keys = keys.sum(dim=-2) / (mask + 1e-6)
437
+ values = values.sum(dim=-2) / (mask + 1e-6)
438
+
439
+ mask = (1. - mask.clamp(0, 1))
440
+ mask *= torch.finfo(mask.dtype).min
441
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
442
+
443
+ def get_sparse_tokens_with_stride(self, queries, keys, values, mask):
444
+
445
+ if self.sparsity_factor == 1:
446
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
447
+
448
+ n, h, t, d = keys.size()
449
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
450
+ sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
451
+ sparse_idx = sparse_idx.expand(n, h, -1, 1)
452
+
453
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
454
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
455
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
456
+
457
+ return keys, values, mask
458
+
459
+ def get_sparse_tokens_with_block_stride(self, queries, keys, values, mask):
460
+
461
+ if self.sparsity_factor == 1:
462
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
463
+
464
+ n, h, t, d = keys.size()
465
+
466
+ t, b = self.block_size, t // self.block_size
467
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device)
468
+ sparse_idx = sparse_idx.reshape(1, 1, 1, -1, 1) + torch.arange(h, device=keys.device).reshape(1, h, 1, 1, 1) * (t // self.sparsity_factor)
469
+ sparse_idx = (sparse_idx % t)
470
+ sparse_idx = sparse_idx + torch.arange(b, device=keys.device).reshape(1, 1, -1, 1, 1) * t
471
+ sparse_idx = sparse_idx.reshape(1, h, -1, 1).expand(n, h, -1, 1)
472
+
473
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
474
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
475
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
476
+
477
+ return keys, values, mask
478
+
479
+ def get_sparse_tokens_with_lsh(self, queries, keys, values, mask):
480
+
481
+ if self.sparsity_factor == 1:
482
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
483
+
484
+ if self.sparsity_factor == self.sparse_block_size:
485
+ return self.get_sparse_tokens_with_bos_pooling(queries, keys, values, mask)
486
+
487
+ block_size = min(self.block_size, self.sparse_block_size)
488
+ keys = self.chunk(keys, block_size)
489
+ values = self.chunk(values, block_size)
490
+
491
+ n, h, b, t, d = keys.size()
492
+ mask = mask.reshape(n, 1, b, 1, t)
493
+ mask = ~mask.transpose(-1, -2).bool()
494
+
495
+ keys = keys * mask
496
+ values = values * mask
497
+ mask = mask.expand(-1, h, -1, -1, -1).float()
498
+
499
+ extra_factor = 1
500
+
501
+ for _ in range(self.lsh_num_pre_rounds):
502
+ keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
503
+
504
+ keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
505
+ keys /= mask + 1e-8
506
+ values /= mask + 1e-8
507
+
508
+ mask = (1. - mask.clamp(0, 1))
509
+ mask *= torch.finfo(mask.dtype).min
510
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
511
+
512
+ def lsh_round(self, keys, values, mask, output_size):
513
+
514
+ with torch.no_grad():
515
+
516
+ n_hashes = output_size // 2
517
+ n, h, b, t, d = keys.size()
518
+ binary_mask = mask.clamp(0, 1)
519
+
520
+ indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
521
+ indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
522
+
523
+ n, h, b, t, d = keys.size()
524
+
525
+ x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
526
+ mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
527
+ keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
528
+ values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
529
+ mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
530
+
531
+ return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
532
+
533
+ def get_sparse_tokens_with_bos_pooling(self, queries, keys, values, mask):
534
+
535
+ if self.sparsity_factor == 1:
536
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
537
+
538
+ queries = queries.unsqueeze(-3)
539
+ mask = self.chunk(mask.transpose(-1, -2), self.sparsity_factor).transpose(-1, -2)
540
+ keys = self.chunk(keys, self.sparsity_factor)
541
+ values = self.chunk(values, self.sparsity_factor)
542
+
543
+ n, h, b, t, d = keys.size()
544
+ scores = (queries[..., :1, :] @ keys.transpose(-1, -2)) / math.sqrt(d)
545
+ if mask is not None:
546
+ scores = scores + mask
547
+
548
+ scores = torch.softmax(scores, dim=-1)
549
+ keys = scores @ keys
550
+ values = scores @ values
551
+ mask = mask.mean(dim=-1)
552
+ mask[mask != torch.finfo(mask.dtype).min] = 0
553
+
554
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
555
+
556
+ def forward(
557
+ self,
558
+ hidden_states,
559
+ attention_mask=None,
560
+ layer_head_mask=None,
561
+ output_attentions=False
562
+ ):
563
+
564
+ query_layer, key_layer, value_layer = self.project_QKV(hidden_states)
565
+ outputs = self.not_causal_forward(
566
+ query_layer,
567
+ key_layer,
568
+ value_layer,
569
+ attention_mask=attention_mask[:, :, :1, :],
570
+ head_mask=layer_head_mask,
571
+ output_attentions=output_attentions
572
+ )
573
+
574
+ return self.out_proj(outputs), None, None
575
+
576
+ def not_causal_forward(
577
+ self,
578
+ query_layer,
579
+ key_layer,
580
+ value_layer,
581
+ attention_mask=None,
582
+ head_mask=None,
583
+ output_attentions=False,
584
+ ):
585
+
586
+ n, h, t, d = query_layer.size()
587
+
588
+ # Cat global mask
589
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
590
+
591
+ # Use normal attention if local attention covers every tokens
592
+ if t <= 2 * self.block_size + self.num_global_tokens:
593
+ context_layer = self.full_attention(
594
+ query_layer=query_layer,
595
+ key_layer=key_layer,
596
+ value_layer=value_layer,
597
+ attention_mask=attention_mask
598
+ )
599
+
600
+ return self.reshape_output(context_layer)
601
+
602
+ # Split input into global tokens and other tokens
603
+ split = (self.num_global_tokens, t - self.num_global_tokens)
604
+ global_query, query_layer = query_layer.split(split, dim=-2)
605
+
606
+ # Get global_attention
607
+ bos = self.full_attention(
608
+ query_layer=global_query,
609
+ key_layer=key_layer,
610
+ value_layer=value_layer,
611
+ attention_mask=attention_mask
612
+ )
613
+
614
+ # Split K Q M on global and non global
615
+ global_key, key_layer = key_layer.split(split, dim=-2)
616
+ global_value, value_layer = value_layer.split(split, dim=-2)
617
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
618
+
619
+ n, h, t, d = key_layer.size()
620
+
621
+ # Get sparse idx
622
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
623
+
624
+ if self.sparse_block_size and self.sparsity_factor > 0:
625
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(query_layer, key_layer, value_layer, attention_mask)
626
+
627
+ # Expand masks on heads
628
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
629
+ global_mask = global_mask.expand(-1, h, -1, -1)
630
+
631
+ # Compute dot product attention
632
+ context_layer = self.attention(
633
+ query_layer,
634
+ key_layer,
635
+ value_layer,
636
+ attention_mask,
637
+ sparse_key=sparse_key,
638
+ sparse_value=sparse_value,
639
+ sparse_mask=sparse_mask,
640
+ global_key=global_key,
641
+ global_value=global_value,
642
+ global_mask=global_mask
643
+ )
644
+
645
+ # Merge global and local-sparse tokens
646
+ context_layer = torch.cat([bos, context_layer], dim=-2)
647
+ context_layer = self.reshape_output(context_layer)
648
+
649
+ return context_layer
650
+
651
+ def chunk(self, x, chunk_size):
652
+
653
+ n, h, t, d = x.size()
654
+ return x.reshape(n, h, -1, chunk_size, d)
655
+
656
+
657
+ class LSGMBartEncoderLayer(MBartEncoderLayer):
658
+
659
+ def __init__(self, config):
660
+
661
+ super().__init__(config)
662
+ self.self_attn = LSGMBartEncoderSelfAttention(
663
+ config=config,
664
+ embed_dim=self.embed_dim,
665
+ num_heads=config.encoder_attention_heads,
666
+ dropout=config.attention_dropout,
667
+ )
668
+
669
+
670
+ class LSGMBartPretrainedModel(MBartPreTrainedModel):
671
+
672
+ config_class = LSGMBartConfig
673
+ base_model_prefix = "model"
674
+ supports_gradient_checkpointing = True
675
+
676
+ def _set_gradient_checkpointing(self, module, value=False):
677
+ if isinstance(module, (MBartDecoder, MBartEncoder, LSGMBartEncoder)):
678
+ module.gradient_checkpointing = value
679
+
680
+
681
+ class LSGMBartEncoder(LSGMBartPretrainedModel, MBartEncoder):
682
+ """
683
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
684
+ [`MBartEncoderLayer`].
685
+ Args:
686
+ config: MBartConfig
687
+ embed_tokens (nn.Embedding): output embedding
688
+ """
689
+
690
+ def __init__(self, config, embed_tokens=None):
691
+
692
+ LSGMBartPretrainedModel.__init__(self, config)
693
+ self.dropout = config.dropout
694
+ self.layerdrop = config.encoder_layerdrop
695
+
696
+ embed_dim = config.d_model
697
+ self.padding_idx = config.pad_token_id
698
+ self.max_source_positions = config.max_position_embeddings
699
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
700
+
701
+ if embed_tokens is not None:
702
+ self.embed_tokens = embed_tokens
703
+ else:
704
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
705
+
706
+ self.embed_positions = MBartLearnedPositionalEmbedding(
707
+ config.max_position_embeddings,
708
+ embed_dim,
709
+ )
710
+ self.layers = nn.ModuleList([LSGMBartEncoderLayer(config) for _ in range(config.encoder_layers)])
711
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
712
+ self.layer_norm = nn.LayerNorm(config.d_model)
713
+
714
+ #
715
+ assert hasattr(config, "num_global_tokens")
716
+ self.num_global_tokens = config.num_global_tokens
717
+ self.pad_idx = config.pad_token_id
718
+
719
+ assert hasattr(config, "block_size") and hasattr(config, "adaptive")
720
+ self.block_size = config.block_size
721
+ self.adaptive = config.adaptive
722
+ self.mask_first_token = config.mask_first_token
723
+ self.pool_with_global = config.pool_with_global
724
+ self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
725
+
726
+ self.global_embeddings = nn.Embedding(512, embedding_dim=config.d_model)
727
+
728
+ self.gradient_checkpointing = False
729
+
730
+ # Initialize weights and apply final processing
731
+ self.post_init()
732
+
733
+ def forward(self,
734
+ input_ids=None,
735
+ attention_mask=None,
736
+ head_mask=None,
737
+ inputs_embeds=None,
738
+ output_attentions=None,
739
+ output_hidden_states=None,
740
+ return_dict=None
741
+ ):
742
+
743
+
744
+ inputs_ = input_ids if input_ids is not None else inputs_embeds
745
+ n, t = inputs_.size()[:2]
746
+
747
+ if attention_mask is None:
748
+ attention_mask = torch.ones(n, t, device=inputs_.device, dtype=inputs_.dtype)
749
+ if self.mask_first_token:
750
+ attention_mask[:, 0] = 0
751
+
752
+ b = self.block_size * 2
753
+ pad = t % self.block_size
754
+
755
+ # Check if t is multiple of block_size and pad
756
+ if self.adaptive and t > b and pad > 0:
757
+ pad_length = self.block_size - pad
758
+ if input_ids is not None:
759
+ input_ids = torch.nn.functional.pad(input_ids, (0, pad_length), value=self.pad_idx)
760
+ else:
761
+ inputs_embeds = torch.nn.functional.pad(inputs_embeds.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
762
+ attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=0)
763
+
764
+ n, t_ = attention_mask.size()
765
+
766
+ encoder_outputs = self.forward_with_adaptive(
767
+ input_ids=input_ids,
768
+ attention_mask=attention_mask,
769
+ head_mask=head_mask,
770
+ inputs_embeds=inputs_embeds,
771
+ output_attentions=output_attentions,
772
+ output_hidden_states=output_hidden_states,
773
+ return_dict=return_dict,
774
+ )
775
+
776
+ context = encoder_outputs[0]
777
+ diff = t - t_
778
+
779
+ if self.pass_global_tokens_to_decoder:
780
+ offset = self.num_global_tokens
781
+ else:
782
+ if self.pool_with_global:
783
+ context[:, self.num_global_tokens] = context[:, 0]
784
+ context = context[..., self.num_global_tokens:, :]
785
+ offset = 0
786
+
787
+ # Adapt sequence to initial shape
788
+ if diff < 0:
789
+ context = context[:, :t + offset]
790
+
791
+ if return_dict:
792
+ encoder_outputs.last_hidden_state = context
793
+ else:
794
+ encoder_outputs = (context, ) + encoder_outputs[1:]
795
+
796
+ return encoder_outputs
797
+
798
+ def forward_with_adaptive(
799
+ self,
800
+ input_ids=None,
801
+ attention_mask=None,
802
+ head_mask=None,
803
+ inputs_embeds=None,
804
+ output_attentions=None,
805
+ output_hidden_states=None,
806
+ return_dict=None,
807
+ ):
808
+
809
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
810
+ output_hidden_states = (
811
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
812
+ )
813
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
814
+
815
+ # retrieve input_ids and inputs_embeds
816
+ if input_ids is not None and inputs_embeds is not None:
817
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
818
+ elif input_ids is not None:
819
+ input = input_ids
820
+ input_shape = input.shape
821
+ input_ids = input_ids.view(-1, input_shape[-1])
822
+ elif inputs_embeds is not None:
823
+ input = inputs_embeds[:, :, -1]
824
+ else:
825
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
826
+
827
+ if inputs_embeds is None:
828
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
829
+
830
+
831
+ embed_pos = self.embed_positions(input).to(inputs_embeds.device)
832
+ hidden_states = inputs_embeds + embed_pos
833
+
834
+ # Add global tokens
835
+ n, t, d = hidden_states.size()
836
+ global_idx = torch.arange(self.num_global_tokens, device=hidden_states.device).reshape(1, -1)
837
+ hidden_states = torch.cat([self.global_embeddings(global_idx).expand(n, -1, -1), hidden_states], dim=-2)
838
+
839
+ hidden_states = self.layernorm_embedding(hidden_states)
840
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
841
+
842
+ # expand attention_mask
843
+ if attention_mask is not None:
844
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
845
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
846
+
847
+ encoder_states = () if output_hidden_states else None
848
+ all_attentions = () if output_attentions else None
849
+
850
+ # check if head_mask has a correct number of layers specified if desired
851
+ if head_mask is not None:
852
+ if head_mask.size()[0] != (len(self.layers)):
853
+ raise ValueError(
854
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
855
+ )
856
+
857
+ for idx, encoder_layer in enumerate(self.layers):
858
+ if output_hidden_states:
859
+ encoder_states = encoder_states + (hidden_states,)
860
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
861
+ to_drop = False
862
+ if self.training:
863
+ dropout_probability = torch.rand([])
864
+ if dropout_probability < self.layerdrop: # skip the layer
865
+ to_drop = True
866
+
867
+ if to_drop:
868
+ layer_outputs = (None, None)
869
+ else:
870
+ if self.gradient_checkpointing and self.training:
871
+
872
+ def create_custom_forward(module):
873
+ def custom_forward(*inputs):
874
+ return module(*inputs, output_attentions)
875
+
876
+ return custom_forward
877
+
878
+ layer_outputs = torch.utils.checkpoint.checkpoint(
879
+ create_custom_forward(encoder_layer),
880
+ hidden_states,
881
+ attention_mask,
882
+ (head_mask[idx] if head_mask is not None else None),
883
+ )
884
+ else:
885
+ layer_outputs = encoder_layer(
886
+ hidden_states,
887
+ attention_mask,
888
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
889
+ output_attentions=output_attentions,
890
+ )
891
+
892
+ hidden_states = layer_outputs[0]
893
+
894
+ if output_attentions:
895
+ all_attentions = all_attentions + (layer_outputs[1],)
896
+
897
+ hidden_states = self.layer_norm(hidden_states)
898
+
899
+ if output_hidden_states:
900
+ encoder_states = encoder_states + (hidden_states,)
901
+
902
+ if not return_dict:
903
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
904
+ return BaseModelOutput(
905
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
906
+ )
907
+
908
+
909
+ class LSGMBartModel(LSGMBartPretrainedModel, MBartModel):
910
+
911
+ _keys_to_ignore_on_load_missing = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
912
+ _tied_weights_keys = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
913
+
914
+ def __init__(self, config):
915
+
916
+ LSGMBartPretrainedModel.__init__(self, config)
917
+
918
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
919
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
920
+
921
+ self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
922
+ self.num_global_tokens = config.num_global_tokens
923
+
924
+ self.encoder = LSGMBartEncoder(config, self.shared)
925
+ self.decoder = MBartDecoder(config, self.shared)
926
+
927
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
928
+ if self._use_flash_attention_2:
929
+ logger.warning(
930
+ "[WARNING flash-attention]: LSG doesnt support flash-attention currently"
931
+ )
932
+
933
+ # Initialize weights and apply final processing
934
+ self.post_init()
935
+
936
+ def forward(
937
+ self,
938
+ input_ids=None,
939
+ attention_mask=None,
940
+ decoder_input_ids=None,
941
+ decoder_attention_mask=None,
942
+ head_mask=None,
943
+ decoder_head_mask=None,
944
+ cross_attn_head_mask=None,
945
+ encoder_outputs=None,
946
+ past_key_values=None,
947
+ inputs_embeds=None,
948
+ decoder_inputs_embeds=None,
949
+ use_cache=None,
950
+ output_attentions=None,
951
+ output_hidden_states=None,
952
+ return_dict=None,
953
+ ):
954
+
955
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
956
+ output_hidden_states = (
957
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
958
+ )
959
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
960
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
961
+
962
+ # different to other models, MBart automatically creates decoder_input_ids from
963
+ # input_ids if no decoder_input_ids are provided
964
+ if decoder_input_ids is None:
965
+ decoder_input_ids = shift_tokens_right(input_ids, self.config.pad_token_id)
966
+
967
+ if encoder_outputs is None:
968
+ encoder_outputs = self.encoder(
969
+ input_ids=input_ids,
970
+ attention_mask=attention_mask,
971
+ head_mask=head_mask,
972
+ inputs_embeds=inputs_embeds,
973
+ output_attentions=output_attentions,
974
+ output_hidden_states=output_hidden_states,
975
+ return_dict=return_dict,
976
+ )
977
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
978
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
979
+ encoder_outputs = BaseModelOutput(
980
+ last_hidden_state=encoder_outputs[0],
981
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
982
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
983
+ )
984
+
985
+ # Pad mask for global tokens
986
+ if self.pass_global_tokens_to_decoder and attention_mask is not None:
987
+ attention_mask = torch.nn.functional.pad(attention_mask, pad=(self.num_global_tokens, 0), value=1)
988
+
989
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
990
+ decoder_outputs = self.decoder(
991
+ input_ids=decoder_input_ids,
992
+ attention_mask=decoder_attention_mask,
993
+ encoder_hidden_states=encoder_outputs[0],
994
+ encoder_attention_mask=attention_mask,
995
+ head_mask=decoder_head_mask,
996
+ cross_attn_head_mask=cross_attn_head_mask,
997
+ past_key_values=past_key_values,
998
+ inputs_embeds=decoder_inputs_embeds,
999
+ use_cache=use_cache,
1000
+ output_attentions=output_attentions,
1001
+ output_hidden_states=output_hidden_states,
1002
+ return_dict=return_dict,
1003
+ )
1004
+
1005
+ if not return_dict:
1006
+ return decoder_outputs + encoder_outputs
1007
+
1008
+ return Seq2SeqModelOutput(
1009
+ last_hidden_state=decoder_outputs.last_hidden_state,
1010
+ past_key_values=decoder_outputs.past_key_values,
1011
+ decoder_hidden_states=decoder_outputs.hidden_states,
1012
+ decoder_attentions=decoder_outputs.attentions,
1013
+ cross_attentions=decoder_outputs.cross_attentions,
1014
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1015
+ encoder_hidden_states=encoder_outputs.hidden_states,
1016
+ encoder_attentions=encoder_outputs.attentions,
1017
+ )
1018
+
1019
+
1020
+ class LSGMBartForConditionalGeneration(LSGMBartPretrainedModel, MBartForConditionalGeneration):
1021
+
1022
+ base_model_prefix = "model"
1023
+ _keys_to_ignore_on_load_missing = [
1024
+ r"final_logits_bias",
1025
+ r"encoder.version",
1026
+ r"decoder.version",
1027
+ r"lm_head.weight",
1028
+ "encoder.embed_tokens.weight",
1029
+ "decoder.embed_tokens.weight",
1030
+ ]
1031
+ _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight", "lm_head.weight"]
1032
+
1033
+ def __init__(self, config):
1034
+
1035
+ LSGMBartPretrainedModel.__init__(self, config)
1036
+ self.model = LSGMBartModel(config)
1037
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1038
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1039
+
1040
+ # Initialize weights and apply final processing
1041
+ self.post_init()
1042
+
1043
+
1044
+ class LSGMBartForSequenceClassification(LSGMBartPretrainedModel, MBartForSequenceClassification):
1045
+
1046
+ _keys_to_ignore_on_load_missing = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1047
+ _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight"]
1048
+
1049
+ def __init__(self, config, **kwargs):
1050
+
1051
+ LSGMBartPretrainedModel.__init__(self, config, **kwargs)
1052
+ self.model = LSGMBartModel(config)
1053
+ self.classification_head = MBartClassificationHead(
1054
+ config.d_model,
1055
+ config.d_model,
1056
+ config.num_labels,
1057
+ config.classifier_dropout,
1058
+ )
1059
+ self.model._init_weights(self.classification_head.dense)
1060
+ self.model._init_weights(self.classification_head.out_proj)
1061
+
1062
+
1063
+ class LSGMBartForQuestionAnswering(LSGMBartPretrainedModel, MBartForQuestionAnswering):
1064
+
1065
+ _keys_to_ignore_on_load_missing = ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"]
1066
+ _tied_weights_keys = ["model.encoder.embed_tokens.weight", "model.decoder.embed_tokens.weight"]
1067
+
1068
+ def __init__(self, config):
1069
+
1070
+ LSGMBartPretrainedModel.__init__(self, config)
1071
+
1072
+ config.num_labels = 2
1073
+ self.num_labels = config.num_labels
1074
+
1075
+ self.model = LSGMBartModel(config)
1076
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1077
+
1078
+ self.model._init_weights(self.qa_outputs)
1079
+
1080
+
1081
+ class LSGMBartForCausalLM(LSGMBartPretrainedModel, MBartForCausalLM):
1082
+
1083
+ _keys_to_ignore_on_load_missing = ["lm_head.weight"]
1084
+ _tied_weights_keys = ["lm_head.weight"]
1085
+
1086
+ def __init__(self, config):
1087
+
1088
+ LSGMBartPretrainedModel.__init__(self, config)
1089
+ MBartForCausalLM.__init__(self, config)
1090
+
1091
+
1092
+ def str_to_class(classname):
1093
+ return getattr(sys.modules[__name__], classname)
1094
+
1095
+ # Register model in Auto API
1096
+ try:
1097
+ LSGMBartConfig.register_for_auto_class()
1098
+ for key, value in AUTO_MAP.items():
1099
+ str_to_class(value.split(".")[-1]).register_for_auto_class(key)
1100
+ except:
1101
+ warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
1102
+ warn("Update to transformers >= 4.36.1 to fix.")