Attention Mechanisms: Transformers vs CNNs - Complete Code Guide
Introduction
Attention mechanisms have revolutionized deep learning by allowing models to focus on relevant parts of input data. While Transformers use self-attention as their core mechanism, CNNs incorporate attention as an enhancement to their convolutional operations.
Transformer Attention
Multi-Head Self-Attention Implementation
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class MultiHeadAttention(nn.Module):
def __init__(self, d_model, num_heads, dropout=0.1):
super().__init__()
assert d_model % num_heads == 0
self.d_model = d_model
self.num_heads = num_heads
self.d_k = d_model // num_heads
# Linear projections for Q, K, V
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)
self.w_o = nn.Linear(d_model, d_model)
self.dropout = nn.Dropout(dropout)
def scaled_dot_product_attention(self, Q, K, V, mask=None):
"""
Compute scaled dot-product attention
Args:
Q: Query matrix [batch_size, num_heads, seq_len, d_k]
K: Key matrix [batch_size, num_heads, seq_len, d_k]
V: Value matrix [batch_size, num_heads, seq_len, d_k]
mask: Optional mask [batch_size, 1, seq_len, seq_len]
"""
# Calculate attention scores
= torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)
scores
# Apply mask if provided
if mask is not None:
= scores.masked_fill(mask == 0, -1e9)
scores
# Softmax normalization
= F.softmax(scores, dim=-1)
attention_weights = self.dropout(attention_weights)
attention_weights
# Apply attention to values
= torch.matmul(attention_weights, V)
output
return output, attention_weights
def forward(self, query, key, value, mask=None):
= query.size(0), query.size(1)
batch_size, seq_len
# Linear projections and reshape for multi-head
= self.w_q(query).view(batch_size, seq_len, self.num_heads, self.d_k).transpose(1, 2)
Q = self.w_k(key).view(batch_size, seq_len, self.num_heads, self.d_k).transpose(1, 2)
K = self.w_v(value).view(batch_size, seq_len, self.num_heads, self.d_k).transpose(1, 2)
V
# Apply attention
= self.scaled_dot_product_attention(Q, K, V, mask)
attention_output, attention_weights
# Concatenate heads
= attention_output.transpose(1, 2).contiguous().view(
attention_output self.d_model
batch_size, seq_len,
)
# Final linear projection
= self.w_o(attention_output)
output
return output, attention_weights
# Complete Transformer Block
class TransformerBlock(nn.Module):
def __init__(self, d_model, num_heads, d_ff, dropout=0.1):
super().__init__()
self.attention = MultiHeadAttention(d_model, num_heads, dropout)
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
self.feed_forward = nn.Sequential(
nn.Linear(d_model, d_ff),
nn.ReLU(),
nn.Dropout(dropout),
nn.Linear(d_ff, d_model)
)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
# Self-attention with residual connection
= self.attention(x, x, x, mask)
attn_output, attn_weights = self.norm1(x + self.dropout(attn_output))
x
# Feed-forward with residual connection
= self.feed_forward(x)
ff_output = self.norm2(x + self.dropout(ff_output))
x
return x, attn_weights
# Example usage
def transformer_example():
= 2, 10, 512
batch_size, seq_len, d_model = 8, 2048
num_heads, d_ff
# Create input
= torch.randn(batch_size, seq_len, d_model)
x
# Create transformer block
= TransformerBlock(d_model, num_heads, d_ff)
transformer
# Forward pass
= transformer(x)
output, attention_weights
print(f"Input shape: {x.shape}")
print(f"Output shape: {output.shape}")
print(f"Attention weights shape: {attention_weights.shape}")
return output, attention_weights
Positional Encoding for Transformers
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=5000):
super().__init__()
= torch.zeros(max_len, d_model)
pe = torch.arange(0, max_len).unsqueeze(1).float()
position
= torch.exp(torch.arange(0, d_model, 2).float() *
div_term -(math.log(10000.0) / d_model))
0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe[:,
self.register_buffer('pe', pe.unsqueeze(0))
def forward(self, x):
return x + self.pe[:, :x.size(1)]
CNN Attention
Spatial Attention Mechanism
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super().__init__()
self.conv = nn.Conv2d(2, 1, kernel_size, padding=kernel_size//2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
# Compute spatial statistics
= torch.mean(x, dim=1, keepdim=True) # [B, 1, H, W]
avg_pool = torch.max(x, dim=1, keepdim=True) # [B, 1, H, W]
max_pool, _
# Concatenate along channel dimension
= torch.cat([avg_pool, max_pool], dim=1) # [B, 2, H, W]
spatial_info
# Generate attention map
= self.conv(spatial_info) # [B, 1, H, W]
attention_map = self.sigmoid(attention_map)
attention_map
# Apply attention
return x * attention_map
class ChannelAttention(nn.Module):
def __init__(self, in_channels, reduction_ratio=16):
super().__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.fc = nn.Sequential(
// reduction_ratio, bias=False),
nn.Linear(in_channels, in_channels
nn.ReLU(),// reduction_ratio, in_channels, bias=False)
nn.Linear(in_channels
)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
= x.size()
b, c, h, w
# Global average pooling and max pooling
= self.avg_pool(x).view(b, c)
avg_pool = self.max_pool(x).view(b, c)
max_pool
# Channel attention
= self.fc(avg_pool)
avg_out = self.fc(max_pool)
max_out
# Combine and apply sigmoid
= self.sigmoid(avg_out + max_out).view(b, c, 1, 1)
channel_attention
return x * channel_attention
# CBAM (Convolutional Block Attention Module)
class CBAM(nn.Module):
def __init__(self, in_channels, reduction_ratio=16, kernel_size=7):
super().__init__()
self.channel_attention = ChannelAttention(in_channels, reduction_ratio)
self.spatial_attention = SpatialAttention(kernel_size)
def forward(self, x):
# Apply channel attention first
= self.channel_attention(x)
x # Then apply spatial attention
= self.spatial_attention(x)
x return x
# Self-Attention for CNNs
class SelfAttention2D(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.in_channels = in_channels
self.query_conv = nn.Conv2d(in_channels, in_channels // 8, 1)
self.key_conv = nn.Conv2d(in_channels, in_channels // 8, 1)
self.value_conv = nn.Conv2d(in_channels, in_channels, 1)
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=-1)
def forward(self, x):
= x.size()
batch_size, channels, height, width
# Generate Q, K, V
= self.query_conv(x).view(batch_size, -1, width * height).permute(0, 2, 1)
proj_query = self.key_conv(x).view(batch_size, -1, width * height)
proj_key = self.value_conv(x).view(batch_size, -1, width * height)
proj_value
# Compute attention
= torch.bmm(proj_query, proj_key)
energy = self.softmax(energy)
attention
# Apply attention to values
= torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(batch_size, channels, height, width)
out
# Residual connection with learnable weight
= self.gamma * out + x
out
return out
# CNN with Attention
class AttentionCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.conv1 = nn.Conv2d(3, 64, 3, padding=1)
self.cbam1 = CBAM(64)
self.conv2 = nn.Conv2d(64, 128, 3, padding=1)
self.cbam2 = CBAM(128)
self.conv3 = nn.Conv2d(128, 256, 3, padding=1)
self.self_attention = SelfAttention2D(256)
self.pool = nn.AdaptiveAvgPool2d(1)
self.classifier = nn.Linear(256, num_classes)
def forward(self, x):
# First block
= F.relu(self.conv1(x))
x = self.cbam1(x)
x = F.max_pool2d(x, 2)
x
# Second block
= F.relu(self.conv2(x))
x = self.cbam2(x)
x = F.max_pool2d(x, 2)
x
# Third block with self-attention
= F.relu(self.conv3(x))
x = self.self_attention(x)
x = F.max_pool2d(x, 2)
x
# Classification
= self.pool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
x
return x
# Example usage
def cnn_attention_example():
= 4
batch_size = torch.randn(batch_size, 3, 224, 224)
x
= AttentionCNN(num_classes=1000)
model = model(x)
output
print(f"Input shape: {x.shape}")
print(f"Output shape: {output.shape}")
return output
Key Differences
1. Computational Complexity
def attention_complexity_comparison():
"""
Compare computational complexity of different attention mechanisms
"""
# Transformer Self-Attention: O(n²d) where n=sequence length, d=dimension
def transformer_complexity(seq_len, d_model):
return seq_len * seq_len * d_model
# CNN Spatial Attention: O(HW) where H=height, W=width
def spatial_attention_complexity(height, width):
return height * width
# CNN Channel Attention: O(C) where C=channels
def channel_attention_complexity(channels):
return channels
# Example calculations
= 512, 512
seq_len, d_model = 224, 224, 256
height, width, channels
= transformer_complexity(seq_len, d_model)
transformer_ops = spatial_attention_complexity(height, width)
spatial_ops = channel_attention_complexity(channels)
channel_ops
print(f"Transformer attention operations: {transformer_ops:,}")
print(f"CNN spatial attention operations: {spatial_ops:,}")
print(f"CNN channel attention operations: {channel_ops:,}")
return {
'transformer': transformer_ops,
'spatial': spatial_ops,
'channel': channel_ops
}
2. Information Flow Patterns
class AttentionAnalysis:
@staticmethod
def analyze_transformer_attention(attention_weights):
"""
Analyze attention patterns in Transformers
Args:
attention_weights: [batch_size, num_heads, seq_len, seq_len]
"""
= attention_weights.shape
batch_size, num_heads, seq_len, _
# Average attention across heads
= attention_weights.mean(dim=1) # [batch_size, seq_len, seq_len]
avg_attention
# Compute attention statistics
= avg_attention.max(dim=-1)[0] # Max attention per position
max_attention = -torch.sum(avg_attention * torch.log(avg_attention + 1e-8), dim=-1)
attention_entropy
return {
'max_attention': max_attention,
'attention_entropy': attention_entropy,
'global_connectivity': True, # All positions can attend to all others
'pattern': 'sequence-to-sequence'
}
@staticmethod
def analyze_cnn_attention(feature_map, attention_map):
"""
Analyze attention patterns in CNNs
Args:
feature_map: [batch_size, channels, height, width]
attention_map: [batch_size, 1, height, width] or [batch_size, channels, 1, 1]
"""
if attention_map.dim() == 4 and attention_map.size(2) == 1:
# Channel attention
= 'channel'
attention_type = False
local_connectivity else:
# Spatial attention
= 'spatial'
attention_type = True
local_connectivity
return {
'attention_type': attention_type,
'local_connectivity': local_connectivity,
'pattern': 'spatial-hierarchy' if attention_type == 'spatial' else 'channel-selection'
}
Performance Comparison
import time
import torch.nn.functional as F
class PerformanceBenchmark:
def __init__(self):
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def benchmark_transformer_attention(self, batch_size=32, seq_len=512, d_model=512, num_heads=8):
"""Benchmark Transformer attention"""
= MultiHeadAttention(d_model, num_heads).to(self.device)
model = torch.randn(batch_size, seq_len, d_model).to(self.device)
x
# Warmup
for _ in range(10):
= model(x, x, x)
_
# Benchmark
if torch.cuda.is_available() else None
torch.cuda.synchronize() = time.time()
start_time
for _ in range(100):
= model(x, x, x)
output, _
if torch.cuda.is_available() else None
torch.cuda.synchronize() = time.time()
end_time
return (end_time - start_time) / 100
def benchmark_cnn_attention(self, batch_size=32, channels=256, height=56, width=56):
"""Benchmark CNN attention"""
= CBAM(channels).to(self.device)
model = torch.randn(batch_size, channels, height, width).to(self.device)
x
# Warmup
for _ in range(10):
= model(x)
_
# Benchmark
if torch.cuda.is_available() else None
torch.cuda.synchronize() = time.time()
start_time
for _ in range(100):
= model(x)
output
if torch.cuda.is_available() else None
torch.cuda.synchronize() = time.time()
end_time
return (end_time - start_time) / 100
def run_comparison(self):
"""Run performance comparison"""
= self.benchmark_transformer_attention()
transformer_time = self.benchmark_cnn_attention()
cnn_time
print(f"Transformer attention time: {transformer_time:.4f}s")
print(f"CNN attention time: {cnn_time:.4f}s")
print(f"Speedup: {transformer_time/cnn_time:.2f}x")
return {
'transformer_time': transformer_time,
'cnn_time': cnn_time,
'speedup': transformer_time/cnn_time
}
# Memory usage comparison
def memory_comparison():
"""Compare memory usage of different attention mechanisms"""
def get_memory_usage():
if torch.cuda.is_available():
return torch.cuda.memory_allocated() / 1024**2 # MB
return 0
# Clear memory
if torch.cuda.is_available() else None
torch.cuda.empty_cache()
# Transformer attention
= MultiHeadAttention(512, 8)
transformer_model = torch.randn(32, 512, 512)
x
if torch.cuda.is_available():
= transformer_model.cuda()
transformer_model = x.cuda()
x
= get_memory_usage()
transformer_memory = transformer_model(x, x, x)
_, _ = get_memory_usage() - transformer_memory
transformer_memory
# Clear memory
del transformer_model, x
if torch.cuda.is_available() else None
torch.cuda.empty_cache()
# CNN attention
= CBAM(256)
cnn_model = torch.randn(32, 256, 56, 56)
x
if torch.cuda.is_available():
= cnn_model.cuda()
cnn_model = x.cuda()
x
= get_memory_usage()
cnn_memory = cnn_model(x)
_ = get_memory_usage() - cnn_memory
cnn_memory
print(f"Transformer attention memory: {transformer_memory:.2f} MB")
print(f"CNN attention memory: {cnn_memory:.2f} MB")
return {
'transformer_memory': transformer_memory,
'cnn_memory': cnn_memory
}
When to Use Each
Decision Framework
class AttentionSelector:
@staticmethod
def recommend_attention_type(data_type, sequence_length=None, spatial_dims=None,
='medium', task_type='classification'):
computational_budget"""
Recommend attention mechanism based on requirements
Args:
data_type: 'sequential', 'spatial', 'mixed'
sequence_length: Length of sequences (for sequential data)
spatial_dims: (height, width) for spatial data
computational_budget: 'low', 'medium', 'high'
task_type: 'classification', 'generation', 'detection'
"""
= []
recommendations
# Sequential data
if data_type == 'sequential':
if sequence_length and sequence_length > 1000 and computational_budget == 'low':
recommendations.append({'type': 'Local Attention',
'reason': 'Long sequences with limited compute',
'implementation': 'sliding_window_attention'
})else:
recommendations.append({'type': 'Transformer Self-Attention',
'reason': 'Global context modeling for sequences',
'implementation': 'MultiHeadAttention'
})
# Spatial data
elif data_type == 'spatial':
if spatial_dims and spatial_dims[0] * spatial_dims[1] > 224 * 224:
recommendations.append({'type': 'CNN Spatial + Channel Attention',
'reason': 'High-resolution spatial data',
'implementation': 'CBAM'
})else:
recommendations.append({'type': 'CNN Self-Attention',
'reason': 'Moderate resolution with global context',
'implementation': 'SelfAttention2D'
})
# Mixed data
elif data_type == 'mixed':
recommendations.append({'type': 'Hybrid Attention',
'reason': 'Combined sequential and spatial processing',
'implementation': 'transformer_cnn_hybrid'
})
return recommendations
@staticmethod
def create_hybrid_model(input_shape, num_classes):
"""Create a hybrid model combining both attention types"""
class HybridAttentionModel(nn.Module):
def __init__(self, input_shape, num_classes):
super().__init__()
# CNN backbone with attention
self.cnn_backbone = nn.Sequential(
0], 64, 3, padding=1),
nn.Conv2d(input_shape[
nn.ReLU(),64),
CBAM(2),
nn.MaxPool2d(
64, 128, 3, padding=1),
nn.Conv2d(
nn.ReLU(),128),
CBAM(2),
nn.MaxPool2d(
128, 256, 3, padding=1),
nn.Conv2d(
nn.ReLU(),256)
SelfAttention2D(
)
# Flatten and prepare for transformer
self.flatten = nn.AdaptiveAvgPool2d(8) # 8x8 spatial grid
self.embed_dim = 256
# Transformer layers
self.transformer = nn.Sequential(
*[TransformerBlock(self.embed_dim, 8, 1024) for _ in range(3)]
)
# Classification head
self.classifier = nn.Linear(self.embed_dim, num_classes)
def forward(self, x):
# CNN processing
= self.cnn_backbone(x)
x
# Reshape for transformer
= x.size(0)
batch_size = self.flatten(x) # [B, 256, 8, 8]
x = x.flatten(2).transpose(1, 2) # [B, 64, 256]
x
# Transformer processing
for transformer_block in self.transformer:
= transformer_block(x)
x, _
# Global average pooling and classification
= x.mean(dim=1) # [B, 256]
x = self.classifier(x)
x
return x
return HybridAttentionModel(input_shape, num_classes)
# Usage examples
def usage_examples():
"""Demonstrate when to use each attention type"""
= AttentionSelector()
selector
# Example 1: NLP task
= selector.recommend_attention_type(
nlp_rec ='sequential',
data_type=512,
sequence_length='high',
computational_budget='generation'
task_type
)
# Example 2: Computer Vision task
= selector.recommend_attention_type(
cv_rec ='spatial',
data_type=(224, 224),
spatial_dims='medium',
computational_budget='classification'
task_type
)
# Example 3: Video analysis
= selector.recommend_attention_type(
video_rec ='mixed',
data_type=30,
sequence_length=(112, 112),
spatial_dims='high',
computational_budget='detection'
task_type
)
print("NLP Recommendation:", nlp_rec)
print("Computer Vision Recommendation:", cv_rec)
print("Video Analysis Recommendation:", video_rec)
return nlp_rec, cv_rec, video_rec
Summary
Aspect | Transformer Attention | CNN Attention |
---|---|---|
Scope | Global, all-to-all | Local, spatial/channel-wise |
Complexity | O(n²) | O(HW) or O(C) |
Best For | Sequential data, language | Spatial data, images |
Memory | High | Moderate |
Parallelization | Limited by sequence length | Highly parallelizable |
Interpretability | Attention weights show relationships | Spatial/channel importance maps |
Choose Transformer attention for tasks requiring global context modeling, and CNN attention for spatially-structured data where local relationships dominate. Consider hybrid approaches for complex multi-modal tasks.