Upload LSGCamembertForMaskedLM
Browse files- config.json +49 -0
- modeling_lsg_camembert.py +1179 -0
- pytorch_model.bin +3 -0
config.json
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "dlicari/Italian-Legal-BERT-SC",
|
3 |
+
"adaptive": true,
|
4 |
+
"architectures": [
|
5 |
+
"LSGCamembertForMaskedLM"
|
6 |
+
],
|
7 |
+
"attention_probs_dropout_prob": 0.1,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "modeling_lsg_camembert.LSGCamembertConfig",
|
10 |
+
"AutoModel": "modeling_lsg_camembert.LSGCamembertModel",
|
11 |
+
"AutoModelForCausalLM": "modeling_lsg_camembert.LSGCamembertForCausalLM",
|
12 |
+
"AutoModelForMaskedLM": "modeling_lsg_camembert.LSGCamembertForMaskedLM",
|
13 |
+
"AutoModelForMultipleChoice": "modeling_lsg_camembert.LSGCamembertForMultipleChoice",
|
14 |
+
"AutoModelForQuestionAnswering": "modeling_lsg_camembert.LSGCamembertForQuestionAnswering",
|
15 |
+
"AutoModelForSequenceClassification": "modeling_lsg_camembert.LSGCamembertForSequenceClassification",
|
16 |
+
"AutoModelForTokenClassification": "modeling_lsg_camembert.LSGCamembertForTokenClassification"
|
17 |
+
},
|
18 |
+
"base_model_prefix": "lsg",
|
19 |
+
"block_size": 128,
|
20 |
+
"bos_token_id": 5,
|
21 |
+
"classifier_dropout": null,
|
22 |
+
"eos_token_id": 6,
|
23 |
+
"gradient_checkpointing": false,
|
24 |
+
"hidden_act": "gelu",
|
25 |
+
"hidden_dropout_prob": 0.1,
|
26 |
+
"hidden_size": 768,
|
27 |
+
"initializer_range": 0.02,
|
28 |
+
"intermediate_size": 3072,
|
29 |
+
"layer_norm_eps": 1e-05,
|
30 |
+
"lsh_num_pre_rounds": 1,
|
31 |
+
"mask_first_token": false,
|
32 |
+
"max_position_embeddings": 16386,
|
33 |
+
"model_type": "camembert",
|
34 |
+
"num_attention_heads": 12,
|
35 |
+
"num_global_tokens": 7,
|
36 |
+
"num_hidden_layers": 12,
|
37 |
+
"output_past": true,
|
38 |
+
"pad_token_id": 1,
|
39 |
+
"pool_with_global": true,
|
40 |
+
"position_embedding_type": "absolute",
|
41 |
+
"sparse_block_size": 128,
|
42 |
+
"sparsity_factor": 2,
|
43 |
+
"sparsity_type": "norm",
|
44 |
+
"torch_dtype": "float32",
|
45 |
+
"transformers_version": "4.25.1",
|
46 |
+
"type_vocab_size": 1,
|
47 |
+
"use_cache": true,
|
48 |
+
"vocab_size": 32005
|
49 |
+
}
|
modeling_lsg_camembert.py
ADDED
@@ -0,0 +1,1179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from logging import warn
|
2 |
+
from transformers.models.camembert.modeling_camembert import *
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
from transformers.models.camembert.configuration_camembert import CamembertConfig
|
6 |
+
import sys
|
7 |
+
|
8 |
+
AUTO_MAP = {
|
9 |
+
"AutoModel": "modeling_lsg_camembert.LSGCamembertModel",
|
10 |
+
"AutoModelForCausalLM": "modeling_lsg_camembert.LSGCamembertForCausalLM",
|
11 |
+
"AutoModelForMaskedLM": "modeling_lsg_camembert.LSGCamembertForMaskedLM",
|
12 |
+
"AutoModelForMultipleChoice": "modeling_lsg_camembert.LSGCamembertForMultipleChoice",
|
13 |
+
"AutoModelForQuestionAnswering": "modeling_lsg_camembert.LSGCamembertForQuestionAnswering",
|
14 |
+
"AutoModelForSequenceClassification": "modeling_lsg_camembert.LSGCamembertForSequenceClassification",
|
15 |
+
"AutoModelForTokenClassification": "modeling_lsg_camembert.LSGCamembertForTokenClassification"
|
16 |
+
}
|
17 |
+
|
18 |
+
class LSGCamembertConfig(CamembertConfig):
|
19 |
+
"""
|
20 |
+
This class overrides :class:`~transformers.CamembertConfig`. Please check the superclass for the appropriate
|
21 |
+
documentation alongside usage examples.
|
22 |
+
"""
|
23 |
+
|
24 |
+
base_model_prefix = "lsg"
|
25 |
+
model_type = "camembert"
|
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 LSGCamembertConfig."""
|
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 CamembertModel 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 CamembertModel 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 LSGCamembertEmbeddings(CamembertEmbeddings):
|
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(CamembertAttention):
|
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 |
+
#if head_mask is not None:
|
718 |
+
# outputs = (outputs[0] * head_mask[:, :, :1, :1], ) + outputs[1:]
|
719 |
+
return outputs
|
720 |
+
|
721 |
+
def causal_forward(
|
722 |
+
self,
|
723 |
+
query_layer,
|
724 |
+
key_layer,
|
725 |
+
value_layer,
|
726 |
+
attention_mask=None,
|
727 |
+
output_attentions=False,
|
728 |
+
):
|
729 |
+
|
730 |
+
n, h, t, d = key_layer.size()
|
731 |
+
|
732 |
+
# Cat global mask
|
733 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
734 |
+
|
735 |
+
# Split input into global tokens and other tokens
|
736 |
+
split = (self.num_global_tokens, t - self.num_global_tokens)
|
737 |
+
global_query, query_layer = query_layer.split(split, dim=-2)
|
738 |
+
|
739 |
+
# Use normal causal attention if local attention covers every tokens
|
740 |
+
if t <= 2 * self.block_size + self.num_global_tokens:
|
741 |
+
context_layer = self.causal_attention(
|
742 |
+
query_layer=query_layer,
|
743 |
+
key_layer=key_layer,
|
744 |
+
value_layer=value_layer,
|
745 |
+
attention_mask=attention_mask,
|
746 |
+
causal_shape=(t - self.num_global_tokens, t - self.num_global_tokens)
|
747 |
+
)
|
748 |
+
|
749 |
+
context_layer = torch.cat([global_query, context_layer], dim=-2)
|
750 |
+
return (self.reshape_output(context_layer), )
|
751 |
+
|
752 |
+
# Split K Q M on global and non global
|
753 |
+
global_key, key_layer = key_layer.split(split, dim=-2)
|
754 |
+
global_value, value_layer = value_layer.split(split, dim=-2)
|
755 |
+
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
756 |
+
|
757 |
+
n, h, t, d = key_layer.size()
|
758 |
+
|
759 |
+
# Get sparse idx
|
760 |
+
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
761 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
762 |
+
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
763 |
+
|
764 |
+
# Expand masks on heads
|
765 |
+
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
766 |
+
global_mask = global_mask.expand(-1, h, -1, -1)
|
767 |
+
|
768 |
+
# Compute dot product attention
|
769 |
+
context_layer = self.attention(
|
770 |
+
query_layer,
|
771 |
+
key_layer,
|
772 |
+
value_layer,
|
773 |
+
attention_mask,
|
774 |
+
sparse_key=sparse_key,
|
775 |
+
sparse_value=sparse_value,
|
776 |
+
sparse_mask=sparse_mask,
|
777 |
+
global_key=global_key,
|
778 |
+
global_value=global_value,
|
779 |
+
global_mask=global_mask
|
780 |
+
)
|
781 |
+
|
782 |
+
# Merge pseudo global (causal) and local-sparse tokens
|
783 |
+
context_layer = torch.cat([global_query, context_layer], dim=-2)
|
784 |
+
context_layer = self.reshape_output(context_layer)
|
785 |
+
|
786 |
+
return (context_layer,)
|
787 |
+
|
788 |
+
def not_causal_forward(
|
789 |
+
self,
|
790 |
+
query_layer,
|
791 |
+
key_layer,
|
792 |
+
value_layer,
|
793 |
+
attention_mask=None,
|
794 |
+
output_attentions=False,
|
795 |
+
):
|
796 |
+
|
797 |
+
n, h, t, d = query_layer.size()
|
798 |
+
|
799 |
+
# Cat global mask
|
800 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
801 |
+
|
802 |
+
# Use normal attention if local attention covers every tokens
|
803 |
+
if t <= 2 * self.block_size + self.num_global_tokens:
|
804 |
+
context_layer = self.full_attention(
|
805 |
+
query_layer=query_layer,
|
806 |
+
key_layer=key_layer,
|
807 |
+
value_layer=value_layer,
|
808 |
+
attention_mask=attention_mask
|
809 |
+
)
|
810 |
+
return (self.reshape_output(context_layer), )
|
811 |
+
|
812 |
+
# Split input into global tokens and other tokens
|
813 |
+
split = (self.num_global_tokens, t - self.num_global_tokens)
|
814 |
+
global_query, query_layer = query_layer.split(split, dim=-2)
|
815 |
+
|
816 |
+
# Get global_attention
|
817 |
+
bos = self.full_attention(
|
818 |
+
query_layer=global_query,
|
819 |
+
key_layer=key_layer,
|
820 |
+
value_layer=value_layer,
|
821 |
+
attention_mask=attention_mask
|
822 |
+
)
|
823 |
+
|
824 |
+
# Split K Q M on global and non global
|
825 |
+
global_key, key_layer = key_layer.split(split, dim=-2)
|
826 |
+
global_value, value_layer = value_layer.split(split, dim=-2)
|
827 |
+
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
828 |
+
|
829 |
+
n, h, t, d = key_layer.size()
|
830 |
+
|
831 |
+
# Get sparse idx
|
832 |
+
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
833 |
+
|
834 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
835 |
+
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
836 |
+
|
837 |
+
# Expand masks on heads
|
838 |
+
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
839 |
+
global_mask = global_mask.expand(-1, h, -1, -1)
|
840 |
+
|
841 |
+
# Compute dot product attention
|
842 |
+
context_layer = self.attention(
|
843 |
+
query_layer,
|
844 |
+
key_layer,
|
845 |
+
value_layer,
|
846 |
+
attention_mask,
|
847 |
+
sparse_key=sparse_key,
|
848 |
+
sparse_value=sparse_value,
|
849 |
+
sparse_mask=sparse_mask,
|
850 |
+
global_key=global_key,
|
851 |
+
global_value=global_value,
|
852 |
+
global_mask=global_mask
|
853 |
+
)
|
854 |
+
|
855 |
+
# Merge global and local-sparse tokens
|
856 |
+
context_layer = torch.cat([bos, context_layer], dim=-2)
|
857 |
+
context_layer = self.reshape_output(context_layer)
|
858 |
+
|
859 |
+
return (context_layer,)
|
860 |
+
|
861 |
+
def cross_attention_forward(
|
862 |
+
self,
|
863 |
+
query_layer,
|
864 |
+
key_layer,
|
865 |
+
value_layer,
|
866 |
+
attention_mask=None,
|
867 |
+
output_attentions=False,
|
868 |
+
):
|
869 |
+
|
870 |
+
context_layer = self.full_attention(
|
871 |
+
query_layer=query_layer,
|
872 |
+
key_layer=key_layer,
|
873 |
+
value_layer=value_layer,
|
874 |
+
attention_mask=attention_mask
|
875 |
+
)
|
876 |
+
return (self.reshape_output(context_layer), )
|
877 |
+
|
878 |
+
def chunk(self, x, chunk_size):
|
879 |
+
|
880 |
+
n, h, t, d = x.size()
|
881 |
+
return x.reshape(n, h, -1, chunk_size, d)
|
882 |
+
|
883 |
+
|
884 |
+
class LSGCamembertLayer(CamembertLayer):
|
885 |
+
|
886 |
+
def __init__(self, config):
|
887 |
+
|
888 |
+
super().__init__(config)
|
889 |
+
|
890 |
+
self.attention = LSGAttention(config)
|
891 |
+
if self.add_cross_attention:
|
892 |
+
assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added"
|
893 |
+
self.crossattention = LSGAttention(config)
|
894 |
+
|
895 |
+
|
896 |
+
class LSGCamembertEncoder(CamembertEncoder):
|
897 |
+
|
898 |
+
def __init__(self, config):
|
899 |
+
|
900 |
+
super().__init__(config)
|
901 |
+
|
902 |
+
self.layer = nn.ModuleList([LSGCamembertLayer(config) for _ in range(config.num_hidden_layers)])
|
903 |
+
|
904 |
+
assert hasattr(config, "num_global_tokens")
|
905 |
+
self.num_global_tokens = config.num_global_tokens
|
906 |
+
self.pad_idx = config.pad_token_id
|
907 |
+
|
908 |
+
assert hasattr(config, "block_size") and hasattr(config, "adaptive")
|
909 |
+
self.block_size = config.block_size
|
910 |
+
self.adaptive = config.adaptive
|
911 |
+
self.mask_first_token = config.mask_first_token
|
912 |
+
self.pool_with_global = config.pool_with_global
|
913 |
+
|
914 |
+
def forward(
|
915 |
+
self,
|
916 |
+
hidden_states: torch.Tensor,
|
917 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
918 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
919 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
920 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
921 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
922 |
+
use_cache: Optional[bool] = None,
|
923 |
+
output_attentions: Optional[bool] = False,
|
924 |
+
output_hidden_states: Optional[bool] = False,
|
925 |
+
return_dict: Optional[bool] = True,
|
926 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
927 |
+
|
928 |
+
mask_value = torch.finfo(attention_mask.dtype).min
|
929 |
+
n, _, __, t = attention_mask.size()
|
930 |
+
|
931 |
+
if not (self.config.is_decoder and encoder_hidden_states is not None):
|
932 |
+
b = self.block_size * 2
|
933 |
+
pad = t % self.block_size
|
934 |
+
|
935 |
+
# Check if t is multiple of block_size and pad
|
936 |
+
if self.adaptive and t > b and pad > 0:
|
937 |
+
pad_length = self.block_size - pad
|
938 |
+
hidden_states = torch.nn.functional.pad(hidden_states.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
|
939 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=mask_value)
|
940 |
+
|
941 |
+
if self.mask_first_token:
|
942 |
+
attention_mask[..., 0] = mask_value
|
943 |
+
|
944 |
+
encoder_outputs = super().forward(
|
945 |
+
hidden_states=hidden_states,
|
946 |
+
attention_mask=attention_mask,
|
947 |
+
head_mask=head_mask,
|
948 |
+
encoder_hidden_states=encoder_hidden_states,
|
949 |
+
encoder_attention_mask=encoder_attention_mask,
|
950 |
+
past_key_values=past_key_values,
|
951 |
+
use_cache=use_cache,
|
952 |
+
output_attentions=output_attentions,
|
953 |
+
output_hidden_states=output_hidden_states,
|
954 |
+
return_dict=return_dict
|
955 |
+
)
|
956 |
+
|
957 |
+
sequence_output = encoder_outputs[0]
|
958 |
+
if self.pool_with_global:
|
959 |
+
sequence_output[:, self.num_global_tokens] = sequence_output[:, 0]
|
960 |
+
|
961 |
+
# Adapt sequence to initial shape
|
962 |
+
sequence_output = sequence_output[..., self.num_global_tokens: t + self.num_global_tokens, :]
|
963 |
+
|
964 |
+
if not return_dict:
|
965 |
+
return (sequence_output, ) + encoder_outputs[1:]
|
966 |
+
|
967 |
+
encoder_outputs.last_hidden_state = sequence_output
|
968 |
+
return encoder_outputs
|
969 |
+
|
970 |
+
class LSGCamembertPreTrainedModel(CamembertPreTrainedModel):
|
971 |
+
"""
|
972 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
973 |
+
models.
|
974 |
+
"""
|
975 |
+
|
976 |
+
config_class = LSGCamembertConfig
|
977 |
+
|
978 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
979 |
+
if isinstance(module, (CamembertEncoder, LSGCamembertEncoder)):
|
980 |
+
module.gradient_checkpointing = value
|
981 |
+
|
982 |
+
|
983 |
+
class LSGCamembertModel(LSGCamembertPreTrainedModel, CamembertModel):
|
984 |
+
"""
|
985 |
+
This class overrides :class:`~transformers.CamembertModel`. Please check the superclass for the appropriate
|
986 |
+
documentation alongside usage examples.
|
987 |
+
"""
|
988 |
+
|
989 |
+
config_class = LSGCamembertConfig
|
990 |
+
|
991 |
+
|
992 |
+
def __init__(self, config, add_pooling_layer=True):
|
993 |
+
|
994 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
995 |
+
|
996 |
+
self.embeddings = LSGCamembertEmbeddings(config)
|
997 |
+
self.encoder = LSGCamembertEncoder(config)
|
998 |
+
self.pooler = CamembertPooler(config) if add_pooling_layer else None
|
999 |
+
|
1000 |
+
if config.add_cross_attention:
|
1001 |
+
logger.warning(
|
1002 |
+
"Cross attention is computed using full attention since it is not LSG compatible."
|
1003 |
+
)
|
1004 |
+
|
1005 |
+
# Initialize weights and apply final processing
|
1006 |
+
self.post_init()
|
1007 |
+
|
1008 |
+
def get_extended_attention_mask(self, attention_mask, input_shape, device=None):
|
1009 |
+
|
1010 |
+
# Do not rely on original triangular mask from BERT/RoBERTa for causalLM
|
1011 |
+
if attention_mask.dim() == 3:
|
1012 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
1013 |
+
elif attention_mask.dim() == 2:
|
1014 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
1015 |
+
else:
|
1016 |
+
raise ValueError(
|
1017 |
+
f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
|
1018 |
+
)
|
1019 |
+
|
1020 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
1021 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(extended_attention_mask.dtype).min
|
1022 |
+
|
1023 |
+
return extended_attention_mask
|
1024 |
+
|
1025 |
+
|
1026 |
+
class LSGCamembertForCausalLM(LSGCamembertPreTrainedModel, CamembertForCausalLM):
|
1027 |
+
|
1028 |
+
_keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
|
1029 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
|
1030 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
1031 |
+
|
1032 |
+
def __init__(self, config):
|
1033 |
+
|
1034 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
1035 |
+
|
1036 |
+
if not config.is_decoder:
|
1037 |
+
logger.warning("If you want to use `LSGCamembertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
1038 |
+
|
1039 |
+
self.roberta = LSGCamembertModel(config, add_pooling_layer=False)
|
1040 |
+
self.lm_head = CamembertLMHead(config)
|
1041 |
+
|
1042 |
+
# The LM head weights require special treatment only when they are tied with the word embeddings
|
1043 |
+
self.update_keys_to_ignore(config, ["lm_head.decoder.weight"])
|
1044 |
+
|
1045 |
+
# Initialize weights and apply final processing
|
1046 |
+
self.post_init()
|
1047 |
+
|
1048 |
+
|
1049 |
+
class LSGCamembertForMaskedLM(LSGCamembertPreTrainedModel, CamembertForMaskedLM):
|
1050 |
+
"""
|
1051 |
+
This class overrides :class:`~transformers.CamembertForMaskedLM`. Please check the superclass for the appropriate
|
1052 |
+
documentation alongside usage examples.
|
1053 |
+
"""
|
1054 |
+
|
1055 |
+
_keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
|
1056 |
+
_keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"]
|
1057 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
1058 |
+
|
1059 |
+
def __init__(self, config):
|
1060 |
+
|
1061 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
1062 |
+
|
1063 |
+
if config.is_decoder:
|
1064 |
+
logger.warning(
|
1065 |
+
"If you want to use `LSGCamembertForMaskedLM` make sure `config.is_decoder=False` for "
|
1066 |
+
"bi-directional self-attention."
|
1067 |
+
)
|
1068 |
+
|
1069 |
+
self.roberta = LSGCamembertModel(config, add_pooling_layer=False)
|
1070 |
+
self.lm_head = CamembertLMHead(config)
|
1071 |
+
|
1072 |
+
# The LM head weights require special treatment only when they are tied with the word embeddings
|
1073 |
+
self.update_keys_to_ignore(config, ["lm_head.decoder.weight"])
|
1074 |
+
|
1075 |
+
# Initialize weights and apply final processing
|
1076 |
+
self.post_init()
|
1077 |
+
|
1078 |
+
|
1079 |
+
class LSGCamembertForSequenceClassification(LSGCamembertPreTrainedModel, CamembertForSequenceClassification):
|
1080 |
+
"""
|
1081 |
+
This class overrides :class:`~transformers.CamembertForSequenceClassification`. Please check the superclass for the
|
1082 |
+
appropriate documentation alongside usage examples.
|
1083 |
+
"""
|
1084 |
+
|
1085 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1086 |
+
|
1087 |
+
def __init__(self, config):
|
1088 |
+
|
1089 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
1090 |
+
|
1091 |
+
self.num_labels = config.num_labels
|
1092 |
+
self.config = config
|
1093 |
+
|
1094 |
+
self.roberta = LSGCamembertModel(config, add_pooling_layer=False)
|
1095 |
+
self.classifier = CamembertClassificationHead(config)
|
1096 |
+
|
1097 |
+
# Initialize weights and apply final processing
|
1098 |
+
self.post_init()
|
1099 |
+
|
1100 |
+
|
1101 |
+
class LSGCamembertForMultipleChoice(LSGCamembertPreTrainedModel, CamembertForMultipleChoice):
|
1102 |
+
"""
|
1103 |
+
This class overrides :class:`~transformers.CamembertForMultipleChoice`. Please check the superclass for the
|
1104 |
+
appropriate documentation alongside usage examples.
|
1105 |
+
"""
|
1106 |
+
|
1107 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1108 |
+
|
1109 |
+
def __init__(self, config):
|
1110 |
+
|
1111 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
1112 |
+
|
1113 |
+
self.roberta = LSGCamembertModel(config)
|
1114 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
1115 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
1116 |
+
|
1117 |
+
# Initialize weights and apply final processing
|
1118 |
+
self.post_init()
|
1119 |
+
|
1120 |
+
|
1121 |
+
class LSGCamembertForTokenClassification(LSGCamembertPreTrainedModel, CamembertForTokenClassification):
|
1122 |
+
"""
|
1123 |
+
This class overrides :class:`~transformers.CamembertForTokenClassification`. Please check the superclass for the
|
1124 |
+
appropriate documentation alongside usage examples.
|
1125 |
+
"""
|
1126 |
+
|
1127 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
1128 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1129 |
+
|
1130 |
+
def __init__(self, config):
|
1131 |
+
|
1132 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
1133 |
+
|
1134 |
+
self.num_labels = config.num_labels
|
1135 |
+
|
1136 |
+
self.roberta = LSGCamembertModel(config, add_pooling_layer=False)
|
1137 |
+
classifier_dropout = (
|
1138 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
1139 |
+
)
|
1140 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1141 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1142 |
+
|
1143 |
+
# Initialize weights and apply final processing
|
1144 |
+
self.post_init()
|
1145 |
+
|
1146 |
+
|
1147 |
+
class LSGCamembertForQuestionAnswering(LSGCamembertPreTrainedModel, CamembertForQuestionAnswering):
|
1148 |
+
"""
|
1149 |
+
This class overrides :class:`~transformers.CamembertForQuestionAnswering`. Please check the superclass for the
|
1150 |
+
appropriate documentation alongside usage examples.
|
1151 |
+
"""
|
1152 |
+
|
1153 |
+
_keys_to_ignore_on_load_unexpected = [r"pooler"]
|
1154 |
+
_keys_to_ignore_on_load_missing = [r"position_ids"]
|
1155 |
+
|
1156 |
+
def __init__(self, config):
|
1157 |
+
|
1158 |
+
LSGCamembertPreTrainedModel.__init__(self, config)
|
1159 |
+
|
1160 |
+
self.num_labels = config.num_labels
|
1161 |
+
|
1162 |
+
self.roberta = LSGCamembertModel(config, add_pooling_layer=False)
|
1163 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
1164 |
+
|
1165 |
+
# Initialize weights and apply final processing
|
1166 |
+
self.post_init()
|
1167 |
+
|
1168 |
+
|
1169 |
+
def str_to_class(classname):
|
1170 |
+
return getattr(sys.modules[__name__], classname)
|
1171 |
+
|
1172 |
+
# Register model in Auto API
|
1173 |
+
try:
|
1174 |
+
LSGCamembertConfig.register_for_auto_class()
|
1175 |
+
for key, value in AUTO_MAP.items():
|
1176 |
+
str_to_class(value.split(".")[-1]).register_for_auto_class(key)
|
1177 |
+
except:
|
1178 |
+
warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
|
1179 |
+
warn("Update to transformers >= 4.17.0 to fix.")
|
pytorch_model.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:acadd2539974ee49397dcfe70ab9fdbd7273f524406a82fe0d5ccbd0ac33fe1c
|
3 |
+
size 493151805
|