Python Implementation
Self-Attention Implementation with NumPy
import numpy as np
import matplotlib.pyplot as plt
class SelfAttention:
def __init__(self, embedding_dim, sequence_length):
self.embedding_dim = embedding_dim
self.sequence_length = sequence_length
self.d_k = embedding_dim
self.W_Q = np.random.randn(embedding_dim, embedding_dim) * 0.1
self.W_K = np.random.randn(embedding_dim, embedding_dim) * 0.1
self.W_V = np.random.randn(embedding_dim, embedding_dim) * 0.1
def forward(self, X):
Q = np.dot(X, self.W_Q)
K = np.dot(X, self.W_K)
V = np.dot(X, self.W_V)
scores = np.dot(Q, K.T) / np.sqrt(self.d_k)
attention_weights = self.softmax(scores)
output = np.dot(attention_weights, V)
return output, attention_weights
def softmax(self, x):
exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
return exp_x / np.sum(exp_x, axis=1, keepdims=True)
np.random.seed(42)
sequence_length = 5
embedding_dim = 4
X = np.random.randn(sequence_length, embedding_dim)
attention = SelfAttention(embedding_dim, sequence_length)
output, weights = attention.forward(X)
print("Input sequence embeddings:")
print(X)
print("\nAttention weights:")
print(weights)
print("\nOutput after attention:")
print(output)
plt.figure(figsize=(8, 6))
plt.imshow(weights, cmap='viridis', aspect='auto')
plt.colorbar()
plt.title('Self-Attention Weights')
plt.xlabel('Key Positions')
plt.ylabel('Query Positions')
plt.xticks(range(sequence_length), [f'Token {i}' for i in range(sequence_length)])
plt.yticks(range(sequence_length), [f'Token {i}' for i in range(sequence_length)])
for i in range(sequence_length):
for j in range(sequence_length):
plt.text(j, i, f'{weights[i, j]:.2f}',
ha='center', va='center', color='white')
plt.show()
Multi-Head Attention with PyTorch
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
class MultiHeadAttention(nn.Module):
def __init__(self, embedding_dim, num_heads, dropout=0.1):
super(MultiHeadAttention, self).__init__()
self.embedding_dim = embedding_dim
self.num_heads = num_heads
self.head_dim = embedding_dim
self.dropout = nn.Dropout(dropout)
assert embedding_dim % num_heads == 0, "embedding_dim must be divisible by num_heads"
self.q_linear = nn.Linear(embedding_dim, embedding_dim)
self.k_linear = nn.Linear(embedding_dim, embedding_dim)
self.v_linear = nn.Linear(embedding_dim, embedding_dim)
self.out_linear = nn.Linear(embedding_dim, embedding_dim)
def forward(self, query, key, value, mask=None):
batch_size = query.size(0)
Q = self.q_linear(query)
K = self.k_linear(key)
V = self.v_linear(value)
Q = Q.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
K = K.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
V = V.view(batch_size, -1, self.num_heads, self.head_dim).transpose(1, 2)
scores = torch.matmul(Q, K.transpose(-2, -1)) / torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32))
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e9)
attention_weights = F.softmax(scores, dim=-1)
attention_weights = self.dropout(attention_weights)
context = torch.matmul(attention_weights, V)
context = context.transpose(1, 2).contiguous().view(batch_size, -1, self.embedding_dim)
output = self.out_linear(context)
return output, attention_weights
embedding_dim = 512
num_heads = 8
sequence_length = 10
batch_size = 32
query = torch.randn(batch_size, sequence_length, embedding_dim)
key = torch.randn(batch_size, sequence_length, embedding_dim)
value = torch.randn(batch_size, sequence_length, embedding_dim)
multihead_attn = MultiHeadAttention(embedding_dim, num_heads)
output, attention_weights = multihead_attn(query, key, value)
print(f"Input shape: {query.shape}")
print(f"Output shape: {output.shape}")
print(f"Attention weights shape: {attention_weights.shape}")
plt.figure(figsize=(10, 8))
first_head_weights = attention_weights[0, 0].detach().numpy()
plt.imshow(first_head_weights, cmap='viridis', aspect='auto')
plt.colorbar()
plt.title('Multi-Head Attention - First Head')
plt.xlabel('Key Positions')
plt.ylabel('Query Positions')
plt.show()
Complete Transformer Block Implementation
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class PositionalEncoding(nn.Module):
def __init__(self, embedding_dim, max_len=5000):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, embedding_dim)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, embedding_dim, 2).float() *
(-(math.log(10000.0) / embedding_dim)))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer('pe', pe)
def forward(self, x):
x = x + self.pe[:x.size(0), :]
return x
class FeedForward(nn.Module):
def __init__(self, embedding_dim, hidden_dim, dropout=0.1):
super(FeedForward, self).__init__()
self.linear1 = nn.Linear(embedding_dim, hidden_dim)
self.dropout = nn.Dropout(dropout)
self.linear2 = nn.Linear(hidden_dim, embedding_dim)
def forward(self, x):
return self.linear2(self.dropout(F.relu(self.linear1(x))))
class TransformerBlock(nn.Module):
def __init__(self, embedding_dim, num_heads, hidden_dim, dropout=0.1):
super(TransformerBlock, self).__init__()
self.attention = MultiHeadAttention(embedding_dim, num_heads, dropout)
self.norm1 = nn.LayerNorm(embedding_dim)
self.norm2 = nn.LayerNorm(embedding_dim)
self.feed_forward = FeedForward(embedding_dim, hidden_dim, dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, x, mask=None):
attn_output, _ = self.attention(x, x, x, mask)
x = self.norm1(x + self.dropout(attn_output))
ff_output = self.feed_forward(x)
x = self.norm2(x + self.dropout(ff_output))
return x
class TransformerEncoder(nn.Module):
def __init__(self, num_layers, embedding_dim, num_heads, hidden_dim, dropout=0.1):
super(TransformerEncoder, self).__init__()
self.layers = nn.ModuleList([
TransformerBlock(embedding_dim, num_heads, hidden_dim, dropout)
for _ in range(num_layers)
])
self.norm = nn.LayerNorm(embedding_dim)
def forward(self, x, mask=None):
for layer in self.layers:
x = layer(x, mask)
return self.norm(x)
embedding_dim = 512
num_heads = 8
hidden_dim = 2048
num_layers = 6
sequence_length = 50
batch_size = 16
x = torch.randn(sequence_length, batch_size, embedding_dim)
pos_encoding = PositionalEncoding(embedding_dim)
x = pos_encoding(x)
encoder = TransformerEncoder(num_layers, embedding_dim, num_heads, hidden_dim)
output = encoder(x)
print(f"Input shape: {x.shape}")
print(f"Output shape: {output.shape}")