Install bidirectional-cross-attention
mainInstall the package using pip:
$ pip install bidirectional-cross-attentionrepository·main·Indexed 41 days ago
https://github.com/lucidrains/bidirectional-cross-attentionA mechanism that updates both a source and a target sequence in a single step using shared query/key attention. Designed for symmetric interaction between different modalities or sequences, the BidirectionalCrossAttention module supports masking for both primary and context sequences while maintaining input shapes in the output.
Install the package using pip:
$ pip install bidirectional-cross-attentionThe BidirectionalCrossAttention module allows for updating both a source sequence and a target sequence in a single step using shared query/key attention. This is useful for multi-modal tasks (e.g., video and audio) where both sequences need to attend to each other.
Key features:
import torch
from bidirectional_cross_attention import BidirectionalCrossAttention
# Example sequences (e.g., video and audio)
video = torch.randn(1, 4096, 512)
audio = torch.randn(1, 8192, 386)
# Masks for the sequences
video_mask = torch.ones((1, 4096)).bool()
audio_mask = torch.ones((1, 8192)).bool()
# Initialize the module
joint_cross_attn = BidirectionalCrossAttention(
dim = 512,
heads = 8,
dim_head = 64,
context_dim = 386
)
# Perform bidirectional cross attention
video_out, audio_out = joint_cross_attn(
video,
audio,
mask = video_mask,
context_mask = audio_mask
)
# Verify output shapes match input shapes
assert video_out.shape == video.shape
assert audio_out.shape == audio.shapeThe BidirectionalCrossAttention class implements a cross-attention mechanism that updates both the source and target sequences.
dim: Dimension of the primary sequence.heads: Number of attention heads.dim_head: Dimension of each attention head.context_dim: Dimension of the context (secondary) sequence.video: The primary sequence tensor.audio: The context sequence tensor.mask: Boolean mask for the primary sequence.context_mask: Boolean mask for the context sequence.(video_out, audio_out), where both tensors have the same shape as their respective inputs.