Upload 3 files
Browse filesinitial commit: library code
- jargon_configuration.py +88 -0
- jargon_model.py +522 -0
- linformer.py +740 -0
jargon_configuration.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
from transformers.models.roberta.modeling_roberta import RobertaConfig
|
3 |
+
|
4 |
+
|
5 |
+
class JargonConfig(RobertaConfig):
|
6 |
+
model_type = "jargon"
|
7 |
+
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
compress_layer= 1,
|
11 |
+
shared_layer_kv_compressed=1,
|
12 |
+
shared_kv_compressed=0,
|
13 |
+
max_positions=512,
|
14 |
+
max_position_embeddings=512,
|
15 |
+
compressed=4,
|
16 |
+
vocab_size=30522,
|
17 |
+
freeze_compress=0,
|
18 |
+
embed_dim=768,
|
19 |
+
num_heads=16,
|
20 |
+
dim_feedforward=4096,
|
21 |
+
dropout=0.1,
|
22 |
+
activation="relu",
|
23 |
+
layer_norm_eps=1e-05,
|
24 |
+
self_attention=True,
|
25 |
+
encoder_decoder_attention=False,
|
26 |
+
bias=True,
|
27 |
+
q_noise=0,
|
28 |
+
qn_block_size=8,
|
29 |
+
add_bias_kv=False,
|
30 |
+
add_zero_attn=False,
|
31 |
+
num_layers=12,
|
32 |
+
untie_weights_roberta=False,
|
33 |
+
layernorm_embedding=False,
|
34 |
+
encoder_normalize_before=False,
|
35 |
+
encoder_embed_dim=768,
|
36 |
+
encoder_attention_heads=12,
|
37 |
+
quant_noise_pq=0.0,
|
38 |
+
quant_noise_pq_block_size=8,
|
39 |
+
quant_noise_scalar=0,
|
40 |
+
encoder_ffn_embed_dim=4096,
|
41 |
+
add_pooling_layer=False,
|
42 |
+
intermediate_size=4096,
|
43 |
+
intermediate_act_fn="relu",
|
44 |
+
hidden_act="relu",
|
45 |
+
output_hidden_states=False,
|
46 |
+
position_embedding_type="learned",
|
47 |
+
**kwargs
|
48 |
+
):
|
49 |
+
super().__init__(**kwargs)
|
50 |
+
|
51 |
+
self.add_pooling_layer = add_pooling_layer
|
52 |
+
self.compress_layer = compress_layer
|
53 |
+
self.shared_layer_kv_compressed = shared_layer_kv_compressed
|
54 |
+
self.shared_kv_compressed = shared_kv_compressed
|
55 |
+
self.max_positions = max_positions
|
56 |
+
self.max_position_embeddings = max_position_embeddings
|
57 |
+
self.compressed = compressed
|
58 |
+
self.freeze_compress = freeze_compress
|
59 |
+
self.embed_dim = embed_dim
|
60 |
+
self.num_heads = num_heads
|
61 |
+
self.dim_feedforward=dim_feedforward
|
62 |
+
self.dropout = dropout
|
63 |
+
self.activation= activation
|
64 |
+
self.layer_norm_eps = layer_norm_eps
|
65 |
+
self.self_attention = self_attention
|
66 |
+
self.encoder_decoder_attention = encoder_decoder_attention
|
67 |
+
self.bias = bias
|
68 |
+
self.q_noise = q_noise
|
69 |
+
self.qn_block_size = qn_block_size
|
70 |
+
self.add_bias_kv = add_bias_kv
|
71 |
+
self.add_zero_attn = add_zero_attn
|
72 |
+
self.num_layers = num_layers
|
73 |
+
self.untie_weights_roberta = untie_weights_roberta
|
74 |
+
self.layernorm_embedding=layernorm_embedding
|
75 |
+
self.encoder_embed_dim = encoder_embed_dim
|
76 |
+
self.encoder_attention_heads=encoder_attention_heads
|
77 |
+
self.quant_noise_pq = quant_noise_pq
|
78 |
+
self.quant_noise_pq_block_size=quant_noise_pq_block_size
|
79 |
+
self.quant_noise_scalar=quant_noise_scalar
|
80 |
+
self.encoder_normalize_before=encoder_normalize_before
|
81 |
+
self.encoder_ffn_embed_dim = encoder_ffn_embed_dim
|
82 |
+
self.vocab_size = vocab_size
|
83 |
+
self.intermediate_size = intermediate_size
|
84 |
+
self.intermediate_act_fn = intermediate_act_fn
|
85 |
+
self.output_hidden_states = output_hidden_states
|
86 |
+
self.hidden_act = hidden_act
|
87 |
+
self.position_embedding_type = position_embedding_type
|
88 |
+
self.encoder_normalize_before = encoder_normalize_before
|
jargon_model.py
ADDED
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from typing import List, Optional, Tuple, Union
|
3 |
+
|
4 |
+
import torch
|
5 |
+
import torch.nn as nn
|
6 |
+
import torch.nn.functional as F
|
7 |
+
from torch.nn import LayerNorm
|
8 |
+
from fairseq.models.roberta import (
|
9 |
+
RobertaModel as RobertModel,
|
10 |
+
RobertaEncoder as RobertaEncoderFS
|
11 |
+
)
|
12 |
+
from transformers.models.roberta.modeling_roberta import (
|
13 |
+
RobertaEncoder,
|
14 |
+
RobertaConfig,
|
15 |
+
RobertaModel,
|
16 |
+
RobertaLMHead,
|
17 |
+
RobertaForMaskedLM,
|
18 |
+
RobertaEmbeddings,
|
19 |
+
RobertaForTokenClassification,
|
20 |
+
RobertaForSequenceClassification
|
21 |
+
)
|
22 |
+
from transformers.modeling_outputs import (
|
23 |
+
MaskedLMOutput,
|
24 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
25 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
26 |
+
)
|
27 |
+
|
28 |
+
from .linformer import LinformerTransformerEncoderLayer
|
29 |
+
from .jargon_configuration import JargonConfig
|
30 |
+
|
31 |
+
|
32 |
+
class JargonForSequenceClassification(RobertaForSequenceClassification):
|
33 |
+
|
34 |
+
config_class = JargonConfig
|
35 |
+
|
36 |
+
def __init__(self, config, **kwargs):
|
37 |
+
base_model_prefix = "jargon"
|
38 |
+
|
39 |
+
super().__init__(config, **kwargs)
|
40 |
+
|
41 |
+
self.roberta = JargonModel(config, add_pooling_layer=False)
|
42 |
+
self.sbo_head = self.build_sbo_head(config)
|
43 |
+
|
44 |
+
def build_sbo_head(self, config):
|
45 |
+
return SBOHead(
|
46 |
+
config,
|
47 |
+
embedding_weights=(
|
48 |
+
self.roberta.embeddings.word_embeddings.weight
|
49 |
+
if not config.untie_weights_roberta
|
50 |
+
else None
|
51 |
+
)
|
52 |
+
)
|
53 |
+
|
54 |
+
|
55 |
+
class JargonForTokenClassification(RobertaForTokenClassification):
|
56 |
+
|
57 |
+
config_class = JargonConfig
|
58 |
+
|
59 |
+
def __init__(self, config, **kwargs):
|
60 |
+
base_model_prefix = "jargon"
|
61 |
+
|
62 |
+
super().__init__(config, **kwargs)
|
63 |
+
|
64 |
+
self.roberta = JargonModel(config, add_pooling_layer=False)
|
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 JargonForMaskedLM(RobertaForMaskedLM):
|
79 |
+
|
80 |
+
config_class = JargonConfig
|
81 |
+
|
82 |
+
def __init__(self, config, **kwargs):
|
83 |
+
base_model_prefix = "jargon"
|
84 |
+
|
85 |
+
super().__init__(config, **kwargs)
|
86 |
+
|
87 |
+
self.roberta = JargonModel(config, add_pooling_layer=False)
|
88 |
+
self.sbo_head = self.build_sbo_head(config)
|
89 |
+
|
90 |
+
def build_sbo_head(self, config):
|
91 |
+
return SBOHead(
|
92 |
+
config,
|
93 |
+
embedding_weights=(
|
94 |
+
self.roberta.embeddings.word_embeddings.weight
|
95 |
+
if not config.untie_weights_roberta
|
96 |
+
else None
|
97 |
+
)
|
98 |
+
)
|
99 |
+
|
100 |
+
|
101 |
+
class JargonForMaskedLMFS(RobertaForMaskedLM):
|
102 |
+
|
103 |
+
def __init__(self, config, dictionary, **kwargs):
|
104 |
+
config_class = JargonConfig
|
105 |
+
base_model_prefix = "jargon"
|
106 |
+
|
107 |
+
super().__init__(config, **kwargs)
|
108 |
+
|
109 |
+
self.roberta = FlaubertEncoder(config, dictionary)
|
110 |
+
|
111 |
+
def build_sbo_head(self, config):
|
112 |
+
return SBOHead(
|
113 |
+
config,
|
114 |
+
embedding_weights=(
|
115 |
+
self.roberta.embeddings.word_embeddings.weight
|
116 |
+
if not config.untie_weights_roberta
|
117 |
+
else None
|
118 |
+
)
|
119 |
+
)
|
120 |
+
|
121 |
+
|
122 |
+
class JargonEmbeddings(RobertaEmbeddings):
|
123 |
+
|
124 |
+
def __init__(self, config, **kwargs):
|
125 |
+
config_class = JargonConfig
|
126 |
+
base_model_prefix = "jargon"
|
127 |
+
super().__init__(config, **kwargs)
|
128 |
+
|
129 |
+
def forward(
|
130 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
131 |
+
):
|
132 |
+
if position_ids is None:
|
133 |
+
if input_ids is not None:
|
134 |
+
# Create the position ids from the input token ids. Any padded tokens remain padded.
|
135 |
+
position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
|
136 |
+
else:
|
137 |
+
position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
|
138 |
+
|
139 |
+
if input_ids is not None:
|
140 |
+
input_shape = input_ids.size()
|
141 |
+
else:
|
142 |
+
input_shape = inputs_embeds.size()[:-1]
|
143 |
+
|
144 |
+
seq_length = input_shape[1]
|
145 |
+
|
146 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
147 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
148 |
+
# issue #5664
|
149 |
+
if token_type_ids is None:
|
150 |
+
if hasattr(self, "token_type_ids"):
|
151 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
152 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
153 |
+
token_type_ids = buffered_token_type_ids_expanded
|
154 |
+
else:
|
155 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
156 |
+
|
157 |
+
if inputs_embeds is None:
|
158 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
159 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
160 |
+
|
161 |
+
embeddings = inputs_embeds + token_type_embeddings
|
162 |
+
position_embeddings = self.position_embeddings(position_ids)
|
163 |
+
|
164 |
+
embeddings += position_embeddings
|
165 |
+
embeddings = self.dropout(embeddings)
|
166 |
+
return embeddings
|
167 |
+
|
168 |
+
|
169 |
+
class JargonEncoder(RobertaEncoder):
|
170 |
+
|
171 |
+
def __init__(self, args):
|
172 |
+
compress_layer = None
|
173 |
+
if args.shared_layer_kv_compressed == 1 and compress_layer is None:
|
174 |
+
compress_layer = nn.Linear(
|
175 |
+
args.max_positions,
|
176 |
+
args.max_positions // args.compressed
|
177 |
+
)
|
178 |
+
# intialize parameters for compressed layer
|
179 |
+
nn.init.xavier_uniform_(compress_layer.weight, gain=1 / math.sqrt(2))
|
180 |
+
if args.freeze_compress == 1:
|
181 |
+
compress_layer.weight.requires_grad = False
|
182 |
+
compress_layer = compress_layer
|
183 |
+
|
184 |
+
super().__init__(args)
|
185 |
+
|
186 |
+
self.layer = nn.ModuleList([LinformerTransformerEncoderLayer(args, compress_layer) for _ in range(args.num_layers)])
|
187 |
+
self.compress_layer = compress_layer
|
188 |
+
|
189 |
+
if args.encoder_normalize_before:
|
190 |
+
self.layer_norm = LayerNorm(args.embed_dim)
|
191 |
+
else:
|
192 |
+
self.layer_norm = None
|
193 |
+
|
194 |
+
self.lm_head = None
|
195 |
+
|
196 |
+
def forward(
|
197 |
+
self,
|
198 |
+
hidden_states: torch.Tensor,
|
199 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
200 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
201 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
202 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
203 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
204 |
+
use_cache: Optional[bool] = None,
|
205 |
+
output_attentions: Optional[bool] = False,
|
206 |
+
output_hidden_states: Optional[bool] = False,
|
207 |
+
return_dict: Optional[bool] = True,
|
208 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
209 |
+
|
210 |
+
x = super().forward(hidden_states=hidden_states,
|
211 |
+
attention_mask=attention_mask,
|
212 |
+
head_mask=head_mask,
|
213 |
+
encoder_hidden_states=encoder_hidden_states,
|
214 |
+
encoder_attention_mask=encoder_attention_mask,
|
215 |
+
past_key_values=past_key_values,
|
216 |
+
use_cache=use_cache,
|
217 |
+
output_attentions=output_attentions,
|
218 |
+
output_hidden_states=output_hidden_states,
|
219 |
+
return_dict=return_dict)
|
220 |
+
|
221 |
+
|
222 |
+
if self.layer_norm is not None:
|
223 |
+
x.last_hidden_state = self.layer_norm(x.last_hidden_state)
|
224 |
+
|
225 |
+
return x
|
226 |
+
|
227 |
+
def build_encoder(self, args, dictionary, embed_tokens):
|
228 |
+
encoder = LinformerTransformerEncoder(args)
|
229 |
+
return encoder
|
230 |
+
if args.use_linformer:
|
231 |
+
encoder = LinformerTransformerEncoder(args, dictionary, embed_tokens)
|
232 |
+
elif args.use_fft:
|
233 |
+
encoder = FourierTransformerEncoder(args, dictionary, embed_tokens)
|
234 |
+
else:
|
235 |
+
encoder = TransformerEncoder(args, dictionary, embed_tokens)
|
236 |
+
|
237 |
+
encoder.apply(init_bert_params)
|
238 |
+
|
239 |
+
return encoder
|
240 |
+
|
241 |
+
def output_layer(self, features, masked_tokens=None, pairs=None, **unused):
|
242 |
+
lm_out = self.lm_head(features, masked_tokens)
|
243 |
+
if pairs is not None:
|
244 |
+
sbo_out = self.sbo_head(features, pairs)
|
245 |
+
return lm_out, sbo_out
|
246 |
+
else:
|
247 |
+
return lm_out
|
248 |
+
|
249 |
+
|
250 |
+
class JargonModel(RobertaModel):
|
251 |
+
config_class = JargonConfig
|
252 |
+
def __init__(self, config, **kwargs):
|
253 |
+
config_class = JargonConfig
|
254 |
+
base_model_prefix = "jargon"
|
255 |
+
|
256 |
+
super().__init__(config, **kwargs)
|
257 |
+
self.embeddings = JargonEmbeddings(config)
|
258 |
+
self.encoder = JargonEncoder(config)
|
259 |
+
# Copied from modeling_roberta.py
|
260 |
+
# Add transpose of embeddings as implemented in fairseq
|
261 |
+
def forward(
|
262 |
+
self,
|
263 |
+
input_ids: Optional[torch.Tensor] = None,
|
264 |
+
attention_mask: Optional[torch.Tensor] = None,
|
265 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
266 |
+
position_ids: Optional[torch.Tensor] = None,
|
267 |
+
head_mask: Optional[torch.Tensor] = None,
|
268 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
269 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
270 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
271 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
272 |
+
use_cache: Optional[bool] = None,
|
273 |
+
output_attentions: Optional[bool] = None,
|
274 |
+
output_hidden_states: Optional[bool] = None,
|
275 |
+
return_dict: Optional[bool] = None,
|
276 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
277 |
+
r"""
|
278 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
279 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
280 |
+
the model is configured as a decoder.
|
281 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
282 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
283 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
284 |
+
|
285 |
+
- 1 for tokens that are **not masked**,
|
286 |
+
- 0 for tokens that are **masked**.
|
287 |
+
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)`):
|
288 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
289 |
+
|
290 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
291 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
292 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
293 |
+
use_cache (`bool`, *optional*):
|
294 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
295 |
+
`past_key_values`).
|
296 |
+
"""
|
297 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
298 |
+
output_hidden_states = (
|
299 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
300 |
+
)
|
301 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
302 |
+
|
303 |
+
if self.config.is_decoder:
|
304 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
305 |
+
else:
|
306 |
+
use_cache = False
|
307 |
+
|
308 |
+
if input_ids is not None and inputs_embeds is not None:
|
309 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
310 |
+
elif input_ids is not None:
|
311 |
+
input_shape = input_ids.size()
|
312 |
+
elif inputs_embeds is not None:
|
313 |
+
input_shape = inputs_embeds.size()[:-1]
|
314 |
+
else:
|
315 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
316 |
+
|
317 |
+
batch_size, seq_length = input_shape
|
318 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
319 |
+
|
320 |
+
# past_key_values_length
|
321 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
322 |
+
|
323 |
+
if attention_mask is None:
|
324 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
325 |
+
|
326 |
+
if token_type_ids is None:
|
327 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
328 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
329 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
|
330 |
+
token_type_ids = buffered_token_type_ids_expanded
|
331 |
+
else:
|
332 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
333 |
+
|
334 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
335 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
336 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
337 |
+
|
338 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
339 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
340 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
341 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
342 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
343 |
+
if encoder_attention_mask is None:
|
344 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
345 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
346 |
+
else:
|
347 |
+
encoder_extended_attention_mask = None
|
348 |
+
|
349 |
+
# Prepare head mask if needed
|
350 |
+
# 1.0 in head_mask indicate we keep the head
|
351 |
+
# attention_probs has shape bsz x n_heads x N x N
|
352 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
353 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
354 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
355 |
+
|
356 |
+
embedding_output = self.embeddings(
|
357 |
+
input_ids=input_ids,
|
358 |
+
position_ids=position_ids,
|
359 |
+
token_type_ids=token_type_ids,
|
360 |
+
inputs_embeds=inputs_embeds,
|
361 |
+
past_key_values_length=past_key_values_length,
|
362 |
+
)
|
363 |
+
|
364 |
+
|
365 |
+
embedding_output = embedding_output.transpose(0,1)
|
366 |
+
encoder_outputs = self.encoder(
|
367 |
+
embedding_output,
|
368 |
+
attention_mask=extended_attention_mask,
|
369 |
+
head_mask=head_mask,
|
370 |
+
encoder_hidden_states=encoder_hidden_states,
|
371 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
372 |
+
past_key_values=past_key_values,
|
373 |
+
use_cache=use_cache,
|
374 |
+
output_attentions=output_attentions,
|
375 |
+
output_hidden_states=output_hidden_states,
|
376 |
+
)
|
377 |
+
|
378 |
+
sequence_output = encoder_outputs[0].transpose(0,1)
|
379 |
+
|
380 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
381 |
+
|
382 |
+
# Fairseq Linformer implementation works with transposed hidden states -> we transpose them back for HF implementation.
|
383 |
+
if output_hidden_states:
|
384 |
+
encoder_outputs.hidden_states = [h.transpose(0,1) for h in encoder_outputs.hidden_states]
|
385 |
+
|
386 |
+
if not return_dict:
|
387 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
388 |
+
|
389 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
390 |
+
last_hidden_state=sequence_output,
|
391 |
+
pooler_output=pooled_output,
|
392 |
+
past_key_values=encoder_outputs.past_key_values,
|
393 |
+
hidden_states=encoder_outputs.hidden_states,
|
394 |
+
attentions=encoder_outputs.attentions,
|
395 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
396 |
+
)
|
397 |
+
|
398 |
+
|
399 |
+
class SBOLayer(nn.Module):
|
400 |
+
|
401 |
+
def __init__(self, input_size, hidden_size, activation, export):
|
402 |
+
super().__init__()
|
403 |
+
self.layer = nn.Linear(input_size, hidden_size)
|
404 |
+
self.activ = get_activation_fn(activation)
|
405 |
+
self.norm = LayerNorm(hidden_size)
|
406 |
+
|
407 |
+
def forward(self, x):
|
408 |
+
return self.norm(self.activ(self.layer(x)))
|
409 |
+
|
410 |
+
|
411 |
+
class SBONetwork(nn.Module):
|
412 |
+
|
413 |
+
def __init__(self, input_size, hidden_size, activation, export):
|
414 |
+
super().__init__()
|
415 |
+
self.layers = nn.ModuleList([
|
416 |
+
self.build_sbo_layer(input_size, hidden_size, activation, export),
|
417 |
+
self.build_sbo_layer(hidden_size, hidden_size, activation, export)
|
418 |
+
])
|
419 |
+
self.layers = nn.Sequential(*self.layers)
|
420 |
+
|
421 |
+
def build_sbo_layer(self, input_size, output_size, activation, export):
|
422 |
+
return SBOLayer(input_size, output_size, activation, export)
|
423 |
+
|
424 |
+
def forward(self, x):
|
425 |
+
return self.layers(x)
|
426 |
+
|
427 |
+
|
428 |
+
class SBOHead(nn.Module):
|
429 |
+
|
430 |
+
def __init__(self, args, embedding_weights, max_targets=10, position_embedding_size=200):
|
431 |
+
super().__init__()
|
432 |
+
|
433 |
+
self.position_embeddings = nn.Embedding(max_targets, position_embedding_size)
|
434 |
+
|
435 |
+
export = getattr(args, "export", False)
|
436 |
+
hidden_size = args.embed_dim
|
437 |
+
input_size = hidden_size * 2 + position_embedding_size
|
438 |
+
activation = getattr(args, "activation_fn", "relu") or "relu"
|
439 |
+
|
440 |
+
self.mlp_layer_norm = self.build_sbo_network(input_size, hidden_size, activation, export)
|
441 |
+
|
442 |
+
# The output weights are the same as the input embeddings, but there is
|
443 |
+
# an output-only bias for each token.
|
444 |
+
self.decoder = nn.Linear(
|
445 |
+
embedding_weights.size(1),
|
446 |
+
embedding_weights.size(0),
|
447 |
+
bias=False
|
448 |
+
)
|
449 |
+
if embedding_weights is not None:
|
450 |
+
self.decoder.weight = embedding_weights
|
451 |
+
|
452 |
+
self.bias = nn.Parameter(torch.zeros(embedding_weights.size(0)))
|
453 |
+
self.max_targets = max_targets
|
454 |
+
|
455 |
+
def build_sbo_network(self, input_size, hidden_size, activation, export):
|
456 |
+
return SBONetwork(input_size, hidden_size, activation, export)
|
457 |
+
|
458 |
+
def forward(self, hidden_states, pairs):
|
459 |
+
bs, num_pairs, _ = pairs.size()
|
460 |
+
bs, seq_len, dim = hidden_states.size()
|
461 |
+
# pair indices: (bs, num_pairs)
|
462 |
+
left, right = pairs[:,:, 0], pairs[:, :, 1]
|
463 |
+
# (bs, num_pairs, dim)
|
464 |
+
left_hidden = torch.gather(hidden_states, 1, left.unsqueeze(2).repeat(1, 1, dim))
|
465 |
+
# pair states: bs * num_pairs, max_targets, dim
|
466 |
+
left_hidden = left_hidden.contiguous().view(bs * num_pairs, dim).unsqueeze(1).repeat(1, self.max_targets, 1)
|
467 |
+
|
468 |
+
right_hidden = torch.gather(hidden_states, 1, right.unsqueeze(2).repeat(1, 1, dim))
|
469 |
+
# bs * num_pairs, max_targets, dim
|
470 |
+
right_hidden = right_hidden.contiguous().view(bs * num_pairs, dim).unsqueeze(1).repeat(1, self.max_targets, 1)
|
471 |
+
|
472 |
+
# (max_targets, dim)
|
473 |
+
position_embeddings = self.position_embeddings.weight
|
474 |
+
|
475 |
+
z = torch.cat((left_hidden, right_hidden, position_embeddings.unsqueeze(0).repeat(bs * num_pairs, 1, 1)), -1)
|
476 |
+
|
477 |
+
hidden_states = self.mlp_layer_norm(torch.cat((left_hidden, right_hidden, position_embeddings.unsqueeze(0).repeat(bs * num_pairs, 1, 1)), -1))
|
478 |
+
# target scores : bs * num_pairs, max_targets, vocab_size
|
479 |
+
target_scores = self.decoder(hidden_states) + self.bias
|
480 |
+
return target_scores
|
481 |
+
|
482 |
+
|
483 |
+
def get_activation_fn(activation):
|
484 |
+
"""Returns the activation function corresponding to `activation`"""
|
485 |
+
|
486 |
+
if activation == "relu":
|
487 |
+
return F.relu
|
488 |
+
elif activation == "relu_squared":
|
489 |
+
return F.relu_squared
|
490 |
+
elif activation == "gelu":
|
491 |
+
return F.gelu
|
492 |
+
elif activation == "gelu_fast":
|
493 |
+
deprecation_warning(
|
494 |
+
"--activation-fn=gelu_fast has been renamed to gelu_accurate"
|
495 |
+
)
|
496 |
+
return F.gelu_accurate
|
497 |
+
elif activation == "gelu_accurate":
|
498 |
+
return F.gelu_accurate
|
499 |
+
elif activation == "tanh":
|
500 |
+
return torch.tanh
|
501 |
+
elif activation == "linear":
|
502 |
+
return lambda x: x
|
503 |
+
elif activation == "swish":
|
504 |
+
return torch.nn.SiLU
|
505 |
+
else:
|
506 |
+
raise RuntimeError("--activation-fn {} not supported".format(activation))
|
507 |
+
|
508 |
+
|
509 |
+
def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
|
510 |
+
"""
|
511 |
+
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
|
512 |
+
are ignored. This is modified from fairseq's `utils.make_positions`.
|
513 |
+
|
514 |
+
Args:
|
515 |
+
x: torch.Tensor x:
|
516 |
+
|
517 |
+
Returns: torch.Tensor
|
518 |
+
"""
|
519 |
+
# The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
|
520 |
+
mask = input_ids.ne(padding_idx).int()
|
521 |
+
incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
|
522 |
+
return incremental_indices.long() + padding_idx
|
linformer.py
ADDED
@@ -0,0 +1,740 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import inspect
|
8 |
+
from typing import Callable, Dict, List, Optional, Set, Tuple, Union
|
9 |
+
|
10 |
+
import torch
|
11 |
+
import torch.nn as nn
|
12 |
+
import torch.nn.functional as F
|
13 |
+
from torch.nn import TransformerEncoder, TransformerEncoderLayer
|
14 |
+
from fairseq import utils
|
15 |
+
from fairseq.models.transformer import *
|
16 |
+
from fairseq.incremental_decoding_utils import with_incremental_state
|
17 |
+
from fairseq.modules.quant_noise import quant_noise
|
18 |
+
from transformers.models.roberta.modeling_roberta import (
|
19 |
+
RobertaEncoder,
|
20 |
+
RobertaConfig,
|
21 |
+
RobertaModel,
|
22 |
+
RobertaLMHead,
|
23 |
+
RobertaForMaskedLM,
|
24 |
+
RobertaLayer
|
25 |
+
)
|
26 |
+
|
27 |
+
# from .multihead_linear_attention import MultiheadLinearAttention
|
28 |
+
|
29 |
+
|
30 |
+
class LinformerTransformerEncoderLayer(RobertaLayer):
|
31 |
+
"""
|
32 |
+
Implements a Linformer Encoder Layer used in BERT/XLM style pre-trained
|
33 |
+
models.
|
34 |
+
"""
|
35 |
+
|
36 |
+
def __init__(self, config, shared_compress_layer):
|
37 |
+
# wrap in a list so it's not automatically registered by PyTorch
|
38 |
+
self.shared_compress_layer = [shared_compress_layer]
|
39 |
+
d_model=config.embed_dim
|
40 |
+
nhead=config.num_heads
|
41 |
+
dim_feedforward=config.dim_feedforward
|
42 |
+
dropout=config.dropout
|
43 |
+
activation=config.activation
|
44 |
+
layer_norm_eps=config.layer_norm_eps
|
45 |
+
|
46 |
+
super().__init__(config)
|
47 |
+
self.attention = self.build_self_attention(config.embed_dim, config)
|
48 |
+
self.attn_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-5)
|
49 |
+
self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=1e-5)
|
50 |
+
self.output = RobertaOutput(config)
|
51 |
+
|
52 |
+
def build_self_attention(self, embed_dim, args):
|
53 |
+
|
54 |
+
attn = MultiheadLinearAttention(
|
55 |
+
embed_dim,
|
56 |
+
args.encoder_attention_heads,
|
57 |
+
dropout=args.dropout,
|
58 |
+
self_attention=True,
|
59 |
+
q_noise=args.quant_noise_pq,
|
60 |
+
qn_block_size=args.quant_noise_pq_block_size,
|
61 |
+
compressed=args.compressed,
|
62 |
+
max_seq_len=args.max_positions,
|
63 |
+
shared_kv_compressed=args.shared_kv_compressed,
|
64 |
+
shared_compress_layer=self.shared_compress_layer[0],
|
65 |
+
freeze_compress=args.freeze_compress,
|
66 |
+
)
|
67 |
+
return attn
|
68 |
+
|
69 |
+
def feed_forward_chunk(self, attention_output):
|
70 |
+
residual = attention_output
|
71 |
+
x = self.intermediate(attention_output)
|
72 |
+
layer_output = self.output(x, residual)
|
73 |
+
return layer_output
|
74 |
+
|
75 |
+
def forward(
|
76 |
+
self,
|
77 |
+
hidden_states: torch.Tensor,
|
78 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
79 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
80 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
81 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
82 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
83 |
+
output_attentions: Optional[bool] = False,
|
84 |
+
) -> Tuple[torch.Tensor]:
|
85 |
+
|
86 |
+
residual = hidden_states
|
87 |
+
|
88 |
+
if self.attn_layer_norm is not None:
|
89 |
+
hidden_states = self.attn_layer_norm(hidden_states)
|
90 |
+
|
91 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
92 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
93 |
+
self_attention_outputs = self.attention(
|
94 |
+
hidden_states,
|
95 |
+
attention_mask,
|
96 |
+
head_mask,
|
97 |
+
output_attentions=output_attentions,
|
98 |
+
past_key_value=self_attn_past_key_value,
|
99 |
+
)
|
100 |
+
attention_output = self_attention_outputs[0]
|
101 |
+
|
102 |
+
# if decoder, the last output is tuple of self-attn cache
|
103 |
+
if self.is_decoder:
|
104 |
+
outputs = self_attention_outputs[1:-1]
|
105 |
+
present_key_value = self_attention_outputs[-1]
|
106 |
+
else:
|
107 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
108 |
+
|
109 |
+
cross_attn_present_key_value = None
|
110 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
111 |
+
if not hasattr(self, "crossattention"):
|
112 |
+
raise ValueError(
|
113 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
114 |
+
" by setting `config.add_cross_attention=True`"
|
115 |
+
)
|
116 |
+
|
117 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
118 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
119 |
+
cross_attention_outputs = self.crossattention(
|
120 |
+
attention_output,
|
121 |
+
attention_mask,
|
122 |
+
head_mask,
|
123 |
+
encoder_hidden_states,
|
124 |
+
encoder_attention_mask,
|
125 |
+
cross_attn_past_key_value,
|
126 |
+
output_attentions,
|
127 |
+
)
|
128 |
+
attention_output = cross_attention_outputs[0]
|
129 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
130 |
+
|
131 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
132 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
133 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
134 |
+
|
135 |
+
attention_output = attention_output + residual
|
136 |
+
residual = attention_output
|
137 |
+
attention_output = self.final_layer_norm(attention_output)
|
138 |
+
layer_output = apply_chunking_to_forward(
|
139 |
+
self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
|
140 |
+
)
|
141 |
+
layer_output = layer_output + residual
|
142 |
+
|
143 |
+
outputs = (layer_output,) + outputs
|
144 |
+
|
145 |
+
# if decoder, return the attn key/values as the last output
|
146 |
+
if self.is_decoder:
|
147 |
+
outputs = outputs + (present_key_value,)
|
148 |
+
|
149 |
+
return outputs
|
150 |
+
|
151 |
+
|
152 |
+
class RobertaOutput(nn.Module):
|
153 |
+
def __init__(self, config):
|
154 |
+
super().__init__()
|
155 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
156 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
157 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
158 |
+
|
159 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
160 |
+
hidden_states = self.dense(hidden_states)
|
161 |
+
return hidden_states
|
162 |
+
|
163 |
+
|
164 |
+
class LinformerTransformerEncoder(RobertaEncoder):
|
165 |
+
"""
|
166 |
+
Implementation for a Bi-directional Linformer based Sentence Encoder used
|
167 |
+
in BERT/XLM style pre-trained models.
|
168 |
+
|
169 |
+
This first computes the token embedding using the token embedding matrix,
|
170 |
+
position embeddings (if specified) and segment embeddings
|
171 |
+
(if specified). After applying the specified number of
|
172 |
+
LinformerEncoderLayers, it outputs all the internal states of the
|
173 |
+
encoder as well as the final representation associated with the first
|
174 |
+
token (usually CLS token).
|
175 |
+
|
176 |
+
Input:
|
177 |
+
- tokens: B x T matrix representing sentences
|
178 |
+
- segment_labels: B x T matrix representing segment label for tokens
|
179 |
+
|
180 |
+
Output:
|
181 |
+
- a tuple of the following:
|
182 |
+
- a list of internal model states used to compute the
|
183 |
+
predictions where each tensor has shape T x B x C
|
184 |
+
- sentence representation associated with first input token
|
185 |
+
in format B x C.
|
186 |
+
"""
|
187 |
+
|
188 |
+
def __init__(self, config,**kwargs):
|
189 |
+
compress_layer = None
|
190 |
+
if config.shared_layer_kv_compressed == 1 and compress_layer is None:
|
191 |
+
compress_layer = nn.Linear(
|
192 |
+
config.max_positions,
|
193 |
+
config.max_positions // config.compressed
|
194 |
+
)
|
195 |
+
# intialize parameters for compressed layer
|
196 |
+
nn.init.xavier_uniform_(compress_layer.weight, gain=1 / math.sqrt(2))
|
197 |
+
if config.freeze_compress == 1:
|
198 |
+
compress_layer.weight.requires_grad = False
|
199 |
+
compress_layer = compress_layer
|
200 |
+
#encoder_layer = LinformerTransformerEncoderLayer(config, compress_layer)
|
201 |
+
|
202 |
+
super().__init__(config)
|
203 |
+
|
204 |
+
self.layer = nn.ModuleList([LinformerTransformerEncoderLayer(config, compress_layer) for _ in range(config.num_layers)])
|
205 |
+
self.compress_layer = compress_layer
|
206 |
+
self.layer_norm = nn.LayerNorm(config.embed_dim)
|
207 |
+
|
208 |
+
|
209 |
+
@with_incremental_state
|
210 |
+
class MultiheadLinearAttention(nn.Module):
|
211 |
+
def __init__(
|
212 |
+
self,
|
213 |
+
embed_dim,
|
214 |
+
num_heads,
|
215 |
+
kdim=None,
|
216 |
+
vdim=None,
|
217 |
+
dropout=0.0,
|
218 |
+
bias=True,
|
219 |
+
add_bias_kv=False,
|
220 |
+
add_zero_attn=False,
|
221 |
+
self_attention=False,
|
222 |
+
encoder_decoder_attention=False,
|
223 |
+
q_noise=0.0,
|
224 |
+
qn_block_size=8,
|
225 |
+
compressed=1,
|
226 |
+
max_seq_len=256,
|
227 |
+
shared_kv_compressed=0,
|
228 |
+
shared_compress_layer=None,
|
229 |
+
freeze_compress=0,
|
230 |
+
):
|
231 |
+
super().__init__()
|
232 |
+
self.embed_dim = embed_dim
|
233 |
+
self.kdim = kdim if kdim is not None else embed_dim
|
234 |
+
self.vdim = vdim if vdim is not None else embed_dim
|
235 |
+
self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim
|
236 |
+
self.num_heads = num_heads
|
237 |
+
self.dropout = dropout
|
238 |
+
self.head_dim = embed_dim // num_heads
|
239 |
+
assert (
|
240 |
+
self.head_dim * num_heads == self.embed_dim
|
241 |
+
), "embed_dim must be divisible by num_heads"
|
242 |
+
self.scaling = self.head_dim ** -0.5
|
243 |
+
|
244 |
+
self.self_attention = self_attention
|
245 |
+
self.encoder_decoder_attention = encoder_decoder_attention
|
246 |
+
assert not self.self_attention or self.qkv_same_dim, (
|
247 |
+
"Self-attention requires query, key and " "value to be of the same size"
|
248 |
+
)
|
249 |
+
|
250 |
+
self.k_proj = quant_noise(
|
251 |
+
nn.Linear(self.kdim, embed_dim, bias=bias), q_noise, qn_block_size
|
252 |
+
)
|
253 |
+
self.v_proj = quant_noise(
|
254 |
+
nn.Linear(self.vdim, embed_dim, bias=bias), q_noise, qn_block_size
|
255 |
+
)
|
256 |
+
self.q_proj = quant_noise(
|
257 |
+
nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size
|
258 |
+
)
|
259 |
+
|
260 |
+
# used for compress sequence to subsequence
|
261 |
+
if shared_compress_layer is None:
|
262 |
+
self.compress_seq_len = max_seq_len // compressed
|
263 |
+
self.compress_k = nn.Linear(max_seq_len, self.compress_seq_len, bias=False)
|
264 |
+
if shared_kv_compressed == 0:
|
265 |
+
self.compress_v = nn.Linear(
|
266 |
+
max_seq_len, self.compress_seq_len, bias=False
|
267 |
+
)
|
268 |
+
self.layerwise_sharing = False
|
269 |
+
else:
|
270 |
+
self.compress_k = shared_compress_layer
|
271 |
+
if shared_kv_compressed == 0:
|
272 |
+
self.compress_v = shared_compress_layer
|
273 |
+
self.layerwise_sharing = True
|
274 |
+
self.shared_kv_compressed = shared_kv_compressed
|
275 |
+
|
276 |
+
self.out_proj = quant_noise(
|
277 |
+
nn.Linear(embed_dim, embed_dim, bias=bias), q_noise, qn_block_size)
|
278 |
+
|
279 |
+
if add_bias_kv:
|
280 |
+
self.bias_k = nn.Parameter(torch.Tensor(1, 1, embed_dim))
|
281 |
+
self.bias_v = nn.Parameter(torch.Tensor(1, 1, embed_dim))
|
282 |
+
else:
|
283 |
+
self.bias_k = self.bias_v = None
|
284 |
+
|
285 |
+
self.add_zero_attn = add_zero_attn
|
286 |
+
|
287 |
+
self.reset_parameters()
|
288 |
+
|
289 |
+
if freeze_compress == 1:
|
290 |
+
self.compress_k.weight.requires_grad = False
|
291 |
+
if shared_kv_compressed == 0:
|
292 |
+
self.compress_v.weight.requires_grad = False
|
293 |
+
|
294 |
+
self.onnx_trace = False
|
295 |
+
def reset_parameters(self):
|
296 |
+
if self.qkv_same_dim:
|
297 |
+
# Empirically observed the convergence to be much better with
|
298 |
+
# the scaled initialization
|
299 |
+
nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
|
300 |
+
nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
|
301 |
+
nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
|
302 |
+
if (
|
303 |
+
not self.layerwise_sharing
|
304 |
+
): # otherwise, we already initialize the parameters
|
305 |
+
nn.init.xavier_uniform_(self.compress_k.weight, gain=1 / math.sqrt(2))
|
306 |
+
if self.shared_kv_compressed == 0:
|
307 |
+
nn.init.xavier_uniform_(
|
308 |
+
self.compress_v.weight, gain=1 / math.sqrt(2)
|
309 |
+
)
|
310 |
+
else:
|
311 |
+
nn.init.xavier_uniform_(self.k_proj.weight)
|
312 |
+
nn.init.xavier_uniform_(self.v_proj.weight)
|
313 |
+
nn.init.xavier_uniform_(self.q_proj.weight)
|
314 |
+
if (
|
315 |
+
not self.layerwise_sharing
|
316 |
+
): # otherwise, we already initialize the parameters
|
317 |
+
nn.init.xavier_uniform_(self.compress_k.weight)
|
318 |
+
if self.shared_kv_compressed == 0:
|
319 |
+
nn.init.xavier_uniform_(self.compress_v.weight)
|
320 |
+
|
321 |
+
nn.init.xavier_uniform_(self.out_proj.weight)
|
322 |
+
if self.out_proj.bias is not None:
|
323 |
+
nn.init.constant_(self.out_proj.bias, 0.0)
|
324 |
+
if self.bias_k is not None:
|
325 |
+
nn.init.xavier_normal_(self.bias_k)
|
326 |
+
if self.bias_v is not None:
|
327 |
+
nn.init.xavier_normal_(self.bias_v)
|
328 |
+
|
329 |
+
def prepare_for_onnx_export_(self):
|
330 |
+
self.onnx_trace = True
|
331 |
+
|
332 |
+
def forward(
|
333 |
+
self,
|
334 |
+
query,
|
335 |
+
key: Optional[torch.Tensor],
|
336 |
+
value: Optional[torch.Tensor],
|
337 |
+
key_padding_mask: Optional[torch.Tensor] = None,
|
338 |
+
incremental_state: Optional[Dict[str, Dict[str, Optional[torch.Tensor]]]] = None,
|
339 |
+
output_attentions: bool = True,
|
340 |
+
need_weights: bool = True,
|
341 |
+
static_kv: bool = False,
|
342 |
+
attn_mask: Optional[torch.Tensor] = None,
|
343 |
+
before_softmax: bool = False,
|
344 |
+
need_head_weights: bool = False,
|
345 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
346 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
347 |
+
"""Input shape: Time x Batch x Channel
|
348 |
+
|
349 |
+
Args:
|
350 |
+
key_padding_mask (ByteTensor, optional): mask to exclude
|
351 |
+
keys that are pads, of shape `(batch, src_len)`, where
|
352 |
+
padding elements are indicated by 1s.
|
353 |
+
need_weights (bool, optional): return the attention weights,
|
354 |
+
averaged over heads (default: False).
|
355 |
+
attn_mask (ByteTensor, optional): typically used to
|
356 |
+
implement causal attention, where the mask prevents the
|
357 |
+
attention from looking forward in time (default: None).
|
358 |
+
before_softmax (bool, optional): return the raw attention
|
359 |
+
weights and values before the attention softmax.
|
360 |
+
need_head_weights (bool, optional): return the attention
|
361 |
+
weights for each head. Implies *need_weights*. Default:
|
362 |
+
return the average attention weights over all heads.
|
363 |
+
"""
|
364 |
+
|
365 |
+
if need_head_weights:
|
366 |
+
need_weights = True
|
367 |
+
|
368 |
+
tgt_len, bsz, embed_dim = query.size()
|
369 |
+
assert embed_dim == self.embed_dim
|
370 |
+
assert list(query.size()) == [tgt_len, bsz, embed_dim]
|
371 |
+
|
372 |
+
if incremental_state is not None:
|
373 |
+
saved_state = self._get_input_buffer(incremental_state)
|
374 |
+
if saved_state is not None and "prev_key" in saved_state:
|
375 |
+
# previous time steps are cached - no need to recompute
|
376 |
+
# key and value if they are static
|
377 |
+
if static_kv:
|
378 |
+
assert self.encoder_decoder_attention and not self.self_attention
|
379 |
+
key = value = None
|
380 |
+
else:
|
381 |
+
saved_state = None
|
382 |
+
|
383 |
+
if self.self_attention:
|
384 |
+
q = self.q_proj(query)
|
385 |
+
|
386 |
+
k_input = query.permute(1, 2, 0).contiguous() # B * C * T
|
387 |
+
k_input = (
|
388 |
+
F.linear(k_input, self.compress_k.weight[:, 0:tgt_len])
|
389 |
+
.permute(2, 0, 1)
|
390 |
+
.contiguous()
|
391 |
+
)
|
392 |
+
k = self.k_proj(k_input)
|
393 |
+
|
394 |
+
v_input = query.permute(1, 2, 0).contiguous() # B * C * T
|
395 |
+
if self.shared_kv_compressed == 0:
|
396 |
+
v_input = (
|
397 |
+
F.linear(v_input, self.compress_v.weight[:, 0:tgt_len])
|
398 |
+
.permute(2, 0, 1)
|
399 |
+
.contiguous()
|
400 |
+
)
|
401 |
+
if self.shared_kv_compressed == 1: # use shared kv compressed linear layer
|
402 |
+
v_input = (
|
403 |
+
F.linear(v_input, self.compress_k.weight[:, 0:tgt_len])
|
404 |
+
.permute(2, 0, 1)
|
405 |
+
.contiguous()
|
406 |
+
)
|
407 |
+
v = self.v_proj(v_input)
|
408 |
+
elif self.encoder_decoder_attention:
|
409 |
+
# encoder-decoder attention
|
410 |
+
q = self.q_proj(query)
|
411 |
+
if key is None:
|
412 |
+
assert value is None
|
413 |
+
k = v = None
|
414 |
+
else:
|
415 |
+
k = self.k_proj(key)
|
416 |
+
v = self.v_proj(key)
|
417 |
+
|
418 |
+
else:
|
419 |
+
assert key is not None and value is not None
|
420 |
+
q = self.q_proj(query)
|
421 |
+
k = self.k_proj(key)
|
422 |
+
v = self.v_proj(value)
|
423 |
+
q *= self.scaling
|
424 |
+
|
425 |
+
if self.bias_k is not None:
|
426 |
+
assert self.bias_v is not None
|
427 |
+
k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
|
428 |
+
v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
|
429 |
+
if attn_mask is not None:
|
430 |
+
attn_mask = torch.cat(
|
431 |
+
[attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
|
432 |
+
)
|
433 |
+
if key_padding_mask is not None:
|
434 |
+
key_padding_mask = torch.cat(
|
435 |
+
[
|
436 |
+
key_padding_mask,
|
437 |
+
key_padding_mask.new_zeros(key_padding_mask.size(0), 1),
|
438 |
+
],
|
439 |
+
dim=1,
|
440 |
+
)
|
441 |
+
|
442 |
+
q = (
|
443 |
+
q.contiguous()
|
444 |
+
.view(tgt_len, bsz * self.num_heads, self.head_dim)
|
445 |
+
.transpose(0, 1)
|
446 |
+
)
|
447 |
+
if k is not None:
|
448 |
+
k = (
|
449 |
+
k.contiguous()
|
450 |
+
.view(-1, bsz * self.num_heads, self.head_dim)
|
451 |
+
.transpose(0, 1)
|
452 |
+
)
|
453 |
+
if v is not None:
|
454 |
+
v = (
|
455 |
+
v.contiguous()
|
456 |
+
.view(-1, bsz * self.num_heads, self.head_dim)
|
457 |
+
.transpose(0, 1)
|
458 |
+
)
|
459 |
+
|
460 |
+
if saved_state is not None:
|
461 |
+
# saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
|
462 |
+
if "prev_key" in saved_state:
|
463 |
+
_prev_key = saved_state["prev_key"]
|
464 |
+
assert _prev_key is not None
|
465 |
+
prev_key = _prev_key.view(bsz * self.num_heads, -1, self.head_dim)
|
466 |
+
if static_kv:
|
467 |
+
k = prev_key
|
468 |
+
else:
|
469 |
+
assert k is not None
|
470 |
+
k = torch.cat([prev_key, k], dim=1)
|
471 |
+
if "prev_value" in saved_state:
|
472 |
+
_prev_value = saved_state["prev_value"]
|
473 |
+
assert _prev_value is not None
|
474 |
+
prev_value = _prev_value.view(bsz * self.num_heads, -1, self.head_dim)
|
475 |
+
if static_kv:
|
476 |
+
v = prev_value
|
477 |
+
else:
|
478 |
+
assert v is not None
|
479 |
+
v = torch.cat([prev_value, v], dim=1)
|
480 |
+
prev_key_padding_mask: Optional[torch.Tensor] = None
|
481 |
+
if "prev_key_padding_mask" in saved_state:
|
482 |
+
prev_key_padding_mask = saved_state["prev_key_padding_mask"]
|
483 |
+
assert k is not None and v is not None
|
484 |
+
key_padding_mask = MultiheadLinearAttention._append_prev_key_padding_mask(
|
485 |
+
key_padding_mask=key_padding_mask,
|
486 |
+
prev_key_padding_mask=prev_key_padding_mask,
|
487 |
+
batch_size=bsz,
|
488 |
+
src_len=k.size(1),
|
489 |
+
static_kv=static_kv,
|
490 |
+
)
|
491 |
+
|
492 |
+
saved_state["prev_key"] = k.view(bsz, self.num_heads, -1, self.head_dim)
|
493 |
+
saved_state["prev_value"] = v.view(bsz, self.num_heads, -1, self.head_dim)
|
494 |
+
saved_state["prev_key_padding_mask"] = key_padding_mask
|
495 |
+
# In this branch incremental_state is never None
|
496 |
+
assert incremental_state is not None
|
497 |
+
incremental_state = self._set_input_buffer(incremental_state, saved_state)
|
498 |
+
assert k is not None
|
499 |
+
src_len = k.size(1)
|
500 |
+
|
501 |
+
if self.add_zero_attn:
|
502 |
+
assert v is not None
|
503 |
+
src_len += 1
|
504 |
+
k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
|
505 |
+
v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
|
506 |
+
if attn_mask is not None:
|
507 |
+
attn_mask = torch.cat(
|
508 |
+
[attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1
|
509 |
+
)
|
510 |
+
|
511 |
+
attn_weights = torch.bmm(q, k.transpose(1, 2))
|
512 |
+
attn_weights = MultiheadLinearAttention.apply_sparse_mask(
|
513 |
+
attn_weights, tgt_len, src_len, bsz
|
514 |
+
)
|
515 |
+
|
516 |
+
assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
|
517 |
+
|
518 |
+
if attn_mask is not None:
|
519 |
+
attn_mask = attn_mask.unsqueeze(0)
|
520 |
+
if self.onnx_trace:
|
521 |
+
attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1)
|
522 |
+
attn_weights += attn_mask
|
523 |
+
|
524 |
+
if before_softmax:
|
525 |
+
return attn_weights, v
|
526 |
+
|
527 |
+
attn_weights_float = utils.softmax(
|
528 |
+
attn_weights, dim=-1, onnx_trace=self.onnx_trace
|
529 |
+
)
|
530 |
+
attn_weights = attn_weights_float.type_as(attn_weights)
|
531 |
+
attn_probs = F.dropout(
|
532 |
+
attn_weights,
|
533 |
+
p=self.dropout,
|
534 |
+
training=self.training,
|
535 |
+
)
|
536 |
+
assert v is not None
|
537 |
+
attn = torch.bmm(attn_probs, v)
|
538 |
+
assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
|
539 |
+
if self.onnx_trace and attn.size(1) == 1:
|
540 |
+
# when ONNX tracing a single decoder step (sequence length == 1)
|
541 |
+
# the transpose is a no-op copy before view, thus unnecessary
|
542 |
+
attn = attn.contiguous().view(tgt_len, bsz, embed_dim)
|
543 |
+
else:
|
544 |
+
attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
|
545 |
+
attn = self.out_proj(attn)
|
546 |
+
attn_weights: Optional[torch.Tensor] = None
|
547 |
+
if output_attentions:
|
548 |
+
attn_weights = attn_weights_float.view(
|
549 |
+
bsz, self.num_heads, tgt_len, src_len
|
550 |
+
).transpose(1, 0)
|
551 |
+
if not need_head_weights:
|
552 |
+
# average attention weights over heads
|
553 |
+
attn_weights = attn_weights.mean(dim=0)
|
554 |
+
|
555 |
+
|
556 |
+
return attn, attn_weights
|
557 |
+
|
558 |
+
@staticmethod
|
559 |
+
def _append_prev_key_padding_mask(
|
560 |
+
key_padding_mask: Optional[torch.Tensor],
|
561 |
+
prev_key_padding_mask: Optional[torch.Tensor],
|
562 |
+
batch_size: int,
|
563 |
+
src_len: int,
|
564 |
+
static_kv: bool,
|
565 |
+
) -> Optional[torch.Tensor]:
|
566 |
+
# saved key padding masks have shape (bsz, seq_len)
|
567 |
+
if prev_key_padding_mask is not None and static_kv:
|
568 |
+
new_key_padding_mask = prev_key_padding_mask
|
569 |
+
elif prev_key_padding_mask is not None and key_padding_mask is not None:
|
570 |
+
new_key_padding_mask = torch.cat(
|
571 |
+
[prev_key_padding_mask.float(), key_padding_mask.float()], dim=1
|
572 |
+
)
|
573 |
+
# During incremental decoding, as the padding token enters and
|
574 |
+
# leaves the frame, there will be a time when prev or current
|
575 |
+
# is None
|
576 |
+
elif prev_key_padding_mask is not None:
|
577 |
+
filler = torch.zeros(
|
578 |
+
(batch_size, src_len - prev_key_padding_mask.size(1)),
|
579 |
+
device=prev_key_padding_mask.device,
|
580 |
+
)
|
581 |
+
new_key_padding_mask = torch.cat(
|
582 |
+
[prev_key_padding_mask.float(), filler.float()], dim=1
|
583 |
+
)
|
584 |
+
elif key_padding_mask is not None:
|
585 |
+
filler = torch.zeros(
|
586 |
+
(batch_size, src_len - key_padding_mask.size(1)),
|
587 |
+
device=key_padding_mask.device,
|
588 |
+
)
|
589 |
+
new_key_padding_mask = torch.cat(
|
590 |
+
[filler.float(), key_padding_mask.float()], dim=1
|
591 |
+
)
|
592 |
+
else:
|
593 |
+
new_key_padding_mask = prev_key_padding_mask
|
594 |
+
return new_key_padding_mask
|
595 |
+
|
596 |
+
@torch.jit.export
|
597 |
+
def reorder_incremental_state(
|
598 |
+
self,
|
599 |
+
incremental_state: Dict[str, Dict[str, Optional[torch.Tensor]]],
|
600 |
+
new_order: torch.Tensor,
|
601 |
+
):
|
602 |
+
"""Reorder buffered internal state (for incremental generation)."""
|
603 |
+
input_buffer = self._get_input_buffer(incremental_state)
|
604 |
+
if input_buffer is not None:
|
605 |
+
for k in input_buffer.keys():
|
606 |
+
input_buffer_k = input_buffer[k]
|
607 |
+
if input_buffer_k is not None:
|
608 |
+
if self.encoder_decoder_attention and input_buffer_k.size(
|
609 |
+
0
|
610 |
+
) == new_order.size(0):
|
611 |
+
break
|
612 |
+
input_buffer[k] = input_buffer_k.index_select(0, new_order)
|
613 |
+
incremental_state = self._set_input_buffer(incremental_state, input_buffer)
|
614 |
+
return incremental_state
|
615 |
+
|
616 |
+
def _get_input_buffer(
|
617 |
+
self, incremental_state: Optional[Dict[str, Dict[str, Optional[torch.Tensor]]]]
|
618 |
+
) -> Dict[str, Optional[torch.Tensor]]:
|
619 |
+
result = self.get_incremental_state(incremental_state, "attn_state")
|
620 |
+
if result is not None:
|
621 |
+
return result
|
622 |
+
else:
|
623 |
+
empty_result: Dict[str, Optional[torch.Tensor]] = {}
|
624 |
+
return empty_result
|
625 |
+
|
626 |
+
def _set_input_buffer(
|
627 |
+
self,
|
628 |
+
incremental_state: Dict[str, Dict[str, Optional[torch.Tensor]]],
|
629 |
+
buffer: Dict[str, Optional[torch.Tensor]],
|
630 |
+
):
|
631 |
+
return self.set_incremental_state(incremental_state, "attn_state", buffer)
|
632 |
+
|
633 |
+
def apply_sparse_mask(attn_weights, tgt_len: int, src_len: int, bsz: int):
|
634 |
+
return attn_weights
|
635 |
+
|
636 |
+
def upgrade_state_dict_named(self, state_dict, name):
|
637 |
+
prefix = name + "." if name != "" else ""
|
638 |
+
items_to_add = {}
|
639 |
+
keys_to_remove = []
|
640 |
+
for k in state_dict.keys():
|
641 |
+
if k.endswith(prefix + "in_proj_weight"):
|
642 |
+
# in_proj_weight used to be q + k + v with same dimensions
|
643 |
+
dim = int(state_dict[k].shape[0] / 3)
|
644 |
+
items_to_add[prefix + "q_proj.weight"] = state_dict[k][:dim]
|
645 |
+
items_to_add[prefix + "k_proj.weight"] = state_dict[k][dim : 2 * dim]
|
646 |
+
items_to_add[prefix + "v_proj.weight"] = state_dict[k][2 * dim :]
|
647 |
+
|
648 |
+
keys_to_remove.append(k)
|
649 |
+
|
650 |
+
k_bias = prefix + "in_proj_bias"
|
651 |
+
if k_bias in state_dict.keys():
|
652 |
+
dim = int(state_dict[k].shape[0] / 3)
|
653 |
+
items_to_add[prefix + "q_proj.bias"] = state_dict[k_bias][:dim]
|
654 |
+
items_to_add[prefix + "k_proj.bias"] = state_dict[k_bias][
|
655 |
+
dim : 2 * dim
|
656 |
+
]
|
657 |
+
items_to_add[prefix + "v_proj.bias"] = state_dict[k_bias][2 * dim :]
|
658 |
+
|
659 |
+
keys_to_remove.append(prefix + "in_proj_bias")
|
660 |
+
|
661 |
+
for k in keys_to_remove:
|
662 |
+
del state_dict[k]
|
663 |
+
|
664 |
+
for key, value in items_to_add.items():
|
665 |
+
state_dict[key] = value
|
666 |
+
|
667 |
+
|
668 |
+
|
669 |
+
def apply_chunking_to_forward(
|
670 |
+
forward_fn: Callable[..., torch.Tensor], chunk_size: int, chunk_dim: int, *input_tensors
|
671 |
+
) -> torch.Tensor:
|
672 |
+
"""
|
673 |
+
This function chunks the `input_tensors` into smaller input tensor parts of size `chunk_size` over the dimension
|
674 |
+
`chunk_dim`. It then applies a layer `forward_fn` to each chunk independently to save memory.
|
675 |
+
|
676 |
+
If the `forward_fn` is independent across the `chunk_dim` this function will yield the same result as directly
|
677 |
+
applying `forward_fn` to `input_tensors`.
|
678 |
+
|
679 |
+
Args:
|
680 |
+
forward_fn (`Callable[..., torch.Tensor]`):
|
681 |
+
The forward function of the model.
|
682 |
+
chunk_size (`int`):
|
683 |
+
The chunk size of a chunked tensor: `num_chunks = len(input_tensors[0]) / chunk_size`.
|
684 |
+
chunk_dim (`int`):
|
685 |
+
The dimension over which the `input_tensors` should be chunked.
|
686 |
+
input_tensors (`Tuple[torch.Tensor]`):
|
687 |
+
The input tensors of `forward_fn` which will be chunked
|
688 |
+
|
689 |
+
Returns:
|
690 |
+
`torch.Tensor`: A tensor with the same shape as the `forward_fn` would have given if applied`.
|
691 |
+
|
692 |
+
|
693 |
+
Examples:
|
694 |
+
|
695 |
+
```python
|
696 |
+
# rename the usual forward() fn to forward_chunk()
|
697 |
+
def forward_chunk(self, hidden_states):
|
698 |
+
hidden_states = self.decoder(hidden_states)
|
699 |
+
return hidden_states
|
700 |
+
|
701 |
+
|
702 |
+
# implement a chunked forward function
|
703 |
+
def forward(self, hidden_states):
|
704 |
+
return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)
|
705 |
+
```"""
|
706 |
+
assert len(input_tensors) > 0, f"{input_tensors} has to be a tuple/list of tensors"
|
707 |
+
|
708 |
+
# inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility
|
709 |
+
num_args_in_forward_chunk_fn = len(inspect.signature(forward_fn).parameters)
|
710 |
+
if num_args_in_forward_chunk_fn != len(input_tensors):
|
711 |
+
raise ValueError(
|
712 |
+
f"forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(input_tensors)} input "
|
713 |
+
"tensors are given"
|
714 |
+
)
|
715 |
+
|
716 |
+
if chunk_size > 0:
|
717 |
+
tensor_shape = input_tensors[0].shape[chunk_dim]
|
718 |
+
for input_tensor in input_tensors:
|
719 |
+
if input_tensor.shape[chunk_dim] != tensor_shape:
|
720 |
+
raise ValueError(
|
721 |
+
f"All input tenors have to be of the same shape: {tensor_shape}, "
|
722 |
+
f"found shape {input_tensor.shape[chunk_dim]}"
|
723 |
+
)
|
724 |
+
|
725 |
+
if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
|
726 |
+
raise ValueError(
|
727 |
+
f"The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk "
|
728 |
+
f"size {chunk_size}"
|
729 |
+
)
|
730 |
+
|
731 |
+
num_chunks = input_tensors[0].shape[chunk_dim] // chunk_size
|
732 |
+
|
733 |
+
# chunk input tensor into tuples
|
734 |
+
input_tensors_chunks = tuple(input_tensor.chunk(num_chunks, dim=chunk_dim) for input_tensor in input_tensors)
|
735 |
+
# apply forward fn to every tuple
|
736 |
+
output_chunks = tuple(forward_fn(*input_tensors_chunk) for input_tensors_chunk in zip(*input_tensors_chunks))
|
737 |
+
# concatenate output at same dimension
|
738 |
+
return torch.cat(output_chunks, dim=chunk_dim)
|
739 |
+
|
740 |
+
return forward_fn(*input_tensors)
|