TCMVince commited on
Commit
a373e6a
1 Parent(s): 73f3210

Upload model

Browse files
config.json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/home/getalp/segonnev/models/multi-domains/FL_multidomains_lin256_base_512_768_lm_LR7e-4//HF-model",
3
+ "activation": "relu",
4
+ "add_bias_kv": false,
5
+ "add_pooling_layer": false,
6
+ "add_zero_attn": false,
7
+ "architectures": [
8
+ "Flaubert2Model"
9
+ ],
10
+ "attention_probs_dropout_prob": 0.1,
11
+ "auto_map": {
12
+ "AutoModel": "flaubert2_model.Flaubert2Model"
13
+ },
14
+ "bias": true,
15
+ "bos_token_id": 0,
16
+ "classifier_dropout": null,
17
+ "compress_layer": 1,
18
+ "compressed": 2,
19
+ "dim_feedforward": 4096,
20
+ "dropout": 0.1,
21
+ "embed_dim": 768,
22
+ "encoder_attention_heads": 16,
23
+ "encoder_decoder_attention": false,
24
+ "encoder_embed_dim": 768,
25
+ "encoder_ffn_embed_dim": 4096,
26
+ "encoder_normalize_before": true,
27
+ "eos_token_id": 2,
28
+ "freeze_compress": 0,
29
+ "hidden_act": "gelu",
30
+ "hidden_dropout_prob": 0.1,
31
+ "hidden_size": 768,
32
+ "initializer_range": 0.02,
33
+ "intermediate_act_fn": "gelu",
34
+ "intermediate_size": 4096,
35
+ "layer_norm_eps": 1e-05,
36
+ "layernorm_embedding": false,
37
+ "max_position_embeddings": 514,
38
+ "max_positions": 512,
39
+ "model_type": "roberta",
40
+ "num_attention_heads": 12,
41
+ "num_heads": 16,
42
+ "num_hidden_layers": 12,
43
+ "num_layers": 12,
44
+ "pad_token_id": 1,
45
+ "position_embedding_type": "learned",
46
+ "q_noise": 0,
47
+ "qn_block_size": 8,
48
+ "quant_noise_pq": 0.0,
49
+ "quant_noise_pq_block_size": 8,
50
+ "quant_noise_scalar": 0,
51
+ "self_attention": true,
52
+ "shared_kv_compressed": 1,
53
+ "shared_layer_kv_compressed": 1,
54
+ "torch_dtype": "float32",
55
+ "transformers_version": "4.30.1",
56
+ "type_vocab_size": 2,
57
+ "untie_weights_roberta": false,
58
+ "use_cache": true,
59
+ "vocab_size": 49993
60
+ }
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,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
30
+ def __init__(self, config, **kwargs):
31
+ base_model_prefix = "flaubert2"
32
+
33
+ super().__init__(config, **kwargs)
34
+
35
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
36
+ self.roberta = Flaubert2Model(config, add_pooling_layer=False)
37
+ #self.encoder = LinformerTransformerEncoder(config)
38
+ #self.encoder = LinformerTransformerEncoder(config)
39
+ self.sbo_head = self.build_sbo_head(config)
40
+
41
+ def build_sbo_head(self, config):
42
+ return SBOHead(
43
+ config,
44
+ embedding_weights=(
45
+ self.roberta.embeddings.word_embeddings.weight
46
+ if not config.untie_weights_roberta
47
+ else None
48
+ )
49
+ )
50
+
51
+
52
+ class Flaubert2ModelForTokenClassification(RobertaForTokenClassification):
53
+
54
+ config_class = Flaubert2Config
55
+
56
+ def __init__(self, config, **kwargs):
57
+ base_model_prefix = "flaubert2"
58
+
59
+ super().__init__(config, **kwargs)
60
+
61
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
62
+ self.roberta = Flaubert2Model(config, add_pooling_layer=False)
63
+ #self.encoder = LinformerTransformerEncoder(config)
64
+ #self.encoder = LinformerTransformerEncoder(config)
65
+ self.sbo_head = self.build_sbo_head(config)
66
+
67
+ def build_sbo_head(self, config):
68
+ return SBOHead(
69
+ config,
70
+ embedding_weights=(
71
+ self.roberta.embeddings.word_embeddings.weight
72
+ if not config.untie_weights_roberta
73
+ else None
74
+ )
75
+ )
76
+
77
+
78
+ class Flaubert2ModelForMaskedLM(RobertaForMaskedLM):
79
+
80
+ config_class = Flaubert2Config
81
+
82
+ def __init__(self, config, **kwargs):
83
+ base_model_prefix = "flaubert2"
84
+
85
+ super().__init__(config, **kwargs)
86
+
87
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
88
+ self.roberta = Flaubert2Model(config, add_pooling_layer=False)
89
+ #self.encoder = LinformerTransformerEncoder(config)
90
+ #self.encoder = LinformerTransformerEncoder(config)
91
+ self.sbo_head = self.build_sbo_head(config)
92
+
93
+ def build_sbo_head(self, config):
94
+ return SBOHead(
95
+ config,
96
+ embedding_weights=(
97
+ self.roberta.embeddings.word_embeddings.weight
98
+ if not config.untie_weights_roberta
99
+ else None
100
+ )
101
+ )
102
+
103
+ class Flaubert2ModelForMaskedLMFS(RobertaForMaskedLM):
104
+
105
+ def __init__(self, config, dictionary, **kwargs):
106
+ config_class = Flaubert2Config
107
+ base_model_prefix = "flaubert2"
108
+
109
+ super().__init__(config, **kwargs)
110
+
111
+ #self.encoder = Flaubert2Model(config, add_pooling_layer=False)
112
+ #self.roberta = Flaubert2ModelFS(config, dictionary, add_pooling_layer=False)
113
+ self.roberta =FlaubertEncoder(config, dictionary)
114
+ #self.encoder =
115
+ #self.encoder = LinformerTransformerEncoder(config)
116
+ #self.sbo_head = self.build_sbo_head(config)
117
+
118
+ def build_sbo_head(self, config):
119
+ return SBOHead(
120
+ config,
121
+ embedding_weights=(
122
+ self.roberta.embeddings.word_embeddings.weight
123
+ if not config.untie_weights_roberta
124
+ else None
125
+ )
126
+ )
127
+
128
+
129
+
130
+ class Flaubert2Embeddings(RobertaEmbeddings):
131
+
132
+ def __init__(self, config, **kwargs):
133
+ config_class = Flaubert2Config
134
+ base_model_prefix = "flaubert2"
135
+ super().__init__(config, **kwargs)
136
+
137
+ def forward(
138
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
139
+ ):
140
+ if position_ids is None:
141
+ if input_ids is not None:
142
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
143
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
144
+ else:
145
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
146
+
147
+ if input_ids is not None:
148
+ input_shape = input_ids.size()
149
+ else:
150
+ input_shape = inputs_embeds.size()[:-1]
151
+
152
+ seq_length = input_shape[1]
153
+
154
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
155
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
156
+ # issue #5664
157
+ if token_type_ids is None:
158
+ if hasattr(self, "token_type_ids"):
159
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
160
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
161
+ token_type_ids = buffered_token_type_ids_expanded
162
+ else:
163
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
164
+
165
+ if inputs_embeds is None:
166
+ inputs_embeds = self.word_embeddings(input_ids)
167
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
168
+
169
+ embeddings = inputs_embeds + token_type_embeddings
170
+ #if self.position_embedding_type == "absolute":
171
+ position_embeddings = self.position_embeddings(position_ids)
172
+ #else:
173
+
174
+ embeddings += position_embeddings
175
+ #embeddings = self.LayerNorm(embeddings)
176
+ embeddings = self.dropout(embeddings)
177
+ return embeddings
178
+
179
+ class Flaubert2Encoder(RobertaEncoder):
180
+
181
+ def __init__(self, args):
182
+ compress_layer = None
183
+ if args.shared_layer_kv_compressed == 1 and compress_layer is None:
184
+ compress_layer = nn.Linear(
185
+ args.max_positions,
186
+ args.max_positions // args.compressed
187
+ )
188
+ # intialize parameters for compressed layer
189
+ nn.init.xavier_uniform_(compress_layer.weight, gain=1 / math.sqrt(2))
190
+ if args.freeze_compress == 1:
191
+ compress_layer.weight.requires_grad = False
192
+ compress_layer = compress_layer
193
+
194
+ super().__init__(args)
195
+
196
+ self.layer = nn.ModuleList([LinformerTransformerEncoderLayer(args, compress_layer) for _ in range(args.num_layers)])
197
+ self.compress_layer = compress_layer
198
+
199
+ if args.encoder_normalize_before:
200
+ self.layer_norm = LayerNorm(args.embed_dim)
201
+ else:
202
+ self.layer_norm = None
203
+
204
+ self.lm_head = None
205
+
206
+ def forward(
207
+ self,
208
+ hidden_states: torch.Tensor,
209
+ attention_mask: Optional[torch.FloatTensor] = None,
210
+ head_mask: Optional[torch.FloatTensor] = None,
211
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
212
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
213
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
214
+ use_cache: Optional[bool] = None,
215
+ output_attentions: Optional[bool] = False,
216
+ output_hidden_states: Optional[bool] = False,
217
+ return_dict: Optional[bool] = True,
218
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
219
+
220
+ x = super().forward(hidden_states=hidden_states,
221
+ attention_mask=attention_mask,
222
+ head_mask=head_mask,
223
+ encoder_hidden_states=encoder_hidden_states,
224
+ encoder_attention_mask=encoder_attention_mask,
225
+ past_key_values=past_key_values,
226
+ use_cache=use_cache,
227
+ output_attentions=output_attentions,
228
+ output_hidden_states=output_hidden_states,
229
+ return_dict=return_dict)
230
+
231
+
232
+ if self.layer_norm is not None:
233
+ x.last_hidden_state = self.layer_norm(x.last_hidden_state)
234
+
235
+ return x
236
+
237
+ def build_encoder(self, args, dictionary, embed_tokens):
238
+ encoder = LinformerTransformerEncoder(args)
239
+ return encoder
240
+ if args.use_linformer:
241
+ encoder = LinformerTransformerEncoder(args, dictionary, embed_tokens)
242
+ elif args.use_fft:
243
+ encoder = FourierTransformerEncoder(args, dictionary, embed_tokens)
244
+ else:
245
+ encoder = TransformerEncoder(args, dictionary, embed_tokens)
246
+
247
+ encoder.apply(init_bert_params)
248
+
249
+ return encoder
250
+
251
+ def output_layer(self, features, masked_tokens=None, pairs=None, **unused):
252
+ lm_out = self.lm_head(features, masked_tokens)
253
+ if pairs is not None:
254
+ sbo_out = self.sbo_head(features, pairs)
255
+ return lm_out, sbo_out
256
+ else:
257
+ return lm_out
258
+
259
+
260
+ class Flaubert2Model(RobertaModel):
261
+
262
+ def __init__(self, config, **kwargs):
263
+ onfig_class = Flaubert2Config
264
+ base_model_prefix = "flaubert2"
265
+
266
+ super().__init__(config, **kwargs)
267
+ self.embeddings = Flaubert2Embeddings(config)
268
+ self.encoder = Flaubert2Encoder(config)
269
+ # Copied from modeling_roberta.py
270
+ # Add transpose of embeddings as implemented in fairseq
271
+ def forward(
272
+ self,
273
+ input_ids: Optional[torch.Tensor] = None,
274
+ attention_mask: Optional[torch.Tensor] = None,
275
+ token_type_ids: Optional[torch.Tensor] = None,
276
+ position_ids: Optional[torch.Tensor] = None,
277
+ head_mask: Optional[torch.Tensor] = None,
278
+ inputs_embeds: Optional[torch.Tensor] = None,
279
+ encoder_hidden_states: Optional[torch.Tensor] = None,
280
+ encoder_attention_mask: Optional[torch.Tensor] = None,
281
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
282
+ use_cache: Optional[bool] = None,
283
+ output_attentions: Optional[bool] = None,
284
+ output_hidden_states: Optional[bool] = None,
285
+ return_dict: Optional[bool] = None,
286
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
287
+ r"""
288
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
289
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
290
+ the model is configured as a decoder.
291
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
292
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
293
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
294
+
295
+ - 1 for tokens that are **not masked**,
296
+ - 0 for tokens that are **masked**.
297
+ 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)`):
298
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
299
+
300
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
301
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
302
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
303
+ use_cache (`bool`, *optional*):
304
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
305
+ `past_key_values`).
306
+ """
307
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
308
+ output_hidden_states = (
309
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
310
+ )
311
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
312
+
313
+ if self.config.is_decoder:
314
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
315
+ else:
316
+ use_cache = False
317
+
318
+ if input_ids is not None and inputs_embeds is not None:
319
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
320
+ elif input_ids is not None:
321
+ input_shape = input_ids.size()
322
+ elif inputs_embeds is not None:
323
+ input_shape = inputs_embeds.size()[:-1]
324
+ else:
325
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
326
+
327
+ batch_size, seq_length = input_shape
328
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
329
+
330
+ # past_key_values_length
331
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
332
+
333
+ if attention_mask is None:
334
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
335
+
336
+ if token_type_ids is None:
337
+ if hasattr(self.embeddings, "token_type_ids"):
338
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
339
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
340
+ token_type_ids = buffered_token_type_ids_expanded
341
+ else:
342
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
343
+
344
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
345
+ # ourselves in which case we just need to make it broadcastable to all heads.
346
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
347
+
348
+ # If a 2D or 3D attention mask is provided for the cross-attention
349
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
350
+ if self.config.is_decoder and encoder_hidden_states is not None:
351
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
352
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
353
+ if encoder_attention_mask is None:
354
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
355
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
356
+ else:
357
+ encoder_extended_attention_mask = None
358
+
359
+ # Prepare head mask if needed
360
+ # 1.0 in head_mask indicate we keep the head
361
+ # attention_probs has shape bsz x n_heads x N x N
362
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
363
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
364
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
365
+
366
+ embedding_output = self.embeddings(
367
+ input_ids=input_ids,
368
+ position_ids=position_ids,
369
+ token_type_ids=token_type_ids,
370
+ inputs_embeds=inputs_embeds,
371
+ past_key_values_length=past_key_values_length,
372
+ )
373
+
374
+
375
+ embedding_output = embedding_output.transpose(0,1)
376
+ encoder_outputs = self.encoder(
377
+ embedding_output,
378
+ attention_mask=extended_attention_mask,
379
+ head_mask=head_mask,
380
+ encoder_hidden_states=encoder_hidden_states,
381
+ encoder_attention_mask=encoder_extended_attention_mask,
382
+ past_key_values=past_key_values,
383
+ use_cache=use_cache,
384
+ output_attentions=output_attentions,
385
+ output_hidden_states=output_hidden_states,
386
+ )
387
+
388
+ sequence_output = encoder_outputs[0].transpose(0,1)
389
+
390
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
391
+
392
+ if not return_dict:
393
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
394
+
395
+ return BaseModelOutputWithPoolingAndCrossAttentions(
396
+ last_hidden_state=sequence_output,
397
+ pooler_output=pooled_output,
398
+ past_key_values=encoder_outputs.past_key_values,
399
+ hidden_states=encoder_outputs.hidden_states,
400
+ attentions=encoder_outputs.attentions,
401
+ cross_attentions=encoder_outputs.cross_attentions,
402
+ )
403
+
404
+ class SBOLayer(nn.Module):
405
+
406
+ def __init__(self, input_size, hidden_size, activation, export):
407
+ super().__init__()
408
+ self.layer = nn.Linear(input_size, hidden_size)
409
+ self.activ = get_activation_fn(activation)
410
+ self.norm = LayerNorm(hidden_size)
411
+
412
+ def forward(self, x):
413
+ return self.norm(self.activ(self.layer(x)))
414
+
415
+ class SBONetwork(nn.Module):
416
+
417
+ def __init__(self, input_size, hidden_size, activation, export):
418
+ super().__init__()
419
+ self.layers = nn.ModuleList([
420
+ self.build_sbo_layer(input_size, hidden_size, activation, export),
421
+ self.build_sbo_layer(hidden_size, hidden_size, activation, export)
422
+ ])
423
+ self.layers = nn.Sequential(*self.layers)
424
+
425
+ def build_sbo_layer(self, input_size, output_size, activation, export):
426
+ return SBOLayer(input_size, output_size, activation, export)
427
+
428
+ def forward(self, x):
429
+ return self.layers(x)
430
+
431
+
432
+ class SBOHead(nn.Module):
433
+
434
+ def __init__(self, args, embedding_weights, max_targets=20, position_embedding_size=200):
435
+ super().__init__()
436
+
437
+ self.position_embeddings = nn.Embedding(max_targets, position_embedding_size)
438
+
439
+ export = getattr(args, "export", False)
440
+ hidden_size = args.embed_dim
441
+ input_size = hidden_size * 2 + position_embedding_size
442
+ activation = getattr(args, "activation_fn", "relu") or "relu"
443
+
444
+ self.mlp_layer_norm = self.build_sbo_network(input_size, hidden_size, activation, export)
445
+
446
+ # The output weights are the same as the input embeddings, but there is
447
+ # an output-only bias for each token.
448
+ self.decoder = nn.Linear(
449
+ embedding_weights.size(1),
450
+ embedding_weights.size(0),
451
+ bias=False
452
+ )
453
+ if embedding_weights is not None:
454
+ self.decoder.weight = embedding_weights
455
+
456
+ self.bias = nn.Parameter(torch.zeros(embedding_weights.size(0)))
457
+ self.max_targets = max_targets
458
+
459
+ def build_sbo_network(self, input_size, hidden_size, activation, export):
460
+ return SBONetwork(input_size, hidden_size, activation, export)
461
+
462
+ def forward(self, hidden_states, pairs):
463
+ bs, num_pairs, _ = pairs.size()
464
+ bs, seq_len, dim = hidden_states.size()
465
+ # pair indices: (bs, num_pairs)
466
+ left, right = pairs[:,:, 0], pairs[:, :, 1]
467
+ # (bs, num_pairs, dim)
468
+ left_hidden = torch.gather(hidden_states, 1, left.unsqueeze(2).repeat(1, 1, dim))
469
+ # pair states: bs * num_pairs, max_targets, dim
470
+ left_hidden = left_hidden.contiguous().view(bs * num_pairs, dim).unsqueeze(1).repeat(1, self.max_targets, 1)
471
+
472
+ right_hidden = torch.gather(hidden_states, 1, right.unsqueeze(2).repeat(1, 1, dim))
473
+ # bs * num_pairs, max_targets, dim
474
+ right_hidden = right_hidden.contiguous().view(bs * num_pairs, dim).unsqueeze(1).repeat(1, self.max_targets, 1)
475
+
476
+ # (max_targets, dim)
477
+ position_embeddings = self.position_embeddings.weight
478
+
479
+ z = torch.cat((left_hidden, right_hidden, position_embeddings.unsqueeze(0).repeat(bs * num_pairs, 1, 1)), -1)
480
+
481
+ hidden_states = self.mlp_layer_norm(torch.cat((left_hidden, right_hidden, position_embeddings.unsqueeze(0).repeat(bs * num_pairs, 1, 1)), -1))
482
+ # target scores : bs * num_pairs, max_targets, vocab_size
483
+ target_scores = self.decoder(hidden_states) + self.bias
484
+ return target_scores
485
+
486
+
487
+ def get_activation_fn(activation):
488
+ """Returns the activation function corresponding to `activation`"""
489
+
490
+ if activation == "relu":
491
+ return F.relu
492
+ elif activation == "relu_squared":
493
+ return F.relu_squared
494
+ elif activation == "gelu":
495
+ return F.gelu
496
+ elif activation == "gelu_fast":
497
+ deprecation_warning(
498
+ "--activation-fn=gelu_fast has been renamed to gelu_accurate"
499
+ )
500
+ return F.gelu_accurate
501
+ elif activation == "gelu_accurate":
502
+ return F.gelu_accurate
503
+ elif activation == "tanh":
504
+ return torch.tanh
505
+ elif activation == "linear":
506
+ return lambda x: x
507
+ elif activation == "swish":
508
+ return torch.nn.SiLU
509
+ else:
510
+ raise RuntimeError("--activation-fn {} not supported".format(activation))
511
+
512
+ def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
513
+ """
514
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
515
+ are ignored. This is modified from fairseq's `utils.make_positions`.
516
+
517
+ Args:
518
+ x: torch.Tensor x:
519
+
520
+ Returns: torch.Tensor
521
+ """
522
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
523
+ mask = input_ids.ne(padding_idx).int()
524
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
525
+ 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:8a22cb65b205f068d57cdec6ac7bcc48300fa1652c0dbf11d01bd2669147d381
3
+ size 573981341