1. Understand the Goal: The user wants a program that implements attention mechanisms for sequence processing. The request is somewhat general ("Create a program"), so I need to decide on the scope, the language (Python is the standard), and the level of abstraction (from scratch using NumPy vs. using a high-level library like PyTorch or TensorFlow).
Determine the Approach:
Option A: NumPy from scratch. Good for understanding the math (matmul, softmax, etc.), but less practical for real-world use.
Option B: PyTorch/TensorFlow High-level API. Easy to code (nn.MultiheadAttention), but hides the "implementation" details.
Option C: PyTorch low-level (Custom Module). This is the sweet spot. It demonstrates understanding of the architecture (Query, Key, Value, Scaled Dot-Product) while using optimized tensor operations.
Decision: I will provide a PyTorch implementation. It's the industry standard for this type of work. I will implement the "Scaled Dot-Product Attention" (the core of the Transformer architecture) and likely a wrapper for Multi-Head Attention.
Core Components of Attention:
Inputs: Query (Q), Key (K), Value (V).
Mechanism:
Calculate scores: Q×KT.
Scale scores: Divide by dk (dimension of keys) to prevent vanishing gradients in softmax.
Masking (Optional but recommended for sequence processing to prevent looking ahead).
Softmax: Convert scores to probabilities (attention weights).
If mask: scores = scores.masked_fill(mask == 0, -1e9)
attn = torch.softmax(scores, dim=-1)
output = torch.matmul(attn, v)
return output, attn
Class MultiHeadAttention:
Need linear layers for Wq,Wk, and output linear layer.
Refining the Example:
Just the classes might be too abstract. I should create a dummy dataset or a specific use case (like a simple sequence-to-vector task or just processing random tensors) to show it running.
Let's stick to a clean, modular implementation of the standard Transformer attention mechanism. I will include two versions:
Basic "Self-Attention" (Scaled Dot-Product): The fundamental math.
Multi-Head Attention: The practical implementation used in models like BERT/GPT.
Structuring the Explanation:
Introduction: Briefly explain what attention is (focusing on specific parts of the input).
The Math: Briefly mention Q,K,V.
The Code (PyTorch):
Import libraries.
Implementation of SelfAttention.
Implementation of MultiHeadAttention.
Example Usage: Generate random tensors representing a batch of sequences and pass them through the model.
Explanation of Code: Walk through the steps (Embedding -> Projections -> Dot Product -> Softmax -> Weighted Sum).
Self-Correction/Review during drafting:
Critique: Should I use TensorFlow?
Correction: PyTorch is generally more pythonic for explaining logic flow. I'll stick with PyTorch.
Critique: Should I write it in pure Python/NumPy?
Correction: No, nobody uses pure Python for attention due to speed. PyTorch is better. However, I will add a small "pure Python/NumPy" section for educational clarity if the user wants to see the math without the deep learning framework overhead? Decision: Let's stick to PyTorch as the primary solution because it's the standard tool, but comment the math heavily.
Actually, providing a NumPy version is often requested in these types of generic prompts to prove the mechanism isn't just "library magic." I will provide a concise NumPy implementation of the core math, then the robust PyTorch class.
Final Plan:
Concept: Explain Q, K, V.
NumPy Implementation: A function demonstrating the raw mathematics (for understanding).
PyTorch Implementation: A robust nn.Module class for Multi-Head Attention (for practical use).
Testing: Code to run the PyTorch module.
Writing the Code (Mental Check of PyTorch Module):
Inputs: (Batch, Seq_Len, D_Model)
Heads: Split D_Model into Heads * D_Head.
Linear layers: nn.Linear(D_Model, D_Model) for Q, K, V.
View/Transpose to separate heads: (Batch, Seq_Len, Heads, D_Head) -> (Batch, Heads, Seq_Len, D_Head).
Attention calc.
Reshape back.
Final Linear.
Constructing the Final Output: (Proceeding to generate the response based on these steps).
Here is a complete implementation using Python.
I will provide two versions:
From Scratch (NumPy): To help you understand the underlying mathematics of attention mechanisms without the abstraction of a deep learning framework.
Production-Ready (PyTorch): A standard Multi-Head Attention implementation suitable for use in Transformer models.
1. The Concept: Query, Key, Value
Before the code, recall the analogy:
Query (Q): What token A is looking for.
Key (K): What token B defines itself as (to be matched against Q).
Value (V): The actual information token B holds.
Score: Dot product of Q and . High score = high attention.
2. Implementation from Scratch (NumPy)
This script demonstrates Scaled Dot-Product Attention. It takes a sequence of vectors (like words in a sentence) and processes them so they "attend" to each other.
import numpy as np
def softmax(x, axis=-1):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x, axis=axis, keepdims=True))
return e_x / np.sum(e_x, axis=axis, keepdims=True)
class ScaledDotProductAttention:
def __init__(self, d_model):
"""
d_model: The dimension of the input vectors (embedding size).
"""
self.d_model = d_model
# Randomly initialize weights for Q, K, V projections
# In a real scenario, these are learned via backpropagation
self.w_q = np.random.randn(d_model, d_model) * 0.1
self.w_k = np.random.randn(d_model, d_model) * 0.1
self.w_v = np.random.randn(d_model, d_model) * 0.1
def forward(self, x, mask=None):
"""
x: Input sequence of shape (Batch_Size, Seq_Len, D_Model)
mask: Optional mask to ignore certain positions (e.g., padding)
"""
# 1. Linear Projections
# Project input X into Query, Key, and Value spaces
# Shape: (Batch, Seq_Len, D_Model)
q = np.dot(x, self.w_q)
k = np.dot(x, self.w_k)
v = np.dot(x, self.w_v)
# 2. Scaled Dot-Product Calculation
# Transpose K for matrix multiplication: (Batch, D_Model, Seq_Len)
k_transposed = np.transpose(k, (0, 2, 1))
# Calculate raw attention scores: Q * K^T
# Result Shape: (Batch, Seq_Len, Seq_Len)
scores = np.matmul(q, k_transposed)
# Scale by sqrt(d_k) to prevent gradients from vanishing/exploding
d_k = self.d_model
scaled_scores = scores / np.sqrt(d_k)
# 3. Apply Masking (Optional)
# Masked positions are set to -infinity so softmax turns them to 0
if mask is not None:
scaled_scores = scaled_scores + (mask * -1e9)
# 4. Softmax
# Converts scores into probabilities (attention weights)
attention_weights = softmax(scaled_scores, axis=-1)
# 5. Weighted Sum of Values
# Multiply weights by V
# Result Shape: (Batch, Seq_Len, D_Model)
output = np.matmul(attention_weights, v)
return output, attention_weights
# --- Example Usage ---
# Parameters
batch_size = 1
seq_len = 3 # e.g., "The cat sat"
d_model = 4 # Embedding size
# Create random input (Batch, Seq_Len, D_Model)
input_sequence = np.random.randn(batch_size, seq_len, d_model)
# Initialize Attention
attention_layer = ScaledDotProductAttention(d_model)
# Run Forward Pass
output, weights = attention_layer.forward(input_sequence)
print("--- NumPy Attention Implementation ---")
print(f"Input Shape: {input_sequence.shape}")
print(f"Output Shape: {output.shape}")
print("\nAttention Weights (How much word i focuses on word j):")
print(np.round(weights[0], 3))
3. Implementation in PyTorch (Multi-Head Attention)
In production, we use Multi-Head Attention. This splits the embedding dimension into multiple "heads" so the model can focus on different types of relationships simultaneously (e.g., one head focuses on grammar, another on semantic meaning).
Here is a clean, object-oriented implementation using PyTorch.
import torch
import torch.nn as nn
import math
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads):
super(MultiHeadAttention, self).__init__()
assert d_model % num_heads == 0, "d_model must be divisible by num_heads"
self.d_model = d_model
self.num_heads = num_heads
self.d_k = d_model // num_heads # Dimension per head
# Linear layers for Q, K, V projections
self.w_q = nn.Linear(d_model, d_model)
self.w_k = nn.Linear(d_model, d_model)
self.w_v = nn.Linear(d_model, d_model)
# Output linear layer
self.fc_out = nn.Linear(d_model, d_model)
def forward(self, q, k, v, mask=None):
batch_size = q.size(0)
# 1. Linear Projections
# (Batch, Seq_Len, D_Model)
q = self.w_q(q)
k = self.w_k(k)
v = self.w_v(v)
# 2. Reshape for Multi-Head
# Split D_Model into (Num_Heads, D_K)
# New shape: (Batch, Seq_Len, Num_Heads, D_K)
q = q.view(batch_size, -1, self.num_heads, self.d_k)
k = k.view(batch_size, -1, self.num_heads, self.d_k)
v = v.view(batch_size, -1, self.num_heads, self.d_k)
# Transpose to: (Batch, Num_Heads, Seq_Len, D_K)
# This allows parallel processing of heads
q = q.transpose(1, 2)
k = k.transpose(1, 2)
v = v.transpose(1, 2)
# 3. Scaled Dot-Product Attention
# Matmul Q and K^T
scores = torch.matmul(q, k.transpose(-2, -1)) / math.sqrt(self.d_k)
# Apply mask (if provided)
if mask is not None:
# Mask is usually (Batch, 1, 1, Seq_Len) for broadcasting
scores = scores.masked_fill(mask == 0, float('-1e20'))
attention_weights = torch.softmax(scores, dim=-1)
# Apply weights to V
# Shape: (Batch, Num_Heads, Seq_Len, D_K)
out = torch.matmul(attention_weights, v)
# 4. Concatenate Heads
# Transpose back: (Batch, Seq_Len, Num_Heads, D_K)
out = out.transpose(1, 2).contiguous()
# Reshape: (Batch, Seq_Len, D_Model)
out = out.view(batch_size, -1, self.d_model)
# 5. Final Linear Layer
out = self.fc_out(out)
return out, attention_weights
# --- Example Usage ---
# Parameters
d_model = 512
num_heads = 8
seq_len = 10
batch_size = 32
# Create Dummy Input
x = torch.randn(batch_size, seq_len, d_model)
# Initialize Model
mha = MultiHeadAttention(d_model, num_heads)
# Forward Pass (Self-Attention: q, k, v are all x)
output, weights = mha(x, x, x)
print("\n--- PyTorch Multi-Head Attention ---")
print(f"Input Shape: {x.shape}")
print(f"Output Shape: {output.shape}") # Should match input
print(f"Weights Shape: {weights.shape}") # (Batch, Heads, Seq_Len, Seq_Len)
Key Differences in the Implementations
Linear Projections: Both versions project the input into Q,K,V spaces. The PyTorch version uses nn.Linear which handles weight initialization and bias automatically.
Reshaping (View/Transpose): The PyTorch version explicitly reshapes the tensor matrix to simulate "Multiple Heads". The NumPy version simulates a "Single Head" for simplicity.
Matrix Multiplication: Both rely on the dot product to determine similarity between vectors.