prudant commited on
Commit
2dad5a6
1 Parent(s): 95a6d8c

Upload model

Browse files
Files changed (3) hide show
  1. config.json +48 -0
  2. model.safetensors +3 -0
  3. modeling_lsg_bert.py +1231 -0
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "hiiamsid/sentence_similarity_spanish_es",
3
+ "adaptive": true,
4
+ "architectures": [
5
+ "LSGBertModel"
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": false,
31
+ "max_position_embeddings": 4096,
32
+ "model_type": "bert",
33
+ "num_attention_heads": 12,
34
+ "num_global_tokens": 7,
35
+ "num_hidden_layers": 12,
36
+ "output_past": true,
37
+ "pad_token_id": 1,
38
+ "pool_with_global": true,
39
+ "position_embedding_type": "absolute",
40
+ "sparse_block_size": 128,
41
+ "sparsity_factor": 2,
42
+ "sparsity_type": "norm",
43
+ "torch_dtype": "float32",
44
+ "transformers_version": "4.36.1",
45
+ "type_vocab_size": 2,
46
+ "use_cache": true,
47
+ "vocab_size": 31002
48
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:09f7e0019611f89dfbcff3f4d4fa558025a5960e9445908ebb9294581e3ad97c
3
+ size 452008920
modeling_lsg_bert.py ADDED
@@ -0,0 +1,1231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "bos_pooling"]:
58
+ logger.warning(
59
+ "[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride', 'bos_pooling'], \
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.num_attention_heads:
65
+ logger.warning(
66
+ "[WARNING CONFIG]: sparsity_factor > num_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
+ # Add causal mask
193
+ causal_shape = (self.block_size, self.block_size) if causal_shape is None else causal_shape
194
+ causal_mask = torch.tril(
195
+ torch.ones(*causal_shape, device=attention_mask.device, dtype=attention_scores.dtype),
196
+ diagonal=-1
197
+ )
198
+
199
+ # Min value
200
+ dtype_min = torch.tensor(
201
+ torch.finfo(attention_scores.dtype).min, device=attention_scores.device, dtype=attention_scores.dtype
202
+ )
203
+
204
+ # Build causal + attention_mask
205
+ causal_mask = torch.nn.functional.pad(causal_mask.T * dtype_min, (attention_mask.size()[-1] - self.block_size, 0), value=0)
206
+ attention_mask = torch.max(attention_mask + causal_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0), dtype_min)
207
+
208
+ attention_scores = attention_scores + attention_mask
209
+ del attention_mask
210
+ del causal_mask
211
+
212
+ # Normalize the attention scores to probabilities.
213
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
214
+
215
+ # This is actually dropping out entire tokens to attend to, which might
216
+ # seem a bit unusual, but is taken from the original Transformer paper.
217
+ context_layer = self.dropout(attention_probs) @ value_layer
218
+
219
+ return context_layer
220
+
221
+
222
+ class LSGAttentionProduct(nn.Module):
223
+
224
+ def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4, is_causal=False):
225
+ """
226
+ Compute block or overlapping blocks attention products
227
+ """
228
+ super().__init__()
229
+
230
+ self.block_size = block_size
231
+ self.sparse_block_size = sparse_block_size
232
+ self.sparsity_factor = sparsity_factor
233
+ self.is_causal = is_causal
234
+
235
+ if self.block_size is None:
236
+ self.block_size = config.block_size
237
+
238
+ if self.sparse_block_size is None:
239
+ self.sparse_block_size = config.sparse_block_size
240
+
241
+ # Shape of blocks
242
+ self.local_shapes = (self.block_size*3, self.block_size)
243
+ if self.sparse_block_size and self.sparsity_factor > 0:
244
+ self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
245
+
246
+ if is_causal:
247
+ self.attention = CausalAttentionProduct(config)
248
+ else:
249
+ self.attention = BaseAttentionProduct(config)
250
+
251
+ def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
252
+
253
+ # Build local tokens
254
+ local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
255
+ del hidden_states
256
+
257
+ # Build sparse tokens
258
+ if sparse_hidden_states is not None:
259
+ sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
260
+
261
+ return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
262
+
263
+ def forward(
264
+ self,
265
+ query_layer,
266
+ key_layer,
267
+ value_layer,
268
+ attention_mask=None,
269
+ sparse_key=None,
270
+ sparse_value=None,
271
+ sparse_mask=None,
272
+ global_key=None,
273
+ global_value=None,
274
+ global_mask=None
275
+ ):
276
+
277
+ # Input batch, heads, length, hidden_size
278
+ n, h, t, d = query_layer.size()
279
+ n_blocks = t // self.block_size
280
+ assert t % self.block_size == 0
281
+
282
+ key_layer = self.build_lsg_inputs(
283
+ key_layer,
284
+ sparse_key,
285
+ global_key
286
+ )
287
+ del sparse_key
288
+ del global_key
289
+
290
+ value_layer = self.build_lsg_inputs(
291
+ value_layer,
292
+ sparse_value,
293
+ global_value
294
+ )
295
+ del sparse_value
296
+ del global_value
297
+
298
+ attention_mask = self.build_lsg_inputs(
299
+ attention_mask,
300
+ sparse_mask,
301
+ global_mask.transpose(-1, -2),
302
+ is_attn_mask=True
303
+ ).transpose(-1, -2)
304
+ del sparse_mask
305
+ del global_mask
306
+
307
+ # expect (..., t, d) shape
308
+ # Compute attention
309
+ context_layer = self.attention(
310
+ query_layer=self.chunk(query_layer, n_blocks),
311
+ key_layer=key_layer,
312
+ value_layer=value_layer,
313
+ attention_mask=attention_mask
314
+ )
315
+
316
+ return context_layer.reshape(n, h, -1, d)
317
+
318
+ def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
319
+
320
+ size, step = self.local_shapes
321
+ s = (size - step) // 2
322
+
323
+ # Pad before block reshaping
324
+ if is_attn_mask:
325
+ pad_value = torch.finfo(hidden_states.dtype).min
326
+ hidden_states = hidden_states.transpose(-1, -2)
327
+ else:
328
+ pad_value = 0
329
+
330
+ hidden_states = torch.nn.functional.pad(
331
+ hidden_states.transpose(-1, -2),
332
+ pad=(s, s),
333
+ value=pad_value
334
+ ).transpose(-1, -2)
335
+
336
+ # Make blocks
337
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
338
+
339
+ # Skip third block if causal
340
+ if self.is_causal:
341
+ return hidden_states[..., :size*2//3, :]
342
+
343
+ return hidden_states
344
+
345
+ def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
346
+
347
+ size, step = self.sparse_shapes
348
+
349
+ # In case of odd case
350
+ odd_offset = (step % 2)
351
+
352
+ # n, h, t, d*2 + 1
353
+ size = size*2
354
+ s = (size - step) // 2 + odd_offset
355
+
356
+ # Pad before block reshaping
357
+ if is_attn_mask:
358
+ pad_value = torch.finfo(hidden_states.dtype).min
359
+ hidden_states = hidden_states.transpose(-1, -2)
360
+ else:
361
+ pad_value = 0
362
+
363
+ hidden_states = torch.nn.functional.pad(
364
+ hidden_states.transpose(-1, -2),
365
+ pad=(s, s),
366
+ value=pad_value
367
+ ).transpose(-1, -2)
368
+
369
+ # Make blocks
370
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
371
+
372
+ # Fix case where block_size == sparsify_factor
373
+ if odd_offset:
374
+ hidden_states = hidden_states[..., :-1, :, :]
375
+
376
+ # Indexes for selection
377
+ u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
378
+ s = self.sparse_block_size
379
+
380
+ # Skip right block if causal
381
+ if self.is_causal:
382
+ return hidden_states[..., u-s:u, :]
383
+
384
+ u_ = u + odd_offset
385
+ return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
386
+
387
+ def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
388
+
389
+ n, h, b, t, d = x_local.size()
390
+ x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
391
+ if x_sparse is not None:
392
+ return torch.cat([x_global, x_sparse, x_local], dim=dim)
393
+ return torch.cat([x_global, x_local], dim=dim)
394
+
395
+ def chunk(self, x, n_blocks):
396
+
397
+ t, d = x.size()[-2:]
398
+ return x.reshape(*x.size()[:-2], n_blocks, -1, d)
399
+
400
+
401
+ class LSGBertEmbeddings(BertEmbeddings):
402
+
403
+ def __init__(self, config):
404
+ super().__init__(config)
405
+
406
+ self.num_global_tokens = config.num_global_tokens
407
+
408
+ # Hardcoded but partially trained
409
+ self.global_embeddings = nn.Embedding(512, embedding_dim=config.hidden_size, )
410
+
411
+ self.block_size = config.block_size
412
+
413
+ def forward(
414
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
415
+ ):
416
+ if input_ids is not None:
417
+ input_shape = input_ids.size()
418
+ else:
419
+ input_shape = inputs_embeds.size()[:-1]
420
+
421
+ seq_length = input_shape[1]
422
+
423
+ if position_ids is None:
424
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
425
+
426
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
427
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
428
+ # issue #5664
429
+ if token_type_ids is None:
430
+ if hasattr(self, "token_type_ids"):
431
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
432
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
433
+ token_type_ids = buffered_token_type_ids_expanded
434
+ else:
435
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
436
+
437
+ if inputs_embeds is None:
438
+ inputs_embeds = self.word_embeddings(input_ids)
439
+ token_type_embeddings = self.token_type_embeddings(token_type_ids[:, :seq_length])
440
+
441
+ embeddings = inputs_embeds + token_type_embeddings
442
+ if self.position_embedding_type == "absolute":
443
+ position_embeddings = self.position_embeddings(position_ids[:, :seq_length])
444
+ embeddings += position_embeddings
445
+
446
+ #if self.num_global_tokens < 0:
447
+ n, t, d = embeddings.size()
448
+
449
+ # Add global_tokens
450
+ indexes = torch.arange(self.num_global_tokens, device=embeddings.device).reshape(1, -1)
451
+ global_embeddings = self.global_embeddings(indexes)
452
+ embeddings = torch.cat([global_embeddings.expand(n, -1, d), embeddings], dim=-2)
453
+
454
+ embeddings = self.LayerNorm(embeddings)
455
+ embeddings = self.dropout(embeddings)
456
+ return embeddings
457
+
458
+
459
+ class LSGSelfAttention(BaseSelfAttention):
460
+ '''
461
+ Compute local attention with overlapping blocs
462
+ Use global attention for tokens with highest norm
463
+ '''
464
+ def __init__(self, config):
465
+ super().__init__()
466
+
467
+ self.init_modules(config)
468
+
469
+ self.block_size = config.block_size
470
+ self.sparse_block_size = config.sparse_block_size
471
+ self.num_global_tokens = config.num_global_tokens
472
+ self.sparsity_factor = config.sparsity_factor
473
+ self.is_causal = config.is_decoder
474
+ self.is_decoder = config.is_decoder
475
+
476
+ self.attention = LSGAttentionProduct(
477
+ config,
478
+ block_size=config.block_size,
479
+ sparse_block_size=config.sparse_block_size,
480
+ sparsity_factor=self.sparsity_factor,
481
+ is_causal=self.is_causal
482
+ )
483
+
484
+ if self.is_causal:
485
+ self.causal_attention = CausalAttentionProduct(config)
486
+ self.full_attention = BaseAttentionProduct(config)
487
+
488
+ sparse_functions = {
489
+ "norm": self.get_sparse_tokens_with_norm,
490
+ "pooling": self.get_sparse_tokens_with_pooling,
491
+ "lsh": self.get_sparse_tokens_with_lsh,
492
+ "stride": self.get_sparse_tokens_with_stride,
493
+ "block_stride": self.get_sparse_tokens_with_block_stride,
494
+ "bos_pooling": self.get_sparse_tokens_with_bos_pooling
495
+ }
496
+
497
+ self.sparsity_type = config.sparsity_type
498
+ self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda w, x, y, z: (None, None, None))
499
+
500
+ if config.sparsity_type == "lsh":
501
+ self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
502
+
503
+ def get_sparse_tokens_with_norm(self, queries, keys, values, mask):
504
+
505
+ if self.sparsity_factor == 1:
506
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
507
+
508
+ with torch.no_grad():
509
+
510
+ block_size = min(self.block_size, self.sparse_block_size)
511
+ key_norm = keys.detach().norm(dim=-1, keepdim=True)
512
+ key_norm = key_norm * ~mask.transpose(-1, -2).bool()
513
+ key_norm = self.chunk(key_norm, block_size)
514
+
515
+ n, h, b, t, d = key_norm.size()
516
+
517
+ idx = key_norm.argsort(dim=-2)
518
+ del key_norm
519
+ idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
520
+
521
+ split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
522
+ sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
523
+
524
+ d = keys.size()[-1]
525
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
526
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
527
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
528
+
529
+ return keys, values, mask
530
+
531
+ def get_sparse_tokens_with_pooling(self, queries, keys, values, mask):
532
+
533
+ if self.sparsity_factor == 1:
534
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
535
+
536
+ keys = self.chunk(keys, self.sparsity_factor)
537
+ values = self.chunk(values, self.sparsity_factor)
538
+
539
+ n, h, b, t, d = keys.size()
540
+ mask = mask.reshape(n, 1, b, 1, t)
541
+ mask = ~mask.transpose(-1, -2).bool()
542
+
543
+ keys = keys * mask
544
+ values = values * mask
545
+
546
+ mask = mask.sum(dim=-2)
547
+ keys = keys.sum(dim=-2) / (mask + 1e-6)
548
+ values = values.sum(dim=-2) / (mask + 1e-6)
549
+
550
+ mask = (1. - mask.clamp(0, 1))
551
+ mask *= torch.finfo(mask.dtype).min
552
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
553
+
554
+ def get_sparse_tokens_with_stride(self, queries, keys, values, mask):
555
+
556
+ if self.sparsity_factor == 1:
557
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
558
+
559
+ n, h, t, d = keys.size()
560
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
561
+ sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
562
+ sparse_idx = sparse_idx.expand(n, h, -1, 1)
563
+
564
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
565
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
566
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
567
+
568
+ return keys, values, mask
569
+
570
+ def get_sparse_tokens_with_block_stride(self, queries, keys, values, mask):
571
+
572
+ if self.sparsity_factor == 1:
573
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
574
+
575
+ n, h, t, d = keys.size()
576
+
577
+ t, b = self.block_size, t // self.block_size
578
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device)
579
+ 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)
580
+ sparse_idx = (sparse_idx % t)
581
+ sparse_idx = sparse_idx + torch.arange(b, device=keys.device).reshape(1, 1, -1, 1, 1) * t
582
+ sparse_idx = sparse_idx.reshape(1, h, -1, 1).expand(n, h, -1, 1)
583
+
584
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
585
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
586
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
587
+
588
+ return keys, values, mask
589
+
590
+ def get_sparse_tokens_with_lsh(self, queries, keys, values, mask):
591
+
592
+ if self.sparsity_factor == 1:
593
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
594
+
595
+ if self.sparsity_factor == self.sparse_block_size:
596
+ return self.get_sparse_tokens_with_bos_pooling(queries, keys, values, mask)
597
+
598
+ block_size = min(self.block_size, self.sparse_block_size)
599
+ keys = self.chunk(keys, block_size)
600
+ values = self.chunk(values, block_size)
601
+
602
+ n, h, b, t, d = keys.size()
603
+ mask = mask.reshape(n, 1, b, 1, t)
604
+ mask = ~mask.transpose(-1, -2).bool()
605
+
606
+ keys = keys * mask
607
+ values = values * mask
608
+ mask = mask.expand(-1, h, -1, -1, -1).float()
609
+
610
+ extra_factor = 1
611
+
612
+ for _ in range(self.lsh_num_pre_rounds):
613
+ keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
614
+
615
+ keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
616
+ keys /= mask + 1e-8
617
+ values /= mask + 1e-8
618
+
619
+ mask = (1. - mask.clamp(0, 1))
620
+ mask *= torch.finfo(mask.dtype).min
621
+
622
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
623
+
624
+ def lsh_round(self, keys, values, mask, output_size):
625
+
626
+ with torch.no_grad():
627
+
628
+ n_hashes = output_size // 2
629
+ n, h, b, t, d = keys.size()
630
+ binary_mask = mask.clamp(0, 1)
631
+
632
+ indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
633
+ indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
634
+
635
+ n, h, b, t, d = keys.size()
636
+
637
+ x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
638
+ mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
639
+ keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
640
+ values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
641
+ mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
642
+
643
+ return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
644
+
645
+ def get_sparse_tokens_with_bos_pooling(self, queries, keys, values, mask):
646
+
647
+ if self.sparsity_factor == 1:
648
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
649
+
650
+ queries = queries.unsqueeze(-3)
651
+ mask = self.chunk(mask.transpose(-1, -2), self.sparsity_factor).transpose(-1, -2)
652
+ keys = self.chunk(keys, self.sparsity_factor)
653
+ values = self.chunk(values, self.sparsity_factor)
654
+
655
+ n, h, b, t, d = keys.size()
656
+ scores = (queries[..., :1, :] @ keys.transpose(-1, -2)) / math.sqrt(d)
657
+ if mask is not None:
658
+ scores = scores + mask
659
+
660
+ scores = torch.softmax(scores, dim=-1)
661
+ keys = scores @ keys
662
+ values = scores @ values
663
+ mask = mask.mean(dim=-1)
664
+ mask[mask != torch.finfo(mask.dtype).min] = 0
665
+
666
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
667
+
668
+ def forward(
669
+ self,
670
+ hidden_states,
671
+ attention_mask=None,
672
+ head_mask=None,
673
+ encoder_hidden_states=None,
674
+ encoder_attention_mask=None,
675
+ past_key_value=None,
676
+ output_attentions=False,
677
+ ):
678
+
679
+ query_layer = self.query(hidden_states)
680
+
681
+ # If this is instantiated as a cross-attention module, the keys
682
+ # and values come from an encoder; the attention mask needs to be
683
+ # such that the encoder's padding tokens are not attended to.
684
+ is_cross_attention = encoder_hidden_states is not None
685
+
686
+ if is_cross_attention and past_key_value is not None:
687
+ # reuse k,v, cross_attentions
688
+ key_layer = past_key_value[0]
689
+ value_layer = past_key_value[1]
690
+ attention_mask = encoder_attention_mask
691
+ elif is_cross_attention:
692
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
693
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
694
+ attention_mask = encoder_attention_mask
695
+ elif past_key_value is not None:
696
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
697
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
698
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
699
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
700
+ else:
701
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
702
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
703
+
704
+ query_layer = self.transpose_for_scores(query_layer)
705
+
706
+ if self.is_decoder:
707
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
708
+ # Further calls to cross_attention layer can then reuse all cross-attention
709
+ # key/value_states (first "if" case)
710
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
711
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
712
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
713
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
714
+ past_key_value = (key_layer, value_layer)
715
+
716
+ if is_cross_attention:
717
+ outputs = self.cross_attention_forward(
718
+ query_layer=query_layer,
719
+ key_layer=key_layer,
720
+ value_layer=value_layer,
721
+ attention_mask=attention_mask,
722
+ output_attentions=output_attentions
723
+ )
724
+ else:
725
+ outputs = self.causal_forward(
726
+ query_layer,
727
+ key_layer,
728
+ value_layer,
729
+ attention_mask=attention_mask,
730
+ output_attentions=output_attentions,
731
+ )
732
+
733
+ outputs = outputs + ((key_layer, value_layer),)
734
+
735
+ else:
736
+ outputs = self.not_causal_forward(
737
+ query_layer,
738
+ key_layer,
739
+ value_layer,
740
+ attention_mask=attention_mask,
741
+ output_attentions=output_attentions
742
+ )
743
+
744
+ return outputs
745
+
746
+ def causal_forward(
747
+ self,
748
+ query_layer,
749
+ key_layer,
750
+ value_layer,
751
+ attention_mask=None,
752
+ output_attentions=False,
753
+ ):
754
+
755
+ n, h, t, d = key_layer.size()
756
+
757
+ # Cat global mask
758
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
759
+
760
+ # Split input into global tokens and other tokens
761
+ split = (self.num_global_tokens, t - self.num_global_tokens)
762
+ global_query, query_layer = query_layer.split(split, dim=-2)
763
+
764
+ # Use normal causal attention if local attention covers every tokens
765
+ if t <= 2 * self.block_size + self.num_global_tokens:
766
+ context_layer = self.causal_attention(
767
+ query_layer=query_layer,
768
+ key_layer=key_layer,
769
+ value_layer=value_layer,
770
+ attention_mask=attention_mask,
771
+ causal_shape=(t - self.num_global_tokens, t - self.num_global_tokens)
772
+ )
773
+
774
+ context_layer = torch.cat([global_query, context_layer], dim=-2)
775
+ return (self.reshape_output(context_layer), )
776
+
777
+ # Split K Q M on global and non global
778
+ global_key, key_layer = key_layer.split(split, dim=-2)
779
+ global_value, value_layer = value_layer.split(split, dim=-2)
780
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
781
+
782
+ n, h, t, d = key_layer.size()
783
+
784
+ # Get sparse idx
785
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
786
+ if self.sparse_block_size and self.sparsity_factor > 0:
787
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(query_layer, key_layer, value_layer, attention_mask)
788
+
789
+ # Expand masks on heads
790
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
791
+ global_mask = global_mask.expand(-1, h, -1, -1)
792
+
793
+ # Compute dot product attention
794
+ context_layer = self.attention(
795
+ query_layer,
796
+ key_layer,
797
+ value_layer,
798
+ attention_mask,
799
+ sparse_key=sparse_key,
800
+ sparse_value=sparse_value,
801
+ sparse_mask=sparse_mask,
802
+ global_key=global_key,
803
+ global_value=global_value,
804
+ global_mask=global_mask
805
+ )
806
+
807
+ # Merge pseudo global (causal) and local-sparse tokens
808
+ context_layer = torch.cat([global_query, context_layer], dim=-2)
809
+ context_layer = self.reshape_output(context_layer)
810
+
811
+ return (context_layer,)
812
+
813
+ def not_causal_forward(
814
+ self,
815
+ query_layer,
816
+ key_layer,
817
+ value_layer,
818
+ attention_mask=None,
819
+ output_attentions=False,
820
+ ):
821
+
822
+ n, h, t, d = query_layer.size()
823
+
824
+ # Cat global mask
825
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
826
+
827
+ # Use normal attention if local attention covers every tokens
828
+ if t <= 2 * self.block_size + self.num_global_tokens:
829
+ context_layer = self.full_attention(
830
+ query_layer=query_layer,
831
+ key_layer=key_layer,
832
+ value_layer=value_layer,
833
+ attention_mask=attention_mask
834
+ )
835
+ return (self.reshape_output(context_layer), )
836
+
837
+ # Split input into global tokens and other tokens
838
+ split = (self.num_global_tokens, t - self.num_global_tokens)
839
+ global_query, query_layer = query_layer.split(split, dim=-2)
840
+
841
+ # Get global_attention
842
+ bos = self.full_attention(
843
+ query_layer=global_query,
844
+ key_layer=key_layer,
845
+ value_layer=value_layer,
846
+ attention_mask=attention_mask
847
+ )
848
+
849
+ # Split K Q M on global and non global
850
+ global_key, key_layer = key_layer.split(split, dim=-2)
851
+ global_value, value_layer = value_layer.split(split, dim=-2)
852
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
853
+
854
+ n, h, t, d = key_layer.size()
855
+
856
+ # Get sparse idx
857
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
858
+
859
+ if self.sparse_block_size and self.sparsity_factor > 0:
860
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(query_layer, key_layer, value_layer, attention_mask)
861
+
862
+ # Expand masks on heads
863
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
864
+ global_mask = global_mask.expand(-1, h, -1, -1)
865
+
866
+ # Compute dot product attention
867
+ context_layer = self.attention(
868
+ query_layer,
869
+ key_layer,
870
+ value_layer,
871
+ attention_mask,
872
+ sparse_key=sparse_key,
873
+ sparse_value=sparse_value,
874
+ sparse_mask=sparse_mask,
875
+ global_key=global_key,
876
+ global_value=global_value,
877
+ global_mask=global_mask
878
+ )
879
+
880
+ # Merge global and local-sparse tokens
881
+ context_layer = torch.cat([bos, context_layer], dim=-2)
882
+ context_layer = self.reshape_output(context_layer)
883
+
884
+ return (context_layer,)
885
+
886
+ def cross_attention_forward(
887
+ self,
888
+ query_layer,
889
+ key_layer,
890
+ value_layer,
891
+ attention_mask=None,
892
+ output_attentions=False,
893
+ ):
894
+
895
+ context_layer = self.full_attention(
896
+ query_layer=query_layer,
897
+ key_layer=key_layer,
898
+ value_layer=value_layer,
899
+ attention_mask=attention_mask
900
+ )
901
+ return (self.reshape_output(context_layer), )
902
+
903
+ def chunk(self, x, chunk_size):
904
+
905
+ n, h, t, d = x.size()
906
+ return x.reshape(n, h, -1, chunk_size, d)
907
+
908
+
909
+ class LSGAttention(BertAttention):
910
+
911
+ def __init__(self, config):
912
+
913
+ nn.Module.__init__(self)
914
+
915
+ self.self = LSGSelfAttention(config)
916
+ self.output = BertSelfOutput(config)
917
+ self.pruned_heads = set()
918
+
919
+
920
+ class LSGBertLayer(BertLayer):
921
+
922
+ def __init__(self, config):
923
+
924
+ super().__init__(config)
925
+
926
+ self.attention = LSGAttention(config)
927
+ if self.add_cross_attention:
928
+ if not self.is_decoder:
929
+ assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added"
930
+ self.crossattention = LSGAttention(config)
931
+
932
+
933
+ class LSGBertEncoder(BertEncoder):
934
+
935
+ def __init__(self, config):
936
+
937
+ super().__init__(config)
938
+
939
+ self.layer = nn.ModuleList([LSGBertLayer(config) for _ in range(config.num_hidden_layers)])
940
+
941
+ assert hasattr(config, "num_global_tokens")
942
+ self.num_global_tokens = config.num_global_tokens
943
+ self.pad_idx = config.pad_token_id
944
+
945
+ assert hasattr(config, "block_size") and hasattr(config, "adaptive")
946
+ self.block_size = config.block_size
947
+ self.adaptive = config.adaptive
948
+ self.mask_first_token = config.mask_first_token
949
+ self.pool_with_global = config.pool_with_global
950
+
951
+ def forward(
952
+ self,
953
+ hidden_states: torch.Tensor,
954
+ attention_mask: Optional[torch.FloatTensor] = None,
955
+ head_mask: Optional[torch.FloatTensor] = None,
956
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
957
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
958
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
959
+ use_cache: Optional[bool] = None,
960
+ output_attentions: Optional[bool] = False,
961
+ output_hidden_states: Optional[bool] = False,
962
+ return_dict: Optional[bool] = True,
963
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
964
+
965
+ mask_value = torch.finfo(attention_mask.dtype).min
966
+ n, _, __, t = attention_mask.size()
967
+
968
+ if not (self.config.is_decoder and encoder_hidden_states is not None):
969
+
970
+ b = self.block_size * 2
971
+ pad = t % self.block_size
972
+
973
+ # Check if t is multiple of block_size and pad
974
+ if self.adaptive and t > b and pad > 0:
975
+ pad_length = self.block_size - pad
976
+ hidden_states = torch.nn.functional.pad(hidden_states.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
977
+ attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=mask_value)
978
+
979
+ if self.mask_first_token:
980
+ attention_mask[..., 0] = mask_value
981
+
982
+ encoder_outputs = super().forward(
983
+ hidden_states=hidden_states,
984
+ attention_mask=attention_mask,
985
+ head_mask=head_mask,
986
+ encoder_hidden_states=encoder_hidden_states,
987
+ encoder_attention_mask=encoder_attention_mask,
988
+ past_key_values=past_key_values,
989
+ use_cache=use_cache,
990
+ output_attentions=output_attentions,
991
+ output_hidden_states=output_hidden_states,
992
+ return_dict=return_dict
993
+ )
994
+
995
+ sequence_output = encoder_outputs[0]
996
+ if self.pool_with_global:
997
+ sequence_output[:, self.num_global_tokens] = sequence_output[:, 0]
998
+
999
+ # Adapt sequence to initial shape
1000
+ sequence_output = sequence_output[..., self.num_global_tokens: t + self.num_global_tokens, :]
1001
+
1002
+ if not return_dict:
1003
+ return (sequence_output, ) + encoder_outputs[1:]
1004
+
1005
+ encoder_outputs.last_hidden_state = sequence_output
1006
+ return encoder_outputs
1007
+
1008
+ class LSGBertPreTrainedModel(BertPreTrainedModel):
1009
+ """
1010
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1011
+ models.
1012
+ """
1013
+
1014
+ config_class = LSGBertConfig
1015
+
1016
+ def _set_gradient_checkpointing(self, module, value=False):
1017
+ if isinstance(module, (BertEncoder, LSGBertEncoder)):
1018
+ module.gradient_checkpointing = value
1019
+
1020
+
1021
+ class LSGBertModel(LSGBertPreTrainedModel, BertModel):
1022
+ """
1023
+ This class overrides :class:`~transformers.BertModel`. Please check the superclass for the appropriate
1024
+ documentation alongside usage examples.
1025
+ """
1026
+
1027
+ def __init__(self, config, add_pooling_layer=True):
1028
+
1029
+ LSGBertPreTrainedModel.__init__(self, config)
1030
+
1031
+ self.config = config
1032
+
1033
+ self.embeddings = LSGBertEmbeddings(config)
1034
+ self.encoder = LSGBertEncoder(config)
1035
+ self.pooler = BertPooler(config) if add_pooling_layer else None
1036
+
1037
+ if config.add_cross_attention:
1038
+ logger.warning(
1039
+ "Cross attention is computed using full attention since it is not LSG compatible."
1040
+ )
1041
+
1042
+ # Initialize weights and apply final processing
1043
+ self.post_init()
1044
+
1045
+ def get_extended_attention_mask(self, attention_mask, input_shape, device=None):
1046
+
1047
+ # Do not rely on original triangular mask from BERT/RoBERTa for causalLM
1048
+ if attention_mask.dim() == 3:
1049
+ extended_attention_mask = attention_mask[:, None, :, :]
1050
+ elif attention_mask.dim() == 2:
1051
+ extended_attention_mask = attention_mask[:, None, None, :]
1052
+ else:
1053
+ raise ValueError(
1054
+ f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
1055
+ )
1056
+
1057
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
1058
+ extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(extended_attention_mask.dtype).min
1059
+
1060
+ return extended_attention_mask
1061
+
1062
+
1063
+ class LSGBertForPreTraining(LSGBertPreTrainedModel, BertForPreTraining):
1064
+
1065
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1066
+
1067
+ def __init__(self, config):
1068
+
1069
+ LSGBertPreTrainedModel.__init__(self, config)
1070
+
1071
+ self.bert = LSGBertModel(config)
1072
+ self.cls = BertPreTrainingHeads(config)
1073
+
1074
+ # Initialize weights and apply final processing
1075
+ self.post_init()
1076
+
1077
+
1078
+ class LSGBertLMHeadModel(LSGBertPreTrainedModel, BertLMHeadModel):
1079
+
1080
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
1081
+
1082
+ def __init__(self, config):
1083
+
1084
+ LSGBertPreTrainedModel.__init__(self, config)
1085
+
1086
+ if not config.is_decoder:
1087
+ logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
1088
+
1089
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1090
+ self.cls = BertOnlyMLMHead(config)
1091
+
1092
+ # Initialize weights and apply final processing
1093
+ self.post_init()
1094
+
1095
+
1096
+ class LSGBertForMaskedLM(LSGBertPreTrainedModel, BertForMaskedLM):
1097
+ """
1098
+ This class overrides :class:`~transformers.BertForMaskedLM`. Please check the superclass for the appropriate
1099
+ documentation alongside usage examples.
1100
+ """
1101
+
1102
+ _tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
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
+ def __init__(self, config):
1141
+
1142
+ LSGBertPreTrainedModel.__init__(self, config)
1143
+
1144
+ self.num_labels = config.num_labels
1145
+ self.config = config
1146
+
1147
+ self.bert = LSGBertModel(config)
1148
+ classifier_dropout = (
1149
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1150
+ )
1151
+ self.dropout = nn.Dropout(classifier_dropout)
1152
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1153
+
1154
+ # Initialize weights and apply final processing
1155
+ self.post_init()
1156
+
1157
+
1158
+ class LSGBertForMultipleChoice(LSGBertPreTrainedModel, BertForMultipleChoice):
1159
+ """
1160
+ This class overrides :class:`~transformers.BertForMultipleChoice`. Please check the superclass for the
1161
+ appropriate documentation alongside usage examples.
1162
+ """
1163
+
1164
+ def __init__(self, config):
1165
+
1166
+ LSGBertPreTrainedModel.__init__(self, config)
1167
+
1168
+ self.bert = LSGBertModel(config)
1169
+ classifier_dropout = (
1170
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1171
+ )
1172
+ self.dropout = nn.Dropout(classifier_dropout)
1173
+ self.classifier = nn.Linear(config.hidden_size, 1)
1174
+
1175
+ # Initialize weights and apply final processing
1176
+ self.post_init()
1177
+
1178
+
1179
+ class LSGBertForTokenClassification(LSGBertPreTrainedModel, BertForTokenClassification):
1180
+ """
1181
+ This class overrides :class:`~transformers.BertForTokenClassification`. Please check the superclass for the
1182
+ appropriate documentation alongside usage examples.
1183
+ """
1184
+
1185
+ def __init__(self, config):
1186
+
1187
+ LSGBertPreTrainedModel.__init__(self, config)
1188
+
1189
+ self.num_labels = config.num_labels
1190
+
1191
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1192
+ classifier_dropout = (
1193
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1194
+ )
1195
+ self.dropout = nn.Dropout(classifier_dropout)
1196
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1197
+
1198
+ # Initialize weights and apply final processing
1199
+ self.post_init()
1200
+
1201
+
1202
+ class LSGBertForQuestionAnswering(LSGBertPreTrainedModel, BertForQuestionAnswering):
1203
+ """
1204
+ This class overrides :class:`~transformers.BertForQuestionAnswering`. Please check the superclass for the
1205
+ appropriate documentation alongside usage examples.
1206
+ """
1207
+
1208
+ def __init__(self, config):
1209
+
1210
+ LSGBertPreTrainedModel.__init__(self, config)
1211
+
1212
+ self.num_labels = config.num_labels
1213
+
1214
+ self.bert = LSGBertModel(config, add_pooling_layer=False)
1215
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1216
+
1217
+ # Initialize weights and apply final processing
1218
+ self.post_init()
1219
+
1220
+
1221
+ def str_to_class(classname):
1222
+ return getattr(sys.modules[__name__], classname)
1223
+
1224
+ # Register model in Auto API
1225
+ try:
1226
+ LSGBertConfig.register_for_auto_class()
1227
+ for key, value in AUTO_MAP.items():
1228
+ str_to_class(value.split(".")[-1]).register_for_auto_class(key)
1229
+ except:
1230
+ warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
1231
+ warn("Update to transformers >= 4.23.1 to fix.")