Transformer Networks

Learn transformer networks with interactive simulations. Understand attention mechanisms, self-attention, and transformer architectures through hands-on visualizations and real-world examples.

Attention Mechanism Encoder Layers Decoder Layers Self-Attention Multi-Head Attention Residual Connections Visualizations

What are Transformer Networks?

Transformer networks are a type of deep learning architecture introduced in the paper "Attention Is btn-info-custom You Need" that relies entirely on attention mechanisms to draw global dependencies between input and output sequences. Unlike traditional recurrent or convolutional architectures, transformers process sequences in parallel, making them highly efficient for tasks like machine translation, text summarization, and language understanding.

Key Benefits

  • Parallel Processing: Process entire sequences simultaneously instead of sequentially
  • Global Dependencies: Capture long-range dependencies without vanishing gradients
  • Scalability: Highly parallelizable architecture for large-scale training
  • Versatility: Applicable to various sequence tasks beyond NLP
  • Interpretability: Attention weights provide insights into model decisions

Common Applications

  • Machine translation and language modeling
  • Text summarization and question answering
  • Image captioning and vision tasks
  • Speech recognition and generation
  • Protein structure prediction and bioinformatics
Parallel Processing
Global Attention
Scalable Architecture
State-of-the-Art

Transformer Architecture Overview

Input Embedding

Convert input tokens into dense vector representations with positional encoding.

  • • Token embeddings
  • • Positional encodings
  • • Sequence processing
  • • Input representation

Attention Layers

Multi-head self-attention mechanism to capture dependencies between tokens.

  • • Scaled dot-product attention
  • • Multi-head attention
  • • Query-Key-Value computation
  • • Contextual representations

Feed-Forward Networks

Position-wise fully connected networks for feature transformation.

  • • Linear transformations
  • • Non-linear activation
  • • Residual connections
  • • Layer normalization

Transformer Networks Simulation

Visualize how transformer networks process sequences with attention mechanisms. Adjust parameters and see how attention weights change!

80%
50%
8
Tokens
4
Attention Heads
0.85
Avg Attention
0ms
Processing Time
How to use:
  • Select a transformer component to visualize
  • Adjust sequence length and attention heads parameters
  • Click "New Sequence" to generate sample data
  • Click "Run Simulation" to see how attention mechanisms work
  • Try different components to understand the full architecture

Attention Weights Visualization

Self-Attention Mechanism

Scaled Dot-Product Attention:

1
Input Transformation

Transform input embeddings into Query (Q), Key (K), and Value (V) representations using learned weight matrices

2
Attention Scores

Compute attention scores by taking dot product of Q and K matrices, then scale by square root of dimension

3
Softmax Normalization

Apply softmax to obtain attention weights that sum to 1 for each position

4
Weighted Sum

Multiply attention weights with Value matrix to produce context-aware representations

Mathematical Formula:

Attention(Q, K, V) = softmax(QKT/√dk)V

Where dk is the dimension of the key vectors

Time Complexity:

O(n² × d) where:
  • n = sequence length
  • d = embedding dimension

Advantages & Disadvantages:

Advantages
  • Global dependencies captured in parallel
  • No vanishing gradient problems
  • Interpretable attention weights
  • Computational efficiency for long sequences
Disadvantages
  • Quadratic memory complexity in sequence length
  • Limited inductive bias for sequential data
  • Requires large amounts of training data
  • Computationally expensive for very long sequences

Other Transformer Components

Description: Run multiple attention functions in parallel to capture different types of relationships between tokens.

Process: Each head learns different attention patterns, and their outputs are concatenated and linearly transformed.

Benefits: Allows the model to jointly attend to information from different representation subspaces at different positions.

Description: Inject information about the relative or absolute position of tokens in the sequence.

Implementation: Use sine and cosine functions of different frequencies to create unique position representations.

Purpose: Compensate for the lack of recurrence and convolution in the model architecture.

Description: Apply fully connected networks independently to each position in the sequence.

Structure: Two linear transformations with a ReLU activation in between.

Parameters: Same weights applied at each position but different across layers.

Description: Add residual connections around each sub-layer and apply layer normalization.

Formula: LayerNorm(x + Sublayer(x))

Benefits: Enable training of deep networks by mitigating gradient vanishing problems.

Advanced Transformer Simulations

Encoder-Decoder Attention

