To enhance a tensor of shape [bs, seq, dim] using cross-attention based on another tensor, you can use a transformer-like attention mechanism. Cross-attention involves computing the compatibility between the query tensor (the tensor that will be enhanced) and the key-value tensor (the additional context tensor).
Here’s an example PyTorch implementation for this:
Code:
import torch
import torch.nn as nn
import torch.nn.functional as F
class CrossAttentionEnhancer(nn.Module):
def __init__(self, input_dim, context_dim, num_heads, dropout=0.1):
"""
Args:
input_dim (int): Dimensionality of the input `query` tensor.
context_dim (int): Dimensionality of the additional context tensor (keys and values).
num_heads (int): Number of attention heads.
dropout (float): Dropout probability for the attention weights.
"""
super(CrossAttentionEnhancer, self).__init__()
self.num_heads = num_heads
self.query_proj = nn.Linear(input_dim, input_dim)
self.key_proj = nn.Linear(context_dim, input_dim)
self.value_proj = nn.Linear(context_dim, input_dim)
self.out_proj = nn.Linear(input_dim, input_dim)
self.dropout = nn.Dropout(dropout)
self.scale = (input_dim // num_heads) ** 0.5 # Scaling factor based on head dimension.
def forward(self, query_tensor, context_tensor, mask=None):
"""
Args:
query_tensor (torch.Tensor): Tensor of shape [bs, seq, dim], the tensor to be enhanced.
context_tensor (torch.Tensor): Tensor of shape [bs, context_seq, context_dim], the context tensor.
mask (torch.Tensor, optional): Attention mask of shape [bs, seq, context_seq].
Specify which positions can or cannot attend (1 or 0).
Returns:
torch.Tensor: The enhanced query tensor of shape [bs, seq, dim].
"""
bs, seq, dim = query_tensor.shape
_, context_seq, _ = context_tensor.shape
# Step 1: Project the query, key, and value tensors.
query = self.query_proj(query_tensor) # Shape: [bs, seq, dim]
key = self.key_proj(context_tensor) # Shape: [bs, context_seq, dim]
value = self.value_proj(context_tensor) # Shape: [bs, context_seq, dim]
# Step 2: Reshape for multi-head attention.
query = query.view(bs, seq, self.num_heads, dim // self.num_heads).transpose(1, 2) # [bs, num_heads, seq, head_dim]
key = key.view(bs, context_seq, self.num_heads, dim // self.num_heads).transpose(1, 2) # [bs, num_heads, context_seq, head_dim]
value = value.view(bs, context_seq, self.num_heads, dim // self.num_heads).transpose(1, 2) # [bs, num_heads, context_seq, head_dim]
# Step 3: Compute scaled dot-product attention.
attention_scores = torch.matmul(query, key.transpose(-2, -1)) / self.scale # [bs, num_heads, seq, context_seq]
if mask is not None:
attention_scores = attention_scores.masked_fill(mask.unsqueeze(1) == 0, float('-inf'))
attention_weights = F.softmax(attention_scores, dim=-1) # [bs, num_heads, seq, context_seq]
attention_weights = self.dropout(attention_weights)
# Step 4: Compute the attention output.
attention_output = torch.matmul(attention_weights, value) # [bs, num_heads, seq, head_dim]
# Step 5: Reshape the output and apply the final linear projection.
attention_output = attention_output.transpose(1, 2).contiguous() # [bs, seq, num_heads, head_dim]
attention_output = attention_output.view(bs, seq, dim) # [bs, seq, dim]
enhanced_query = self.out_proj(attention_output) # [bs, seq, dim]
return enhanced_query
# Example usage:
bs = 4 # Batch size
seq = 10 # Sequence length of the query tensor
context_seq = 15 # Sequence length of the context tensor
input_dim = 32 # Dimension of the query tensor
context_dim = 64 # Dimension of the context tensor
num_heads = 4 # Number of attention heads
query_tensor = torch.randn(bs, seq, input_dim) # Query tensor
context_tensor = torch.randn(bs, context_seq, context_dim) # Context tensor
# Create and apply the CrossAttentionEnhancer
enhancer = CrossAttentionEnhancer(input_dim=input_dim, context_dim=context_dim, num_heads=num_heads)
enhanced_query = enhancer(query_tensor, context_tensor) # [bs, seq, input_dim]
print("Enhanced query shape:", enhanced_query.shape) # Should be [bs, seq, input_dim]
Explanation of the steps:
-
Projection:
query, key, and value tensors are computed using linear projections of query_tensor and context_tensor.
-
Multi-Head Split:
- The tensors are split into multiple attention heads.
-
Scaled Dot-Product Attention:
- Attention scores are computed by taking the dot product of the
query and key tensors and scaling by the square root of the head dimensions.
- A softmax function normalizes the scores, turning them into probabilities.
- These scores are then used to weight the
value tensor to produce the output.
-
Combine Heads:
- The output tensors from all attention heads are concatenated and projected back to the original dimension.
This produces an enhanced version of the query_tensor, informed by the context_tensor.