efederici commited on
Commit
6532ad6
1 Parent(s): ef2bc60

Upload model

Browse files
Files changed (3) hide show
  1. config.json +48 -0
  2. modeling_lsg_xlm_roberta.py +1177 -0
  3. pytorch_model.bin +3 -0
config.json ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "intfloat/multilingual-e5-base",
3
+ "adaptive": true,
4
+ "architectures": [
5
+ "LSGXLMRobertaModel"
6
+ ],
7
+ "attention_probs_dropout_prob": 0.1,
8
+ "auto_map": {
9
+ "AutoConfig": "modeling_lsg_xlm_roberta.LSGXLMRobertaConfig",
10
+ "AutoModel": "modeling_lsg_xlm_roberta.LSGXLMRobertaModel",
11
+ "AutoModelForCausalLM": "modeling_lsg_xlm_roberta.LSGXLMRobertaForCausalLM",
12
+ "AutoModelForMaskedLM": "modeling_lsg_xlm_roberta.LSGXLMRobertaForMaskedLM",
13
+ "AutoModelForMultipleChoice": "modeling_lsg_xlm_roberta.LSGXLMRobertaForMultipleChoice",
14
+ "AutoModelForQuestionAnswering": "modeling_lsg_xlm_roberta.LSGXLMRobertaForQuestionAnswering",
15
+ "AutoModelForSequenceClassification": "modeling_lsg_xlm_roberta.LSGXLMRobertaForSequenceClassification",
16
+ "AutoModelForTokenClassification": "modeling_lsg_xlm_roberta.LSGXLMRobertaForTokenClassification"
17
+ },
18
+ "base_model_prefix": "lsg",
19
+ "block_size": 128,
20
+ "bos_token_id": 0,
21
+ "classifier_dropout": null,
22
+ "eos_token_id": 2,
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-05,
29
+ "lsh_num_pre_rounds": 1,
30
+ "mask_first_token": false,
31
+ "max_position_embeddings": 4098,
32
+ "model_type": "xlm-roberta",
33
+ "num_attention_heads": 12,
34
+ "num_global_tokens": 1,
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.30.2",
45
+ "type_vocab_size": 1,
46
+ "use_cache": true,
47
+ "vocab_size": 250002
48
+ }
modeling_lsg_xlm_roberta.py ADDED
@@ -0,0 +1,1177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from logging import warn
2
+ from transformers.models.roberta.modeling_roberta import *
3
+ import torch
4
+ import torch.nn as nn
5
+ from transformers.models.xlm_roberta.configuration_xlm_roberta import XLMRobertaConfig
6
+ import sys
7
+
8
+ AUTO_MAP = {
9
+ "AutoModel": "modeling_lsg_xlm_roberta.LSGXLMRobertaModel",
10
+ "AutoModelForCausalLM": "modeling_lsg_xlm_roberta.LSGXLMRobertaForCausalLM",
11
+ "AutoModelForMaskedLM": "modeling_lsg_xlm_roberta.LSGXLMRobertaForMaskedLM",
12
+ "AutoModelForMultipleChoice": "modeling_lsg_xlm_roberta.LSGXLMRobertaForMultipleChoice",
13
+ "AutoModelForQuestionAnswering": "modeling_lsg_xlm_roberta.LSGXLMRobertaForQuestionAnswering",
14
+ "AutoModelForSequenceClassification": "modeling_lsg_xlm_roberta.LSGXLMRobertaForSequenceClassification",
15
+ "AutoModelForTokenClassification": "modeling_lsg_xlm_roberta.LSGXLMRobertaForTokenClassification"
16
+ }
17
+
18
+ class LSGXLMRobertaConfig(XLMRobertaConfig):
19
+ """
20
+ This class overrides :class:`~transformers.RobertaConfig`. Please check the superclass for the appropriate
21
+ documentation alongside usage examples.
22
+ """
23
+
24
+ base_model_prefix = "lsg"
25
+ model_type = "xlm-roberta"
26
+
27
+ def __init__(
28
+ self,
29
+ adaptive=True,
30
+ base_model_prefix="lsg",
31
+ block_size=128,
32
+ lsh_num_pre_rounds=1,
33
+ mask_first_token=False,
34
+ num_global_tokens=1,
35
+ pool_with_global=True,
36
+ sparse_block_size=128,
37
+ sparsity_factor=2,
38
+ sparsity_type="norm",
39
+ **kwargs
40
+ ):
41
+ """Constructs LSGXLMRobertaConfig."""
42
+ super().__init__(**kwargs)
43
+
44
+ self.adaptive = adaptive
45
+ self.auto_map = AUTO_MAP
46
+ self.base_model_prefix = base_model_prefix
47
+ self.block_size = block_size
48
+ self.lsh_num_pre_rounds = lsh_num_pre_rounds
49
+ self.mask_first_token = mask_first_token
50
+ self.num_global_tokens = num_global_tokens
51
+ self.pool_with_global = pool_with_global
52
+ self.sparse_block_size = sparse_block_size
53
+ self.sparsity_factor = sparsity_factor
54
+ self.sparsity_type = sparsity_type
55
+
56
+ if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride", "block_stride"]:
57
+ logger.warning(
58
+ "[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride'], \
59
+ setting sparsity_type=None, computation will skip sparse attention")
60
+ self.sparsity_type = None
61
+
62
+ if self.sparsity_type in ["stride", "block_stride"]:
63
+ if self.sparsity_factor > self.encoder_attention_heads:
64
+ logger.warning(
65
+ "[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
66
+ )
67
+
68
+ if self.num_global_tokens < 1:
69
+ logger.warning(
70
+ "[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
71
+ )
72
+ self.num_global_tokens = 1
73
+ elif self.num_global_tokens > 512:
74
+ logger.warning(
75
+ "[WARNING CONFIG]: num_global_tokens > 512 is not allowed, setting num_global_tokens=512"
76
+ )
77
+ self.num_global_tokens = 512
78
+
79
+ if self.sparsity_factor > 0:
80
+ assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
81
+ assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
82
+
83
+ if self.mask_first_token and not pool_with_global:
84
+ logger.warning(
85
+ "[WARNING CONFIG]: pool_with_global==False is not compatible with mask_first_token==True. Setting pool_with_global to True.")
86
+ self.pool_with_global = True
87
+
88
+ if hasattr(self, "position_embedding_type"):
89
+ if self.position_embedding_type != "absolute":
90
+ logger.warning(
91
+ "[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.")
92
+
93
+
94
+ class BaseSelfAttention(nn.Module):
95
+
96
+ def init_modules(self, config):
97
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
98
+ config, "embedding_size"
99
+ ):
100
+ raise ValueError(
101
+ "The hidden size (%d) is not a multiple of the number of attention "
102
+ "heads (%d)" % (config.hidden_size, config.num_attention_heads)
103
+ )
104
+
105
+ self.num_attention_heads = config.num_attention_heads
106
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
107
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
108
+
109
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
110
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
111
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
112
+
113
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
114
+
115
+ def transpose_for_scores(self, x):
116
+ new_x_shape = x.size()[:-1] + (
117
+ self.num_attention_heads,
118
+ self.attention_head_size,
119
+ )
120
+ x = x.view(*new_x_shape)
121
+ return x.permute(0, 2, 1, 3)
122
+
123
+ def reshape_output(self, context_layer):
124
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
125
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
126
+ return context_layer.view(*new_context_layer_shape)
127
+
128
+ def project_QKV(self, hidden_states):
129
+
130
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
131
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
132
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
133
+ return query_layer, key_layer, value_layer
134
+
135
+
136
+ class BaseAttentionProduct(nn.Module):
137
+
138
+ def __init__(self, config):
139
+ """
140
+ Compute attention: softmax(Q @ K.T) @ V
141
+ """
142
+ super().__init__()
143
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
144
+
145
+ def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
146
+
147
+ d = query_layer.shape[-1]
148
+
149
+ # Take the dot product between "query" and "key" to get the raw attention scores.
150
+ attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
151
+
152
+ del query_layer
153
+ del key_layer
154
+
155
+ if attention_mask is not None:
156
+ # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
157
+ attention_scores = attention_scores + attention_mask
158
+ del attention_mask
159
+
160
+ # Normalize the attention scores to probabilities.
161
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
162
+
163
+ # This is actually dropping out entire tokens to attend to, which might
164
+ # seem a bit unusual, but is taken from the original Transformer paper.
165
+ context_layer = self.dropout(attention_probs) @ value_layer
166
+
167
+ return context_layer
168
+
169
+
170
+ class CausalAttentionProduct(nn.Module):
171
+
172
+ def __init__(self, config):
173
+ """
174
+ Compute attention: softmax(Q @ K.T) @ V
175
+ """
176
+ super().__init__()
177
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
178
+ self.block_size = config.block_size
179
+
180
+ def forward(self, query_layer, key_layer, value_layer, attention_mask=None, causal_shape=None):
181
+
182
+ d = query_layer.shape[-1]
183
+
184
+ # Take the dot product between "query" and "key" to get the raw attention scores.
185
+ attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
186
+
187
+ del query_layer
188
+ del key_layer
189
+
190
+ if attention_mask is not None:
191
+ # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
192
+ attention_scores = attention_scores + attention_mask
193
+
194
+ # Add causal mask
195
+ causal_shape = (self.block_size, self.block_size) if causal_shape is None else causal_shape
196
+ causal_mask = torch.tril(
197
+ torch.ones(*causal_shape, device=attention_mask.device, dtype=attention_scores.dtype),
198
+ diagonal=-1
199
+ )
200
+ causal_mask = causal_mask.T * torch.finfo(attention_scores.dtype).min
201
+ attention_scores[..., -causal_shape[0]:, -causal_shape[1] + 1:] = causal_mask[:, 1:]
202
+
203
+ del attention_mask
204
+
205
+ # Normalize the attention scores to probabilities.
206
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
207
+
208
+ # This is actually dropping out entire tokens to attend to, which might
209
+ # seem a bit unusual, but is taken from the original Transformer paper.
210
+ context_layer = self.dropout(attention_probs) @ value_layer
211
+
212
+ return context_layer
213
+
214
+
215
+ class LSGAttentionProduct(nn.Module):
216
+
217
+ def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4, is_causal=False):
218
+ """
219
+ Compute block or overlapping blocks attention products
220
+ """
221
+ super().__init__()
222
+
223
+ self.block_size = block_size
224
+ self.sparse_block_size = sparse_block_size
225
+ self.sparsity_factor = sparsity_factor
226
+ self.is_causal = is_causal
227
+
228
+ if self.block_size is None:
229
+ self.block_size = config.block_size
230
+
231
+ if self.sparse_block_size is None:
232
+ self.sparse_block_size = config.sparse_block_size
233
+
234
+ # Shape of blocks
235
+ self.local_shapes = (self.block_size*3, self.block_size)
236
+ if self.sparse_block_size and self.sparsity_factor > 0:
237
+ self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
238
+
239
+ if is_causal:
240
+ self.attention = CausalAttentionProduct(config)
241
+ else:
242
+ self.attention = BaseAttentionProduct(config)
243
+
244
+ def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
245
+
246
+ # Build local tokens
247
+ local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
248
+ del hidden_states
249
+
250
+ # Build sparse tokens
251
+ if sparse_hidden_states is not None:
252
+ sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
253
+
254
+ return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
255
+
256
+ def forward(
257
+ self,
258
+ query_layer,
259
+ key_layer,
260
+ value_layer,
261
+ attention_mask=None,
262
+ sparse_key=None,
263
+ sparse_value=None,
264
+ sparse_mask=None,
265
+ global_key=None,
266
+ global_value=None,
267
+ global_mask=None
268
+ ):
269
+
270
+ # Input batch, heads, length, hidden_size
271
+ n, h, t, d = query_layer.size()
272
+ n_blocks = t // self.block_size
273
+ assert t % self.block_size == 0
274
+
275
+ key_layer = self.build_lsg_inputs(
276
+ key_layer,
277
+ sparse_key,
278
+ global_key
279
+ )
280
+ del sparse_key
281
+ del global_key
282
+
283
+ value_layer = self.build_lsg_inputs(
284
+ value_layer,
285
+ sparse_value,
286
+ global_value
287
+ )
288
+ del sparse_value
289
+ del global_value
290
+
291
+ attention_mask = self.build_lsg_inputs(
292
+ attention_mask,
293
+ sparse_mask,
294
+ global_mask.transpose(-1, -2),
295
+ is_attn_mask=True
296
+ ).transpose(-1, -2)
297
+ del sparse_mask
298
+ del global_mask
299
+
300
+ # expect (..., t, d) shape
301
+ # Compute attention
302
+ context_layer = self.attention(
303
+ query_layer=self.chunk(query_layer, n_blocks),
304
+ key_layer=key_layer,
305
+ value_layer=value_layer,
306
+ attention_mask=attention_mask
307
+ )
308
+
309
+ return context_layer.reshape(n, h, -1, d)
310
+
311
+ def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
312
+
313
+ size, step = self.local_shapes
314
+ s = (size - step) // 2
315
+
316
+ # Pad before block reshaping
317
+ if is_attn_mask:
318
+ pad_value = torch.finfo(hidden_states.dtype).min
319
+ hidden_states = hidden_states.transpose(-1, -2)
320
+ else:
321
+ pad_value = 0
322
+
323
+ hidden_states = torch.nn.functional.pad(
324
+ hidden_states.transpose(-1, -2),
325
+ pad=(s, s),
326
+ value=pad_value
327
+ ).transpose(-1, -2)
328
+
329
+ # Make blocks
330
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
331
+
332
+ # Skip third block if causal
333
+ if self.is_causal:
334
+ return hidden_states[..., :size*2//3, :]
335
+
336
+ return hidden_states
337
+
338
+ def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
339
+
340
+ size, step = self.sparse_shapes
341
+
342
+ # In case of odd case
343
+ odd_offset = (step % 2)
344
+
345
+ # n, h, t, d*2 + 1
346
+ size = size*2
347
+ s = (size - step) // 2 + odd_offset
348
+
349
+ # Pad before block reshaping
350
+ if is_attn_mask:
351
+ pad_value = torch.finfo(hidden_states.dtype).min
352
+ hidden_states = hidden_states.transpose(-1, -2)
353
+ else:
354
+ pad_value = 0
355
+
356
+ hidden_states = torch.nn.functional.pad(
357
+ hidden_states.transpose(-1, -2),
358
+ pad=(s, s),
359
+ value=pad_value
360
+ ).transpose(-1, -2)
361
+
362
+ # Make blocks
363
+ hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
364
+
365
+ # Fix case where block_size == sparsify_factor
366
+ if odd_offset:
367
+ hidden_states = hidden_states[..., :-1, :, :]
368
+
369
+ # Indexes for selection
370
+ u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
371
+ s = self.sparse_block_size
372
+
373
+ # Skip right block if causal
374
+ if self.is_causal:
375
+ return hidden_states[..., u-s:u, :]
376
+
377
+ u_ = u + odd_offset
378
+ return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
379
+
380
+ def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
381
+
382
+ n, h, b, t, d = x_local.size()
383
+ x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
384
+ if x_sparse is not None:
385
+ return torch.cat([x_global, x_sparse, x_local], dim=dim)
386
+ return torch.cat([x_global, x_local], dim=dim)
387
+
388
+ def chunk(self, x, n_blocks):
389
+
390
+ t, d = x.size()[-2:]
391
+ return x.reshape(*x.size()[:-2], n_blocks, -1, d)
392
+
393
+
394
+ class LSGRobertaEmbeddings(RobertaEmbeddings):
395
+
396
+ def __init__(self, config):
397
+ super().__init__(config)
398
+
399
+ self.num_global_tokens = config.num_global_tokens
400
+
401
+ # Hardcoded but partially trained
402
+ self.global_embeddings = nn.Embedding(512, embedding_dim=config.hidden_size, )
403
+
404
+ self.block_size = config.block_size
405
+
406
+ def forward(
407
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
408
+ ):
409
+ if position_ids is None:
410
+ if input_ids is not None:
411
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
412
+ position_ids = create_position_ids_from_input_ids(
413
+ input_ids, self.padding_idx, past_key_values_length
414
+ ).to(input_ids.device)
415
+ else:
416
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
417
+
418
+ if input_ids is not None:
419
+ input_shape = input_ids.size()
420
+ else:
421
+ input_shape = inputs_embeds.size()[:-1]
422
+
423
+ seq_length = input_shape[-1]
424
+
425
+ if token_type_ids is None:
426
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
427
+
428
+ if inputs_embeds is None:
429
+ inputs_embeds = self.word_embeddings(input_ids)
430
+ token_type_embeddings = self.token_type_embeddings(token_type_ids[:, :seq_length])
431
+
432
+ embeddings = inputs_embeds + token_type_embeddings
433
+ if self.position_embedding_type == "absolute":
434
+ position_embeddings = self.position_embeddings(position_ids[:, :seq_length])
435
+ embeddings += position_embeddings
436
+
437
+ #if self.num_global_tokens < 0:
438
+ n, t, d = embeddings.size()
439
+
440
+ # Add global_tokens
441
+ indexes = torch.arange(self.num_global_tokens, device=embeddings.device).reshape(1, -1)
442
+ global_embeddings = self.global_embeddings(indexes)
443
+ embeddings = torch.cat([global_embeddings.expand(n, -1, d), embeddings], dim=-2)
444
+
445
+ embeddings = self.LayerNorm(embeddings)
446
+ embeddings = self.dropout(embeddings)
447
+ return embeddings
448
+
449
+
450
+ class LSGAttention(RobertaAttention):
451
+
452
+ def __init__(self, config):
453
+
454
+ super().__init__(config)
455
+
456
+ self.self = LSGSelfAttention(config)
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
+ }
495
+
496
+ self.sparsity_type = config.sparsity_type
497
+ self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda x, y, z: (None, None, None))
498
+
499
+ if config.sparsity_type == "lsh":
500
+ self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
501
+
502
+ def get_sparse_tokens_with_norm(self, keys, values, mask):
503
+
504
+ if self.sparsity_factor == 1:
505
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
506
+
507
+ with torch.no_grad():
508
+
509
+ block_size = min(self.block_size, self.sparse_block_size)
510
+ key_norm = keys.detach().norm(dim=-1, keepdim=True)
511
+ key_norm = key_norm * ~mask.transpose(-1, -2).bool()
512
+ key_norm = self.chunk(key_norm, block_size)
513
+
514
+ n, h, b, t, d = key_norm.size()
515
+
516
+ idx = key_norm.argsort(dim=-2)
517
+ del key_norm
518
+ idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
519
+
520
+ split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
521
+ sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
522
+
523
+ d = keys.size()[-1]
524
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
525
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
526
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
527
+
528
+ return keys, values, mask
529
+
530
+ def get_sparse_tokens_with_pooling(self, keys, values, mask):
531
+
532
+ if self.sparsity_factor == 1:
533
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
534
+
535
+ keys = self.chunk(keys, self.sparsity_factor)
536
+ values = self.chunk(values, self.sparsity_factor)
537
+
538
+ n, h, b, t, d = keys.size()
539
+ mask = mask.reshape(n, 1, b, 1, t)
540
+ mask = ~mask.transpose(-1, -2).bool()
541
+
542
+ keys = keys * mask
543
+ values = values * mask
544
+
545
+ mask = mask.sum(dim=-2)
546
+ keys = keys.sum(dim=-2) / (mask + 1e-6)
547
+ values = values.sum(dim=-2) / (mask + 1e-6)
548
+
549
+ mask = (1. - mask.clamp(0, 1))
550
+ mask *= torch.finfo(mask.dtype).min
551
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
552
+
553
+ def get_sparse_tokens_with_stride(self, keys, values, mask):
554
+
555
+ if self.sparsity_factor == 1:
556
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
557
+
558
+ n, h, t, d = keys.size()
559
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
560
+ sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
561
+ sparse_idx = sparse_idx.expand(n, h, -1, 1)
562
+
563
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
564
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
565
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
566
+
567
+ return keys, values, mask
568
+
569
+ def get_sparse_tokens_with_block_stride(self, keys, values, mask):
570
+
571
+ if self.sparsity_factor == 1:
572
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
573
+
574
+ n, h, t, d = keys.size()
575
+
576
+ t, b = self.block_size, t // self.block_size
577
+ sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device)
578
+ 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)
579
+ sparse_idx = (sparse_idx % t)
580
+ sparse_idx = sparse_idx + torch.arange(b, device=keys.device).reshape(1, 1, -1, 1, 1) * t
581
+ sparse_idx = sparse_idx.reshape(1, h, -1, 1).expand(n, h, -1, 1)
582
+
583
+ keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
584
+ values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
585
+ mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
586
+
587
+ return keys, values, mask
588
+
589
+ def get_sparse_tokens_with_lsh(self, keys, values, mask):
590
+
591
+ if self.sparsity_factor == 1:
592
+ return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
593
+
594
+ block_size = min(self.block_size, self.sparse_block_size)
595
+ keys = self.chunk(keys, block_size)
596
+ values = self.chunk(values, block_size)
597
+
598
+ n, h, b, t, d = keys.size()
599
+ mask = mask.reshape(n, 1, b, 1, t)
600
+ mask = ~mask.transpose(-1, -2).bool()
601
+
602
+ keys = keys * mask
603
+ values = values * mask
604
+ mask = mask.expand(-1, h, -1, -1, -1).float()
605
+
606
+ extra_factor = 1
607
+
608
+ for _ in range(self.lsh_num_pre_rounds):
609
+ keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
610
+
611
+ keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
612
+ keys /= mask + 1e-8
613
+ values /= mask + 1e-8
614
+
615
+ mask = (1. - mask.clamp(0, 1))
616
+ mask *= torch.finfo(mask.dtype).min
617
+
618
+ return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
619
+
620
+ def lsh_round(self, keys, values, mask, output_size):
621
+
622
+ with torch.no_grad():
623
+
624
+ n_hashes = output_size // 2
625
+ n, h, b, t, d = keys.size()
626
+ binary_mask = mask.clamp(0, 1)
627
+
628
+ indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
629
+ indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
630
+
631
+ n, h, b, t, d = keys.size()
632
+
633
+ x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
634
+ mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
635
+ keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
636
+ values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
637
+ mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
638
+
639
+ return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
640
+
641
+ def forward(
642
+ self,
643
+ hidden_states,
644
+ attention_mask=None,
645
+ head_mask=None,
646
+ encoder_hidden_states=None,
647
+ encoder_attention_mask=None,
648
+ past_key_value=None,
649
+ output_attentions=False,
650
+ ):
651
+
652
+ query_layer = self.query(hidden_states)
653
+
654
+ # If this is instantiated as a cross-attention module, the keys
655
+ # and values come from an encoder; the attention mask needs to be
656
+ # such that the encoder's padding tokens are not attended to.
657
+ is_cross_attention = encoder_hidden_states is not None
658
+
659
+ if is_cross_attention and past_key_value is not None:
660
+ # reuse k,v, cross_attentions
661
+ key_layer = past_key_value[0]
662
+ value_layer = past_key_value[1]
663
+ attention_mask = encoder_attention_mask
664
+ elif is_cross_attention:
665
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
666
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
667
+ attention_mask = encoder_attention_mask
668
+ elif past_key_value is not None:
669
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
670
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
671
+ key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
672
+ value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
673
+ else:
674
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
675
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
676
+
677
+ query_layer = self.transpose_for_scores(query_layer)
678
+
679
+ if self.is_decoder:
680
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
681
+ # Further calls to cross_attention layer can then reuse all cross-attention
682
+ # key/value_states (first "if" case)
683
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
684
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
685
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
686
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
687
+ past_key_value = (key_layer, value_layer)
688
+
689
+ if is_cross_attention:
690
+ outputs = self.cross_attention_forward(
691
+ query_layer=query_layer,
692
+ key_layer=key_layer,
693
+ value_layer=value_layer,
694
+ attention_mask=attention_mask,
695
+ output_attentions=output_attentions
696
+ )
697
+ else:
698
+ outputs = self.causal_forward(
699
+ query_layer,
700
+ key_layer,
701
+ value_layer,
702
+ attention_mask=attention_mask,
703
+ output_attentions=output_attentions,
704
+ )
705
+
706
+ outputs = outputs + ((key_layer, value_layer),)
707
+
708
+ else:
709
+ outputs = self.not_causal_forward(
710
+ query_layer,
711
+ key_layer,
712
+ value_layer,
713
+ attention_mask=attention_mask,
714
+ output_attentions=output_attentions
715
+ )
716
+
717
+ return outputs
718
+
719
+ def causal_forward(
720
+ self,
721
+ query_layer,
722
+ key_layer,
723
+ value_layer,
724
+ attention_mask=None,
725
+ output_attentions=False,
726
+ ):
727
+
728
+ n, h, t, d = key_layer.size()
729
+
730
+ # Cat global mask
731
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
732
+
733
+ # Split input into global tokens and other tokens
734
+ split = (self.num_global_tokens, t - self.num_global_tokens)
735
+ global_query, query_layer = query_layer.split(split, dim=-2)
736
+
737
+ # Use normal causal attention if local attention covers every tokens
738
+ if t <= 2 * self.block_size + self.num_global_tokens:
739
+ context_layer = self.causal_attention(
740
+ query_layer=query_layer,
741
+ key_layer=key_layer,
742
+ value_layer=value_layer,
743
+ attention_mask=attention_mask,
744
+ causal_shape=(t - self.num_global_tokens, t - self.num_global_tokens)
745
+ )
746
+
747
+ context_layer = torch.cat([global_query, context_layer], dim=-2)
748
+ return (self.reshape_output(context_layer), )
749
+
750
+ # Split K Q M on global and non global
751
+ global_key, key_layer = key_layer.split(split, dim=-2)
752
+ global_value, value_layer = value_layer.split(split, dim=-2)
753
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
754
+
755
+ n, h, t, d = key_layer.size()
756
+
757
+ # Get sparse idx
758
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
759
+ if self.sparse_block_size and self.sparsity_factor > 0:
760
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
761
+
762
+ # Expand masks on heads
763
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
764
+ global_mask = global_mask.expand(-1, h, -1, -1)
765
+
766
+ # Compute dot product attention
767
+ context_layer = self.attention(
768
+ query_layer,
769
+ key_layer,
770
+ value_layer,
771
+ attention_mask,
772
+ sparse_key=sparse_key,
773
+ sparse_value=sparse_value,
774
+ sparse_mask=sparse_mask,
775
+ global_key=global_key,
776
+ global_value=global_value,
777
+ global_mask=global_mask
778
+ )
779
+
780
+ # Merge pseudo global (causal) and local-sparse tokens
781
+ context_layer = torch.cat([global_query, context_layer], dim=-2)
782
+ context_layer = self.reshape_output(context_layer)
783
+
784
+ return (context_layer,)
785
+
786
+ def not_causal_forward(
787
+ self,
788
+ query_layer,
789
+ key_layer,
790
+ value_layer,
791
+ attention_mask=None,
792
+ output_attentions=False,
793
+ ):
794
+
795
+ n, h, t, d = query_layer.size()
796
+
797
+ # Cat global mask
798
+ attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
799
+
800
+ # Use normal attention if local attention covers every tokens
801
+ if t <= 2 * self.block_size + self.num_global_tokens:
802
+ context_layer = self.full_attention(
803
+ query_layer=query_layer,
804
+ key_layer=key_layer,
805
+ value_layer=value_layer,
806
+ attention_mask=attention_mask
807
+ )
808
+ return (self.reshape_output(context_layer), )
809
+
810
+ # Split input into global tokens and other tokens
811
+ split = (self.num_global_tokens, t - self.num_global_tokens)
812
+ global_query, query_layer = query_layer.split(split, dim=-2)
813
+
814
+ # Get global_attention
815
+ bos = self.full_attention(
816
+ query_layer=global_query,
817
+ key_layer=key_layer,
818
+ value_layer=value_layer,
819
+ attention_mask=attention_mask
820
+ )
821
+
822
+ # Split K Q M on global and non global
823
+ global_key, key_layer = key_layer.split(split, dim=-2)
824
+ global_value, value_layer = value_layer.split(split, dim=-2)
825
+ global_mask, attention_mask = attention_mask.split(split, dim=-1)
826
+
827
+ n, h, t, d = key_layer.size()
828
+
829
+ # Get sparse idx
830
+ sparse_key, sparse_value, sparse_mask = (None, None, None)
831
+
832
+ if self.sparse_block_size and self.sparsity_factor > 0:
833
+ sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
834
+
835
+ # Expand masks on heads
836
+ attention_mask = attention_mask.expand(-1, h, -1, -1)
837
+ global_mask = global_mask.expand(-1, h, -1, -1)
838
+
839
+ # Compute dot product attention
840
+ context_layer = self.attention(
841
+ query_layer,
842
+ key_layer,
843
+ value_layer,
844
+ attention_mask,
845
+ sparse_key=sparse_key,
846
+ sparse_value=sparse_value,
847
+ sparse_mask=sparse_mask,
848
+ global_key=global_key,
849
+ global_value=global_value,
850
+ global_mask=global_mask
851
+ )
852
+
853
+ # Merge global and local-sparse tokens
854
+ context_layer = torch.cat([bos, context_layer], dim=-2)
855
+ context_layer = self.reshape_output(context_layer)
856
+
857
+ return (context_layer,)
858
+
859
+ def cross_attention_forward(
860
+ self,
861
+ query_layer,
862
+ key_layer,
863
+ value_layer,
864
+ attention_mask=None,
865
+ output_attentions=False,
866
+ ):
867
+
868
+ context_layer = self.full_attention(
869
+ query_layer=query_layer,
870
+ key_layer=key_layer,
871
+ value_layer=value_layer,
872
+ attention_mask=attention_mask
873
+ )
874
+ return (self.reshape_output(context_layer), )
875
+
876
+ def chunk(self, x, chunk_size):
877
+
878
+ n, h, t, d = x.size()
879
+ return x.reshape(n, h, -1, chunk_size, d)
880
+
881
+
882
+ class LSGRobertaLayer(RobertaLayer):
883
+
884
+ def __init__(self, config):
885
+
886
+ super().__init__(config)
887
+
888
+ self.attention = LSGAttention(config)
889
+ if self.add_cross_attention:
890
+ assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added"
891
+ self.crossattention = LSGAttention(config)
892
+
893
+
894
+ class LSGRobertaEncoder(RobertaEncoder):
895
+
896
+ def __init__(self, config):
897
+
898
+ super().__init__(config)
899
+ self.layer = nn.ModuleList([LSGRobertaLayer(config) for _ in range(config.num_hidden_layers)])
900
+
901
+ assert hasattr(config, "num_global_tokens")
902
+ self.num_global_tokens = config.num_global_tokens
903
+ self.pad_idx = config.pad_token_id
904
+
905
+ assert hasattr(config, "block_size") and hasattr(config, "adaptive")
906
+ self.block_size = config.block_size
907
+ self.adaptive = config.adaptive
908
+ self.mask_first_token = config.mask_first_token
909
+ self.pool_with_global = config.pool_with_global
910
+
911
+ def forward(
912
+ self,
913
+ hidden_states: torch.Tensor,
914
+ attention_mask: Optional[torch.FloatTensor] = None,
915
+ head_mask: Optional[torch.FloatTensor] = None,
916
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
917
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
918
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
919
+ use_cache: Optional[bool] = None,
920
+ output_attentions: Optional[bool] = False,
921
+ output_hidden_states: Optional[bool] = False,
922
+ return_dict: Optional[bool] = True,
923
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
924
+
925
+ mask_value = torch.finfo(attention_mask.dtype).min
926
+ n, _, __, t = attention_mask.size()
927
+
928
+ if not (self.config.is_decoder and encoder_hidden_states is not None):
929
+ b = self.block_size * 2
930
+ pad = t % self.block_size
931
+
932
+ # Check if t is multiple of block_size and pad
933
+ if self.adaptive and t > b and pad > 0:
934
+ pad_length = self.block_size - pad
935
+ hidden_states = torch.nn.functional.pad(hidden_states.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
936
+ attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=mask_value)
937
+
938
+ if self.mask_first_token:
939
+ attention_mask[..., 0] = mask_value
940
+
941
+ encoder_outputs = super().forward(
942
+ hidden_states=hidden_states,
943
+ attention_mask=attention_mask,
944
+ head_mask=head_mask,
945
+ encoder_hidden_states=encoder_hidden_states,
946
+ encoder_attention_mask=encoder_attention_mask,
947
+ past_key_values=past_key_values,
948
+ use_cache=use_cache,
949
+ output_attentions=output_attentions,
950
+ output_hidden_states=output_hidden_states,
951
+ return_dict=return_dict
952
+ )
953
+
954
+ sequence_output = encoder_outputs[0]
955
+ if self.pool_with_global:
956
+ sequence_output[:, self.num_global_tokens] = sequence_output[:, 0]
957
+
958
+ # Adapt sequence to initial shape
959
+ sequence_output = sequence_output[..., self.num_global_tokens: t + self.num_global_tokens, :]
960
+
961
+ if not return_dict:
962
+ return (sequence_output, ) + encoder_outputs[1:]
963
+
964
+ encoder_outputs.last_hidden_state = sequence_output
965
+ return encoder_outputs
966
+
967
+ class LSGRobertaPreTrainedModel(RobertaPreTrainedModel):
968
+ """
969
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
970
+ models.
971
+ """
972
+
973
+ config_class = LSGXLMRobertaConfig
974
+
975
+ def _set_gradient_checkpointing(self, module, value=False):
976
+ if isinstance(module, (RobertaEncoder, LSGRobertaEncoder)):
977
+ module.gradient_checkpointing = value
978
+
979
+
980
+ class LSGXLMRobertaModel(LSGRobertaPreTrainedModel, RobertaModel):
981
+ """
982
+ This class overrides :class:`~transformers.RobertaModel`. Please check the superclass for the appropriate
983
+ documentation alongside usage examples.
984
+ """
985
+
986
+ config_class = LSGXLMRobertaConfig
987
+
988
+
989
+ def __init__(self, config, add_pooling_layer=True):
990
+
991
+ LSGRobertaPreTrainedModel.__init__(self, config)
992
+
993
+ self.embeddings = LSGRobertaEmbeddings(config)
994
+ self.encoder = LSGRobertaEncoder(config)
995
+ self.pooler = RobertaPooler(config) if add_pooling_layer else None
996
+
997
+ if config.add_cross_attention:
998
+ logger.warning(
999
+ "Cross attention is computed using full attention since it is not LSG compatible."
1000
+ )
1001
+
1002
+ # Initialize weights and apply final processing
1003
+ self.post_init()
1004
+
1005
+ def get_extended_attention_mask(self, attention_mask, input_shape, device=None):
1006
+
1007
+ # Do not rely on original triangular mask from BERT/RoBERTa for causalLM
1008
+ if attention_mask.dim() == 3:
1009
+ extended_attention_mask = attention_mask[:, None, :, :]
1010
+ elif attention_mask.dim() == 2:
1011
+ extended_attention_mask = attention_mask[:, None, None, :]
1012
+ else:
1013
+ raise ValueError(
1014
+ f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
1015
+ )
1016
+
1017
+ extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
1018
+ extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(extended_attention_mask.dtype).min
1019
+
1020
+ return extended_attention_mask
1021
+
1022
+
1023
+ class LSGXLMRobertaForCausalLM(LSGRobertaPreTrainedModel, RobertaForCausalLM):
1024
+
1025
+ config_class = LSGXLMRobertaConfig
1026
+ _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
1027
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
1028
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1029
+
1030
+ def __init__(self, config):
1031
+
1032
+ LSGRobertaPreTrainedModel.__init__(self, config)
1033
+
1034
+ if not config.is_decoder:
1035
+ logger.warning("If you want to use `LSGRobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
1036
+
1037
+ self.roberta = LSGXLMRobertaModel(config, add_pooling_layer=False)
1038
+ self.lm_head = RobertaLMHead(config)
1039
+
1040
+ # The LM head weights require special treatment only when they are tied with the word embeddings
1041
+ self.update_keys_to_ignore(config, ["lm_head.decoder.weight"])
1042
+
1043
+ # Initialize weights and apply final processing
1044
+ self.post_init()
1045
+
1046
+
1047
+ class LSGXLMRobertaForMaskedLM(LSGRobertaPreTrainedModel, RobertaForMaskedLM):
1048
+ """
1049
+ This class overrides :class:`~transformers.RobertaForMaskedLM`. Please check the superclass for the appropriate
1050
+ documentation alongside usage examples.
1051
+ """
1052
+ config_class = LSGXLMRobertaConfig
1053
+ _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
1054
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
1055
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1056
+
1057
+ def __init__(self, config):
1058
+
1059
+ LSGRobertaPreTrainedModel.__init__(self, config)
1060
+
1061
+ if config.is_decoder:
1062
+ logger.warning(
1063
+ "If you want to use `LSGRobertaForMaskedLM` make sure `config.is_decoder=False` for "
1064
+ "bi-directional self-attention."
1065
+ )
1066
+
1067
+ self.roberta = LSGXLMRobertaModel(config, add_pooling_layer=False)
1068
+ self.lm_head = RobertaLMHead(config)
1069
+
1070
+ # The LM head weights require special treatment only when they are tied with the word embeddings
1071
+ self.update_keys_to_ignore(config, ["lm_head.decoder.weight"])
1072
+
1073
+ # Initialize weights and apply final processing
1074
+ self.post_init()
1075
+
1076
+
1077
+ class LSGXLMRobertaForSequenceClassification(LSGRobertaPreTrainedModel, RobertaForSequenceClassification):
1078
+ """
1079
+ This class overrides :class:`~transformers.RobertaForSequenceClassification`. Please check the superclass for the
1080
+ appropriate documentation alongside usage examples.
1081
+ """
1082
+ config_class = LSGXLMRobertaConfig
1083
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1084
+
1085
+ def __init__(self, config):
1086
+
1087
+ LSGRobertaPreTrainedModel.__init__(self, config)
1088
+
1089
+ self.num_labels = config.num_labels
1090
+ self.config = config
1091
+
1092
+ self.roberta = LSGXLMRobertaModel(config, add_pooling_layer=False)
1093
+ self.classifier = RobertaClassificationHead(config)
1094
+
1095
+ # Initialize weights and apply final processing
1096
+ self.post_init()
1097
+
1098
+
1099
+ class LSGXLMRobertaForMultipleChoice(LSGRobertaPreTrainedModel, RobertaForMultipleChoice):
1100
+ """
1101
+ This class overrides :class:`~transformers.RobertaForMultipleChoice`. Please check the superclass for the
1102
+ appropriate documentation alongside usage examples.
1103
+ """
1104
+ config_class = LSGXLMRobertaConfig
1105
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1106
+
1107
+ def __init__(self, config):
1108
+
1109
+ LSGRobertaPreTrainedModel.__init__(self, config)
1110
+
1111
+ self.roberta = LSGXLMRobertaModel(config)
1112
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
1113
+ self.classifier = nn.Linear(config.hidden_size, 1)
1114
+
1115
+ # Initialize weights and apply final processing
1116
+ self.post_init()
1117
+
1118
+
1119
+ class LSGXLMRobertaForTokenClassification(LSGRobertaPreTrainedModel, RobertaForTokenClassification):
1120
+ """
1121
+ This class overrides :class:`~transformers.RobertaForTokenClassification`. Please check the superclass for the
1122
+ appropriate documentation alongside usage examples.
1123
+ """
1124
+ config_class = LSGXLMRobertaConfig
1125
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1126
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1127
+
1128
+ def __init__(self, config):
1129
+
1130
+ LSGRobertaPreTrainedModel.__init__(self, config)
1131
+
1132
+ self.num_labels = config.num_labels
1133
+
1134
+ self.roberta = LSGXLMRobertaModel(config, add_pooling_layer=False)
1135
+ classifier_dropout = (
1136
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
1137
+ )
1138
+ self.dropout = nn.Dropout(classifier_dropout)
1139
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1140
+
1141
+ # Initialize weights and apply final processing
1142
+ self.post_init()
1143
+
1144
+
1145
+ class LSGXLMRobertaForQuestionAnswering(LSGRobertaPreTrainedModel, RobertaForQuestionAnswering):
1146
+ """
1147
+ This class overrides :class:`~transformers.RobertaForQuestionAnswering`. Please check the superclass for the
1148
+ appropriate documentation alongside usage examples.
1149
+ """
1150
+ config_class = LSGXLMRobertaConfig
1151
+ _keys_to_ignore_on_load_unexpected = [r"pooler"]
1152
+ _keys_to_ignore_on_load_missing = [r"position_ids"]
1153
+
1154
+ def __init__(self, config):
1155
+
1156
+ LSGRobertaPreTrainedModel.__init__(self, config)
1157
+
1158
+ self.num_labels = config.num_labels
1159
+
1160
+ self.roberta = LSGXLMRobertaModel(config, add_pooling_layer=False)
1161
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1162
+
1163
+ # Initialize weights and apply final processing
1164
+ self.post_init()
1165
+
1166
+
1167
+ def str_to_class(classname):
1168
+ return getattr(sys.modules[__name__], classname)
1169
+
1170
+ # Register model in Auto API
1171
+ try:
1172
+ LSGXLMRobertaConfig.register_for_auto_class()
1173
+ for key, value in AUTO_MAP.items():
1174
+ str_to_class(value.split(".")[-1]).register_for_auto_class(key)
1175
+ except:
1176
+ warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
1177
+ warn("Update to transformers >= 4.23.1 to fix.")
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a2ed01b013ef1a01178d52cb4e062eb7eb1de82032447affdee663b829c4318
3
+ size 1124854897