Transformers Cheat Sheet β€” Attention, BERT, GPT, Positional Encoding, Fine-tuning Dataplexa
Transformers icon

Transformers

attention Β· positional encoding Β· encoder Β· decoder Β· BERT Β· GPT Β· T5 Β· fine-tuning

Sheet 4 of 4 Deep Learning Advanced Printable

Why Transformers?

Motivation

Transformers replace recurrence with self-attention β€” processing all tokens in parallel and directly modelling relationships between any two positions regardless of distance.

Problem with RNNsTransformer Solution
Sequential β€” can't paralleliseAll tokens processed in parallel
Vanishing gradient over long seqsDirect attention β€” any two tokens connect
Fixed-size context vector bottleneckAttention over all encoder states
Hard to scale to very long seqsScales with compute (O(nΒ²) attention)
"Attention is All You Need" β€” Vaswani et al., 2017. The original Transformer paper introduced the architecture that powers BERT, GPT, T5, and every modern LLM.

Self-Attention

Core Mechanism

Each token attends to every other token in the sequence simultaneously. Three learned projections β€” Query, Key, Value β€” control what each token looks for and what it shares.

Scaled Dot-Product Attention
Attention(Q, K, V) = softmax(QKα΅€ / √dβ‚–) Β· V
Q = query Β· K = key Β· V = value Β· dβ‚– = key dimension Β· √dβ‚– prevents softmax saturation
MatrixShapeRole
Q (Query)(seq, dβ‚–)"What am I looking for?"
K (Key)(seq, dβ‚–)"What do I have to offer?"
V (Value)(seq, dα΅₯)"What do I actually send?"
Output(seq, dα΅₯)Weighted sum of Values
Complexity: Self-attention is O(nΒ²Β·d) β€” quadratic in sequence length. For very long sequences (n > 2048), efficient variants (Longformer, Flash Attention) are used.

Multi-Head Attention

Parallel Heads

Run h attention heads in parallel, each with its own Q, K, V projections β€” allowing the model to attend to different aspects of the sequence simultaneously (syntax, semantics, coreference…).

Multi-Head Attention
MultiHead(Q,K,V) = Concat(head₁,…,headβ‚•)Β·Wα΄Ό headα΅’ = Attention(QΒ·Wα΅’α΄Ό, KΒ·Wα΅’α΄·, VΒ·Wα΅’α΅›)
Each head uses dβ‚– = dmodel/h Β· Wα΄Ό = output projection
Modeld_modelHeads (h)dβ‚– per head
BERT-Base7681264
BERT-Large10241664
GPT-2 Small7681264
GPT-31228896128
ViT-B/167681264

Positional Encoding

Order Information

Transformers have no inherent order β€” attention is permutation invariant. Positional encoding injects position information into token embeddings.

Sinusoidal PE (Original Paper)
PE(pos, 2i) = sin(pos / 10000^(2i/dmodel)) PE(pos, 2i+1) = cos(pos / 10000^(2i/dmodel))
pos = token position Β· i = dimension index Β· added directly to embeddings
PE TypeLearned?Used In
SinusoidalNo β€” fixedOriginal Transformer
Learned AbsoluteYesBERT, GPT-2
Relative (RoPE)YesLLaMA, GPT-NeoX, Mistral
ALiBiNo β€” biasMPT, BLOOM
RoPE (Rotary Position Embedding) is the current standard in open LLMs β€” it encodes relative positions directly in the attention computation via rotation matrices.

Full Transformer Architecture

Encoder + Decoder

Encoder Block (Γ—N layers)

Sub-layerOperation
1. Multi-Head Self-AttentionEach token attends to all tokens
2. Add & LayerNormResidual connection + normalise
3. Feed-Forward NetworkTwo Dense layers: dmodel β†’ 4Β·dmodel β†’ dmodel
4. Add & LayerNormResidual connection + normalise

Decoder Block (Γ—N layers)

Sub-layerOperation
1. Masked Self-AttentionAttend to past tokens only (causal mask)
2. Add & LayerNormResidual + normalise
3. Cross-AttentionQ from decoder, K/V from encoder output
4. Add & LayerNormResidual + normalise
5. Feed-Forward + NormSame as encoder FFN block

Feed-Forward Network (FFN)

FFN Formula
FFN(x) = max(0, xW₁+b₁)Wβ‚‚+bβ‚‚
dmodel=512 β†’ dff=2048 β†’ dmodel=512 Β· applied position-wise independently

Layer Normalisation

