1. Understand the Goal: The user wants a program that implements "attention mechanisms" for "sequence processing". This is a broad request, so I need to provide a clear, understandable, and educational implementation.
-
Identify the Core Concepts:
- Sequence Processing: Typically involves input sequences (like text or time series) and output sequences (or a classification).
- Attention Mechanism: The core idea is to weight the importance of different input elements when producing an output. The standard "Scaled Dot-Product Attention" (used in Transformers) is the most relevant and widely used version to teach.
-
Determine the Scope & Tools:
- Language: Python is the standard.
- Library: PyTorch is the best choice for deep learning implementations due to its dynamic graph and popularity. TensorFlow/Keras is okay, but PyTorch usually allows for more explicit implementation of equations, which helps in understanding the mechanics. NumPy is good for a "from scratch" version, but users usually want something usable in a DL context.
- Type of Attention: "Self-Attention" is the building block of modern NLP.
- Level of Abstraction: I should provide two levels:
- From Scratch (NumPy/PyTorch basics): To show the math (Query, Key, Value).
- Using PyTorch Modules: To show how it's done in production code.
-
Drafting the Implementation (Mental or Scratchpad):
-
Structuring the Code:
-
Part 1: The "Manual" Implementation (Educational):
- Define a class
SelfAttention.
- Initialize linear layers for Query, Key, Value.
- Forward pass:
- Project inputs to Q, K, V.
- Calculate scores:
torch.matmul(Q, K.transpose(-2, -1)).
- Scale: divide by
sqrt(d_k).
- Softmax:
torch.nn.functional.softmax.
- Apply to V:
torch.matmul(attention_weights, V).
-
Part 2: Multi-Head Attention (Advanced but necessary):
- Usually, single head isn't enough. Splitting the embedding dimension allows the model to focus on different context sub-spaces.
- This might be too complex for a basic request, but I should probably stick to a clear Single-Head implementation first, or a simplified Multi-Head if the code remains readable. Let's stick to a modular approach: A class for Scaled Dot-Product Attention and a class for the full Attention module.
-
Part 3: A runnable Example (The "Program" aspect):
- Create some dummy data (random tensors representing a batch of sequences).
- Pass it through the module.
- Print the shapes to verify.
-
Refining the Explanation:
- I need to explain why we do each step.
- Query: What I'm looking for.
- Key: What defines the input.
- Value: The actual content.
-
Writing the Code (Iterative refinement):
-
Import: torch, torch.nn, torch.nn.functional.
-
Class Structure:
class SelfAttention(nn.Module):
def __init__(self, embed_size, heads): ...
-
Wait, let's start simple. Just Scaled Dot-Product Attention.
-
Actually, let's implement a standard Self-Attention block. It's the most common interpretation of "Attention for sequence processing".
-
Drafting the logic:
q = self.query(x)
k = self.key(x)
v = self.value(x)
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.embed_size)
attn = F.softmax(scores, dim=-1)
out = torch.matmul(attn, v)
-
Adding Masking (Optional but good):
- Sequence processing often involves padding. A mask is needed. I'll add a comment about it or a parameter for
mask.
-
Final Code Structure:
- Imports: PyTorch.
- Class
SelfAttention: Basic single-head implementation.
- Class
TransformerBlock: (Optional, but adds context) Adding a Feed Forward Network makes it a complete processing unit. Let's keep it strictly to Attention to answer the specific prompt.
- Usage Example: Create dummy input, run it, print output shape and attention weights.
-
Review against constraints: "Create a program".
- I should provide a complete script that can be copied and run immediately.
-
Self-Correction during drafting:
- Issue: Matrix multiplication dimensions can be tricky for beginners.
- Fix: Be explicit about
(Batch, Seq_Len, Embed_Dim). Add comments explaining the transpose.
-
Final Polish:
- Add docstrings.
- Explain the "Scaled Dot-Product" formula in the comments.
- Include a visualization logic? No, standard output is text. But I can print the attention matrix to show what it learned (randomly initialized weights will show random attention, but the shape illustrates the mechanism).
-
Let's create the response. (Proceeding to generate the Python code with PyTorch).
- Step 1: Pure Python/NumPy implementation? No, PyTorch is the industry standard.
- Step 2: Write the
SelfAttention class.
- Step 3: Write a
MultiHeadAttention class (as it's the real-world standard).
- Step 4: Main execution block.
(Self-Correction): The prompt asks for "Attention mechanisms". I should provide the Scaled Dot-Product Attention (the engine) and a wrapper for Self-Attention.
Let's write the code.
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
def __init__(self, embed_size, heads):
# ... init ...
def forward(self, values, keys, query, mask):
# ... forward logic ...
Wait, F.scaled_dot_product_attention exists in newer PyTorch versions. I should probably implement it manually so the user sees the math, but mention the built-in one for performance. I will implement it manually using nn.Linear and matmul.
Plan:
- Concept explanation: Briefly define Query, Key, Value.
- The Code:
- A class
Attention implementing the logic manually.
- A dummy dataset generator.
- A runner to demonstrate shape transformations.
- Explanation of the steps: Breakdown of the matrix math.
Let's refine the Multi-Head part. Multi-head attention splits the embedding dimension into heads chunks.
Input: (batch, seq_len, embed_size)
Split: (batch, seq_len, heads, head_dim)
This is crucial for performance.
Let's go with a robust SelfAttention implementation.
Code Structure:
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
def __init__(self, embed_size, heads):
...
def forward(self, x, mask):
...
# Usage
...
This looks solid. I will add comments explaining the dimensions at every step.
Here is a complete Python program implementing an Attention Mechanism using PyTorch.
This implementation focuses on Scaled Dot-Product Attention, which is the core engine of modern models like Transformers and BERT. I have implemented it from scratch (without using pre-built Transformer blocks) so you can see exactly how the mathematics works.
The Program
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class SelfAttention(nn.Module):
"""
Implements Scaled Dot-Product Self-Attention.
This mechanism allows the model to weigh the importance of different words
in a sequence relative to each other.
"""
def __init__(self, embed_size, heads):
super(SelfAttention, self).__init__()
self.embed_size = embed_size
self.heads = heads
self.head_dim = embed_size // heads
assert (self.head_dim * heads == embed_size), "Embed size must be divisible by heads"
# Linear layers to project inputs into Query, Key, and Value vectors
self.values = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.keys = nn.Linear(self.head_dim, self.head_dim, bias=False)
self.queries = nn.Linear(self.head_dim, self.head_dim, bias=False)
# Output layer to concatenate heads and project back to embed_size
self.fc_out = nn.Linear(heads * self.head_dim, embed_size)
def forward(self, values, keys, query, mask):
"""
Forward pass.
Args:
values: Input tensor (batch_size, seq_len, embed_size)
keys: Input tensor (usually same as values)
query: Input tensor (usually same as values)
mask: Optional mask to hide future tokens (for decoding)
"""
N = query.shape[0] # Batch size
value_len, key_len, query_len = values.shape[1], keys.shape[1], query.shape[1]
# Split embeddings into multiple heads
# Reshape: (N, Length, Heads, Head_Dim)
values = values.reshape(N, value_len, self.heads, self.head_dim)
keys = keys.reshape(N, key_len, self.heads, self.head_dim)
queries = query.reshape(N, query_len, self.heads, self.head_dim)
# Pass through linear layers
values = self.values(values)
keys = self.keys(keys)
queries = self.queries(queries)
# --- Attention Calculation ---
# 1. Matrix Multiplication (Query * Key Transpose)
# We use Einstein summation (einsum) for efficient matrix multiplication across dimensions.
# queries: (N, query_len, heads, head_dim)
# keys: (N, key_len, heads, head_dim)
# Result 'energy': (N, heads, query_len, key_len)
energy = torch.einsum("nqhd,nkhd->nhqk", [queries, keys])
# 2. Scaling
# Divide by sqrt(head_dim) to prevent gradients from becoming too small.
energy = energy / (self.embed_size ** (1/2))
# 3. Masking (Optional)
# If a mask is provided (e.g., for a decoder), set masked positions to -infinity
# so they become 0 after Softmax.
if mask is not None:
energy = energy.masked_fill(mask == 0, float("-1e20"))
# 4. Softmax
# Converts raw scores into probabilities (attention weights).
attention = torch.softmax(energy, dim=3)
# 5. Apply Attention to Values
# attention: (N, heads, query_len, key_len)
# values: (N, value_len, heads, head_dim)
# out: (N, query_len, heads, head_dim)
out = torch.einsum("nhql,nlhd->nqhd", [attention, values])
# Concatenate heads
out = out.reshape(N, query_len, self.heads * self.head_dim)
# Final linear projection
return self.fc_out(out)
class TransformerBlock(nn.Module):
"""
A standard Transformer block containing Self-Attention and a Feed Forward Network.
"""
def __init__(self, embed_size, heads, dropout, forward_expansion):
super(TransformerBlock, self).__init__()
self.attention = SelfAttention(embed_size, heads)
# Normalization and Dropout
self.norm1 = nn.LayerNorm(embed_size)
self.norm2 = nn.LayerNorm(embed_size)
self.dropout = nn.Dropout(dropout)
# Feed Forward Network
self.ff = nn.Sequential(
nn.Linear(embed_size, forward_expansion * embed_size),
nn.ReLU(),
nn.Linear(forward_expansion * embed_size, embed_size)
)
def forward(self, value, key, query, mask):
# 1. Attention Layer
attention_out = self.attention(value, key, query, mask)
# 2. Add & Norm (Residual Connection)
x = self.dropout(self.norm1(attention_out + query))
# 3. Feed Forward Layer
forward_out = self.ff(x)
# 4. Add & Norm (Residual Connection)
out = self.dropout(self.norm2(forward_out + x))
return out
# --- Example Usage ---
def run_example():
# Parameters
batch_size = 2
seq_length = 10 # Number of words/tokens
embed_size = 256 # Vector size for each word
heads = 8 # Number of attention heads
dropout = 0.1
forward_expansion = 4
# Create dummy input data (Batch, Seq_Len, Embed_Size)
# Represents a batch of 2 sentences, each with 10 words, each word a 256-dim vector
inputs = torch.randn((batch_size, seq_length, embed_size))
# Initialize the model
model = TransformerBlock(embed_size, heads, dropout, forward_expansion)
# Forward pass (No mask for this example)
output = model(inputs, inputs, inputs, mask=None)
print("--- Attention Mechanism Test ---")
print(f"Input shape: {inputs.shape}")
print(f"Output shape: {output.shape}")
print("\nSuccess! The model processed the sequence and preserved dimensions.")
# Inspecting the Attention Weights (Conceptual)
print("\n--- How it works ---")
print("1. Input vectors are projected into Query (Q), Key (K), and Value (V).")
print("2. Compatibility function calculated: (Q * K^T) / sqrt(d_k)")
print("3. Softmax applied to get weights (probability distribution).")
print("4. Weights multiplied by V to get the final context-aware output.")
if __name__ == "__main__":
run_example()
How to understand this code
-
The Inputs (Q, K, V):
- Query: What vector am I looking for?
- Key: What features does this vector have?
- Value: What actual content does this vector hold?
- In Self-Attention, the input is copied into all three.
-
torch.einsum:
- You will see
einsum used in the code. It is a powerful way to handle matrix multiplications across complex dimensions without manually reshaping and transposing tensors repeatedly.
"nqhd,nkhd->nhqk" essentially calculates the dot product between every Query and every Key.
-
Multi-Head Attention:
- Instead of calculating a single huge attention map, the model splits the embedding vector (size 256) into 8 "heads" (size 32). This allows the model to focus on different types of relationships (e.g., grammatical vs. semantic) simultaneously.
-
Residual Connections (Add & Norm):
- In
TransformerBlock, we add the input back to the output (x + attention_out). This helps gradients flow through deep networks during training.