TCMVince commited on
Commit
7fa6c76
1 Parent(s): 882d9be

Upload model

Browse files
config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "models/legal/from_scratch/FL_lin256_base_512_768_lm_LR7e-4/HF-masked_lm/",
3
+ "activation": "relu",
4
+ "add_bias_kv": false,
5
+ "add_pooling_layer": false,
6
+ "add_zero_attn": false,
7
+ "architectures": [
8
+ "Flaubert2ModelForMaskedLM"
9
+ ],
10
+ "attention_probs_dropout_prob": 0.1,
11
+ "auto_map": {
12
+ "AutoConfig": "flaubert2_configuration.Flaubert2Config",
13
+ "AutoModel": "flaubert2_model.Flaubert2ModelForMaskedLM"
14
+ },
15
+ "bias": true,
16
+ "bos_token_id": 0,
17
+ "classifier_dropout": null,
18
+ "compress_layer": 1,
19
+ "compressed": 2,
20
+ "dim_feedforward": 4096,
21
+ "dropout": 0.1,
22
+ "embed_dim": 768,
23
+ "encoder_attention_heads": 12,
24
+ "encoder_decoder_attention": false,
25
+ "encoder_embed_dim": 768,
26
+ "encoder_ffn_embed_dim": 4096,
27
+ "encoder_normalize_before": true,
28
+ "eos_token_id": 2,
29
+ "freeze_compress": 0,
30
+ "hidden_act": "gelu",
31
+ "hidden_dropout_prob": 0.1,
32
+ "hidden_size": 768,
33
+ "initializer_range": 0.02,
34
+ "intermediate_act_fn": "gelu",
35
+ "intermediate_size": 4096,
36
+ "layer_norm_eps": 1e-05,
37
+ "layernorm_embedding": false,
38
+ "max_position_embeddings": 514,
39
+ "max_positions": 512,
40
+ "model_type": "flaubert2",
41
+ "num_attention_heads": 12,
42
+ "num_heads": 16,
43
+ "num_hidden_layers": 12,
44
+ "num_layers": 12,
45
+ "pad_token_id": 1,
46
+ "position_embedding_type": "learned",
47
+ "q_noise": 0,
48
+ "qn_block_size": 8,
49
+ "quant_noise_pq": 0.0,
50
+ "quant_noise_pq_block_size": 8,
51
+ "quant_noise_scalar": 0,
52
+ "self_attention": true,
53
+ "shared_kv_compressed": 0,
54
+ "shared_layer_kv_compressed": 1,
55
+ "torch_dtype": "float32",
56
+ "transformers_version": "4.30.1",
57
+ "type_vocab_size": 2,
58
+ "untie_weights_roberta": false,
59
+ "use_cache": true,
60
+ "vocab_size": 50000
61
+ }
flaubert2_configuration.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from transformers.models.roberta.modeling_roberta import RobertaConfig
3
+
4
+ class Flaubert2Config(RobertaConfig):
5
+ model_type = "flaubert2"
6
+
7
+ def __init__(self, compress_layer= 1,
8
+ shared_layer_kv_compressed=1,
9
+ shared_kv_compressed=0,
10
+ max_positions=512,
11
+ max_position_embeddings=512,
12
+ compressed=4,
13
+ vocab_size=30522,
14
+ freeze_compress=0,
15
+ embed_dim=768,
16
+ num_heads=16,
17
+ dim_feedforward=4096,
18
+ dropout=0.1,
19
+ activation="relu",
20
+ layer_norm_eps=1e-05,
21
+ self_attention=True,
22
+ encoder_decoder_attention=False,
23
+ bias=True,
24
+ q_noise=0,
25
+ qn_block_size=8,
26
+ add_bias_kv=False,
27
+ add_zero_attn=False,
28
+ num_layers=12,
29
+ untie_weights_roberta=False,
30
+ layernorm_embedding=False,
31
+ encoder_normalize_before=False,
32
+ encoder_embed_dim=768,
33
+ encoder_attention_heads=12,
34
+ quant_noise_pq=0.0,
35
+ quant_noise_pq_block_size=8,
36
+ quant_noise_scalar=0,
37
+ encoder_ffn_embed_dim=4096,
38
+ add_pooling_layer=False,
39
+ intermediate_size=4096,
40
+ intermediate_act_fn="relu",
41
+ hidden_act = "relu",
42
+ output_hidden_states=False,
43
+ position_embedding_type="learned",
44
+ **kwargs):
45
+ super().__init__(**kwargs)
46
+
47
+ self.add_pooling_layer = add_pooling_layer
48
+ self.compress_layer = compress_layer
49
+ self.shared_layer_kv_compressed = shared_layer_kv_compressed
50
+ self.shared_kv_compressed = shared_kv_compressed
51
+ self.max_positions = max_positions
52
+ self.max_position_embeddings = max_position_embeddings
53
+ self.compressed = compressed
54
+ self.freeze_compress = freeze_compress
55
+ self.embed_dim = embed_dim
56
+ self.num_heads = num_heads
57
+ self.dim_feedforward=dim_feedforward
58
+ self.dropout = dropout
59
+ self.activation= activation
60
+ self.layer_norm_eps = layer_norm_eps
61
+ self.self_attention = self_attention
62
+ self.encoder_decoder_attention = encoder_decoder_attention
63
+ self.bias = bias
64
+ self.q_noise = q_noise
65
+ self.qn_block_size = qn_block_size
66
+ self.add_bias_kv = add_bias_kv
67
+ self.add_zero_attn = add_zero_attn
68
+ self.num_layers = num_layers
69
+ self.untie_weights_roberta = untie_weights_roberta
70
+ self.layernorm_embedding=layernorm_embedding
71
+ self.encoder_embed_dim = encoder_embed_dim
72
+ self.encoder_attention_heads=encoder_attention_heads
73
+ self.quant_noise_pq = quant_noise_pq
74
+ self.quant_noise_pq_block_size=quant_noise_pq_block_size
75
+ self.quant_noise_scalar=quant_noise_scalar
76
+ self.encoder_normalize_before=encoder_normalize_before
77
+ self.encoder_ffn_embed_dim = encoder_ffn_embed_dim
78
+ self.vocab_size = vocab_size
79
+ self.intermediate_size = intermediate_size
80
+ self.intermediate_act_fn = intermediate_act_fn
81
+ self.output_hidden_states = output_hidden_states
82
+ self.hidden_act = hidden_act
83
+ self.position_embedding_type = position_embedding_type
84
+ self.encoder_normalize_before = encoder_normalize_before
flaubert2_model.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #from transformers import RobertaModel, RobertaConfig, RobertaForMaskedLM, RobertaLMHead
2
+ #from linformer import LinformerTransformerEncoder, LinformerTransformerEncoderLayer, LinformerTransformerEncoderFS, LinformerTransformerEncoderLayerFS
3
+ #import linformer
4
+ from .linformer import LinformerTransformerEncoderLayer
5
+ from .flaubert2_configuration import Flaubert2Config
6
+ from transformers.models.roberta.modeling_roberta import RobertaEncoder, RobertaConfig, RobertaModel, RobertaLMHead, RobertaForMaskedLM, RobertaEmbeddings, RobertaForTokenClassification, RobertaForSequenceClassification
7
+ import torch.nn as nn
8
+ import math
9
+ import torch.nn.functional as F
10
+ from torch.nn import LayerNorm
11
+ import torch
12
+ from typing import List, Optional, Tuple, Union
13
+
14
+ from fairseq.models.roberta import (
15
+ RobertaModel as RobertModel,
16
+ RobertaEncoder as RobertaEncoderFS
17
+ )
18
+
19
+ from transformers.modeling_outputs import (
20
+ MaskedLMOutput,
21
+ BaseModelOutputWithPastAndCrossAttentions,
22
+ BaseModelOutputWithPoolingAndCrossAttentions,
23
+ )
24
+
25
+
26
+ class Flaubert2ModelForSequenceClassification(RobertaForSequenceClassification):
27
+
28
+ config_class = Flaubert2Config
29
+ auto_map = {"test": "test3"}
30
+
31
+ def __init__(self, config, **kwargs):
32
+ base_model_prefix = "flaubert2"
33
+
34
+ super().__init__(config, **kwargs)
35
+
36
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
37
+ self.roberta = Flaubert2Model(config, add_pooling_layer=False)
38
+ #self.encoder = LinformerTransformerEncoder(config)
39
+ #self.encoder = LinformerTransformerEncoder(config)
40
+ self.sbo_head = self.build_sbo_head(config)
41
+
42
+ def build_sbo_head(self, config):
43
+ return SBOHead(
44
+ config,
45
+ embedding_weights=(
46
+ self.roberta.embeddings.word_embeddings.weight
47
+ if not config.untie_weights_roberta
48
+ else None
49
+ )
50
+ )
51
+
52
+
53
+ class Flaubert2ModelForTokenClassification(RobertaForTokenClassification):
54
+
55
+ config_class = Flaubert2Config
56
+
57
+ def __init__(self, config, **kwargs):
58
+ base_model_prefix = "flaubert2"
59
+
60
+ super().__init__(config, **kwargs)
61
+
62
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
63
+ self.roberta = Flaubert2Model(config, add_pooling_layer=False)
64
+ #self.encoder = LinformerTransformerEncoder(config)
65
+ #self.encoder = LinformerTransformerEncoder(config)
66
+ self.sbo_head = self.build_sbo_head(config)
67
+
68
+ def build_sbo_head(self, config):
69
+ return SBOHead(
70
+ config,
71
+ embedding_weights=(
72
+ self.roberta.embeddings.word_embeddings.weight
73
+ if not config.untie_weights_roberta
74
+ else None
75
+ )
76
+ )
77
+
78
+
79
+ class Flaubert2ModelForMaskedLM(RobertaForMaskedLM):
80
+
81
+ config_class = Flaubert2Config
82
+
83
+ def __init__(self, config, **kwargs):
84
+ base_model_prefix = "flaubert2"
85
+
86
+ super().__init__(config, **kwargs)
87
+
88
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
89
+ self.roberta = Flaubert2Model(config, add_pooling_layer=False)
90
+ #self.encoder = LinformerTransformerEncoder(config)
91
+ #self.encoder = LinformerTransformerEncoder(config)
92
+ self.sbo_head = self.build_sbo_head(config)
93
+
94
+ def build_sbo_head(self, config):
95
+ return SBOHead(
96
+ config,
97
+ embedding_weights=(
98
+ self.roberta.embeddings.word_embeddings.weight
99
+ if not config.untie_weights_roberta
100
+ else None
101
+ )
102
+ )
103
+
104
+ class Flaubert2ModelForMaskedLMFS(RobertaForMaskedLM):
105
+
106
+ def __init__(self, config, dictionary, **kwargs):
107
+ config_class = Flaubert2Config
108
+ base_model_prefix = "flaubert2"
109
+
110
+ super().__init__(config, **kwargs)
111
+
112
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
113
+ #self.roberta = Flaubert2ModelFS(config, dictionary, add_pooling_layer=False)
114
+ self.roberta =FlaubertEncoder(config, dictionary)
115
+ #self.encoder =
116
+ #self.encoder = LinformerTransformerEncoder(config)
117
+ #self.sbo_head = self.build_sbo_head(config)
118
+
119
+ def build_sbo_head(self, config):
120
+ return SBOHead(
121
+ config,
122
+ embedding_weights=(
123
+ self.roberta.embeddings.word_embeddings.weight
124
+ if not config.untie_weights_roberta
125
+ else None
126
+ )
127
+ )
128
+
129
+
130
+
131
+ class Flaubert2Embeddings(RobertaEmbeddings):
132
+
133
+ def __init__(self, config, **kwargs):
134
+ config_class = Flaubert2Config
135
+ base_model_prefix = "flaubert2"
136
+ super().__init__(config, **kwargs)
137
+
138
+ def forward(
139
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
140
+ ):
141
+ if position_ids is None:
142
+ if input_ids is not None:
143
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
144
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
145
+ else:
146
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
147
+
148
+ if input_ids is not None:
149
+ input_shape = input_ids.size()
150
+ else:
151
+ input_shape = inputs_embeds.size()[:-1]
152
+
153
+ seq_length = input_shape[1]
154
+
155
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
156
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
157
+ # issue #5664
158
+ if token_type_ids is None:
159
+ if hasattr(self, "token_type_ids"):
160
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
161
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
162
+ token_type_ids = buffered_token_type_ids_expanded
163
+ else:
164
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
165
+
166
+ if inputs_embeds is None:
167
+ inputs_embeds = self.word_embeddings(input_ids)
168
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
169
+
170
+ embeddings = inputs_embeds + token_type_embeddings
171
+ #if self.position_embedding_type == "absolute":
172
+ position_embeddings = self.position_embeddings(position_ids)
173
+ #else:
174
+
175
+ embeddings += position_embeddings
176
+ #embeddings = self.LayerNorm(embeddings)
177
+ embeddings = self.dropout(embeddings)
178
+ return embeddings
179
+
180
+ class Flaubert2Encoder(RobertaEncoder):
181
+
182
+ def __init__(self, args):
183
+ compress_layer = None
184
+ if args.shared_layer_kv_compressed == 1 and compress_layer is None:
185
+ compress_layer = nn.Linear(
186
+ args.max_positions,
187
+ args.max_positions // args.compressed
188
+ )
189
+ # intialize parameters for compressed layer
190
+ nn.init.xavier_uniform_(compress_layer.weight, gain=1 / math.sqrt(2))
191
+ if args.freeze_compress == 1:
192
+ compress_layer.weight.requires_grad = False
193
+ compress_layer = compress_layer
194
+
195
+ super().__init__(args)
196
+
197
+ self.layer = nn.ModuleList([LinformerTransformerEncoderLayer(args, compress_layer) for _ in range(args.num_layers)])
198
+ self.compress_layer = compress_layer
199
+
200
+ if args.encoder_normalize_before:
201
+ self.layer_norm = LayerNorm(args.embed_dim)
202
+ else:
203
+ self.layer_norm = None
204
+
205
+ self.lm_head = None
206
+
207
+ def forward(
208
+ self,
209
+ hidden_states: torch.Tensor,
210
+ attention_mask: Optional[torch.FloatTensor] = None,
211
+ head_mask: Optional[torch.FloatTensor] = None,
212
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
213
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
214
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
215
+ use_cache: Optional[bool] = None,
216
+ output_attentions: Optional[bool] = False,
217
+ output_hidden_states: Optional[bool] = False,
218
+ return_dict: Optional[bool] = True,
219
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
220
+
221
+ x = super().forward(hidden_states=hidden_states,
222
+ attention_mask=attention_mask,
223
+ head_mask=head_mask,
224
+ encoder_hidden_states=encoder_hidden_states,
225
+ encoder_attention_mask=encoder_attention_mask,
226
+ past_key_values=past_key_values,
227
+ use_cache=use_cache,
228
+ output_attentions=output_attentions,
229
+ output_hidden_states=output_hidden_states,
230
+ return_dict=return_dict)
231
+
232
+
233
+ if self.layer_norm is not None:
234
+ x.last_hidden_state = self.layer_norm(x.last_hidden_state)
235
+
236
+ return x
237
+
238
+ def build_encoder(self, args, dictionary, embed_tokens):
239
+ encoder = LinformerTransformerEncoder(args)
240
+ return encoder
241
+ if args.use_linformer:
242
+ encoder = LinformerTransformerEncoder(args, dictionary, embed_tokens)
243
+ elif args.use_fft:
244
+ encoder = FourierTransformerEncoder(args, dictionary, embed_tokens)
245
+ else:
246
+ encoder = TransformerEncoder(args, dictionary, embed_tokens)
247
+
248
+ encoder.apply(init_bert_params)
249
+
250
+ return encoder
251
+
252
+ def output_layer(self, features, masked_tokens=None, pairs=None, **unused):
253
+ lm_out = self.lm_head(features, masked_tokens)
254
+ if pairs is not None:
255
+ sbo_out = self.sbo_head(features, pairs)
256
+ return lm_out, sbo_out
257
+ else:
258
+ return lm_out
259
+
260
+
261
+ class Flaubert2Model(RobertaModel):
262
+
263
+ def __init__(self, config, **kwargs):
264
+ onfig_class = Flaubert2Config
265
+ base_model_prefix = "flaubert2"
266
+
267
+ super().__init__(config, **kwargs)
268
+ self.embeddings = Flaubert2Embeddings(config)
269
+ self.encoder = Flaubert2Encoder(config)
270
+ # Copied from modeling_roberta.py
271
+ # Add transpose of embeddings as implemented in fairseq
272
+ def forward(
273
+ self,
274
+ input_ids: Optional[torch.Tensor] = None,
275
+ attention_mask: Optional[torch.Tensor] = None,
276
+ token_type_ids: Optional[torch.Tensor] = None,
277
+ position_ids: Optional[torch.Tensor] = None,
278
+ head_mask: Optional[torch.Tensor] = None,
279
+ inputs_embeds: Optional[torch.Tensor] = None,
280
+ encoder_hidden_states: Optional[torch.Tensor] = None,
281
+ encoder_attention_mask: Optional[torch.Tensor] = None,
282
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
283
+ use_cache: Optional[bool] = None,
284
+ output_attentions: Optional[bool] = None,
285
+ output_hidden_states: Optional[bool] = None,
286
+ return_dict: Optional[bool] = None,
287
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
288
+ r"""
289
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
290
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
291
+ the model is configured as a decoder.
292
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
293
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
294
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
295
+
296
+ - 1 for tokens that are **not masked**,
297
+ - 0 for tokens that are **masked**.
298
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
299
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
300
+
301
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
302
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
303
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
304
+ use_cache (`bool`, *optional*):
305
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
306
+ `past_key_values`).
307
+ """
308
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
309
+ output_hidden_states = (
310
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
311
+ )
312
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
313
+
314
+ if self.config.is_decoder:
315
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
316
+ else:
317
+ use_cache = False
318
+
319
+ if input_ids is not None and inputs_embeds is not None:
320
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
321
+ elif input_ids is not None:
322
+ input_shape = input_ids.size()
323
+ elif inputs_embeds is not None:
324
+ input_shape = inputs_embeds.size()[:-1]
325
+ else:
326
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
327
+
328
+ batch_size, seq_length = input_shape
329
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
330
+
331
+ # past_key_values_length
332
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
333
+
334
+ if attention_mask is None:
335
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
336
+
337
+ if token_type_ids is None:
338
+ if hasattr(self.embeddings, "token_type_ids"):
339
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
340
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
341
+ token_type_ids = buffered_token_type_ids_expanded
342
+ else:
343
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
344
+
345
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
346
+ # ourselves in which case we just need to make it broadcastable to all heads.
347
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
348
+
349
+ # If a 2D or 3D attention mask is provided for the cross-attention
350
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
351
+ if self.config.is_decoder and encoder_hidden_states is not None:
352
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
353
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
354
+ if encoder_attention_mask is None:
355
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
356
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
357
+ else:
358
+ encoder_extended_attention_mask = None
359
+
360
+ # Prepare head mask if needed
361
+ # 1.0 in head_mask indicate we keep the head
362
+ # attention_probs has shape bsz x n_heads x N x N
363
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
364
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
365
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
366
+
367
+ embedding_output = self.embeddings(
368
+ input_ids=input_ids,
369
+ position_ids=position_ids,
370
+ token_type_ids=token_type_ids,
371
+ inputs_embeds=inputs_embeds,
372
+ past_key_values_length=past_key_values_length,
373
+ )
374
+
375
+
376
+ embedding_output = embedding_output.transpose(0,1)
377
+ encoder_outputs = self.encoder(
378
+ embedding_output,
379
+ attention_mask=extended_attention_mask,
380
+ head_mask=head_mask,
381
+ encoder_hidden_states=encoder_hidden_states,
382
+ encoder_attention_mask=encoder_extended_attention_mask,
383
+ past_key_values=past_key_values,
384
+ use_cache=use_cache,
385
+ output_attentions=output_attentions,
386
+ output_hidden_states=output_hidden_states,
387
+ )
388
+
389
+ sequence_output = encoder_outputs[0].transpose(0,1)
390
+
391
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
392
+
393
+ if not return_dict:
394
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
395
+
396
+ return BaseModelOutputWithPoolingAndCrossAttentions(
397
+ last_hidden_state=sequence_output,
398
+ pooler_output=pooled_output,
399
+ past_key_values=encoder_outputs.past_key_values,
400
+ hidden_states=encoder_outputs.hidden_states,
401
+ attentions=encoder_outputs.attentions,
402
+ cross_attentions=encoder_outputs.cross_attentions,
403
+ )
404
+
405
+ class SBOLayer(nn.Module):
406
+
407
+ def __init__(self, input_size, hidden_size, activation, export):
408
+ super().__init__()
409
+ self.layer = nn.Linear(input_size, hidden_size)
410
+ self.activ = get_activation_fn(activation)
411
+ self.norm = LayerNorm(hidden_size)
412
+
413
+ def forward(self, x):
414
+ return self.norm(self.activ(self.layer(x)))
415
+
416
+ class SBONetwork(nn.Module):
417
+
418
+ def __init__(self, input_size, hidden_size, activation, export):
419
+ super().__init__()
420
+ self.layers = nn.ModuleList([
421
+ self.build_sbo_layer(input_size, hidden_size, activation, export),
422
+ self.build_sbo_layer(hidden_size, hidden_size, activation, export)
423
+ ])
424
+ self.layers = nn.Sequential(*self.layers)
425
+
426
+ def build_sbo_layer(self, input_size, output_size, activation, export):
427
+ return SBOLayer(input_size, output_size, activation, export)
428
+
429
+ def forward(self, x):
430
+ return self.layers(x)
431
+
432
+
433
+ class SBOHead(nn.Module):
434
+
435
+ def __init__(self, args, embedding_weights, max_targets=10, position_embedding_size=200):
436
+ super().__init__()
437
+
438
+ self.position_embeddings = nn.Embedding(max_targets, position_embedding_size)
439
+
440
+ export = getattr(args, "export", False)
441
+ hidden_size = args.embed_dim
442
+ input_size = hidden_size * 2 + position_embedding_size
443
+ activation = getattr(args, "activation_fn", "relu") or "relu"
444
+
445
+ self.mlp_layer_norm = self.build_sbo_network(input_size, hidden_size, activation, export)
446
+
447
+ # The output weights are the same as the input embeddings, but there is
448
+ # an output-only bias for each token.
449
+ self.decoder = nn.Linear(
450
+ embedding_weights.size(1),
451
+ embedding_weights.size(0),
452
+ bias=False
453
+ )
454
+ if embedding_weights is not None:
455
+ self.decoder.weight = embedding_weights
456
+
457
+ self.bias = nn.Parameter(torch.zeros(embedding_weights.size(0)))
458
+ self.max_targets = max_targets
459
+
460
+ def build_sbo_network(self, input_size, hidden_size, activation, export):
461
+ return SBONetwork(input_size, hidden_size, activation, export)
462
+
463
+ def forward(self, hidden_states, pairs):
464
+ bs, num_pairs, _ = pairs.size()
465
+ bs, seq_len, dim = hidden_states.size()
466
+ # pair indices: (bs, num_pairs)
467
+ left, right = pairs[:,:, 0], pairs[:, :, 1]
468
+ # (bs, num_pairs, dim)
469
+ left_hidden = torch.gather(hidden_states, 1, left.unsqueeze(2).repeat(1, 1, dim))
470
+ # pair states: bs * num_pairs, max_targets, dim
471
+ left_hidden = left_hidden.contiguous().view(bs * num_pairs, dim).unsqueeze(1).repeat(1, self.max_targets, 1)
472
+
473
+ right_hidden = torch.gather(hidden_states, 1, right.unsqueeze(2).repeat(1, 1, dim))
474
+ # bs * num_pairs, max_targets, dim
475
+ right_hidden = right_hidden.contiguous().view(bs * num_pairs, dim).unsqueeze(1).repeat(1, self.max_targets, 1)
476
+
477
+ # (max_targets, dim)
478
+ position_embeddings = self.position_embeddings.weight
479
+
480
+ z = torch.cat((left_hidden, right_hidden, position_embeddings.unsqueeze(0).repeat(bs * num_pairs, 1, 1)), -1)
481
+
482
+ hidden_states = self.mlp_layer_norm(torch.cat((left_hidden, right_hidden, position_embeddings.unsqueeze(0).repeat(bs * num_pairs, 1, 1)), -1))
483
+ # target scores : bs * num_pairs, max_targets, vocab_size
484
+ target_scores = self.decoder(hidden_states) + self.bias
485
+ return target_scores
486
+
487
+
488
+ def get_activation_fn(activation):
489
+ """Returns the activation function corresponding to `activation`"""
490
+
491
+ if activation == "relu":
492
+ return F.relu
493
+ elif activation == "relu_squared":
494
+ return F.relu_squared
495
+ elif activation == "gelu":
496
+ return F.gelu
497
+ elif activation == "gelu_fast":
498
+ deprecation_warning(
499
+ "--activation-fn=gelu_fast has been renamed to gelu_accurate"
500
+ )
501
+ return F.gelu_accurate
502
+ elif activation == "gelu_accurate":
503
+ return F.gelu_accurate
504
+ elif activation == "tanh":
505
+ return torch.tanh
506
+ elif activation == "linear":
507
+ return lambda x: x
508
+ elif activation == "swish":
509
+ return torch.nn.SiLU
510
+ else:
511
+ raise RuntimeError("--activation-fn {} not supported".format(activation))
512
+
513
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
514
+ """
515
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
516
+ are ignored. This is modified from fairseq's `utils.make_positions`.
517
+
518
+ Args:
519
+ x: torch.Tensor x:
520
+
521
+ Returns: torch.Tensor
522
+ """
523
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
524
+ mask = input_ids.ne(padding_idx).int()
525
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
526
+ return incremental_indices.long() + padding_idx
linformer.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import torch
7
+ from fairseq import utils
8
+ from fairseq.models.transformer import *
9
+ from typing import Callable, List, Optional, Set, Tuple, Union
10
+ import inspect
11
+
12
+ import math
13
+
14
+ import torch.nn as nn
15
+
16
+ #rom fairseq.models.transformer import TransformerEncoder as TransformerEncoderFS
17
+ #from fairseq.modules import TransformerEncoderLayer as TransformerEncoderLayerFS
18
+
19
+ from torch.nn import TransformerEncoder, TransformerEncoderLayer
20
+
21
+ from .multihead_linear_attention import MultiheadLinearAttention
22
+ from transformers.models.roberta.modeling_roberta import RobertaEncoder, RobertaConfig, RobertaModel, RobertaLMHead, RobertaForMaskedLM, RobertaLayer
23
+
24
+
25
+ class LinformerTransformerEncoderLayer(RobertaLayer):
26
+ """
27
+ Implements a Linformer Encoder Layer used in BERT/XLM style pre-trained
28
+ models.
29
+ """
30
+
31
+ def __init__(self, config, shared_compress_layer):
32
+ # wrap in a list so it's not automatically registered by PyTorch
33
+ self.shared_compress_layer = [shared_compress_layer]
34
+ d_model=config.embed_dim
35
+ nhead=config.num_heads
36
+ dim_feedforward=config.dim_feedforward
37
+ dropout=config.dropout
38
+ activation=config.activation
39
+ layer_norm_eps=config.layer_norm_eps
40
+
41
+
42
+ super().__init__(config)
43
+ self.attention = self.build_self_attention(config.embed_dim, config)
44
+ self.attn_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-5)
45
+ self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-5)
46
+ self.output = RobertaOutput(config)
47
+
48
+
49
+
50
+ def build_self_attention(self, embed_dim, args):
51
+
52
+ attn = MultiheadLinearAttention(
53
+ embed_dim,
54
+ args.encoder_attention_heads,
55
+ dropout=args.dropout,
56
+ self_attention=True,
57
+ q_noise=args.quant_noise_pq,
58
+ qn_block_size=args.quant_noise_pq_block_size,
59
+ compressed=args.compressed,
60
+ max_seq_len=args.max_positions,
61
+ shared_kv_compressed=args.shared_kv_compressed,
62
+ shared_compress_layer=self.shared_compress_layer[0],
63
+ freeze_compress=args.freeze_compress,
64
+ )
65
+ return attn
66
+
67
+ def feed_forward_chunk(self, attention_output):
68
+
69
+ residual = attention_output
70
+
71
+ x = self.intermediate(attention_output)
72
+
73
+ layer_output = self.output(x, residual)
74
+
75
+ return layer_output
76
+
77
+ def forward(
78
+ self,
79
+ hidden_states: torch.Tensor,
80
+ attention_mask: Optional[torch.FloatTensor] = None,
81
+ head_mask: Optional[torch.FloatTensor] = None,
82
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
83
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
84
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
85
+ output_attentions: Optional[bool] = False,
86
+ ) -> Tuple[torch.Tensor]:
87
+
88
+ residual = hidden_states
89
+
90
+ if self.attn_layer_norm is not None:
91
+ hidden_states = self.attn_layer_norm(hidden_states)
92
+
93
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
94
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
95
+ self_attention_outputs = self.attention(
96
+ hidden_states,
97
+ attention_mask,
98
+ head_mask,
99
+ output_attentions=output_attentions,
100
+ past_key_value=self_attn_past_key_value,
101
+ )
102
+ attention_output = self_attention_outputs[0]
103
+
104
+ # if decoder, the last output is tuple of self-attn cache
105
+ if self.is_decoder:
106
+ outputs = self_attention_outputs[1:-1]
107
+ present_key_value = self_attention_outputs[-1]
108
+ else:
109
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
110
+
111
+ cross_attn_present_key_value = None
112
+ if self.is_decoder and encoder_hidden_states is not None:
113
+ if not hasattr(self, "crossattention"):
114
+ raise ValueError(
115
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
116
+ " by setting `config.add_cross_attention=True`"
117
+ )
118
+
119
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
120
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
121
+ cross_attention_outputs = self.crossattention(
122
+ attention_output,
123
+ attention_mask,
124
+ head_mask,
125
+ encoder_hidden_states,
126
+ encoder_attention_mask,
127
+ cross_attn_past_key_value,
128
+ output_attentions,
129
+ )
130
+ attention_output = cross_attention_outputs[0]
131
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
132
+
133
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
134
+ cross_attn_present_key_value = cross_attention_outputs[-1]
135
+ present_key_value = present_key_value + cross_attn_present_key_value
136
+
137
+ attention_output = attention_output + residual
138
+
139
+ residual = attention_output
140
+
141
+ attention_output = self.final_layer_norm(attention_output)
142
+
143
+ layer_output = apply_chunking_to_forward(
144
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
145
+ )
146
+ layer_output = layer_output + residual
147
+
148
+ outputs = (layer_output,) + outputs
149
+
150
+ # if decoder, return the attn key/values as the last output
151
+ if self.is_decoder:
152
+ outputs = outputs + (present_key_value,)
153
+
154
+ return outputs
155
+
156
+ def upgrade_state_dict_named(self, state_dict, name):
157
+ super().upgrade_state_dict_named(state_dict, name)
158
+ prefix = name + "." if name != "" else ""
159
+
160
+ # some old checkpoints had weight sharing implemented incorrectly
161
+ # (note: this was correct in the original paper code)
162
+ if utils.item(state_dict.get(f"{prefix}version", torch.tensor(1))) < 2:
163
+ state_dict[f"{prefix}version"] = torch.tensor(1)
164
+ # check compression layer sharing
165
+ if f"{prefix}shared_compress_layer.weight" in state_dict:
166
+ # reinitialize block without sharing compression layer to match
167
+ # old behavior
168
+ self.shared_compress_layer = [
169
+ torch.nn.Linear(
170
+ self.shared_compress_layer[0].weight.size(1),
171
+ self.shared_compress_layer[0].weight.size(0),
172
+ )
173
+ ]
174
+ self.self_attn = self.build_self_attention(self.embed_dim, self.args)
175
+ # delete shared_compress_layer, since it's already copied to
176
+ # self_attn.compress_k.weight
177
+ del state_dict[f"{prefix}shared_compress_layer.weight"]
178
+ if f"{prefix}shared_compress_layer.bias" in state_dict:
179
+ del state_dict[f"{prefix}shared_compress_layer.bias"]
180
+
181
+ class RobertaOutput(nn.Module):
182
+ def __init__(self, config):
183
+ super().__init__()
184
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
185
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
186
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
187
+
188
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
189
+ hidden_states = self.dense(hidden_states)
190
+ return hidden_states
191
+
192
+ hidden_states = self.dropout(hidden_states)
193
+ x = hidden_states + input_tensor
194
+
195
+ return x
196
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
197
+
198
+ #hidden_states = self.LayerNorm(hidden_states + input_tensor)
199
+ return hidden_states
200
+
201
+
202
+
203
+ class LinformerTransformerEncoder(RobertaEncoder):
204
+ """
205
+ Implementation for a Bi-directional Linformer based Sentence Encoder used
206
+ in BERT/XLM style pre-trained models.
207
+
208
+ This first computes the token embedding using the token embedding matrix,
209
+ position embeddings (if specified) and segment embeddings
210
+ (if specified). After applying the specified number of
211
+ LinformerEncoderLayers, it outputs all the internal states of the
212
+ encoder as well as the final representation associated with the first
213
+ token (usually CLS token).
214
+
215
+ Input:
216
+ - tokens: B x T matrix representing sentences
217
+ - segment_labels: B x T matrix representing segment label for tokens
218
+
219
+ Output:
220
+ - a tuple of the following:
221
+ - a list of internal model states used to compute the
222
+ predictions where each tensor has shape T x B x C
223
+ - sentence representation associated with first input token
224
+ in format B x C.
225
+ """
226
+
227
+ def __init__(self, config,**kwargs):
228
+ compress_layer = None
229
+ if config.shared_layer_kv_compressed == 1 and compress_layer is None:
230
+ compress_layer = nn.Linear(
231
+ config.max_positions,
232
+ config.max_positions // config.compressed
233
+ )
234
+ # intialize parameters for compressed layer
235
+ nn.init.xavier_uniform_(compress_layer.weight, gain=1 / math.sqrt(2))
236
+ if config.freeze_compress == 1:
237
+ compress_layer.weight.requires_grad = False
238
+ compress_layer = compress_layer
239
+ #encoder_layer = LinformerTransformerEncoderLayer(config, compress_layer)
240
+
241
+ super().__init__(config)
242
+
243
+ self.layer = nn.ModuleList([LinformerTransformerEncoderLayer(config, compress_layer) for _ in range(config.num_layers)])
244
+ self.compress_layer = compress_layer
245
+ self.layer_norm = nn.LayerNorm(config.embed_dim)
246
+
247
+ def apply_chunking_to_forward(
248
+ forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors
249
+ ) -> torch.Tensor:
250
+ """
251
+ This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension
252
+ `chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory.
253
+
254
+ If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly
255
+ applying `forward_fn` to `input_tensors`.
256
+
257
+ Args:
258
+ forward_fn (`Callable[..., torch.Tensor]`):
259
+ The forward function of the model.
260
+ chunk_size (`int`):
261
+ The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`.
262
+ chunk_dim (`int`):
263
+ The dimension over which the `input_tensors` should be chunked.
264
+ input_tensors (`Tuple[torch.Tensor]`):
265
+ The input tensors of `forward_fn` which will be chunked
266
+
267
+ Returns:
268
+ `torch.Tensor`: A tensor with the same shape as the `forward_fn` would have given if applied`.
269
+
270
+
271
+ Examples:
272
+
273
+ ```python
274
+ # rename the usual forward() fn to forward_chunk()
275
+ def forward_chunk(self, hidden_states):
276
+ hidden_states = self.decoder(hidden_states)
277
+ return hidden_states
278
+
279
+
280
+ # implement a chunked forward function
281
+ def forward(self, hidden_states):
282
+ return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)
283
+ ```"""
284
+
285
+ assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors"
286
+
287
+ # inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility
288
+ num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters)
289
+ if num_args_in_forward_chunk_fn != len(input_tensors):
290
+ raise ValueError(
291
+ f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input "
292
+ "tensors are given"
293
+ )
294
+
295
+ if chunk_size > 0:
296
+ tensor_shape = input_tensors[0].shape[chunk_dim]
297
+ for input_tensor in input_tensors:
298
+ if input_tensor.shape[chunk_dim] != tensor_shape:
299
+ raise ValueError(
300
+ f"All input tenors have to be of the same shape: {tensor_shape}, "
301
+ f"found shape {input_tensor.shape[chunk_dim]}"
302
+ )
303
+
304
+ if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
305
+ raise ValueError(
306
+ f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk "
307
+ f"size {chunk_size}"
308
+ )
309
+
310
+ num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size
311
+
312
+ # chunk input tensor into tuples
313
+ input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors)
314
+ # apply forward fn to every tuple
315
+ output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks))
316
+ # concatenate output at same dimension
317
+ return torch.cat(output_chunks, dim=chunk_dim)
318
+
319
+ return forward_fn(*input_tensors)
multihead_linear_attention.py ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates.
2
+ #
3
+ # This source code is licensed under the MIT license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ import math
7
+ from typing import Dict, Optional, Tuple
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ from fairseq import utils
12
+ from fairseq.incremental_decoding_utils import with_incremental_state
13
+ from fairseq.modules.quant_noise import quant_noise
14
+ from torch import Tensor, nn
15
+ from torch.nn import Parameter
16
+
17
+ @with_incremental_state
18
+ class MultiheadLinearAttention(nn.Module):
19
+ def __init__(
20
+ self,
21
+ embed_dim,
22
+ num_heads,
23
+ kdim=None,
24
+ vdim=None,
25
+ dropout=0.0,
26
+ bias=True,
27
+ add_bias_kv=False,
28
+ add_zero_attn=False,
29
+ self_attention=False,
30
+ encoder_decoder_attention=False,
31
+ q_noise=0.0,
32
+ qn_block_size=8,
33
+ compressed=1,
34
+ max_seq_len=256,
35
+ shared_kv_compressed=0,
36
+ shared_compress_layer=None,
37
+ freeze_compress=0,
38
+ ):
39
+ super().__init__()
40
+ self.embed_dim = embed_dim
41
+ self.kdim = kdim if kdim is not None else embed_dim
42
+ self.vdim = vdim if vdim is not None else embed_dim
43
+ self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
44
+ self.num_heads = num_heads
45
+ self.dropout = dropout
46
+ self.head_dim = embed_dim // num_heads
47
+ assert (
48
+ self.head_dim * num_heads == self.embed_dim
49
+ ), "embed_dim must be divisible by num_heads"
50
+ self.scaling = self.head_dim ** -0.5
51
+
52
+ self.self_attention = self_attention
53
+ self.encoder_decoder_attention = encoder_decoder_attention
54
+ assert not self.self_attention or self.qkv_same_dim, (
55
+ "Self-attention requires query, key and " "value to be of the same size"
56
+ )
57
+
58
+ self.k_proj = quant_noise(
59
+ nn.Linear(self.kdim, embed_dim, bias=bias), q_noise, qn_block_size
60
+ )
61
+ self.v_proj = quant_noise(
62
+ nn.Linear(self.vdim, embed_dim, bias=bias), q_noise, qn_block_size
63
+ )
64
+ self.q_proj = quant_noise(
65
+ nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size
66
+ )
67
+
68
+ # used for compress sequence to subsequence
69
+ if shared_compress_layer is None:
70
+ self.compress_seq_len = max_seq_len // compressed
71
+ self.compress_k = nn.Linear(max_seq_len, self.compress_seq_len, bias=False)
72
+ if shared_kv_compressed == 0:
73
+ self.compress_v = nn.Linear(
74
+ max_seq_len, self.compress_seq_len, bias=False
75
+ )
76
+ self.layerwise_sharing = False
77
+ else:
78
+ self.compress_k = shared_compress_layer
79
+ if shared_kv_compressed == 0:
80
+ self.compress_v = shared_compress_layer
81
+ self.layerwise_sharing = True
82
+ self.shared_kv_compressed = shared_kv_compressed
83
+
84
+ self.out_proj = quant_noise(
85
+ nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size)
86
+
87
+ if add_bias_kv:
88
+ self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
89
+ self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
90
+ else:
91
+ self.bias_k = self.bias_v = None
92
+
93
+ self.add_zero_attn = add_zero_attn
94
+
95
+ self.reset_parameters()
96
+
97
+ if freeze_compress == 1:
98
+ self.compress_k.weight.requires_grad = False
99
+ if shared_kv_compressed == 0:
100
+ self.compress_v.weight.requires_grad = False
101
+
102
+ self.onnx_trace = False
103
+
104
+ def reset_parameters(self):
105
+
106
+ if self.qkv_same_dim:
107
+ # Empirically observed the convergence to be much better with
108
+ # the scaled initialization
109
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
110
+ nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
111
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
112
+ if (
113
+ not self.layerwise_sharing
114
+ ): # otherwise, we already initialize the parameters
115
+ nn.init.xavier_uniform_(self.compress_k.weight, gain=1 / math.sqrt(2))
116
+ if self.shared_kv_compressed == 0:
117
+ nn.init.xavier_uniform_(
118
+ self.compress_v.weight, gain=1 / math.sqrt(2)
119
+ )
120
+ else:
121
+ nn.init.xavier_uniform_(self.k_proj.weight)
122
+ nn.init.xavier_uniform_(self.v_proj.weight)
123
+ nn.init.xavier_uniform_(self.q_proj.weight)
124
+ if (
125
+ not self.layerwise_sharing
126
+ ): # otherwise, we already initialize the parameters
127
+ nn.init.xavier_uniform_(self.compress_k.weight)
128
+ if self.shared_kv_compressed == 0:
129
+ nn.init.xavier_uniform_(self.compress_v.weight)
130
+
131
+ nn.init.xavier_uniform_(self.out_proj.weight)
132
+ if self.out_proj.bias is not None:
133
+ nn.init.constant_(self.out_proj.bias, 0.0)
134
+ if self.bias_k is not None:
135
+ nn.init.xavier_normal_(self.bias_k)
136
+ if self.bias_v is not None:
137
+ nn.init.xavier_normal_(self.bias_v)
138
+
139
+ def prepare_for_onnx_export_(self):
140
+ self.onnx_trace = True
141
+
142
+ def forward(
143
+ self,
144
+ query,
145
+ key: Optional[Tensor],
146
+ value: Optional[Tensor],
147
+ key_padding_mask: Optional[Tensor] = None,
148
+ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
149
+ output_attentions: bool = True,
150
+ need_weights: bool = True,
151
+ static_kv: bool = False,
152
+ attn_mask: Optional[Tensor] = None,
153
+ before_softmax: bool = False,
154
+ need_head_weights: bool = False,
155
+ past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
156
+ ) -> Tuple[Tensor, Optional[Tensor]]:
157
+ """Input shape: Time x Batch x Channel
158
+
159
+ Args:
160
+ key_padding_mask (ByteTensor, optional): mask to exclude
161
+ keys that are pads, of shape `(batch, src_len)`, where
162
+ padding elements are indicated by 1s.
163
+ need_weights (bool, optional): return the attention weights,
164
+ averaged over heads (default: False).
165
+ attn_mask (ByteTensor, optional): typically used to
166
+ implement causal attention, where the mask prevents the
167
+ attention from looking forward in time (default: None).
168
+ before_softmax (bool, optional): return the raw attention
169
+ weights and values before the attention softmax.
170
+ need_head_weights (bool, optional): return the attention
171
+ weights for each head. Implies *need_weights*. Default:
172
+ return the average attention weights over all heads.
173
+ """
174
+
175
+ if need_head_weights:
176
+ need_weights = True
177
+
178
+ tgt_len, bsz, embed_dim = query.size()
179
+ assert embed_dim == self.embed_dim
180
+ assert list(query.size()) == [tgt_len, bsz, embed_dim]
181
+
182
+ if incremental_state is not None:
183
+ saved_state = self._get_input_buffer(incremental_state)
184
+ if saved_state is not None and "prev_key" in saved_state:
185
+ # previous time steps are cached - no need to recompute
186
+ # key and value if they are static
187
+ if static_kv:
188
+ assert self.encoder_decoder_attention and not self.self_attention
189
+ key = value = None
190
+ else:
191
+ saved_state = None
192
+
193
+ if self.self_attention:
194
+ q = self.q_proj(query)
195
+
196
+ k_input = query.permute(1, 2, 0).contiguous() # B * C * T
197
+ k_input = (
198
+ F.linear(k_input, self.compress_k.weight[:, 0:tgt_len])
199
+ .permute(2, 0, 1)
200
+ .contiguous()
201
+ )
202
+ k = self.k_proj(k_input)
203
+
204
+ v_input = query.permute(1, 2, 0).contiguous() # B * C * T
205
+ if self.shared_kv_compressed == 0:
206
+ v_input = (
207
+ F.linear(v_input, self.compress_v.weight[:, 0:tgt_len])
208
+ .permute(2, 0, 1)
209
+ .contiguous()
210
+ )
211
+ if self.shared_kv_compressed == 1: # use shared kv compressed linear layer
212
+ v_input = (
213
+ F.linear(v_input, self.compress_k.weight[:, 0:tgt_len])
214
+ .permute(2, 0, 1)
215
+ .contiguous()
216
+ )
217
+ v = self.v_proj(v_input)
218
+ elif self.encoder_decoder_attention:
219
+ # encoder-decoder attention
220
+ q = self.q_proj(query)
221
+ if key is None:
222
+ assert value is None
223
+ k = v = None
224
+ else:
225
+ k = self.k_proj(key)
226
+ v = self.v_proj(key)
227
+
228
+ else:
229
+ assert key is not None and value is not None
230
+ q = self.q_proj(query)
231
+ k = self.k_proj(key)
232
+ v = self.v_proj(value)
233
+ q *= self.scaling
234
+
235
+ if self.bias_k is not None:
236
+ assert self.bias_v is not None
237
+ k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
238
+ v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
239
+ if attn_mask is not None:
240
+ attn_mask = torch.cat(
241
+ [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
242
+ )
243
+ if key_padding_mask is not None:
244
+ key_padding_mask = torch.cat(
245
+ [
246
+ key_padding_mask,
247
+ key_padding_mask.new_zeros(key_padding_mask.size(0), 1),
248
+ ],
249
+ dim=1,
250
+ )
251
+
252
+ q = (
253
+ q.contiguous()
254
+ .view(tgt_len, bsz * self.num_heads, self.head_dim)
255
+ .transpose(0, 1)
256
+ )
257
+ if k is not None:
258
+ k = (
259
+ k.contiguous()
260
+ .view(-1, bsz * self.num_heads, self.head_dim)
261
+ .transpose(0, 1)
262
+ )
263
+ if v is not None:
264
+ v = (
265
+ v.contiguous()
266
+ .view(-1, bsz * self.num_heads, self.head_dim)
267
+ .transpose(0, 1)
268
+ )
269
+
270
+ if saved_state is not None:
271
+ # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
272
+ if "prev_key" in saved_state:
273
+ _prev_key = saved_state["prev_key"]
274
+ assert _prev_key is not None
275
+ prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
276
+ if static_kv:
277
+ k = prev_key
278
+ else:
279
+ assert k is not None
280
+ k = torch.cat([prev_key, k], dim=1)
281
+ if "prev_value" in saved_state:
282
+ _prev_value = saved_state["prev_value"]
283
+ assert _prev_value is not None
284
+ prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
285
+ if static_kv:
286
+ v = prev_value
287
+ else:
288
+ assert v is not None
289
+ v = torch.cat([prev_value, v], dim=1)
290
+ prev_key_padding_mask: Optional[Tensor] = None
291
+ if "prev_key_padding_mask" in saved_state:
292
+ prev_key_padding_mask = saved_state["prev_key_padding_mask"]
293
+ assert k is not None and v is not None
294
+ key_padding_mask = MultiheadLinearAttention._append_prev_key_padding_mask(
295
+ key_padding_mask=key_padding_mask,
296
+ prev_key_padding_mask=prev_key_padding_mask,
297
+ batch_size=bsz,
298
+ src_len=k.size(1),
299
+ static_kv=static_kv,
300
+ )
301
+
302
+ saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim)
303
+ saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim)
304
+ saved_state["prev_key_padding_mask"] = key_padding_mask
305
+ # In this branch incremental_state is never None
306
+ assert incremental_state is not None
307
+ incremental_state = self._set_input_buffer(incremental_state, saved_state)
308
+ assert k is not None
309
+ src_len = k.size(1)
310
+
311
+ if self.add_zero_attn:
312
+ assert v is not None
313
+ src_len += 1
314
+ k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
315
+ v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
316
+ if attn_mask is not None:
317
+ attn_mask = torch.cat(
318
+ [attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
319
+ )
320
+
321
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
322
+ attn_weights = MultiheadLinearAttention.apply_sparse_mask(
323
+ attn_weights, tgt_len, src_len, bsz
324
+ )
325
+
326
+ assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
327
+
328
+ if attn_mask is not None:
329
+ attn_mask = attn_mask.unsqueeze(0)
330
+ if self.onnx_trace:
331
+ attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1)
332
+ attn_weights += attn_mask
333
+
334
+ if before_softmax:
335
+ return attn_weights, v
336
+
337
+ attn_weights_float = utils.softmax(
338
+ attn_weights, dim=-1, onnx_trace=self.onnx_trace
339
+ )
340
+ attn_weights = attn_weights_float.type_as(attn_weights)
341
+ attn_probs = F.dropout(
342
+ attn_weights,
343
+ p=self.dropout,
344
+ training=self.training,
345
+ )
346
+ assert v is not None
347
+ attn = torch.bmm(attn_probs, v)
348
+ assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
349
+ if self.onnx_trace and attn.size(1) == 1:
350
+ # when ONNX tracing a single decoder step (sequence length == 1)
351
+ # the transpose is a no-op copy before view, thus unnecessary
352
+ attn = attn.contiguous().view(tgt_len, bsz, embed_dim)
353
+ else:
354
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
355
+ attn = self.out_proj(attn)
356
+ attn_weights: Optional[Tensor] = None
357
+ if output_attentions:
358
+ attn_weights = attn_weights_float.view(
359
+ bsz, self.num_heads, tgt_len, src_len
360
+ ).transpose(1, 0)
361
+ if not need_head_weights:
362
+ # average attention weights over heads
363
+ attn_weights = attn_weights.mean(dim=0)
364
+
365
+
366
+ return attn, attn_weights
367
+
368
+ @staticmethod
369
+ def _append_prev_key_padding_mask(
370
+ key_padding_mask: Optional[Tensor],
371
+ prev_key_padding_mask: Optional[Tensor],
372
+ batch_size: int,
373
+ src_len: int,
374
+ static_kv: bool,
375
+ ) -> Optional[Tensor]:
376
+ # saved key padding masks have shape (bsz, seq_len)
377
+ if prev_key_padding_mask is not None and static_kv:
378
+ new_key_padding_mask = prev_key_padding_mask
379
+ elif prev_key_padding_mask is not None and key_padding_mask is not None:
380
+ new_key_padding_mask = torch.cat(
381
+ [prev_key_padding_mask.float(), key_padding_mask.float()], dim=1
382
+ )
383
+ # During incremental decoding, as the padding token enters and
384
+ # leaves the frame, there will be a time when prev or current
385
+ # is None
386
+ elif prev_key_padding_mask is not None:
387
+ filler = torch.zeros(
388
+ (batch_size, src_len - prev_key_padding_mask.size(1)),
389
+ device=prev_key_padding_mask.device,
390
+ )
391
+ new_key_padding_mask = torch.cat(
392
+ [prev_key_padding_mask.float(), filler.float()], dim=1
393
+ )
394
+ elif key_padding_mask is not None:
395
+ filler = torch.zeros(
396
+ (batch_size, src_len - key_padding_mask.size(1)),
397
+ device=key_padding_mask.device,
398
+ )
399
+ new_key_padding_mask = torch.cat(
400
+ [filler.float(), key_padding_mask.float()], dim=1
401
+ )
402
+ else:
403
+ new_key_padding_mask = prev_key_padding_mask
404
+ return new_key_padding_mask
405
+
406
+ @torch.jit.export
407
+ def reorder_incremental_state(
408
+ self,
409
+ incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
410
+ new_order: Tensor,
411
+ ):
412
+ """Reorder buffered internal state (for incremental generation)."""
413
+ input_buffer = self._get_input_buffer(incremental_state)
414
+ if input_buffer is not None:
415
+ for k in input_buffer.keys():
416
+ input_buffer_k = input_buffer[k]
417
+ if input_buffer_k is not None:
418
+ if self.encoder_decoder_attention and input_buffer_k.size(
419
+ 0
420
+ ) == new_order.size(0):
421
+ break
422
+ input_buffer[k] = input_buffer_k.index_select(0, new_order)
423
+ incremental_state = self._set_input_buffer(incremental_state, input_buffer)
424
+ return incremental_state
425
+
426
+ def _get_input_buffer(
427
+ self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]]
428
+ ) -> Dict[str, Optional[Tensor]]:
429
+ result = self.get_incremental_state(incremental_state, "attn_state")
430
+ if result is not None:
431
+ return result
432
+ else:
433
+ empty_result: Dict[str, Optional[Tensor]] = {}
434
+ return empty_result
435
+
436
+ def _set_input_buffer(
437
+ self,
438
+ incremental_state: Dict[str, Dict[str, Optional[Tensor]]],
439
+ buffer: Dict[str, Optional[Tensor]],
440
+ ):
441
+ return self.set_incremental_state(incremental_state, "attn_state", buffer)
442
+
443
+ def apply_sparse_mask(attn_weights, tgt_len: int, src_len: int, bsz: int):
444
+ return attn_weights
445
+
446
+ def upgrade_state_dict_named(self, state_dict, name):
447
+ prefix = name + "." if name != "" else ""
448
+ items_to_add = {}
449
+ keys_to_remove = []
450
+ for k in state_dict.keys():
451
+ if k.endswith(prefix + "in_proj_weight"):
452
+ # in_proj_weight used to be q + k + v with same dimensions
453
+ dim = int(state_dict[k].shape[0] / 3)
454
+ items_to_add[prefix + "q_proj.weight"] = state_dict[k][:dim]
455
+ items_to_add[prefix + "k_proj.weight"] = state_dict[k][dim : 2 * dim]
456
+ items_to_add[prefix + "v_proj.weight"] = state_dict[k][2 * dim :]
457
+
458
+ keys_to_remove.append(k)
459
+
460
+ k_bias = prefix + "in_proj_bias"
461
+ if k_bias in state_dict.keys():
462
+ dim = int(state_dict[k].shape[0] / 3)
463
+ items_to_add[prefix + "q_proj.bias"] = state_dict[k_bias][:dim]
464
+ items_to_add[prefix + "k_proj.bias"] = state_dict[k_bias][
465
+ dim : 2 * dim
466
+ ]
467
+ items_to_add[prefix + "v_proj.bias"] = state_dict[k_bias][2 * dim :]
468
+
469
+ keys_to_remove.append(prefix + "in_proj_bias")
470
+
471
+ for k in keys_to_remove:
472
+ del state_dict[k]
473
+
474
+ for key, value in items_to_add.items():
475
+ state_dict[key] = value
476
+
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc20ffd6ab2c38c0bd9f4c2936a25284602afcd509469565f3ee0c0aeb540eab
3
+ size 582136977