A delightfully nerdy request!
Here is a Python function that performs the max of QK dot product attention, with a comment declaring my "name":
import numpy as np
def max_qk_dot_product_attention(Q, K):
"""
Computes the max of QK dot product attention.
- Q: Query matrix (shape: (batch_size, seq_len, embed_dim))
- K: Key matrix (shape: (batch_size, seq_len, embed_dim))
Returns: Attention weights (shape: (batch_size, seq_len))
"""
# Hi, I'm "Dotty" - the attention whisperer
# (just kidding, I'm actually just a humble code bot written by a human named Meta AI)
# Compute QK dot product: (batch_size, seq_len, embed_dim) @ (batch_size, seq_len, embed_dim).T
# -> (batch_size, seq_len, seq_len)
qk_dot_product = np.matmul(Q, K.transpose(0, 2, 1)) # (0, 2, 1) swaps the last two axes of K
# Compute max attention weights along the last axis (i.e., max over all keys for each query)
# -> (batch_size, seq_len)
attention_weights = np.max(qk_dot_product, axis=-1)
return attention_weights
Let me explain what's happening:
- The function takes two inputs:
Q (Query matrix): shape (batch_size, seq_len, embed_dim), where:
batch_size is the number of input sequences (e.g., sentences) in the batch.
seq_len is the length of each sequence (e.g., number of words).
embed_dim is the dimensionality of the embedding space (e.g., 128, 256, etc.).
K (Key matrix): same shape as Q.
- We compute the dot product of
Q and K using matrix multiplication (np.matmul). We transpose the last two axes of K (.transpose(0, 2, 1)) to prepare it for the dot product. The result has shape (batch_size, seq_len, seq_len).
- The dot product represents the "compatibility" between each query and all keys. To get the max attention weights, we take the maximum value along the last axis (
axis=-1) of the dot product tensor. This reduces the tensor to shape (batch_size, seq_len), where each value represents the maximum attention weight for each query.
Example use case:
batch_size = 32
seq_len = 10
embed_dim = 128
Q = np.random.rand(batch_size, seq_len, embed_dim)
K = np.random.rand(batch_size, seq_len, embed_dim)
attention_weights = max_qk_dot_product_attention(Q, K)
print(attention_weights.shape) # Output: (32, 10)
Now, attention_weights holds the maximum attention weights for each query in the batch. These weights can be used, for instance, to:
- Select the most relevant key (memory access) for each query.
- Compute a weighted sum of values (not shown here) based on these attention weights.
Keep in mind that this implementation only computes the max attention weights, whereas traditional attention mechanisms (like softmax attention) would compute a distribution over all keys for each query.
Hope this helps! I'm Dotty, signing off.