Visualize how decoder attends to encoder outputs in sequence-to-sequence tasks.

BERT Pre-training

Understand masked language modeling and next sentence prediction tasks.

GPT Autoregressive Modeling

Visualize how GPT models generate text through autoregressive prediction.

Vision Transformers

See how transformers can be applied to image processing tasks.

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 # For simplicity, d_k = embedding_dim # Initialize weight matrices for Q, K, V 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): # X shape: (sequence_length, embedding_dim) # Compute Q, K, V matrices Q = np.dot(X, self.W_Q) # (sequence_length, embedding_dim) K = np.dot(X, self.W_K) # (sequence_length, embedding_dim) V = np.dot(X, self.W_V) # (sequence_length, embedding_dim) # Compute attention scores scores = np.dot(Q, K.T) / np.sqrt(self.d_k) # (sequence_length, sequence_length) # Apply softmax to get attention weights attention_weights = self.softmax(scores) # (sequence_length, sequence_length) # Compute weighted sum output = np.dot(attention_weights, V) # (sequence_length, embedding_dim) 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) # Generate sample data np.random.seed(42) sequence_length = 5 embedding_dim = 4 # Create sample sequence embeddings X = np.random.randn(sequence_length, embedding_dim) # Initialize and run self-attention 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) # Visualize attention weights 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" # Linear projections for Q, K, V 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) # Output projection self.out_linear = nn.Linear(embedding_dim, embedding_dim) def forward(self, query, key, value, mask=None): batch_size = query.size(0) # Linear projections Q = self.q_linear(query) # (batch_size, seq_len, embedding_dim) K = self.k_linear(key) # (batch_size, seq_len, embedding_dim) V = self.v_linear(value) # (batch_size, seq_len, embedding_dim) # Split into multiple heads 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) # Scaled dot-product attention 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) # Apply attention weights to values context = torch.matmul(attention_weights, V) # (batch_size, num_heads, seq_len, head_dim) # Concatenate heads context = context.transpose(1, 2).contiguous().view(batch_size, -1, self.embedding_dim) # Output projection output = self.out_linear(context) return output, attention_weights # Example usage embedding_dim = 512 num_heads = 8 sequence_length = 10 batch_size = 32 # Create sample data 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) # Initialize and run multi-head attention 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}") # Visualize attention weights for first head of first batch 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): # Self-attention with residual connection attn_output, _ = self.attention(x, x, x, mask) x = self.norm1(x + self.dropout(attn_output)) # Feed-forward with residual connection 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) # Example usage embedding_dim = 512 num_heads = 8 hidden_dim = 2048 num_layers = 6 sequence_length = 50 batch_size = 16 # Create sample data x = torch.randn(sequence_length, batch_size, embedding_dim) # Add positional encoding pos_encoding = PositionalEncoding(embedding_dim) x = pos_encoding(x) # Initialize and run transformer encoder 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}")

Test Your Knowledge

Answer these questions to test your understanding of transformer networks concepts.

Question 1: What is the primary advantage of self-attention over recurrent neural networks?
A) Ability to capture long-range dependencies in parallel
B) Lower computational complexity for btn-info-custom sequence lengths
C) Better performance on small datasets
D) Simpler implementation
Question 2: In the scaled dot-product attention formula, why is the dot product scaled by √d_k?
A) To reduce computational complexity
B) To prevent the softmax function from entering regions with extremely small gradients
C) To normalize the attention weights
D) To make the attention weights sum to 1
Question 3: What is the purpose of multi-head attention in transformers?
A) To reduce the number of parameters in the model
B) To speed up training time
C) To allow the model to jointly attend to information from different representation subspaces
D) To reduce memory usage
Question 4: How does positional encoding work in transformers?
A) By adding sine and cosine functions of different frequencies to the input embeddings
B) By using recurrent connections to maintain position information
C) By training separate position embeddings for each position
D) By sorting the input tokens by their positions
Question 5: What is the main difference between BERT and GPT architectures?
A) BERT uses convolutional layers while GPT uses recurrent layers
B) BERT uses bidirectional attention while GPT uses autoregressive (causal) attention
C) BERT is designed for text generation while GPT is designed for text classification
D) BERT uses fewer parameters than GPT
Question 6: What is the time complexity of self-attention with respect to sequence length?
A) O(n)
B) O(n log n)
C) O(n²)
D) O(n³)