multihead_attention.py 14.3 KB
Newer Older
1
# Copyright (c) Facebook, Inc. and its affiliates.
Myle Ott's avatar
Myle Ott committed
2
#
3
4
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
Myle Ott's avatar
Myle Ott committed
5

6
import math
Myle Ott's avatar
Myle Ott committed
7
8
9
10
11
import torch
from torch import nn
from torch.nn import Parameter
import torch.nn.functional as F

Myle Ott's avatar
Myle Ott committed
12
13
from fairseq import utils

Myle Ott's avatar
Myle Ott committed
14
15
16
17
18
19

class MultiheadAttention(nn.Module):
    """Multi-headed attention.

    See "Attention Is All You Need" for more details.
    """
20

Sergey Edunov's avatar
Sergey Edunov committed
21
22
23
    def __init__(self, embed_dim, num_heads, kdim=None, vdim=None, dropout=0., bias=True,
                 add_bias_kv=False, add_zero_attn=False, self_attention=False,
                 encoder_decoder_attention=False):
Myle Ott's avatar
Myle Ott committed
24
25
        super().__init__()
        self.embed_dim = embed_dim
Myle Ott's avatar
Myle Ott committed
26
27
28
29
        self.kdim = kdim if kdim is not None else embed_dim
        self.vdim = vdim if vdim is not None else embed_dim
        self.qkv_same_dim = self.kdim == embed_dim and self.vdim == embed_dim

Myle Ott's avatar
Myle Ott committed
30
31
32
        self.num_heads = num_heads
        self.dropout = dropout
        self.head_dim = embed_dim // num_heads
33
        assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads"
34
        self.scaling = self.head_dim ** -0.5
Myle Ott's avatar
Myle Ott committed
35

Sergey Edunov's avatar
Sergey Edunov committed
36
37
38
39
40
41
        self.self_attention = self_attention
        self.encoder_decoder_attention = encoder_decoder_attention

        assert not self.self_attention or self.qkv_same_dim, 'Self-attention requires query, key and ' \
                                                             'value to be of the same size'

42
43
44
        self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias)
        self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias)
        self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
Myle Ott's avatar
Myle Ott committed
45

46
        self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
Myle Ott's avatar
Myle Ott committed
47

48
49
50
51
52
53
54
55
        if add_bias_kv:
            self.bias_k = Parameter(torch.Tensor(1, 1, embed_dim))
            self.bias_v = Parameter(torch.Tensor(1, 1, embed_dim))
        else:
            self.bias_k = self.bias_v = None

        self.add_zero_attn = add_zero_attn

Myle Ott's avatar
Myle Ott committed
56
57
        self.reset_parameters()

Myle Ott's avatar
Myle Ott committed
58
59
        self.onnx_trace = False

60
61
62
63
64
65
        self.enable_torch_version = False
        if hasattr(F, "multi_head_attention_forward"):
            self.enable_torch_version = True
        else:
            self.enable_torch_version = False

Myle Ott's avatar
Myle Ott committed
66
67
68
69
    @property
    def in_proj_weight(self):
        return torch.cat((self.q_proj.weight, self.k_proj.weight, self.v_proj.weight))

70
71
72
    @property
    def in_proj_bias(self):
        return torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias))
73

Myle Ott's avatar
Myle Ott committed
74
75
76
    def prepare_for_onnx_export_(self):
        self.onnx_trace = True

Myle Ott's avatar
Myle Ott committed
77
    def reset_parameters(self):
Myle Ott's avatar
Myle Ott committed
78
        if self.qkv_same_dim:
79
80
81
82
83
            # Empirically observed the convergence to be much better with
            # the scaled initialization
            nn.init.xavier_uniform_(self.k_proj.weight, gain=1/math.sqrt(2))
            nn.init.xavier_uniform_(self.v_proj.weight, gain=1/math.sqrt(2))
            nn.init.xavier_uniform_(self.q_proj.weight, gain=1/math.sqrt(2))
