44# This source code is licensed under the BSD-style license found in the
55# LICENSE file in the root directory of this source tree.
66
7- from typing import Any , Dict , Optional , Tuple , Union
7+ from typing import Any , Dict , Optional
88
99import torch
1010from torch import nn , Tensor
@@ -29,8 +29,7 @@ def forward(
2929 k : Tensor ,
3030 v : Tensor ,
3131 attention_mask : Optional [Tensor ] = None ,
32- head_mask : Optional [Tensor ] = None ,
33- ) -> Tuple [Tensor , Tensor ]:
32+ ) -> Tensor :
3433 """
3534 Args:
3635 q (Tensor): Query input of shape ``(b, h, d1, ..., dn, dim_q)`` where ``h`` is the number of
@@ -42,11 +41,9 @@ def forward(
4241 attention_mask (Tensor, optional): Tensor of shape ``(b, h, q_dn, k_dn)`` where ``q_dn`` is the
4342 dimension of the flattened query input along its latent dimensions and ``k_dn`` that of the
4443 flattened key input. Contains 1s for positions to attend to and 0s for masked positions.
45- head_mask (Tensor, optional): Tensor of shape ``(b, h, q_dn, k_dn)``.
46- Contains 1s for positions to attend to and 0s for masked positions.
4744
4845 Returns:
49- A tuple of output tensor and attention probabilities .
46+ Output tensor.
5047 """
5148 _ , _ , * shape , _ = q .shape
5249
@@ -55,16 +52,15 @@ def forward(
5552 k = k .flatten (start_dim = 2 , end_dim = - 2 )
5653 v = v .flatten (start_dim = 2 , end_dim = - 2 )
5754
58- out , attn_probs = scaled_dot_product_attention (
55+ out = scaled_dot_product_attention (
5956 q ,
6057 k ,
6158 v ,
6259 attention_mask = attention_mask ,
63- head_mask = head_mask ,
6460 attn_dropout = self .attn_dropout if self .training else 0.0 ,
6561 )
6662
67- return out .unflatten (2 , shape ), attn_probs
63+ return out .unflatten (2 , shape )
6864
6965
7066class MultiHeadAttention (nn .Module ):
@@ -121,11 +117,10 @@ def forward(
121117 self ,
122118 q : Tensor ,
123119 kv : Optional [Tensor ] = None ,
124- return_attn_weights : bool = False ,
125120 use_cache : bool = False ,
126121 causal : bool = False ,
127122 ** attn_kwargs : Any ,
128- ) -> Union [ Tensor , Tuple [ Tensor , Tensor ]] :
123+ ) -> Tensor :
129124 """
130125 Args:
131126 q (Tensor): Query of shape ``(b, d1, ..., dn, dim_q)`` or ``(b, seq_len, dim_q)``
@@ -138,8 +133,7 @@ def forward(
138133 causal (bool): Whether to use causal attention or not. Default is ``False``.
139134
140135 Returns:
141- * If ``return_attn_weights`` is ``True``: A tuple of output tensor and attention probabilities.
142- * If ``return_attn_weights`` is ``False``: A single output tensor.
136+ Output tensor.
143137 """
144138 # If kv is specified use those inputs for cross-attention, otherwise use q
145139 k = v = q if kv is None else kv
@@ -169,51 +163,33 @@ def forward(
169163 k , v = self .cache ["k" ], self .cache ["v" ]
170164
171165 attn_out = self .attn (q , k , v , ** attn_kwargs )
172- attn_probs = None
173- # Unpack if attn module also returns attn probs
174- if isinstance (attn_out , tuple ):
175- attn_out , attn_probs = attn_out
176166 a = merge_multihead (attn_out )
177167 a = self .output (a )
178168
179- if return_attn_weights :
180- return a , attn_probs
181- else :
182- return a
169+ return a
183170
184171
185172def scaled_dot_product_attention (
186173 q : Tensor ,
187174 k : Tensor ,
188175 v : Tensor ,
189176 attention_mask : Optional [Tensor ] = None ,
190- head_mask : Optional [Tensor ] = None ,
191177 attn_dropout : float = 0.0 ,
192- ) -> Tuple [ Tensor , Tensor ] :
193- """Similar to PyTorch Core's _scaled_dot_product_attention but generalized
194- to handle n-dimensional input tokens (images, video) and support multihead.
195- Computes attention as described in Attention Is All You Need (Vaswani et al. 2017)
178+ ) -> Tensor :
179+ """Computes scaled dot-product attention. Similar to PyTorch Core's
180+ ``scaled_dot_product_attention`` but generalized to handle n-dimensional
181+ input tokens (images, video) and support multihead.
196182
197183 Args:
198- q (Tensor): Query of shape ``(b, h, d1, ..., dn, dim_qk)`` or ``(b, h, seq_len, dim_qk)`` where
199- ``h`` is number of attention heads, ``d1, ..., dn`` are latent dimensions and ``dim_qk` is
200- the embedding dim of the query tensor.
201- k (Tensor): Key of shape ``(b, h, d1', ...., dn', dim_qk)`` or ``(b, h, seq_len', dim_qk)`` where
202- ``h`` is the number of attention heads, ``d1', ..., dn'` are latent dimensions and ``dim_qk``
203- is the key embedding dim aligned with query embedding dim,
204- see :class:`~torchmultimodal.modules.layers.attention.MultiHeadAttention`.
205- v (Tensor): Value of shape ``(b, h, d1', ..., dn', dim_v)`` or ``(b, h, seq_len', dim_v)`` where
206- ``h`` is the number of attention heads, ``d1', ..., dn'`` are latent dimensions and ``dim_v``
207- is the embedding dim of the value tensor.
184+ q (Tensor): Query of shape ``(b, h, d1, ..., dn, dim_qk)`` or ``(b, h, seq_len, dim_qk)``.
185+ k (Tensor): Key of shape ``(b, h, d1', ...., dn', dim_qk)`` or ``(b, h, seq_len', dim_qk)``.
186+ v (Tensor): Value of shape ``(b, h, d1', ..., dn', dim_v)`` or ``(b, h, seq_len', dim_v)``.
208187 attention_mask (Tensor, optional): Tensor of shape ``(b, h, d1, ..., q_dn, k_dn)``.
209- Contains 1s for positions to attend to and 0s for masked positions. Applied before softmax.
210- head_mask (Tensor, optional): Tensor of shape ``(b, h, d1, ..., q_dn, k_dn)``.
211188 Contains 1s for positions to attend to and 0s for masked positions.
212- Applied after dropout, before matrix multiplication with values.
213189 attn_dropout (float): Probability of dropout after softmax. Default is ``0.0``.
214190
215191 Returns:
216- A tuple of output tensor and attention probabilities .
192+ Output tensor.
217193 """
218194
219195 # Take the dot product between "query" and "key" and scale to get the raw attention scores.
@@ -232,13 +208,10 @@ def scaled_dot_product_attention(
232208 # This is actually dropping out entire tokens to attend to, which might
233209 # seem a bit unusual, but is taken from the original Transformer paper.
234210 attn = F .dropout (attn , p = attn_dropout )
235- # Mask heads if we want to
236- if head_mask is not None :
237- attn = attn * head_mask
238211 # For each query sum over the key/value dim with attention weights
239212 a = torch .matmul (attn , v ) # b, h, d1, ..., q_dn, c
240213
241- return a , attn
214+ return a
242215
243216
244217def split_multihead (x : Tensor , n_head : int ) -> Tensor :
0 commit comments