LayerNorm vs BatchNorm
LN(x) = Ξ³ Β· (x βˆ’ ΞΌ) / √(σ²+Ξ΅) + Ξ²
Normalises across features (not batch) β€” stable for variable-length sequences
Pre-LN vs Post-LN: Original paper uses Post-LN (after residual). Modern LLMs use Pre-LN (before sub-layer) β€” more stable training, no learning rate warmup needed.
Transformer Block (Keras)
class TransformerBlock(keras.layers.Layer):
 def __init__(self, d_model, n_heads, dff):
 super().__init__()
 self.attn = keras.layers.MultiHeadAttention(
 num_heads=n_heads, key_dim=d_model//n_heads)
 self.ff1 = keras.layers.Dense(dff, activation='relu')
 self.ff2 = keras.layers.Dense(d_model)
 self.ln1 = keras.layers.LayerNormalization()
 self.ln2 = keras.layers.LayerNormalization()

 def call(self, x, training=False):
 attn_out = self.attn(x, x) # self-attention
 x = self.ln1(x + attn_out) # residual + norm
 ff_out = self.ff2(self.ff1(x)) # FFN
 return self.ln2(x + ff_out) # residual + norm

BERT

Encoder-Only

Bidirectional Encoder Representations from Transformers β€” encoder-only model pretrained on Masked Language Modelling (MLM) and Next Sentence Prediction (NSP).

BERT-BaseBERT-Large
Layers1224
d_model7681024
Heads1216
Parameters110M340M
Max seq len512512
BERT Pretraining Tasks
# 1. Masked Language Model (MLM)
# Mask 15% of tokens β†’ predict them
"The [MASK] sat on the mat"
# β†’ predict "cat"

# 2. Next Sentence Prediction (NSP)
# Given sentence A + B, is B next?
[CLS] Sentence A [SEP] Sentence B [SEP]
# β†’ IsNext or NotNext
[CLS] token: The first token's final hidden state is used as the sequence representation for classification tasks.

GPT Family

Decoder-Only

Generative Pretrained Transformer β€” decoder-only, autoregressive model. Trained on next-token prediction with a causal (left-to-right) mask.

ModelParamsContextKey Feature
GPT-1117M512Original GPT β€” unsupervised pretraining
GPT-21.5B1024Zero-shot generation; "too dangerous"
GPT-3175B4096Few-shot in-context learning
GPT-4~1T?128KMultimodal; RLHF aligned
LLaMA 38B–70B8KOpen-source; RoPE; GQA
Causal Language Modelling
# Predict each token from past tokens only
# Causal mask: token i cannot attend to j > i

P(tokenβ‚… token₁, tokenβ‚‚, token₃, tokenβ‚„)

# Training loss: cross-entropy over all positions
# L = -Ξ£ log P(xβ‚œ x<β‚œ)

Transformer Model Zoo

Encoder Β· Decoder Β· Encoder-Decoder
ModelTypePretrainingBest ForUse Via
BERTEncoderMLM + NSPClassification, NER, QAHuggingFace
RoBERTaEncoderMLM (no NSP, more data)Better BERT for most NLPHuggingFace
DistilBERTEncoderKnowledge distillation of BERTFast/lightweight NLPHuggingFace
GPT-2DecoderCLM (causal LM)Text generationHuggingFace
LLaMA 3DecoderCLM on 15T tokensOpen-source chat/generationOllama / HF
T5Enc-DecSpan corruption β†’ reconstructTranslation, summarisation, QAHuggingFace
BARTEnc-DecDenoising autoencoderSummarisation, translationHuggingFace
WhisperEnc-DecAudio β†’ text (multitask)Speech recognitionOpenAI / HF
ViTEncoderImage patches as tokensImage classificationHuggingFace
CLIPDual EncImage-text contrastiveZero-shot vision-languageOpenAI / HF
Choosing: Classification/NER β†’ RoBERTa. Generation/chat β†’ LLaMA 3 / GPT. Summarisation/translation β†’ T5 or BART. Speech β†’ Whisper. Vision β†’ ViT or CLIP.

Fine-tuning β€” HuggingFace

Transformers Library
Text Classification (BERT)
from transformers import (
 AutoTokenizer, AutoModelForSequenceClassification,
 TrainingArguments, Trainer
)

# Load pretrained
tokenizer = AutoTokenizer.from_pretrained(
 "bert-base-uncased")
model = AutoModelForSequenceClassification\
 .from_pretrained("bert-base-uncased",
 num_labels=2)

# Tokenize dataset
def tokenize(batch):
 return tokenizer(batch["text"],
 padding=True, truncation=True)

# Train
args = TrainingArguments(
 output_dir="./results",
 num_train_epochs=3,
 per_device_train_batch_size=16,
 learning_rate=2e-5,
 weight_decay=0.01,
)
trainer = Trainer(model=model, args=args,
 train_dataset=train_ds, eval_dataset=val_ds)
trainer.train()

Fine-tuning Strategies

Full Β· LoRA Β· Prompt
StrategyUpdatesGPU RAMBest For
Full Fine-tuneAll paramsVery HighMax accuracy; lots of data
Head OnlyClassifier headLowSmall datasets; quick baseline
LoRALow-rank adaptersLowLLMs on consumer GPU
QLoRALoRA + 4-bit quantVery Low7B–13B models on 1Γ— GPU
Prompt TuningSoft prompt tokensMinimalFrozen model; task switching
RLHFPolicy + reward modelHighAlign to human preferences
LoRA with PEFT Library
from peft import LoraConfig, get_peft_model

config = LoraConfig(
 r=16, # rank
 lora_alpha=32, # scaling
 target_modules=["q_proj", "v_proj"],
 lora_dropout=0.05,
 task_type="CAUSAL_LM"
)
model = get_peft_model(base_model, config)
model.print_trainable_parameters()
# trainable params: 4.2M / 6.7B (0.06%)

Tokenisation

BPE Β· WordPiece Β· SentencePiece
MethodHowUsed In
BPEMerge frequent byte pairs iterativelyGPT-2, GPT-4, LLaMA, RoBERTa
WordPieceLike BPE but maximises LM likelihoodBERT, DistilBERT
SentencePieceLanguage-agnostic; treats raw textT5, LLaMA, mBERT
UnigramProbabilistic; prune vocab by likelihoodXLNet, mBART
HuggingFace Tokeniser
tokenizer = AutoTokenizer\
 .from_pretrained("bert-base-uncased")

tokens = tokenizer(
 "Deep learning is powerful",
 return_tensors="pt",
 padding=True,
 truncation=True,
 max_length=128
)
# tokens.input_ids, tokens.attention_mask
# β†’ [101, 2784, 4083, 2003, 3928, 102]
Token β‰  word: "unbelievable" β†’ ["un", "##believe", "##able"] in WordPiece. Always check your tokeniser's vocabulary and special tokens ([CLS], [SEP], [PAD], [MASK]).

Efficient Attention Variants

Beyond O(nΒ²)
VariantComplexityKey Idea
Full AttentionO(nΒ²)Baseline β€” all pairs
Sparse AttentionO(n√n)Only attend to subset of positions
LongformerO(n)Local window + global tokens
LinformerO(n)Low-rank K/V projection
Flash AttentionO(nΒ²) but IO-awareTiled SRAM computation β€” 2–4Γ— faster
GQAO(nΒ²) β€” fewer KVGrouped Query Attention β€” LLaMA 2/3
MQAO(nΒ²) β€” 1 KV headMulti-Query β€” PaLM, Falcon
Flash Attention 2 is now the default in most production LLM training β€” same mathematical result as standard attention but uses hardware-aware tiling to avoid slow HBM reads/writes. Enable with attn_implementation="flash_attention_2" in HuggingFace.

Hyperparameters, Training Tips & Troubleshooting

Tuning Guide

Key Hyperparameters

ParamTypical Value
Learning rate2e-5 – 5e-5 (fine-tune)
Batch size16 – 64
Warmup steps5–10% of total steps
Weight decay0.01
Max seq length128 / 256 / 512
Epochs2 – 5 (fine-tune)
Dropout0.1 (attention + FFN)
LoRA rank r8 – 64
LR schedulerLinear decay / cosine

Common Problems & Fixes

ProblemFix
Catastrophic forgettingLower LR Β· fewer epochs Β· LoRA
OOM on GPUGradient checkpointing Β· mixed precision Β· QLoRA
Loss spikesLR warmup Β· gradient clipping (max norm 1.0)
Slow convergenceIncrease warmup Β· check tokenisation
Poor generation qualityTune temperature / top-p / top-k Β· beam search
Overfitting small datasetEarly stop Β· reduce epochs Β· data augmentation

Inference: Generation Settings

HuggingFace generate()
model.generate(
 input_ids,
 max_new_tokens=200,
 do_sample=True,
 temperature=0.7, # creativity
 top_p=0.9, # nucleus sampling
 top_k=50, # top-k sampling
 repetition_penalty=1.2,
 num_beams=1 # 1=greedy, >1=beam
)
SettingEffect
temp β†’ 0Deterministic (greedy)
temp β†’ 1+More creative/random
top_p=0.9Nucleus: top 90% prob mass
top_k=50Sample from top 50 tokens

Transformers β€” Mastery Checklist

Self-Assessment

Architecture Fundamentals

  • Write the scaled dot-product attention formula from memory
  • Explain Q, K, V and what each represents intuitively
  • Describe why √dβ‚– scaling is used in attention
  • Explain multi-head attention and how heads work in parallel
  • List all sub-layers in one encoder block and one decoder block
  • Explain sinusoidal vs learned vs RoPE positional encoding
  • Describe the causal mask used in GPT-style decoders

Pretrained Models

  • Distinguish encoder-only, decoder-only, and encoder-decoder models
  • Explain BERT's MLM and NSP pretraining objectives
  • Explain GPT's causal language modelling objective
  • Choose the right model for: classification, generation, summarisation
  • Load a pretrained model and tokeniser with HuggingFace AutoModel
  • Fine-tune BERT on a classification task using the Trainer API

Efficient Training & Inference

  • Explain LoRA and why it reduces trainable parameters
  • Apply QLoRA to fine-tune a 7B model on a consumer GPU
  • Explain Flash Attention and why it's faster despite same complexity
  • Tune temperature, top-p, and top-k for text generation
  • Diagnose and fix catastrophic forgetting during fine-tuning
  • Enable gradient checkpointing and mixed precision for large models
Deep Learning Series Complete!
All 4 Sheets Done β€” DL Basics Β· CNN Β· RNN & LSTM Β· Transformers
Explore more series: ML Fundamentals Β· Statistics & Math Β· NLP Β· Computer Vision
All Cheat Sheets β†’
← Back