🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Transformers — Attention Is All You Need Complete Guide

Deep LearningTransformers🟢 Free Lesson

Advertisement

Prerequisites

Before diving into Transformers, you should be comfortable with:

  • Neural Network Fundamentals: Forward/backward pass, activation functions, backpropagation (see Tutorial 21)
  • RNNs and LSTMs: Sequential processing, vanishing gradients, attention motivation (see Tutorial 23)
  • Linear Algebra: Matrix multiplication, softmax, dot-product similarity
  • PyTorch: nn.Module, batch processing, mask operations
  • NLP Basics: Tokenization, embeddings, sequence-to-sequence tasks

Deep Learning

Transformers — The Architecture That Changed Everything

Master the Transformer architecture that powers GPT, BERT, and all modern language models.

  • Self-attention mechanism — process all tokens simultaneously
  • Parallel processing — much faster than sequential RNNs
  • Foundation of LLMs — powers ChatGPT, Claude, and more

Attention is all you need.

Learning Objectives

By the end of this tutorial, you will be able to:

  1. Implement scaled dot-product self-attention from scratch
  2. Explain why multi-head attention captures different relationship types
  3. Compare sinusoidal, learned, and rotary positional encodings
  4. Differentiate encoder (BERT) vs decoder (GPT) architectures
  5. Understand the quadratic complexity bottleneck and its solutions
  6. Build a Transformer block in PyTorch with proper masking
  7. Explain why Transformers replaced RNNs for most NLP tasks

Transformers — Attention Is All You Need

Transformers (Vaswani et al., 2017) replaced RNNs as the dominant architecture for sequence processing. They achieve sequential operations (vs for RNNs), enabling massive parallelism on GPUs.


Self-Attention

The core mechanism: each token attends to every other token to compute a weighted representation.


Multi-Head Attention

Multiple attention heads capture different types of relationships simultaneously:

where


Positional Encoding

Since self-attention is permutation-invariant, we must inject position information:


Transformer Block


Encoder vs Decoder

  • Encoder (BERT): Bidirectional self-attention — every token attends to every other token. Good for understanding tasks (classification, NER, QA).
  • Decoder (GPT): Masked self-attention — each token attends only to previous tokens. Good for text generation, completion.

PyTorch Implementation


Real-World Applications

1. Large Language Models (LLMs) GPT-4, Claude, LLaMA, and Gemini are all Transformer-based. GPT-4 reportedly uses ~96 Transformer layers with trillions of parameters, powering ChatGPT's conversational abilities.

2. Machine Translation Transformer-based models (mBART, NLLB) translate between 200+ languages. They handle long-range dependencies that RNNs miss, achieving state-of-the-art BLEU scores.

3. Code Generation GitHub Copilot, Codex, and Code Llama use decoder Transformers trained on code repositories. They understand programming context and generate functional code from natural language descriptions.

4. Vision Transformers (ViT) ViT splits images into patches and processes them as token sequences. When pre-trained on large datasets, ViT matches or exceeds CNN performance on ImageNet and other vision benchmarks.

5. Scientific Discovery AlphaFold2 uses Transformers to predict protein 3D structures from amino acid sequences, solving a 50-year grand challenge in biology. The same architecture is being applied to drug discovery and materials science.

6. Multi-Modal AI GPT-4V, Gemini, and LLaVA process text and images together. CLIP aligns text and image embeddings for zero-shot classification. These models understand content across modalities using cross-attention.


Common Mistakes & How to Avoid Them


Key Formulas Reference

FormulaExpressionUse Case
Self-Attentionsoftmax(QK^T / sqrt(d_k)) VCore mechanism
Multi-HeadConcat(head_1,...,head_h) W_OMultiple relationship types
FFNW_2 * GELU(W_1 x + b_1) + b_2Position-wise processing
Sinusoidal PEsin(pos / 10000^{2i/d})Position information
Attention ComplexityO(n^2 * d) per layerCompute budget
Causal Maskmask[i,j] = 0 if j <= i else -infAutoregressive generation

Interview Questions

Q1: Why do Transformers scale better than RNNs?
Transformers process all tokens in parallel (O(1) sequential ops vs O(n) for RNNs), enabling massive GPU parallelism. Their O(n^2 * d) computation per layer can be fully parallelized, while RNNs must process tokens sequentially. For long sequences with sufficient data/compute, Transformers achieve much better performance.

Q2: What is the purpose of the scaling factor sqrt(d_k) in attention?
Without scaling, dot products grow proportionally to d_k, pushing softmax outputs toward extreme values (near 0 or 1). This causes vanishing gradients because softmax becomes nearly one-hot. Dividing by sqrt(d_k) keeps the dot product variance at ~1 regardless of dimension, maintaining useful gradients.

Q3: Explain the difference between encoder-only, decoder-only, and encoder-decoder Transformers.
Encoder-only (BERT): Bidirectional attention for understanding tasks. Decoder-only (GPT): Causal attention for text generation. Encoder-decoder (T5, BART): Encoder processes input, decoder generates output with cross-attention — ideal for seq2seq tasks like translation. Most modern LLMs are decoder-only for simplicity.

Q4: What is the quadratic complexity bottleneck and how is it addressed?
Self-attention requires O(n^2 * d) computation and memory for sequence length n. Solutions: (1) Sparse attention (Longformer, BigBird) — attend to local windows + global tokens. (2) Linear attention (Performer) — approximate softmax with kernel functions. (3) Flash attention — compute in tiles to use O(n) memory. (4) Sliding window attention (Mistral).

Q5: Why do Transformers need positional encoding?
Self-attention computes pairwise interactions between tokens regardless of their position — it's permutation-invariant. Without positional encoding, "The cat sat" and "sat cat The" produce identical outputs. Positional encoding adds position information so the model knows token order, which is essential for language understanding.

Q6: How does the FFN in a Transformer work?
The FFN is applied independently to each position (token). It consists of two linear layers with GELU activation: expand from d_model to 4*d_model, apply GELU, then project back. It acts as a "thinking" layer — after attention gathers context from other tokens, the FFN processes that context at each position to make decisions.

Q7: What are scaling laws in Transformers?
Scaling laws (Kaplan et al., 2020) show that Transformer performance scales predictably with: (1) Number of parameters (model size), (2) Dataset size, (3) Compute budget. Performance follows power laws — doubling parameters gives a consistent improvement. This enabled predicting optimal model size given a compute budget, leading to GPT-4's training strategy.


Practice Exercise

Challenge: Build a Transformer from Scratch
import torch
import torch.nn as nn
import math

# Task 1: Implement scaled dot-product attention
def scaled_dot_product_attention(Q, K, V, mask=None):
    # Compute attention scores
    # Apply mask if provided
    # Apply softmax and scale
    # Return weighted sum of values
    pass

# Task 2: Implement multi-head attention
class MultiHeadAttention(nn.Module):
    def __init__(self, d_model=512, n_heads=8):
        super().__init__()
        # Create Q, K, V projection layers
        # Create output projection layer
        pass

    def forward(self, Q, K, V, mask=None):
        # Split into heads
        # Apply attention per head
        # Concatenate and project
        pass

# Task 3: Implement positional encoding
class SinusoidalPositionalEncoding(nn.Module):
    def __init__(self, d_model, max_len=5000):
        super().__init__()
        # Create sinusoidal encoding matrix
        pass

    def forward(self, x):
        # Add positional encoding to input
        pass

# Task 4: Assemble full Transformer encoder
class TransformerEncoder(nn.Module):
    def __init__(self, d_model=512, n_heads=8, n_layers=6):
        super().__init__()
        # Stack of Transformer blocks
        pass

# Task 5: Train on a language modeling task
# - Use WikiText-2 dataset
# - Autoregressive (next token prediction)
# - Adam optimizer with warmup schedule

Success criteria: Implement all components and achieve perplexity <40 on WikiText-2 validation set.


Key Takeaways


What to Learn Next

-> BERT Learn about bidirectional language understanding.

-> GPT Architecture Explore how GPT generates text.

-> Attention Deep Dive Master attention mechanisms in detail.

-> Vision Transformers Apply Transformers to computer vision.

-> Transfer Learning Leverage pre-trained Transformer models.

-> Training Deep Networks Master optimizers and regularization for Transformers.


Advanced Topics

Efficient Attention Mechanisms