Myle Ott's avatar
Myle Ott committed
84
        else:
85
86
87
            nn.init.xavier_uniform_(self.k_proj.weight)
            nn.init.xavier_uniform_(self.v_proj.weight)
            nn.init.xavier_uniform_(self.q_proj.weight)
Myle Ott's avatar
Myle Ott committed
88

Myle Ott's avatar
Myle Ott committed
89
        nn.init.xavier_uniform_(self.out_proj.weight)
90
        nn.init.constant_(self.out_proj.bias, 0.)
91
92
93
94
        if self.bias_k is not None:
            nn.init.xavier_normal_(self.bias_k)
        if self.bias_v is not None:
            nn.init.xavier_normal_(self.bias_v)
Myle Ott's avatar
Myle Ott committed
95

96
97
98
99
100
101
102
103
104
105
106
    def forward(
        self,
        query, key, value,
        key_padding_mask=None,
        incremental_state=None,
        need_weights=True,
        static_kv=False,
        attn_mask=None,
        before_softmax=False,
        need_head_weights=False,
    ):
Myle Ott's avatar
Myle Ott committed
107
108
        """Input shape: Time x Batch x Channel

109
110
111
112
113
114
115
116
117
118
119
120
121
122
        Args:
            key_padding_mask (ByteTensor, optional): mask to exclude
                keys that are pads, of shape `(batch, src_len)`, where
                padding elements are indicated by 1s.
            need_weights (bool, optional): return the attention weights,
                averaged over heads (default: False).
            attn_mask (ByteTensor, optional): typically used to
                implement causal attention, where the mask prevents the
                attention from looking forward in time (default: None).
            before_softmax (bool, optional): return the raw attention
                weights and values before the attention softmax.
            need_head_weights (bool, optional): return the attention
                weights for each head. Implies *need_weights*. Default:
                return the average attention weights over all heads.
Myle Ott's avatar
Myle Ott committed
123
        """
124
125
126
        if need_head_weights:
            need_weights = True

127
        tgt_len, bsz, embed_dim = query.size()
Myle Ott's avatar
Myle Ott committed
128
129
130
        assert embed_dim == self.embed_dim
        assert list(query.size()) == [tgt_len, bsz, embed_dim]

131
        if self.enable_torch_version and not self.onnx_trace and incremental_state is None and not static_kv:
132
133
134
135
136
137
138
139
            return F.multi_head_attention_forward(query, key, value,
                                                  self.embed_dim, self.num_heads,
                                                  torch.empty([0]),
                                                  self.in_proj_bias, self.bias_k, self.bias_v,
                                                  self.add_zero_attn, self.dropout,
                                                  self.out_proj.weight, self.out_proj.bias,
                                                  self.training, key_padding_mask, need_weights,
                                                  attn_mask, use_separate_proj_weight=True,
140
141
142
                                                  q_proj_weight=self.q_proj.weight,
                                                  k_proj_weight=self.k_proj.weight,
                                                  v_proj_weight=self.v_proj.weight)
143

144
145
146
147
148
149
        if incremental_state is not None:
            saved_state = self._get_input_buffer(incremental_state)
            if 'prev_key' in saved_state:
                # previous time steps are cached - no need to recompute
                # key and value if they are static
                if static_kv:
Sergey Edunov's avatar
Sergey Edunov committed
150
                    assert self.encoder_decoder_attention and not self.self_attention
151
152
153
                    key = value = None
        else:
            saved_state = None
Myle Ott's avatar
Myle Ott committed
154

Sergey Edunov's avatar
Sergey Edunov committed
155
        if self.self_attention:
156
157
158
            q = self.q_proj(query)
            k = self.k_proj(query)
            v = self.v_proj(query)
Sergey Edunov's avatar
Sergey Edunov committed
159
        elif self.encoder_decoder_attention:
Myle Ott's avatar
Myle Ott committed
160
            # encoder-decoder attention
161
            q = self.q_proj(query)
162
163
            if key is None:
                assert value is None
