ccdv commited on
Commit
62b7c18
1 Parent(s): 4035c52

first commit

Browse files
README.md ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ tags:
4
+ - bert
5
+ - long context
6
+ pipeline_tag: fill-mask
7
+ ---
8
+
9
+ # LSG model
10
+ **Transformers >= 4.18.0**\
11
+ **This model relies on a custom modeling file, you need to add trust_remote_code=True**\
12
+ **See [\#13467](https://github.com/huggingface/transformers/pull/13467)**
13
+
14
+ * [Usage](#usage)
15
+ * [Parameters](#parameters)
16
+ * [Sparse selection type](#sparse-selection-type)
17
+ * [Tasks](#tasks)
18
+ * [Training global tokens](#training-global-tokens)
19
+
20
+ This model is adapted from [BERT-base-uncased](https://huggingface.co/bert-base-uncased) without additional pretraining yet. It uses the same number of parameters/layers and the same tokenizer.
21
+
22
+
23
+ This model can handle long sequences but faster and more efficiently than Longformer or BigBird (from Transformers) and relies on Local + Sparse + Global attention (LSG).
24
+
25
+ The model requires sequences whose length is a multiple of the block size. The model is "adaptive" and automatically pads the sequences if needed (adaptive=True in config). It is however recommended, thanks to the tokenizer, to truncate the inputs (truncation=True) and optionally to pad with a multiple of the block size (pad_to_multiple_of=...). \
26
+
27
+ Support encoder-decoder but I didnt test it extensively.\
28
+ Implemented in PyTorch.
29
+
30
+ ![attn](attn.png)
31
+
32
+ ## Usage
33
+ The model relies on a custom modeling file, you need to add trust_remote_code=True to use it.
34
+
35
+ ```python:
36
+ from transformers import AutoModel, AutoTokenizer
37
+
38
+ model = AutoModel.from_pretrained("ccdv/lsg-bert-base-uncased-4096", trust_remote_code=True)
39
+ tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bert-base-uncased-4096")
40
+ ```
41
+
42
+ ## Parameters
43
+ You can change various parameters like :
44
+ * the number of global tokens (num_global_tokens=1)
45
+ * local block size (block_size=128)
46
+ * sparse block size (sparse_block_size=128)
47
+ * sparsity factor (sparsity_factor=2)
48
+ * mask_first_token (mask first token since it is redundant with the first global token)
49
+ * see config.json file
50
+
51
+ Default parameters work well in practice. If you are short on memory, reduce block sizes, increase sparsity factor and remove dropout in the attention score matrix.
52
+
53
+ ```python:
54
+ from transformers import AutoModel
55
+
56
+ model = AutoModel.from_pretrained("ccdv/lsg-bert-base-uncased-4096",
57
+ trust_remote_code=True,
58
+ num_global_tokens=16,
59
+ block_size=64,
60
+ sparse_block_size=64,
61
+ attention_probs_dropout_prob=0.0
62
+ sparsity_factor=4,
63
+ sparsity_type="none",
64
+ mask_first_token=True
65
+ )
66
+ ```
67
+
68
+ ## Sparse selection type
69
+
70
+ There are 5 different sparse selection patterns. The best type is task dependent. \
71
+ Note that for sequences with length < 2*block_size, the type has no effect.
72
+
73
+ * sparsity_type="norm", select highest norm tokens
74
+ * Works best for a small sparsity_factor (2 to 4)
75
+ * Additional parameters:
76
+ * None
77
+ * sparsity_type="pooling", use average pooling to merge tokens
78
+ * Works best for a small sparsity_factor (2 to 4)
79
+ * Additional parameters:
80
+ * None
81
+ * sparsity_type="lsh", use the LSH algorithm to cluster similar tokens
82
+ * Works best for a large sparsity_factor (4+)
83
+ * LSH relies on random projections, thus inference may differ slightly with different seeds
84
+ * Additional parameters:
85
+ * lsg_num_pre_rounds=1, pre merge tokens n times before computing centroids
86
+ * sparsity_type="stride", use a striding mecanism per head
87
+ * Each head will use different tokens strided by sparsify_factor
88
+ * Not recommended if sparsify_factor > num_heads
89
+ * sparsity_type="block_stride", use a striding mecanism per head
90
+ * Each head will use block of tokens strided by sparsify_factor
91
+ * Not recommended if sparsify_factor > num_heads
92
+
93
+ ## Tasks
94
+ Fill mask example:
95
+ ```python:
96
+ from transformers import FillMaskPipeline, AutoModelForMaskedLM, AutoTokenizer
97
+
98
+ model = AutoModelForMaskedLM.from_pretrained("ccdv/lsg-bert-base-uncased-4096", trust_remote_code=True)
99
+ tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bert-base-uncased-4096")
100
+
101
+ SENTENCES = "Paris is the [MASK] of France."
102
+ pipeline = FillMaskPipeline(model, tokenizer)
103
+ output = pipeline(SENTENCES)
104
+
105
+ > 'Paris is the capital of France.'
106
+ ```
107
+
108
+
109
+ Classification example:
110
+ ```python:
111
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
112
+
113
+ model = AutoModelForSequenceClassification.from_pretrained("ccdv/lsg-bert-base-uncased-4096",
114
+ trust_remote_code=True,
115
+ pool_with_global=True, # pool with a global token instead of first token
116
+ )
117
+ tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bert-base-uncased-4096")
118
+
119
+ SENTENCE = "This is a test for sequence classification. " * 300
120
+ token_ids = tokenizer(
121
+ SENTENCE,
122
+ return_tensors="pt",
123
+ #pad_to_multiple_of=... # Optional
124
+ truncation=True
125
+ )
126
+ output = model(**token_ids)
127
+
128
+ > SequenceClassifierOutput(loss=None, logits=tensor([[-0.3051, -0.1762]], grad_fn=<AddmmBackward>), hidden_states=None, attentions=None)
129
+ ```
130
+
131
+ ## Training global tokens
132
+ To train global tokens and the classification head only:
133
+ ```python:
134
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
135
+
136
+ model = AutoModelForSequenceClassification.from_pretrained("ccdv/lsg-bert-base-uncased-4096",
137
+ trust_remote_code=True,
138
+ pool_with_global=True, # pool with a global token instead of first token
139
+ num_global_tokens=16
140
+ )
141
+ tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bert-base-uncased-4096")
142
+
143
+ for name, param in model.named_parameters():
144
+ if "global_embeddings" not in name:
145
+ param.requires_grad = False
146
+ else:
147
+ param.required_grad = True
148
+ ```
149
+
150
+ **BERT**
151
+ ```
152
+ @article{DBLP:journals/corr/abs-1810-04805,
153
+ author = {Jacob Devlin and
154
+ Ming{-}Wei Chang and
155
+ Kenton Lee and
156
+ Kristina Toutanova},
157
+ title = {{BERT:} Pre-training of Deep Bidirectional Transformers for Language
158
+ Understanding},
159
+ journal = {CoRR},
160
+ volume = {abs/1810.04805},
161
+ year = {2018},
162
+ url = {http://arxiv.org/abs/1810.04805},
163
+ archivePrefix = {arXiv},
164
+ eprint = {1810.04805},
165
+ timestamp = {Tue, 30 Oct 2018 20:39:56 +0100},
166
+ biburl = {https://dblp.org/rec/journals/corr/abs-1810-04805.bib},
167
+ bibsource = {dblp computer science bibliography, https://dblp.org}
168
+ }
169
+ ```
attn.png ADDED
config.json ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "roberta-test2",
3
+ "adaptive": true,
4
+ "architectures": [
5
+ "LSGBertForMaskedLM"
6
+ ],
7
+ "attention_probs_dropout_prob": 0.1,
8
+ "auto_map": {
9
+ "AutoConfig": "modeling_lsg_bert.LSGBertConfig",
10
+ "AutoModel": "modeling_lsg_bert.LSGBertModel",
11
+ "AutoModelForCausalLM": "modeling_lsg_bert.LSGBertLMHeadModel",
12
+ "AutoModelForMaskedLM": "modeling_lsg_bert.LSGBertForMaskedLM",
13
+ "AutoModelForMultipleChoice": "modeling_lsg_bert.LSGBertForMultipleChoice",
14
+ "AutoModelForPreTraining": "modeling_lsg_bert.LSGBertForPreTraining",
15
+ "AutoModelForQuestionAnswering": "modeling_lsg_bert.LSGBertForQuestionAnswering",
16
+ "AutoModelForSequenceClassification": "modeling_lsg_bert.LSGBertForSequenceClassification",
17
+ "AutoModelForTokenClassification": "modeling_lsg_bert.LSGBertForTokenClassification"
18
+ },
19
+ "base_model_prefix": "lsg",
20
+ "block_size": 128,
21
+ "classifier_dropout": null,
22
+ "gradient_checkpointing": false,
23
+ "hidden_act": "gelu",
24
+ "hidden_dropout_prob": 0.1,
25
+ "hidden_size": 768,
26
+ "initializer_range": 0.02,
27
+ "intermediate_size": 3072,
28
+ "layer_norm_eps": 1e-12,
29
+ "lsh_num_pre_rounds": 1,
30
+ "mask_first_token": true,
31
+ "max_position_embeddings": 4096,
32
+ "model_type": "bert",
33
+ "num_attention_heads": 12,
34
+ "num_global_tokens": 1,
35
+ "num_hidden_layers": 12,
36
+ "pad_token_id": 0,
37
+ "pool_with_global": true,
38
+ "position_embedding_type": "absolute",
39
+ "sparse_block_size": 128,
40
+ "sparsity_factor": 2,
41
+ "sparsity_type": "norm",
42
+ "torch_dtype": "float32",
43
+ "transformers_version": "4.21.0",
44
+ "type_vocab_size": 2,
45
+ "use_cache": true,
46
+ "vocab_size": 30522
47
+ }
modeling_lsg_bert.py ADDED
@@ -0,0 +1,1241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import warn
2
+ from transformers.models.bert.modeling_bert import *
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers.models.bert.configuration_bert import BertConfig
6
+ import sys
7
+
8
+ AUTO_MAP = {
9
+ "AutoModel": "modeling_lsg_bert.LSGBertModel",
10
+ "AutoModelForCausalLM": "modeling_lsg_bert.LSGBertLMHeadModel",
11
+ "AutoModelForMaskedLM": "modeling_lsg_bert.LSGBertForMaskedLM",
12
+ "AutoModelForPreTraining": "modeling_lsg_bert.LSGBertForPreTraining",
13
+ "AutoModelForMultipleChoice": "modeling_lsg_bert.LSGBertForMultipleChoice",
14
+ "AutoModelForQuestionAnswering": "modeling_lsg_bert.LSGBertForQuestionAnswering",
15
+ "AutoModelForSequenceClassification": "modeling_lsg_bert.LSGBertForSequenceClassification",
16
+ "AutoModelForTokenClassification": "modeling_lsg_bert.LSGBertForTokenClassification"
17
+ }
18
+
19
+ class LSGBertConfig(BertConfig):
20
+ """
21
+ This class overrides :class:`~transformers.BertConfig`. Please check the superclass for the appropriate
22
+ documentation alongside usage examples.
23
+ """
24
+
25
+ base_model_prefix = "lsg"
26
+ model_type = "bert"
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
+ mask_first_token=False,
35
+ num_global_tokens=1,
36
+ pool_with_global=True,
37
+ sparse_block_size=128,
38
+ sparsity_factor=2,
39
+ sparsity_type="norm",
40
+ **kwargs
41
+ ):
42
+ """Constructs LSGBertConfig."""
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.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", "block_stride"]:
58
+ logger.warning(
59
+ "[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride'], \
60
+ setting sparsity_type=None, computation will skip sparse attention")
61
+ self.sparsity_type = None
62
+
63
+ if self.sparsity_type in ["stride", "block_stride"]:
64
+ if self.sparsity_factor > self.encoder_attention_heads:
65
+ logger.warning(
66
+ "[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
67
+ )
68
+
69
+ if self.num_global_tokens < 1:
70
+ logger.warning(
71
+ "[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
72
+ )
73
+ self.num_global_tokens = 1
74
+ elif self.num_global_tokens > 512:
75
+ logger.warning(
76
+ "[WARNING CONFIG]: num_global_tokens > 512 is not allowed, setting num_global_tokens=512"
77
+ )
78
+ self.num_global_tokens = 512
79
+
80
+ if self.sparsity_factor > 0:
81
+ assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
82
+ assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
83
+
84
+ if self.mask_first_token and not pool_with_global:
85
+ logger.warning(
86
+ "[WARNING CONFIG]: pool_with_global==False is not compatible with mask_first_token==True. Setting pool_with_global to True.")
87
+ self.pool_with_global = True
88
+
89
+ if hasattr(self, "position_embedding_type"):
90
+ if self.position_embedding_type != "absolute":
91
+ logger.warning(
92
+ "[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.")
93
+
94
+
95
+ class BaseSelfAttention(nn.Module):
96
+
97
+ def init_modules(self, config):
98
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
99
+ config, "embedding_size"
100
+ ):
101
+ raise ValueError(
102
+ "The hidden size (%d) is not a multiple of the number of attention "
103
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
104
+ )
105
+
106
+ self.num_attention_heads = config.num_attention_heads
107
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
108
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
109
+
110
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
111
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
112
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
113
+
114
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
115
+
116
+ def transpose_for_scores(self, x):
117
+ new_x_shape = x.size()[:-1] + (
118
+ self.num_attention_heads,
119
+ self.attention_head_size,
120
+ )
121
+ x = x.view(*new_x_shape)
122
+ return x.permute(0, 2, 1, 3)
123
+
124
+ def reshape_output(self, context_layer):
125
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
126
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
127
+ return context_layer.view(*new_context_layer_shape)
128
+
129
+ def project_QKV(self, hidden_states):
130
+
131
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
132
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
133
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
134
+ return query_layer, key_layer, value_layer
135
+
136
+
137
+ class BaseAttentionProduct(nn.Module):
138
+
139
+ def __init__(self, config):
140
+ """
141
+ Compute attention: softmax(Q @ K.T) @ V
142
+ """
143
+ super().__init__()
144
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
145
+
146
+ def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
147
+
148
+ d = query_layer.shape[-1]
149
+
150
+ # Take the dot product between "query" and "key" to get the raw attention scores.
151
+ attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
152
+
153
+ del query_layer
154
+ del key_layer
155
+
156
+ if attention_mask is not None:
157
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
158
+ attention_scores = attention_scores + attention_mask
159
+ del attention_mask
160
+
161
+ # Normalize the attention scores to probabilities.
162
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
163
+
164
+ # This is actually dropping out entire tokens to attend to, which might
165
+ # seem a bit unusual, but is taken from the original Transformer paper.
166
+ context_layer = self.dropout(attention_probs) @ value_layer
167
+
168
+ return context_layer
169
+
170
+
171
+ class CausalAttentionProduct(nn.Module):
172
+
173
+ def __init__(self, config):
174
+ """
175
+ Compute attention: softmax(Q @ K.T) @ V
176
+ """
177
+ super().__init__()
178
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
179
+ self.block_size = config.block_size
180
+
181
+ def forward(self, query_layer, key_layer, value_layer, attention_mask=None, causal_shape=None):
182
+
183
+ d = query_layer.shape[-1]
184
+
185
+ # Take the dot product between "query" and "key" to get the raw attention scores.
186
+ attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
187
+
188
+ del query_layer
189
+ del key_layer
190
+
191
+ if attention_mask is not None:
192
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
193
+ attention_scores = attention_scores + attention_mask
194
+
195
+ # Add causal mask
196
+ causal_shape = (self.block_size, self.block_size) if causal_shape is None else causal_shape
197
+ causal_mask = torch.tril(
198
+ torch.ones(*causal_shape, device=attention_mask.device, dtype=attention_scores.dtype),
199
+ diagonal=-1
200
+ )
201
+ causal_mask = causal_mask.T * torch.finfo(attention_scores.dtype).min
202
+ attention_scores[..., -causal_shape[0]:, -causal_shape[1]:] = causal_mask
203
+
204
+ del attention_mask
205
+
206
+ # Normalize the attention scores to probabilities.
207
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
208
+
209
+ # This is actually dropping out entire tokens to attend to, which might
210
+ # seem a bit unusual, but is taken from the original Transformer paper.
211
+ context_layer = self.dropout(attention_probs) @ value_layer
212
+
213
+ return context_layer
214
+
215
+
216
+ class LSGAttentionProduct(nn.Module):
217
+
218
+ def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4, is_causal=False):
219
+ """
220
+ Compute block or overlapping blocks attention products
221
+ """
222
+ super().__init__()
223
+
224
+ self.block_size = block_size
225
+ self.sparse_block_size = sparse_block_size
226
+ self.sparsity_factor = sparsity_factor
227
+ self.is_causal = is_causal
228
+
229
+ if self.block_size is None:
230
+ self.block_size = config.block_size
231
+
232
+ if self.sparse_block_size is None:
233
+ self.sparse_block_size = config.sparse_block_size
234
+
235
+ # Shape of blocks
236
+ self.local_shapes = (self.block_size*3, self.block_size)
237
+ if self.sparse_block_size and self.sparsity_factor > 0:
238
+ self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
239
+
240
+ if is_causal:
241
+ self.attention = CausalAttentionProduct(config)
242
+ else:
243
+ self.attention = BaseAttentionProduct(config)
244
+
245
+ def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
246
+
247
+ # Build local tokens
248
+ local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
249
+ del hidden_states
250
+
251
+ # Build sparse tokens
252
+ if sparse_hidden_states is not None:
253
+ sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
254
+
255
+ return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
256
+
257
+ def forward(
258
+ self,
259
+ query_layer,
260
+ key_layer,
261
+ value_layer,
262
+ attention_mask=None,
263
+ sparse_key=None,
264
+ sparse_value=None,
265
+ sparse_mask=None,
266
+ global_key=None,
267
+ global_value=None,
268
+ global_mask=None
269
+ ):
270
+
271
+ # Input batch, heads, length, hidden_size
272
+ n, h, t, d = query_layer.size()
273
+ n_blocks = t // self.block_size
274
+ assert t % self.block_size == 0
275
+
276
+ key_layer = self.build_lsg_inputs(
277
+ key_layer,
278
+ sparse_key,
279
+ global_key
280
+ )
281
+ del sparse_key
282
+ del global_key
283
+
284
+ value_layer = self.build_lsg_inputs(
285
+ value_layer,
286
+ sparse_value,
287
+ global_value
288
+ )
289
+ del sparse_value
290
+ del global_value
291
+
292
+ attention_mask = self.build_lsg_inputs(
293
+ attention_mask,
294
+ sparse_mask,
295
+ global_mask.transpose(-1, -2),
296
+ is_attn_mask=True
297
+ ).transpose(-1, -2)
298
+ del sparse_mask
299
+ del global_mask
300
+
301
+ # expect (..., t, d) shape
302
+ # Compute attention
303
+ context_layer = self.attention(
304
+ query_layer=self.chunk(query_layer, n_blocks),
305
+ key_layer=key_layer,
306
+ value_layer=value_layer,
307
+ attention_mask=attention_mask
308
+ )
309
+
310
+ return context_layer.reshape(n, h, -1, d)
311
+
312
+ def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
313
+
314
+ size, step = self.local_shapes
315
+ s = (size - step) // 2
316
+
317
+ # Pad before block reshaping
318
+ if is_attn_mask:
319
+ pad_value = torch.finfo(hidden_states.dtype).min
320
+ hidden_states = hidden_states.transpose(-1, -2)
321
+ else:
322
+ pad_value = 0
323
+
324
+ hidden_states = torch.nn.functional.pad(
325
+ hidden_states.transpose(-1, -2),
326
+ pad=(s, s),
327
+ value=pad_value
328
+ ).transpose(-1, -2)
329
+
330
+ # Make blocks
331
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
332
+
333
+ # Skip third block if causal
334
+ if self.is_causal:
335
+ return hidden_states[..., :size*2//3, :]
336
+
337
+ return hidden_states
338
+
339
+ def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
340
+
341
+ size, step = self.sparse_shapes
342
+
343
+ # In case of odd case
344
+ odd_offset = (step % 2)
345
+
346
+ # n, h, t, d*2 + 1
347
+ size = size*2
348
+ s = (size - step) // 2 + odd_offset
349
+
350
+ # Pad before block reshaping
351
+ if is_attn_mask:
352
+ pad_value = torch.finfo(hidden_states.dtype).min
353
+ hidden_states = hidden_states.transpose(-1, -2)
354
+ else:
355
+ pad_value = 0
356
+
357
+ hidden_states = torch.nn.functional.pad(
358
+ hidden_states.transpose(-1, -2),
359
+ pad=(s, s),
360
+ value=pad_value
361
+ ).transpose(-1, -2)
362
+
363
+ # Make blocks
364
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
365
+
366
+ # Fix case where block_size == sparsify_factor
367
+ if odd_offset:
368
+ hidden_states = hidden_states[..., :-1, :, :]
369
+
370
+ # Indexes for selection
371
+ u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
372
+ s = self.sparse_block_size
373
+
374
+ # Skip right block if causal
375
+ if self.is_causal:
376
+ return hidden_states[..., u-s:u, :]
377
+
378
+ u_ = u + odd_offset
379
+ return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
380
+
381
+ def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
382
+
383
+ n, h, b, t, d = x_local.size()
384
+ x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
385
+ if x_sparse is not None:
386
+ return torch.cat([x_global, x_sparse, x_local], dim=dim)
387
+ return torch.cat([x_global, x_local], dim=dim)
388
+
389
+ def chunk(self, x, n_blocks):
390
+
391
+ t, d = x.size()[-2:]
392
+ return x.reshape(*x.size()[:-2], n_blocks, -1, d)
393
+
394
+
395
+ class LSGBertEmbeddings(BertEmbeddings):
396
+
397
+ def __init__(self, config):
398
+ super().__init__(config)
399
+
400
+ self.num_global_tokens = config.num_global_tokens
401
+
402
+ # Hardcoded but partially trained
403
+ self.global_embeddings = nn.Embedding(512, embedding_dim=config.hidden_size, )
404
+
405
+ self.block_size = config.block_size
406
+
407
+ def forward(
408
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
409
+ ):
410
+ if input_ids is not None:
411
+ input_shape = input_ids.size()
412
+ else:
413
+ input_shape = inputs_embeds.size()[:-1]
414
+
415
+ seq_length = input_shape[1]
416
+
417
+ if position_ids is None:
418
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
419
+
420
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
421
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
422
+ # issue #5664
423
+ if token_type_ids is None:
424
+ if hasattr(self, "token_type_ids"):
425
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
426
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
427
+ token_type_ids = buffered_token_type_ids_expanded
428
+ else:
429
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
430
+
431
+ if inputs_embeds is None:
432
+ inputs_embeds = self.word_embeddings(input_ids)
433
+ token_type_embeddings = self.token_type_embeddings(token_type_ids[:, :seq_length])
434
+
435
+ embeddings = inputs_embeds + token_type_embeddings
436
+ if self.position_embedding_type == "absolute":
437
+ position_embeddings = self.position_embeddings(position_ids[:, :seq_length])
438
+ embeddings += position_embeddings
439
+
440
+ #if self.num_global_tokens < 0:
441
+ n, t, d = embeddings.size()
442
+
443
+ # Add global_tokens
444
+ indexes = torch.arange(self.num_global_tokens, device=embeddings.device).reshape(1, -1)
445
+ global_embeddings = self.global_embeddings(indexes)
446
+ embeddings = torch.cat([global_embeddings.expand(n, -1, d), embeddings], dim=-2)
447
+
448
+ embeddings = self.LayerNorm(embeddings)
449
+ embeddings = self.dropout(embeddings)
450
+ return embeddings
451
+
452
+
453
+ class LSGSelfAttention(BaseSelfAttention):
454
+ '''
455
+ Compute local attention with overlapping blocs
456
+ Use global attention for tokens with highest norm
457
+ '''
458
+ def __init__(self, config):
459
+ super().__init__()
460
+
461
+ self.init_modules(config)
462
+
463
+ self.block_size = config.block_size
464
+ self.sparse_block_size = config.sparse_block_size
465
+ self.num_global_tokens = config.num_global_tokens
466
+ self.sparsity_factor = config.sparsity_factor
467
+ self.is_causal = config.is_decoder
468
+ self.is_decoder = config.is_decoder
469
+
470
+ self.attention = LSGAttentionProduct(
471
+ config,
472
+ block_size=config.block_size,
473
+ sparse_block_size=config.sparse_block_size,
474
+ sparsity_factor=self.sparsity_factor,
475
+ is_causal=self.is_causal
476
+ )
477
+
478
+ if self.is_causal:
479
+ self.causal_attention = CausalAttentionProduct(config)
480
+ self.full_attention = BaseAttentionProduct(config)
481
+
482
+ sparse_functions = {
483
+ "norm": self.get_sparse_tokens_with_norm,
484
+ "pooling": self.get_sparse_tokens_with_pooling,
485
+ "lsh": self.get_sparse_tokens_with_lsh,
486
+ "stride": self.get_sparse_tokens_with_stride,
487
+ "block_stride": self.get_sparse_tokens_with_block_stride,
488
+ }
489
+
490
+ self.sparsity_type = config.sparsity_type
491
+ self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda x, y, z: (None, None, None))
492
+
493
+ if config.sparsity_type == "lsh":
494
+ self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
495
+
496
+ def get_sparse_tokens_with_norm(self, keys, values, mask):
497
+
498
+ if self.sparsity_factor == 1:
499
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
500
+
501
+ with torch.no_grad():
502
+
503
+ block_size = min(self.block_size, self.sparse_block_size)
504
+ key_norm = keys.detach().norm(dim=-1, keepdim=True)
505
+ key_norm = key_norm * ~mask.transpose(-1, -2).bool()
506
+ key_norm = self.chunk(key_norm, block_size)
507
+
508
+ n, h, b, t, d = key_norm.size()
509
+
510
+ idx = key_norm.argsort(dim=-2)
511
+ del key_norm
512
+ idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
513
+
514
+ split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
515
+ sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
516
+
517
+ d = keys.size()[-1]
518
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
519
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
520
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
521
+
522
+ return keys, values, mask
523
+
524
+ def get_sparse_tokens_with_pooling(self, keys, values, mask):
525
+
526
+ if self.sparsity_factor == 1:
527
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
528
+
529
+ keys = self.chunk(keys, self.sparsity_factor)
530
+ values = self.chunk(values, self.sparsity_factor)
531
+
532
+ n, h, b, t, d = keys.size()
533
+ mask = mask.reshape(n, 1, b, 1, t)
534
+ mask = ~mask.transpose(-1, -2).bool()
535
+
536
+ keys = keys * mask
537
+ values = values * mask
538
+
539
+ mask = mask.sum(dim=-2)
540
+ keys = keys.sum(dim=-2) / (mask + 1e-6)
541
+ values = values.sum(dim=-2) / (mask + 1e-6)
542
+
543
+ mask = (1. - mask.clamp(0, 1)) * torch.finfo(mask.dtype).min
544
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
545
+
546
+ def get_sparse_tokens_with_stride(self, keys, values, mask):
547
+
548
+ if self.sparsity_factor == 1:
549
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
550
+
551
+ n, h, t, d = keys.size()
552
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
553
+ sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
554
+ sparse_idx = sparse_idx.expand(n, h, -1, 1)
555
+
556
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
557
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
558
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
559
+
560
+ return keys, values, mask
561
+
562
+ def get_sparse_tokens_with_block_stride(self, keys, values, mask):
563
+
564
+ if self.sparsity_factor == 1:
565
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
566
+
567
+ n, h, t, d = keys.size()
568
+
569
+ t, b = self.block_size, t // self.block_size
570
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device)
571
+ 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)
572
+ sparse_idx = (sparse_idx % t)
573
+ sparse_idx = sparse_idx + torch.arange(b, device=keys.device).reshape(1, 1, -1, 1, 1) * t
574
+ sparse_idx = sparse_idx.reshape(1, h, -1, 1).expand(n, h, -1, 1)
575
+
576
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
577
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
578
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
579
+
580
+ return keys, values, mask
581
+
582
+ def get_sparse_tokens_with_lsh(self, keys, values, mask):
583
+
584
+ if self.sparsity_factor == 1:
585
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
586
+
587
+ block_size = min(self.block_size, self.sparse_block_size)
588
+ keys = self.chunk(keys, block_size)
589
+ values = self.chunk(values, block_size)
590
+
591
+ n, h, b, t, d = keys.size()
592
+ mask = mask.reshape(n, 1, b, 1, t)
593
+ mask = ~mask.transpose(-1, -2).bool()
594
+
595
+ keys = keys * mask
596
+ values = values * mask
597
+ mask = mask.expand(-1, h, -1, -1, -1).float()
598
+
599
+ extra_factor = 1
600
+
601
+ for _ in range(self.lsh_num_pre_rounds):
602
+ keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
603
+
604
+ keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
605
+ keys /= mask + 1e-8
606
+ values /= mask + 1e-8
607
+
608
+ mask = (1. - mask.clamp(0, 1)) * torch.finfo(mask.dtype).min
609
+
610
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
611
+
612
+ def lsh_round(self, keys, values, mask, output_size):
613
+
614
+ with torch.no_grad():
615
+
616
+ n_hashes = output_size // 2
617
+ n, h, b, t, d = keys.size()
618
+ binary_mask = mask.clamp(0, 1)
619
+
620
+ indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
621
+ indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
622
+
623
+ n, h, b, t, d = keys.size()
624
+
625
+ x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
626
+ mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
627
+ keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
628
+ values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
629
+ mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
630
+
631
+ return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
632
+
633
+ def forward(
634
+ self,
635
+ hidden_states,
636
+ attention_mask=None,
637
+ head_mask=None,
638
+ encoder_hidden_states=None,
639
+ encoder_attention_mask=None,
640
+ past_key_value=None,
641
+ output_attentions=False,
642
+ ):
643
+
644
+ query_layer = self.query(hidden_states)
645
+
646
+ # If this is instantiated as a cross-attention module, the keys
647
+ # and values come from an encoder; the attention mask needs to be
648
+ # such that the encoder's padding tokens are not attended to.
649
+ is_cross_attention = encoder_hidden_states is not None
650
+
651
+ if is_cross_attention and past_key_value is not None:
652
+ # reuse k,v, cross_attentions
653
+ key_layer = past_key_value[0]
654
+ value_layer = past_key_value[1]
655
+ attention_mask = encoder_attention_mask
656
+ elif is_cross_attention:
657
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
658
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
659
+ attention_mask = encoder_attention_mask
660
+ elif past_key_value is not None:
661
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
662
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
663
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
664
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
665
+ else:
666
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
667
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
668
+
669
+ query_layer = self.transpose_for_scores(query_layer)
670
+
671
+ if self.is_decoder:
672
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
673
+ # Further calls to cross_attention layer can then reuse all cross-attention
674
+ # key/value_states (first "if" case)
675
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
676
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
677
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
678
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
679
+ past_key_value = (key_layer, value_layer)
680
+
681
+ if is_cross_attention:
682
+ outputs = self.cross_attention_forward(
683
+ query_layer=query_layer,
684
+ key_layer=key_layer,
685
+ value_layer=value_layer,
686
+ attention_mask=attention_mask,
687
+ output_attentions=output_attentions
688
+ )
689
+ else:
690
+ outputs = self.causal_forward(
691
+ query_layer,
692
+ key_layer,
693
+ value_layer,
694
+ attention_mask=attention_mask,
695
+ output_attentions=output_attentions,
696
+ )
697
+
698
+ outputs = outputs + ((key_layer, value_layer),)
699
+
700
+ else:
701
+ outputs = self.not_causal_forward(
702
+ query_layer,
703
+ key_layer,
704
+ value_layer,
705
+ attention_mask=attention_mask,
706
+ output_attentions=output_attentions
707
+ )
708
+
709
+ return outputs
710
+
711
+ def causal_forward(
712
+ self,
713
+ query_layer,
714
+ key_layer,
715
+ value_layer,
716
+ attention_mask=None,
717
+ output_attentions=False,
718
+ ):
719
+
720
+ n, h, t, d = key_layer.size()
721
+
722
+ # Cat global mask
723
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
724
+
725
+ # Split input into global tokens and other tokens
726
+ split = (self.num_global_tokens, t - self.num_global_tokens)
727
+ global_query, query_layer = query_layer.split(split, dim=-2)
728
+
729
+ # Use normal causal attention if local attention covers every tokens
730
+ if t <= 2 * self.block_size + self.num_global_tokens:
731
+ context_layer = self.causal_attention(
732
+ query_layer=query_layer,
733
+ key_layer=key_layer,
734
+ value_layer=value_layer,
735
+ attention_mask=attention_mask,
736
+ causal_shape=(t - self.num_global_tokens, t - self.num_global_tokens)
737
+ )
738
+
739
+ context_layer = torch.cat([global_query, context_layer], dim=-2)
740
+ return (self.reshape_output(context_layer), )
741
+
742
+ # Split K Q M on global and non global
743
+ global_key, key_layer = key_layer.split(split, dim=-2)
744
+ global_value, value_layer = value_layer.split(split, dim=-2)
745
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
746
+
747
+ n, h, t, d = key_layer.size()
748
+
749
+ # Get sparse idx
750
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
751
+ if self.sparse_block_size and self.sparsity_factor > 0:
752
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
753
+
754
+ # Expand masks on heads
755
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
756
+ global_mask = global_mask.expand(-1, h, -1, -1)
757
+
758
+ # Compute dot product attention
759
+ context_layer = self.attention(
760
+ query_layer,
761
+ key_layer,
762
+ value_layer,
763
+ attention_mask,
764
+ sparse_key=sparse_key,
765
+ sparse_value=sparse_value,
766
+ sparse_mask=sparse_mask,
767
+ global_key=global_key,
768
+ global_value=global_value,
769
+ global_mask=global_mask
770
+ )
771
+
772
+ # Merge pseudo global (causal) and local-sparse tokens
773
+ context_layer = torch.cat([global_query, context_layer], dim=-2)
774
+ context_layer = self.reshape_output(context_layer)
775
+
776
+ return (context_layer,)
777
+
778
+ def not_causal_forward(
779
+ self,
780
+ query_layer,
781
+ key_layer,
782
+ value_layer,
783
+ attention_mask=None,
784
+ output_attentions=False,
785
+ ):
786
+
787
+ n, h, t, d = query_layer.size()
788
+
789
+ # Cat global mask
790
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
791
+
792
+ # Use normal attention if local attention covers every tokens
793
+ if t <= 2 * self.block_size + self.num_global_tokens:
794
+ context_layer = self.full_attention(
795
+ query_layer=query_layer,
796
+ key_layer=key_layer,
797
+ value_layer=value_layer,
798
+ attention_mask=attention_mask
799
+ )
800
+ return (self.reshape_output(context_layer), )
801
+
802
+ # Split input into global tokens and other tokens
803
+ split = (self.num_global_tokens, t - self.num_global_tokens)
804
+ global_query, query_layer = query_layer.split(split, dim=-2)
805
+
806
+ # Get global_attention
807
+ bos = self.full_attention(
808
+ query_layer=global_query,
809
+ key_layer=key_layer,
810
+ value_layer=value_layer,
811
+ attention_mask=attention_mask
812
+ )
813
+
814
+ # Split K Q M on global and non global
815
+ global_key, key_layer = key_layer.split(split, dim=-2)
816
+ global_value, value_layer = value_layer.split(split, dim=-2)
817
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
818
+
819
+ n, h, t, d = key_layer.size()
820
+
821
+ # Get sparse idx
822
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
823
+
824
+ if self.sparse_block_size and self.sparsity_factor > 0:
825
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
826
+
827
+ # Expand masks on heads
828
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
829
+ global_mask = global_mask.expand(-1, h, -1, -1)
830
+
831
+ # Compute dot product attention
832
+ context_layer = self.attention(
833
+ query_layer,
834
+ key_layer,
835
+ value_layer,
836
+ attention_mask,
837
+ sparse_key=sparse_key,
838
+ sparse_value=sparse_value,
839
+ sparse_mask=sparse_mask,
840
+ global_key=global_key,
841
+ global_value=global_value,
842
+ global_mask=global_mask
843
+ )
844
+
845
+ # Merge global and local-sparse tokens
846
+ context_layer = torch.cat([bos, context_layer], dim=-2)
847
+ context_layer = self.reshape_output(context_layer)
848
+
849
+ return (context_layer,)
850
+
851
+ def cross_attention_forward(
852
+ self,
853
+ query_layer,
854
+ key_layer,
855
+ value_layer,
856
+ attention_mask=None,
857
+ output_attentions=False,
858
+ ):
859
+
860
+ context_layer = self.full_attention(
861
+ query_layer=query_layer,
862
+ key_layer=key_layer,
863
+ value_layer=value_layer,
864
+ attention_mask=attention_mask
865
+ )
866
+ return (self.reshape_output(context_layer), )
867
+
868
+ def chunk(self, x, chunk_size):
869
+
870
+ n, h, t, d = x.size()
871
+ return x.reshape(n, h, -1, chunk_size, d)
872
+
873
+
874
+ class LSGAttention(BertAttention):
875
+
876
+ def __init__(self, config):
877
+
878
+ nn.Module.__init__(self)
879
+
880
+ self.self = LSGSelfAttention(config)
881
+ self.output = BertSelfOutput(config)
882
+ self.pruned_heads = set()
883
+
884
+
885
+ class LSGBertLayer(BertLayer):
886
+
887
+ def __init__(self, config):
888
+
889
+ super().__init__(config)
890
+
891
+ self.attention = LSGAttention(config)
892
+ if self.add_cross_attention:
893
+ if not self.is_decoder:
894
+ assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added"
895
+ self.crossattention = LSGAttention(config)
896
+
897
+
898
+ class LSGBertEncoder(BertEncoder):
899
+
900
+ def __init__(self, config):
901
+
902
+ super().__init__(config)
903
+
904
+ self.layer = nn.ModuleList([LSGBertLayer(config) for _ in range(config.num_hidden_layers)])
905
+
906
+
907
+ class LSGBertPreTrainedModel(BertPreTrainedModel):
908
+ """
909
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
910
+ models.
911
+ """
912
+
913
+ config_class = LSGBertConfig
914
+
915
+ def _set_gradient_checkpointing(self, module, value=False):
916
+ if isinstance(module, (BertEncoder, LSGBertEncoder)):
917
+ module.gradient_checkpointing = value
918
+
919
+
920
+ class LSGBertModel(LSGBertPreTrainedModel, BertModel):
921
+ """
922
+ This class overrides :class:`~transformers.BertModel`. Please check the superclass for the appropriate
923
+ documentation alongside usage examples.
924
+ """
925
+
926
+ config_class = LSGBertConfig
927
+
928
+ def __init__(self, config, add_pooling_layer=True):
929
+
930
+ LSGBertPreTrainedModel.__init__(self, config)
931
+
932
+ self.config = config
933
+ assert hasattr(config, "num_global_tokens")
934
+ self.num_global_tokens = config.num_global_tokens
935
+ self.pad_idx = config.pad_token_id
936
+
937
+ assert hasattr(config, "block_size") and hasattr(config, "adaptive")
938
+ self.block_size = config.block_size
939
+ self.adaptive = config.adaptive
940
+ self.mask_first_token = config.mask_first_token
941
+ self.pool_with_global = config.pool_with_global
942
+
943
+ self.embeddings = LSGBertEmbeddings(config)
944
+ self.encoder = LSGBertEncoder(config)
945
+ self.pooler = BertPooler(config) if add_pooling_layer else None
946
+
947
+ if config.add_cross_attention:
948
+ logger.warning(
949
+ "Cross attention is computed using full attention since it is not LSG compatible."
950
+ )
951
+
952
+ # Initialize weights and apply final processing
953
+ self.post_init()
954
+
955
+ def forward(
956
+ self,
957
+ input_ids=None,
958
+ attention_mask=None,
959
+ token_type_ids=None,
960
+ position_ids=None,
961
+ head_mask=None,
962
+ inputs_embeds=None,
963
+ encoder_hidden_states=None,
964
+ encoder_attention_mask=None,
965
+ past_key_values=None,
966
+ use_cache=None,
967
+ output_attentions=None,
968
+ output_hidden_states=None,
969
+ return_dict=None
970
+ ):
971
+
972
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
973
+ output_hidden_states = (
974
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
975
+ )
976
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
977
+
978
+ inputs_ = input_ids if input_ids is not None else inputs_embeds
979
+ n, t = inputs_.size()[:2]
980
+
981
+ if attention_mask is None:
982
+ attention_mask = torch.ones(n, t, device=inputs_.device, dtype=inputs_.dtype)
983
+ if self.mask_first_token:
984
+ attention_mask[:,0] = 0
985
+ if token_type_ids is None:
986
+ token_type_ids = torch.zeros(n, t, device=inputs_.device).long()
987
+
988
+ b = self.block_size * 2
989
+ pad = t % self.block_size
990
+
991
+ # Check if t is multiple of block_size and pad
992
+ if self.adaptive and t > b and pad > 0:
993
+ pad_length = self.block_size - pad
994
+ if input_ids is not None:
995
+ input_ids = torch.nn.functional.pad(input_ids, (0, pad_length), value=self.pad_idx)
996
+ else:
997
+ inputs_embeds = torch.nn.functional.pad(inputs_embeds.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
998
+
999
+ attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=0)
1000
+ token_type_ids = torch.nn.functional.pad(token_type_ids, (0, pad_length), value=0)
1001
+
1002
+ if position_ids is not None:
1003
+ position_ids = torch.nn.functional.pad(position_ids, (0, pad_length), value=0)
1004
+
1005
+ n, t_ = attention_mask.size()
1006
+
1007
+ encoder_outputs = super().forward(
1008
+ input_ids=input_ids,
1009
+ attention_mask=attention_mask,
1010
+ token_type_ids=token_type_ids,
1011
+ position_ids=position_ids,
1012
+ head_mask=head_mask,
1013
+ inputs_embeds=inputs_embeds,
1014
+ encoder_hidden_states=encoder_hidden_states,
1015
+ encoder_attention_mask=encoder_attention_mask,
1016
+ past_key_values=past_key_values,
1017
+ use_cache=use_cache,
1018
+ output_attentions=output_attentions,
1019
+ output_hidden_states=output_hidden_states,
1020
+ return_dict=return_dict
1021
+ )
1022
+
1023
+ sequence_output = encoder_outputs[0]
1024
+ if self.pool_with_global:
1025
+ sequence_output[:, self.num_global_tokens] = sequence_output[:, 0]
1026
+
1027
+ diff = t - t_
1028
+ n, _, d = sequence_output.size()
1029
+ sequence_output = sequence_output[..., self.num_global_tokens:, :]
1030
+
1031
+ # Adapt sequence to initial shape
1032
+ if diff < 0:
1033
+ sequence_output = sequence_output[:, :t]
1034
+
1035
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
1036
+
1037
+ if not return_dict:
1038
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
1039
+
1040
+ encoder_outputs.last_hidden_state = sequence_output
1041
+ encoder_outputs.pooler_output = pooled_output
1042
+ return encoder_outputs
1043
+
1044
+ def get_extended_attention_mask(self, attention_mask, input_shape, device=None):
1045
+
1046
+ # Do not rely on original triangular mask from BERT/RoBERTa for causalLM
1047
+ if attention_mask.dim() == 3:
1048
+ extended_attention_mask = attention_mask[:, None, :, :]
1049
+ elif attention_mask.dim() == 2:
1050
+ extended_attention_mask = attention_mask[:, None, None, :]
1051
+ else:
1052
+ raise ValueError(
1053
+ f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
1054
+ )
1055
+
1056
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
1057
+ extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(extended_attention_mask.dtype).min
1058
+
1059
+ return extended_attention_mask
1060
+
1061
+
1062
+ class LSGBertForPreTraining(LSGBertPreTrainedModel, BertForPreTraining):
1063
+
1064
+ def __init__(self, config):
1065
+
1066
+ LSGBertPreTrainedModel.__init__(self, config)
1067
+
1068
+ self.bert = LSGBertModel(config)
1069
+ self.cls = BertPreTrainingHeads(config)
1070
+
1071
+ # Initialize weights and apply final processing
1072
+ self.post_init()
1073
+
1074
+
1075
+ class LSGBertLMHeadModel(LSGBertPreTrainedModel, BertLMHeadModel):
1076
+
1077
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1078
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1079
+
1080
+ def __init__(self, config):
1081
+
1082
+ LSGBertPreTrainedModel.__init__(self, config)
1083
+
1084
+ if not config.is_decoder:
1085
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
1086
+
1087
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1088
+ self.cls = BertOnlyMLMHead(config)
1089
+
1090
+ # Initialize weights and apply final processing
1091
+ self.post_init()
1092
+
1093
+
1094
+ class LSGBertForMaskedLM(LSGBertPreTrainedModel, BertForMaskedLM):
1095
+ """
1096
+ This class overrides :class:`~transformers.BertForMaskedLM`. Please check the superclass for the appropriate
1097
+ documentation alongside usage examples.
1098
+ """
1099
+
1100
+ config_class = LSGBertConfig
1101
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1102
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
1103
+
1104
+ def __init__(self, config):
1105
+
1106
+ LSGBertPreTrainedModel.__init__(self, config)
1107
+
1108
+ if config.is_decoder:
1109
+ logger.warning(
1110
+ "If you want to use `LSGBertForMaskedLM` make sure `config.is_decoder=False` for "
1111
+ "bi-directional self-attention."
1112
+ )
1113
+
1114
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1115
+ self.cls = BertOnlyMLMHead(config)
1116
+
1117
+ # Initialize weights and apply final processing
1118
+ self.post_init()
1119
+
1120
+
1121
+ class LSGBertForNextSentencePrediction(LSGBertPreTrainedModel, BertForNextSentencePrediction):
1122
+
1123
+ def __init__(self, config):
1124
+
1125
+ LSGBertPreTrainedModel.__init__(self, config)
1126
+
1127
+ self.bert = LSGBertModel(config)
1128
+ self.cls = BertOnlyNSPHead(config)
1129
+
1130
+ # Initialize weights and apply final processing
1131
+ self.post_init()
1132
+
1133
+
1134
+ class LSGBertForSequenceClassification(LSGBertPreTrainedModel, BertForSequenceClassification):
1135
+ """
1136
+ This class overrides :class:`~transformers.BertForSequenceClassification`. Please check the superclass for the
1137
+ appropriate documentation alongside usage examples.
1138
+ """
1139
+
1140
+ config_class = LSGBertConfig
1141
+
1142
+ def __init__(self, config):
1143
+
1144
+ LSGBertPreTrainedModel.__init__(self, config)
1145
+
1146
+ self.num_labels = config.num_labels
1147
+ self.config = config
1148
+
1149
+ self.bert = LSGBertModel(config)
1150
+ classifier_dropout = (
1151
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1152
+ )
1153
+ self.dropout = nn.Dropout(classifier_dropout)
1154
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1155
+
1156
+ # Initialize weights and apply final processing
1157
+ self.post_init()
1158
+
1159
+
1160
+ class LSGBertForMultipleChoice(LSGBertPreTrainedModel, BertForMultipleChoice):
1161
+ """
1162
+ This class overrides :class:`~transformers.BertForMultipleChoice`. Please check the superclass for the
1163
+ appropriate documentation alongside usage examples.
1164
+ """
1165
+
1166
+ config_class = LSGBertConfig
1167
+
1168
+ def __init__(self, config):
1169
+
1170
+ LSGBertPreTrainedModel.__init__(self, config)
1171
+
1172
+ self.bert = LSGBertModel(config)
1173
+ classifier_dropout = (
1174
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1175
+ )
1176
+ self.dropout = nn.Dropout(classifier_dropout)
1177
+ self.classifier = nn.Linear(config.hidden_size, 1)
1178
+
1179
+ # Initialize weights and apply final processing
1180
+ self.post_init()
1181
+
1182
+
1183
+ class LSGBertForTokenClassification(LSGBertPreTrainedModel, BertForTokenClassification):
1184
+ """
1185
+ This class overrides :class:`~transformers.BertForTokenClassification`. Please check the superclass for the
1186
+ appropriate documentation alongside usage examples.
1187
+ """
1188
+
1189
+ config_class = LSGBertConfig
1190
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1191
+
1192
+ def __init__(self, config):
1193
+
1194
+ LSGBertPreTrainedModel.__init__(self, config)
1195
+
1196
+ self.num_labels = config.num_labels
1197
+
1198
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1199
+ classifier_dropout = (
1200
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1201
+ )
1202
+ self.dropout = nn.Dropout(classifier_dropout)
1203
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1204
+
1205
+ # Initialize weights and apply final processing
1206
+ self.post_init()
1207
+
1208
+
1209
+ class LSGBertForQuestionAnswering(LSGBertPreTrainedModel, BertForQuestionAnswering):
1210
+ """
1211
+ This class overrides :class:`~transformers.BertForQuestionAnswering`. Please check the superclass for the
1212
+ appropriate documentation alongside usage examples.
1213
+ """
1214
+
1215
+ config_class = LSGBertConfig
1216
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1217
+
1218
+ def __init__(self, config):
1219
+
1220
+ LSGBertPreTrainedModel.__init__(self, config)
1221
+
1222
+ self.num_labels = config.num_labels
1223
+
1224
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1225
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1226
+
1227
+ # Initialize weights and apply final processing
1228
+ self.post_init()
1229
+
1230
+
1231
+ def str_to_class(classname):
1232
+ return getattr(sys.modules[__name__], classname)
1233
+
1234
+ # Register model in Auto API
1235
+ try:
1236
+ LSGBertConfig.register_for_auto_class()
1237
+ for key, value in AUTO_MAP.items():
1238
+ str_to_class(value.split(".")[-1]).register_for_auto_class(key)
1239
+ except:
1240
+ warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
1241
+ 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:672aec6c2b777de8fb689b8fbafa3efd5960a6dd897ad4070fee85f17cf12b96
3
+ size 452310761
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_lower_case": true,
4
+ "mask_token": "[MASK]",
5
+ "model_max_length": 4096,
6
+ "name_or_path": "bert-base-uncased",
7
+ "pad_token": "[PAD]",
8
+ "sep_token": "[SEP]",
9
+ "special_tokens_map_file": null,
10
+ "strip_accents": null,
11
+ "tokenize_chinese_chars": true,
12
+ "tokenizer_class": "BertTokenizer",
13
+ "unk_token": "[UNK]"
14
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff