Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

multihead_attention.py 8.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
  1. # Copyright (c) 2017-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the LICENSE file in
  5. # the root directory of this source tree. An additional grant of patent rights
  6. # can be found in the PATENTS file in the same directory.
  7. import torch
  8. from torch import nn
  9. from torch.nn import Parameter
  10. import torch.nn.functional as F
  11. from fairseq import utils
  12. class MultiheadAttention(nn.Module):
  13. """Multi-headed attention.
  14. See "Attention Is All You Need" for more details.
  15. """
  16. def __init__(self, embed_dim, num_heads, dropout=0., bias=True):
  17. super().__init__()
  18. self.embed_dim = embed_dim
  19. self.num_heads = num_heads
  20. self.dropout = dropout
  21. self.head_dim = embed_dim // num_heads
  22. assert self.head_dim * num_heads == self.embed_dim
  23. self.scaling = self.head_dim**-0.5
  24. self._mask = None
  25. self.in_proj_weight = Parameter(torch.Tensor(3*embed_dim, embed_dim))
  26. if bias:
  27. self.in_proj_bias = Parameter(torch.Tensor(3*embed_dim))
  28. else:
  29. self.register_parameter('in_proj_bias', None)
  30. self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  31. self.reset_parameters()
  32. def reset_parameters(self):
  33. nn.init.xavier_uniform(self.in_proj_weight)
  34. nn.init.xavier_uniform(self.out_proj.weight)
  35. if self.in_proj_bias is not None:
  36. nn.init.constant(self.in_proj_bias, 0.)
  37. nn.init.constant(self.out_proj.bias, 0.)
  38. def forward(self, query, key, value, mask_future_timesteps=False,
  39. key_padding_mask=None, incremental_state=None,
  40. need_weights=True, static_kv=False):
  41. """Input shape: Time x Batch x Channel
  42. Self-attention can be implemented by passing in the same arguments for
  43. query, key and value. Future timesteps can be masked with the
  44. `mask_future_timesteps` argument. Padding elements can be excluded from
  45. the key by passing a binary ByteTensor (`key_padding_mask`) with shape:
  46. batch x src_len, where padding elements are indicated by 1s.
  47. """
  48. qkv_same = query.data_ptr() == key.data_ptr() == value.data_ptr()
  49. kv_same = key.data_ptr() == value.data_ptr()
  50. tgt_len, bsz, embed_dim = query.size()
  51. assert embed_dim == self.embed_dim
  52. assert list(query.size()) == [tgt_len, bsz, embed_dim]
  53. assert key.size() == value.size()
  54. if incremental_state is not None:
  55. saved_state = self._get_input_buffer(incremental_state)
  56. if 'prev_key' in saved_state:
  57. # previous time steps are cached - no need to recompute
  58. # key and value if they are static
  59. if static_kv:
  60. assert kv_same and not qkv_same
  61. key = value = None
  62. else:
  63. saved_state = None
  64. if qkv_same:
  65. # self-attention
  66. q, k, v = self.in_proj_qkv(query)
  67. elif kv_same:
  68. # encoder-decoder attention
  69. q = self.in_proj_q(query)
  70. if key is None:
  71. assert value is None
  72. # this will allow us to concat it with previous value and get
  73. # just get the previous value
  74. k = v = q.new(0)
  75. else:
  76. k, v = self.in_proj_kv(key)
  77. else:
  78. q = self.in_proj_q(query)
  79. k = self.in_proj_k(key)
  80. v = self.in_proj_v(value)
  81. q *= self.scaling
  82. if saved_state is not None:
  83. if 'prev_key' in saved_state:
  84. k = torch.cat((saved_state['prev_key'], k), dim=0)
  85. if 'prev_value' in saved_state:
  86. v = torch.cat((saved_state['prev_value'], v), dim=0)
  87. saved_state['prev_key'] = k
  88. saved_state['prev_value'] = v
  89. self._set_input_buffer(incremental_state, saved_state)
  90. src_len = k.size(0)
  91. if key_padding_mask is not None:
  92. assert key_padding_mask.size(0) == bsz
  93. assert key_padding_mask.size(1) == src_len
  94. q = q.contiguous().view(tgt_len, bsz*self.num_heads, self.head_dim).transpose(0, 1)
  95. k = k.contiguous().view(src_len, bsz*self.num_heads, self.head_dim).transpose(0, 1)
  96. v = v.contiguous().view(src_len, bsz*self.num_heads, self.head_dim).transpose(0, 1)
  97. attn_weights = torch.bmm(q, k.transpose(1, 2))
  98. assert list(attn_weights.size()) == [bsz * self.num_heads, tgt_len, src_len]
  99. # only apply masking at training time (when incremental state is None)
  100. if mask_future_timesteps and incremental_state is None:
  101. assert query.size() == key.size(), \
  102. 'mask_future_timesteps only applies to self-attention'
  103. attn_weights += self.buffered_mask(attn_weights).unsqueeze(0)
  104. if key_padding_mask is not None:
  105. # don't attend to padding symbols
  106. attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
  107. attn_weights = attn_weights.float().masked_fill(
  108. key_padding_mask.unsqueeze(1).unsqueeze(2),
  109. float('-inf'),
  110. ).type_as(attn_weights) # FP16 support: cast to float and back
  111. attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
  112. attn_weights = F.softmax(attn_weights.float(), dim=-1).type_as(attn_weights)
  113. attn_weights = F.dropout(attn_weights, p=self.dropout, training=self.training)
  114. attn = torch.bmm(attn_weights, v)
  115. assert list(attn.size()) == [bsz * self.num_heads, tgt_len, self.head_dim]
  116. attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embed_dim)
  117. attn = self.out_proj(attn)
  118. if need_weights:
  119. # average attention weights over heads
  120. attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
  121. attn_weights = attn_weights.sum(dim=1) / self.num_heads
  122. else:
  123. attn_weights = None
  124. return attn, attn_weights
  125. def in_proj_qkv(self, query):
  126. return self._in_proj(query).chunk(3, dim=-1)
  127. def in_proj_kv(self, key):
  128. return self._in_proj(key, start=self.embed_dim).chunk(2, dim=-1)
  129. def in_proj_q(self, query):
  130. return self._in_proj(query, end=self.embed_dim)
  131. def in_proj_k(self, key):
  132. return self._in_proj(key, start=self.embed_dim, end=2*self.embed_dim)
  133. def in_proj_v(self, value):
  134. return self._in_proj(value, start=2*self.embed_dim)
  135. def _in_proj(self, input, start=None, end=None):
  136. weight = self.in_proj_weight
  137. bias = self.in_proj_bias
  138. if end is not None:
  139. weight = weight[:end, :]
  140. if bias is not None:
  141. bias = bias[:end]
  142. if start is not None:
  143. weight = weight[start:, :]
  144. if bias is not None:
  145. bias = bias[start:]
  146. return F.linear(input, weight, bias)
  147. def buffered_mask(self, tensor):
  148. dim = tensor.size(-1)
  149. if self._mask is None:
  150. self._mask = torch.triu(utils.fill_with_neg_inf(tensor.new(dim, dim)), 1)
  151. if self._mask.size(0) < dim:
  152. self._mask = torch.triu(utils.fill_with_neg_inf(self._mask.resize_(dim, dim)), 1)
  153. return self._mask[:dim, :dim]
  154. def reorder_incremental_state(self, incremental_state, new_order):
  155. """Reorder buffered internal state (for incremental generation)."""
  156. input_buffer = self._get_input_buffer(incremental_state)
  157. if input_buffer is not None:
  158. for k in input_buffer.keys():
  159. input_buffer[k] = input_buffer[k].index_select(1, new_order)
  160. self._set_input_buffer(incremental_state, input_buffer)
  161. def _get_input_buffer(self, incremental_state):
  162. return utils.get_incremental_state(
  163. self,
  164. incremental_state,
  165. 'attn_state',
  166. ) or {}
  167. def _set_input_buffer(self, incremental_state, buffer):
  168. utils.set_incremental_state(
  169. self,
  170. incremental_state,
  171. 'attn_state',
  172. buffer,
  173. )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...