Standard self-attention has O(n^2) complexity. Several methods address this:

  • Sparse Attention (Longformer, BigBird): Attend to local windows (e.g., 512 tokens) + a few global tokens. Complexity: O(n * window_size).
  • Linear Attention (Performer): Approximate softmax with kernel functions to avoid materializing the full n x n matrix.
  • Flash Attention (Dao et al.): Compute attention in tiles on GPU SRAM, using O(n) memory instead of O(n^2). 2-4x speedup with zero approximation.
  • Sliding Window (Mistral): Each token attends only to a fixed window of neighbors, reducing complexity to O(n * w).

Scaling Laws

Kaplan et al. (2020) discovered power law relationships:

where is loss, is parameters, is data tokens, is compute FLOPs.

Key insight: Optimal performance requires balancing all three. Doubling parameters gives diminishing returns without proportional data/compute increases. This led to Chinchilla's compute-optimal training: for a given budget, train a smaller model on more data.

Transformer Variants

  • BERT (Encoder-only): Bidirectional attention, masked language modeling. Good for understanding.
  • GPT (Decoder-only): Causal attention, next-token prediction. Good for generation.
  • T5 (Encoder-decoder): Text-to-text framework. Any task as text generation.
  • Vision Transformer (ViT): Treats image patches as tokens. ViT-L/14 achieves 87.8% on ImageNet.
  • Perceiver: Processes arbitrary modalities (text, images, audio, point clouds) through a learned latent space.
  • State Space Models (Mamba): Linear-time alternative to Transformers for very long sequences (100K+ tokens).

KV Cache in Inference

During autoregressive generation, previously computed Key and Value matrices are cached to avoid recomputation. Without KV cache, generating tokens requires total computation. With KV cache, each new token requires only computation (for the new token's Q against all cached KVs).


Comparison Table

ModelTypeParamsContextBest For
BERT-baseEncoder110M512Classification, NER, QA
GPT-2Decoder1.5B1024Text generation
T5-11BEnc-Dec11B512Text-to-text tasks
GPT-4Decoder~1.8T (est.)128KGeneral AI assistant
LLaMA-3 70BDecoder70B8KOpen-source LLM
ViT-L/14Encoder307MN/A (patches)Computer vision

Further Reading

  • Vaswani, A. et al. (2017). "Attention Is All You Need." — The original Transformer paper, one of the most influential in ML history.
  • Devlin, J. et al. (2018). "BERT: Pre-training of Deep Bidirectional Transformers." — Bidirectional encoder for language understanding.
  • Radford, A. et al. (2018/2019). "Improving Language Understanding by Generative Pre-Training." — GPT-1 and GPT-2.
  • Kaplan, J. et al. (2020). "Scaling Laws for Neural Language Models." — Power law relationships between compute, data, and performance.
  • Dao, T. et al. (2022). "FlashAttention: Fast and Memory-Efficient Exact Attention." — Hardware-aware attention algorithm.
  • Su, J. et al. (2021). "RoFormer: Enhanced Transformer with Rotary Position Embedding." — RoPE for long-context models.

Quick Reference Cheat Sheet

ComponentPyTorchKey Parameters
Multi-Head Attentionnn.MultiheadAttention()d_model, n_heads, dropout
Positional Encodingnn.Embedding(max_len, d_model)or sinusoidal (fixed)
FFNnn.Sequential(Linear, GELU, Linear)d_ff = 4 * d_model typically
Layer Normnn.LayerNorm()d_model
Causal Masktorch.triu(torch.ones(n,n)) == 0Fill with -inf for masked positions

Model Comparison: Encoder vs Decoder vs Encoder-Decoder

PropertyEncoder (BERT)Decoder (GPT)Enc-Dec (T5)
Attention typeBidirectionalCausal (masked)Both + cross-attention
Pre-trainingMLM + NSPNext token predictionSpan corruption / denoising
InferenceParallel (all tokens)Autoregressive (one at a time)Encode parallel, decode auto
Fine-tuningAdd task headPrompt/in-context learningText-to-text format
Modern examplesBERT, RoBERTa, DeBERTaGPT-4, LLaMA, MistralT5, BART, mBART

Need Expert Machine Learning Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement