Transformers & Self-Attention: Simple Complete Guide
Introduced in the landmark 2017 research paper Attention Is All You Need, the Transformer architecture reshaped artificial intelligence. It powers modern Large Language Models (LLMs), machine translation systems, code-generation tools, and many image and audio models.
Before Transformers, architectures such as RNNs, LSTMs, and GRUs processed sequences step by step. This made parallel training difficult and created challenges when learning long-range dependencies.
Transformers introduced a powerful alternative: Self-Attention.
Instead of relying on a recurrent hidden state, self-attention allows each token to gather relevant information from other tokens in a sequence.
Transformers can process sequence positions in parallel during training, making them highly effective for large-scale deep learning.
Let's understand how Transformers work, explore their architecture and mathematical foundations, and implement self-attention using Python and PyTorch.
1. What Is a Transformer?
A Transformer is a neural network architecture designed to process sequential and structured data using attention mechanisms rather than recurrent connections.
It is widely used for:
- Natural Language Processing (NLP)
- Machine translation
- Text generation
- Question answering
- Code generation
- Image understanding
- Speech and audio processing
Consider this sentence:
"The student placed the book on the table because it was heavy."
To understand the word "it", a model needs to identify which earlier word it refers to.
A Transformer uses self-attention to calculate relationships between tokens and build contextual representations.
Unlike a traditional RNN, a Transformer does not need to update one recurrent hidden state after another.
Important: Transformers can process input positions in parallel during training. However, autoregressive language models generally generate new tokens sequentially during inference because each generated token depends on the previous ones.
2. How Self-Attention Works (In Plain Language)
Self-Attention is the mechanism that allows a model to determine how much information each token should gather from other tokens in the same sequence.
Consider these two sentences:
- "The animal didn't cross the street because it was too tired."
- "The animal didn't cross the street because it was too wide."
The word "it" has different meanings in these sentences.
- In sentence 1, "it" refers to the animal.
- In sentence 2, "it" refers to the street.
Self-attention helps a model learn these contextual relationships.
2.1 Query, Key, and Value (Q, K, V)
To calculate attention, a Transformer creates three representations for each input token:
Query (Q): What information is this token looking for?
Key (K): What information does this token offer for matching?
Value (V): What information should be passed along if this token receives attention?
Think of a search engine:
- Query represents the search request.
- Key represents the information used to match a result.
- Value represents the content retrieved from that result.
The model learns these representations through trainable weight matrices.
For an input representation \(X\):
\[ Q=XW_Q \]
\[ K=XW_K \]
\[ V=XW_V \]
Where:
- \(X\) = Input token representations
- \(W_Q\) = Query projection matrix
- \(W_K\) = Key projection matrix
- \(W_V\) = Value projection matrix
These matrices are learned during model training.
2.2 The Three Steps of Attention
Self-attention works through three main operations.
Step 1: Calculate Attention Scores
The model compares each Query with the Keys of all relevant tokens.
\[ S=QK^T \]
A higher score indicates a stronger compatibility between a query and a key.
Step 2: Scale and Normalize the Scores
The scores are divided by the square root of the key dimension:
\[ S_{\text{scaled}}= \frac{QK^T}{\sqrt{d_k}} \]
Then Softmax converts the scores into attention weights:
\[ A=\operatorname{softmax} \left(\frac{QK^T}{\sqrt{d_k}}\right) \]
For each query position, the attention weights sum to 1 across the allowed key positions.
Step 3: Combine the Values
The model multiplies the attention weights by the Value matrix:
\[ Z=AV \]
The final result is a context-aware representation of each token.
The complete scaled dot-product attention equation is:
\[ \boxed{ \operatorname{Attention}(Q,K,V)= \operatorname{softmax} \left(\frac{QK^T}{\sqrt{d_k}}\right)V } \]
2.3 Why Divide by \(\sqrt{d_k}\)?
When the Query and Key dimensions become large, their dot products can also become large.
Large attention scores can cause Softmax to produce extremely concentrated probabilities, resulting in weaker gradients.
Dividing by \(\sqrt{d_k}\) helps control the scale of these scores and supports stable training.
3. A Simple Numerical Example of Self-Attention
Suppose a token has attention scores for three other tokens:
\[ S=[2,1,0] \]
Applying Softmax:
\[ \operatorname{softmax}(S) \approx[0.665,0.245,0.090] \]
This means the token assigns approximately:
| Token | Attention Weight |
|---|---|
| Token 1 | 66.5% |
| Token 2 | 24.5% |
| Token 3 | 9.0% |
The model then uses these weights to combine the corresponding Value vectors.
For example, if the three Value vectors are:
\[ V_1=[1,0] \]
\[ V_2=[0,1] \]
\[ V_3=[1,1] \]
The resulting context vector is:
\[ Z=0.665V_1+0.245V_2+0.090V_3 \]
\[ Z=[0.755,0.335] \]
This is a simplified numerical illustration. Real Transformers calculate attention using learned, high-dimensional vectors across many tokens and attention heads.
4. Multi-Head Attention: Looking at Different Relationships
A single attention operation can learn relationships between tokens, but different types of relationships may be useful at the same time.
For example, consider:
"The boy kicked the ball because he was excited."
Different attention heads may learn to focus on:
- Relationships between pronouns and nouns.
- Relationships between verbs and their subjects.
- Relationships between nearby words.
- Relationships between distant words.
This is the motivation behind Multi-Head Attention.
Instead of calculating attention once, the model performs several attention operations using separate learned projections.
For each head:
\[ \text{head}_i= \operatorname{Attention} (QW_i^Q,KW_i^K,VW_i^V) \]
The individual heads are concatenated:
\[ \operatorname{MultiHead}(Q,K,V)= \operatorname{Concat}(\text{head}_1,\ldots,\text{head}_h)W^O \]
Where:
- \(h\) = Number of attention heads.
- \(W_i^Q,W_i^K,W_i^V\) = Learned projection matrices for head \(i\).
- \(W^O\) = Output projection matrix.
Example
Suppose the model has:
- Embedding dimension = 512
- Attention heads = 8
Each head commonly uses:
\[ d_k=d_v=\frac{512}{8}=64 \]
The eight heads process different learned projections of the input representation.
Their outputs are combined into a representation with dimension 512.
Why is Multi-Head Attention useful?
- It allows different attention patterns to be learned.
- It captures multiple relationships between tokens.
- It provides richer contextual representations.
- It improves the model's ability to represent complex sequence relationships.
5. Positional Encoding: Understanding Word Order
Self-attention does not inherently know the order in which tokens appear.
For example:
"Dog bites man."
"Man bites dog."
The same words appear, but their order changes the meaning.
A Transformer therefore needs information about token positions.
This is achieved using Positional Encoding or positional embeddings.
5.1 Original Sinusoidal Positional Encoding
The original Transformer used sine and cosine functions to generate positional representations.
The equations are:
\[ PE(pos,2i)= \sin\left( \frac{pos}{10000^{2i/d_{\text{model}}}} \right) \]
\[ PE(pos,2i+1)= \cos\left( \frac{pos}{10000^{2i/d_{\text{model}}}} \right) \]
Where:
- \(pos\) = Token position.
- \(i\) = Dimension index.
- \(d_{\text{model}}\) = Embedding dimension.
The positional representation is added to the token embedding:
\[ X_{\text{input}}= E_{\text{token}}+PE \]
This gives the model information about both token identity and position.
5.2 Learned Positional Embeddings
Some Transformer architectures use trainable positional embeddings instead of fixed sinusoidal encodings.
The model learns positional representations as part of training.
5.3 Modern Positional Methods
Modern architectures also use approaches such as:
- Rotary Positional Embeddings (RoPE)
- Relative positional representations
- ALiBi (Attention with Linear Biases)
RoPE is widely used in modern decoder-only language models.
These approaches provide different ways to represent positional relationships.
6. The Complete Transformer Architecture
The original Transformer introduced an encoder-decoder architecture.
Its main components include:
- Input embeddings
- Positional encoding
- Multi-head attention
- Feed-forward neural networks
- Residual connections
- Layer Normalization
- Output projection and Softmax
6.1 Original Encoder-Decoder Structure
INPUT TOKENS
|
v
[Token Embeddings]
|
v
[Positional Encoding]
|
v
┌─────────────┐
│ ENCODER │
│ │
│ Self-Attn │
│ ↓ │
│ Add & Norm │
│ ↓ │
│ Feed Forward│
│ ↓ │
│ Add & Norm │
└─────────────┘
|
v
Encoder Representations
|
v
┌─────────────┐
│ DECODER │
│ │
│ Masked │
│ Self-Attn │
│ ↓ │
│ Cross-Attn │
│ ↓ │
│ Feed Forward│
│ ↓ │
│ Add & Norm │
└─────────────┘
|
v
[Linear + Softmax]
|
v
OUTPUT TOKENS
The encoder and decoder each contain multiple repeated layers.
The original paper used six encoder layers and six decoder layers in its base architecture.
6.2 Encoder Block
The encoder processes the input sequence and creates contextual representations.
Each original encoder layer contains:
Multi-Head Self-Attention
Each token can attend to other tokens in the input sequence.
Feed-Forward Network
After attention, each position passes through a small neural network.
A common formulation is:
\[ FFN(x)= \max(0,xW_1+b_1)W_2+b_2 \]
This is applied independently to each sequence position using shared parameters.
Residual Connections and Layer Normalization
The original Transformer uses residual connections around its sublayers, followed by Layer Normalization.
A simplified expression is:
\[ \operatorname{LayerNorm}(x+Sublayer(x)) \]
These mechanisms help stabilize and improve optimization.
6.3 Decoder Block
The decoder generates output tokens.
It contains three important components:
- Masked Multi-Head Self-Attention
- Encoder-Decoder Cross-Attention
- Feed-Forward Network
Masked Self-Attention
The decoder is prevented from accessing future output tokens.
For example, when generating:
"I love machine learning"
At the position of "love", the model can use "I" and "love", but cannot use "machine" or "learning" from the future.
This is called causal masking.
Cross-Attention
Cross-attention connects the decoder to the encoder's output.
In this operation:
- Queries come from the decoder.
- Keys come from the encoder.
- Values come from the encoder.
This allows the decoder to retrieve relevant information from the input sequence while generating output tokens.
7. Residual Connections and Layer Normalization
Attention and feed-forward operations transform token representations.
To help train deeper Transformer networks, the architecture uses residual connections and normalization.
7.1 Residual Connections
A residual connection adds the input of a sublayer to its output:
\[ y=x+F(x) \]
Where:
- \(x\) = Original input.
- \(F(x)\) = Output of the sublayer.
- \(y\) = Combined output.
This creates a direct information and gradient pathway around the sublayer.
7.2 Layer Normalization
Layer Normalization normalizes feature values within each individual token representation.
A simplified formula is:
\[ \hat{x}= \frac{x-\mu} {\sqrt{\sigma^2+\epsilon}} \]
The result is then scaled and shifted using learnable parameters:
\[ y=\gamma\hat{x}+\beta \]
Layer Normalization helps stabilize the distribution of activations during training.
7.3 Pre-LN vs. Post-LN
Transformer implementations differ in where Layer Normalization is applied.
Post-LN:
\[ y=\operatorname{LayerNorm}(x+F(x)) \]
This follows the original Transformer paper's arrangement.
Pre-LN:
\[ y=x+F(\operatorname{LayerNorm}(x)) \]
Pre-LN is commonly used in many modern Transformer architectures because it can improve optimization behavior in deeper networks.
8. Three Major Transformer Architecture Types
Not all Transformers use the same encoder-decoder structure.
Modern models generally fall into three broad categories.
8.1 Encoder-Only Transformers
Encoder-only models process input sequences using bidirectional self-attention.
They can use information from both earlier and later positions when creating contextual representations.
A popular example is BERT.
Common applications:
- Text classification
- Sentiment analysis
- Named Entity Recognition
- Document understanding
- Question-answering tasks
8.2 Decoder-Only Transformers
Decoder-only models use causal self-attention.
Each token can attend only to itself and permitted earlier tokens.
They are designed for autoregressive generation.
Examples include GPT-style language models.
Common applications:
- Text generation
- Code generation
- Conversational AI
- Autocomplete
- Language modeling
8.3 Encoder-Decoder Transformers
These models contain both an encoder and a decoder.
The encoder processes the input, while the decoder generates an output using both causal self-attention and cross-attention.
Examples include the original Transformer and T5.
Common applications:
- Machine translation
- Text summarization
- Text-to-text tasks
- Sequence transformation
Comparison
| Feature | Encoder-Only | Decoder-Only | Encoder-Decoder |
|---|---|---|---|
| Attention | Bidirectional | Causal | Encoder bidirectional; decoder causal |
| Main Purpose | Understanding input | Generating sequences | Transforming input into output |
| Future Tokens Visible | Generally yes | No, during causal prediction | Encoder yes; decoder no |
| Examples | BERT | GPT | Original Transformer, T5 |
| Common Tasks | Classification, representation learning | Text and code generation | Translation, summarization |
9. Why Transformers Are Faster Than Traditional RNNs During Training
Traditional RNNs process a sequence step by step.
For a sequence containing 100 tokens, recurrent computation at one position depends on the previous position.
This limits parallelization across time steps.
Transformers use self-attention to calculate relationships between multiple sequence positions together.
This makes parallel training much easier.
Comparison
| Feature | RNN / LSTM / GRU | Transformer |
|---|---|---|
| Processing | Recurrent and sequential | Parallel across positions during training |
| Long-range relationships | Through recurrent state updates | Direct attention connections |
| Training parallelization | Limited across time steps | Generally high |
| Memory mechanism | Hidden state and optional cell state | Attention-based contextual representations |
| Long-sequence attention cost | Recurrent computation is approximately linear in sequence length for fixed dimensions | Standard full attention has quadratic sequence-length cost |
| Common modern applications | Time series and some sequence tasks | NLP, LLMs, vision, multimodal AI |
The Computational Cost of Self-Attention
For a sequence of length \(n\), standard full self-attention calculates an \(n \times n\) attention-score matrix.
Its attention computation and score storage scale approximately as:
\[ O(n^2d) \]
for hidden dimension \(d\), with the score matrix itself requiring:
\[ O(n^2) \]
storage per attention head and batch element in a straightforward implementation.
This can become expensive for very long sequences.
Techniques such as FlashAttention improve memory efficiency and execution speed without changing the standard attention result.
Other approaches include sparse attention, sliding-window attention, and other efficient attention mechanisms.
10. Implementing Self-Attention Using Python and PyTorch
Let's implement a simple self-attention layer.
Step 1: Install PyTorch
pip install torch
Step 2: Import Required Libraries
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
Step 3: Create a Self-Attention Layer
class SelfAttention(nn.Module):
def __init__(self, embed_dim):
super().__init__()
self.query = nn.Linear(
embed_dim,
embed_dim
)
self.key = nn.Linear(
embed_dim,
embed_dim
)
self.value = nn.Linear(
embed_dim,
embed_dim
)
def forward(self, x):
Q = self.query(x)
K = self.key(x)
V = self.value(x)
scores = torch.matmul(
Q,
K.transpose(-2, -1)
)
scores = scores / math.sqrt(
Q.size(-1)
)
attention_weights = F.softmax(
scores,
dim=-1
)
output = torch.matmul(
attention_weights,
V
)
return output, attention_weights
Step 4: Test the Self-Attention Layer
batch_size = 2
sequence_length = 5
embed_dim = 64
X = torch.randn(
batch_size,
sequence_length,
embed_dim
)
attention = SelfAttention(embed_dim)
output, weights = attention(X)
print("Input Shape:", X.shape)
print("Output Shape:", output.shape)
print("Attention Shape:", weights.shape)
Expected output:
Input Shape: torch.Size([2, 5, 64])
Output Shape: torch.Size([2, 5, 64])
Attention Shape: torch.Size([2, 5, 5])
The attention matrix has dimensions:
\[ (B,T,T) \]
Where:
- \(B\) = Batch size.
- \(T\) = Sequence length.
Each position has an attention distribution over the sequence positions it is allowed to attend to.
This example implements single-head self-attention without positional encoding or attention masking.
11. Implementing Multi-Head Attention Using PyTorch
PyTorch provides a built-in module called nn.MultiheadAttention.
It implements multi-head attention and can be used to construct Transformer architectures.
import torch
import torch.nn as nn
embed_dim = 128
num_heads = 8
attention = nn.MultiheadAttention(
embed_dim=embed_dim,
num_heads=num_heads,
batch_first=True
)
X = torch.randn(
32,
10,
128
)
output, attention_weights = attention(
X,
X,
X
)
print("Output Shape:", output.shape)
print("Attention Shape:", attention_weights.shape)
Expected output shapes:
Output Shape: torch.Size([32, 10, 128])
Attention Shape: torch.Size([32, 10, 10])
Here, the same input is supplied as Query, Key, and Value. That is self-attention.
For causal self-attention, use an appropriate attention mask so that a token cannot access future positions.
12. Building a Simple Transformer Encoder Using PyTorch
Now let's combine attention, a feed-forward network, residual connections, and Layer Normalization.
PyTorch provides nn.TransformerEncoderLayer for this purpose.
import torch
import torch.nn as nn
embed_dim = 128
num_heads = 8
feedforward_dim = 512
encoder_layer = nn.TransformerEncoderLayer(
d_model=embed_dim,
nhead=num_heads,
dim_feedforward=feedforward_dim,
dropout=0.1,
batch_first=True
)
transformer_encoder = nn.TransformerEncoder(
encoder_layer,
num_layers=4
)
X = torch.randn(
32,
20,
embed_dim
)
output = transformer_encoder(X)
print("Input Shape:", X.shape)
print("Output Shape:", output.shape)
Expected output:
Input Shape: torch.Size([32, 20, 128])
Output Shape: torch.Size([32, 20, 128])
The encoder preserves the batch size, sequence length, and embedding dimension.
Important: This is a simplified encoder implementation. A complete model also needs token embeddings, positional information, appropriate padding masks, and a task-specific output layer.
13. Applications of Transformers in Real-World AI
Transformers are used across a wide range of industries and applications.
13.1 Natural Language Processing
Transformers power many modern language-processing systems.
Examples:
- Text summarization
- Sentiment analysis
- Translation
- Question answering
- Information extraction
13.2 Large Language Models
Decoder-only Transformers are a major foundation of modern LLMs.
Examples include GPT-style models and other autoregressive language models.
Applications:
- Chatbots
- AI assistants
- Content generation
- Code completion
- Reasoning and language tasks
13.3 Computer Vision
Vision Transformers (ViT) divide images into patches and process them as a sequence of representations.
Applications include:
- Image classification
- Object detection
- Image segmentation
- Visual recognition
13.4 Speech and Audio Processing
Transformer-based models can process audio representations and generate or recognize speech.
Applications include:
- Speech recognition
- Audio transcription
- Text-to-speech
- Audio understanding
13.5 Multimodal AI
Multimodal systems combine different forms of information.
Examples:
- Text and images
- Audio and text
- Video and language
- Documents and visual content
Transformers and attention mechanisms help these models learn relationships across different modalities.
14. Limitations of Transformers
Despite their success, Transformers have several challenges.
1. High Computational Requirements
Large Transformer models can require significant GPU memory, computing power, and training time.
2. Attention Cost for Long Sequences
Standard full attention has quadratic sequence-length scaling for its attention-score computation and storage.
3. Large Data Requirements
Large-scale Transformer models often benefit from substantial training datasets and compute resources.
4. Positional Information
Self-attention alone does not encode sequence order. Appropriate positional representations or other ordering mechanisms are required.
5. Hallucinations
Language models can generate incorrect or fabricated information while producing fluent responses.
Their outputs should be evaluated and verified for important applications.
6. Inference Cost
Autoregressive models generate tokens sequentially. Long outputs can therefore require substantial inference time.
Techniques such as KV caching help avoid repeatedly calculating key and value representations for previous tokens.
15. Best Practices for Working with Transformers
When developing Transformer-based models, consider these practices:
- Use suitable tokenization: Select a tokenizer appropriate for the language and task.
- Add positional information: Use positional embeddings, RoPE, or another suitable method.
- Choose the correct architecture: Encoder-only, decoder-only, or encoder-decoder depending on the problem.
- Apply attention masks correctly: Prevent access to padding or future tokens when required.
- Use pretrained models: Fine-tuning can reduce training requirements.
- Monitor training and validation loss: Identify overfitting and optimization problems.
- Use suitable learning-rate schedules: Warmup and decay are common training strategies.
- Manage memory: Use mixed precision and efficient attention implementations when appropriate.
- Evaluate model outputs: Use task-specific metrics and human evaluation where necessary.
- Control inference costs: Consider batching, KV caching, and appropriate sequence lengths.
Conclusion
Transformers changed modern deep learning by introducing attention-based sequence processing.
Self-attention allows each token to gather information from other relevant tokens, while Multi-Head Attention learns multiple types of relationships simultaneously.
Positional encoding provides information about token order, and feed-forward networks, residual connections, and Layer Normalization help build deep and effective architectures.
The original encoder-decoder Transformer also inspired three major architectural families: encoder-only, decoder-only, and encoder-decoder models.
The key idea is simple: instead of relying on a recurrent memory chain, Transformers use attention to build contextual representations by learning relationships between sequence positions.
Understanding Query, Key, Value, Self-Attention, Multi-Head Attention, and Transformer blocks provides an essential foundation for studying modern LLMs, Generative AI, and multimodal systems.