Myle Ott's avatar
Myle Ott committed
164
                k = v = None
165
            else:
166
167
                k = self.k_proj(key)
                v = self.v_proj(key)
Myle Ott's avatar
Myle Ott committed
168

Myle Ott's avatar
Myle Ott committed
169
        else:
170
171
172
            q = self.q_proj(query)
            k = self.k_proj(key)
            v = self.v_proj(value)
Myle Ott's avatar
Myle Ott committed
173
174
        q *= self.scaling

175
176
177
178
179
180
181
182
183
184
        if self.bias_k is not None:
            assert self.bias_v is not None
            k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])
            v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])
            if attn_mask is not None:
                attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)
            if key_padding_mask is not None:
                key_padding_mask = torch.cat(
                    [key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1)], dim=1)

185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
        if k is not None:
            k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
        if v is not None:
            v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)

        if saved_state is not None:
            # saved states are stored with shape (bsz, num_heads, seq_len, head_dim)
            if 'prev_key' in saved_state:
                prev_key = saved_state['prev_key'].view(bsz * self.num_heads, -1, self.head_dim)
                if static_kv:
                    k = prev_key
                else:
                    k = torch.cat((prev_key, k), dim=1)
            if 'prev_value' in saved_state:
                prev_value = saved_state['prev_value'].view(bsz * self.num_heads, -1, self.head_dim)
                if static_kv:
                    v = prev_value
                else:
                    v = torch.cat((prev_value, v), dim=1)
205
206
207
208
209
210
            if 'prev_key_padding_mask' in saved_state and saved_state['prev_key_padding_mask'] is not None:
                prev_key_padding_mask = saved_state['prev_key_padding_mask']
                if static_kv:
                    key_padding_mask = prev_key_padding_mask
                else:
                    key_padding_mask = torch.cat((prev_key_padding_mask, key_padding_mask), dim=1)
211
212
            saved_state['prev_key'] = k.view(bsz, self.num_heads, -1, self.head_dim)
            saved_state['prev_value'] = v.view(bsz, self.num_heads, -1, self.head_dim)
213
            saved_state['prev_key_padding_mask'] = key_padding_mask
214
215
216
217

            self._set_input_buffer(incremental_state, saved_state)

        src_len = k.size(1)
218

219
220
221
222
223
        # This is part of a workaround to get around fork/join parallelism
        # not supporting Optional types.
        if key_padding_mask is not None and key_padding_mask.shape == torch.Size([]):
            key_padding_mask = None

224
225
226
227
        if key_padding_mask is not None:
            assert key_padding_mask.size(0) == bsz
            assert key_padding_mask.size(1) == src_len

228
229
230
231
232
233
234
        if self.add_zero_attn:
            src_len += 1
            k = torch.cat([k, k.new_zeros((k.size(0), 1) + k.size()[2:])], dim=1)
            v = torch.cat([v, v.new_zeros((v.size(0), 1) + v.size()[2:])], dim=1)
            if attn_mask is not None:
                attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)
            if key_padding_mask is not None:
Haoran Li's avatar
Haoran Li committed
235
236
                key_padding_mask = torch.cat(
                    [key_padding_mask, torch.zeros(key_padding_mask.size(0), 1).type_as(key_padding_mask)], dim=1)
Myle Ott's avatar
Myle Ott committed
237
238

        attn_weights = torch.bmm(q, k.transpose(1, 2))
239
240
        attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)

Myle Ott's avatar
Myle Ott committed
241
        assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
242

243
        if attn_mask is not None:
Haoran Li's avatar
Haoran Li committed
244
245
246
247
248
            attn_mask = attn_mask.unsqueeze(0)
            if self.onnx_trace:
                attn_mask = attn_mask.repeat(attn_weights.size(0), 1, 1)
            attn_weights += attn_mask

249
        if key_padding_mask is not None:
Myle Ott's avatar
Myle Ott committed
250
            # don't attend to padding symbols
251
            attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
252
253
254
255
            attn_weights = attn_weights.masked_fill(
                key_padding_mask.unsqueeze(1).unsqueeze(2),
                float('-inf'),
            )
256
            attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
257

258
259
260
        if before_softmax:
            return attn_weights, v

261
262
263
        attn_weights_float = utils.softmax(attn_weights, dim=-1, onnx_trace=self.onnx_trace)
        attn_weights = attn_weights_float.type_as(attn_weights)
        attn_probs = F.dropout(attn_weights_float.type_as(attn_weights), p=self.dropout, training=self.training)
Myle Ott's avatar
Myle Ott committed
264

265
        attn = torch.bmm(attn_probs, v)
Myle Ott's avatar
Myle Ott committed
266
        assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
267
268
269
270
271
272
        if (self.onnx_trace and attn.size(1) == 1):
            # when ONNX tracing a single decoder step (sequence length == 1)
            # the transpose is a no-op copy before view, thus unnecessary
            attn = attn.contiguous().view(tgt_len, bsz, embed_dim)
        else:
            attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
Myle Ott's avatar
Myle Ott committed
273
274
        attn = self.out_proj(attn)

275
        if need_weights:
276
277
278
279
            attn_weights = attn_weights_float.view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0)
            if not need_head_weights:
                # average attention weights over heads
                attn_weights = attn_weights.mean(dim=0)
280
281
        else:
            attn_weights = None
Myle Ott's avatar
Myle Ott committed
282
283
284

        return attn, attn_weights

285
286
287
288
289
    def reorder_incremental_state(self, incremental_state, new_order):
        """Reorder buffered internal state (for incremental generation)."""
        input_buffer = self._get_input_buffer(incremental_state)
        if input_buffer is not None:
            for k in input_buffer.keys():
290
291
                if input_buffer[k] is not None:
                    input_buffer[k] = input_buffer[k].index_select(0, new_order)
292
293
294
295
            self._set_input_buffer(incremental_state, input_buffer)

    def _get_input_buffer(self, incremental_state):
        return utils.get_incremental_state(
296
297
298
299
            self,
            incremental_state,
            'attn_state',
        ) or {}
300
301
302
303
304
305
306
307

    def _set_input_buffer(self, incremental_state, buffer):
        utils.set_incremental_state(
            self,
            incremental_state,
            'attn_state',
            buffer,
        )
308
309
310

    def apply_sparse_mask(self, attn_weights, tgt_len, src_len, bsz):
        return attn_weights
311
312
313
314
315
316
317
318
319

    def upgrade_state_dict_named(self, state_dict, name):
        prefix = name + '.' if name != '' else ''
        items_to_add = {}
        keys_to_remove = []
        for k in state_dict.keys():
            if k.endswith(prefix + 'in_proj_weight'):
                # in_proj_weight used to be q + k + v with same dimensions
                dim = int(state_dict[k].shape[0] / 3)
320
321
322
                items_to_add[prefix + 'q_proj.weight'] = state_dict[k][:dim]
                items_to_add[prefix + 'k_proj.weight'] = state_dict[k][dim:2*dim]
                items_to_add[prefix + 'v_proj.weight'] = state_dict[k][2*dim:]
323
324
325

                keys_to_remove.append(k)

326
327
328
329
330
331
332
333
334
                k_bias = prefix + 'in_proj_bias'
                if k_bias in state_dict.keys():
                    dim = int(state_dict[k].shape[0] / 3)
                    items_to_add[prefix + 'q_proj.bias'] = state_dict[k_bias][:dim]
                    items_to_add[prefix + 'k_proj.bias'] = state_dict[k_bias][dim:2*dim]
                    items_to_add[prefix + 'v_proj.bias'] = state_dict[k_bias][2*dim:]

                    keys_to_remove.append(prefix + 'in_proj_bias')

335
336
337
338
339
        for k in keys_to_remove:
            del state_dict[k]

        for key, value in items_to_add.items():
            state_dict[key] = value