Every model answers the same question: given examples of inputs and the outputs we want, which function maps one to the other, and how do we find it? A model fixes the shape of that function, a loss scores how wrong it is, an optimizer adjusts it, and an evaluation on data it never saw says whether it learned anything. The pages below take that one idea from a straight line through a cloud of points to a model with billions of parameters.
Each page follows the same order: the problem the idea solves, the intuition in plain language, the mechanics with shapes and formulas, a worked example with real numbers, the implementation linked line by line to library source, its tradeoffs, and its connections to what comes before and after. Each page is marked intro, core or advanced by where it starts, but every page goes all the way down. Start with the learning path if this is all new, or jump to any area.
The learning path
Seven steps for someone starting from zero. Pages not written yet show as plain text.
- Tensor shapes and matrix multiplication
- Backpropagation and optimization
- Embeddings and attention
- The full Transformer block
- Training versus inference
- Evaluation and data leakage
- Classical baselines
The map
Three building blocks (top) make up the encoder-decoder Transformer of 2017 (middle). Every model family below it keeps those blocks and changes what goes in, what comes out, or which part is kept. All of them are trained by the same loop (bottom). Each box links to its page, or to the pinned PyTorch source while the page is being written.
Shared vocabulary
Every page uses the same names. A model reads a batch of token IDs (integers
that index a vocabulary), looks each one up in an embedding table to get a
vector of width d_model, passes those vectors through N
layers, and ends with one score per vocabulary entry, the logits.
Inside a layer, attention splits d_model into heads slices of width
d_head = d_model / heads.
| Component | Shape/Params | Meaning | Source |
|---|---|---|---|
| Token IDs | [batch, seq], integers |
Which vocabulary entry sits at each position. seq is the sequence length. |
input to nn.Embedding |
| Embedding | weight [vocab, d_model]; out [batch, seq, d_model] |
A lookup table: row i is the learned vector for token i. | Embedding.weight |
| Linear | weight [out, in] + bias [out] |
y = x·Wᵀ + b over the last dimension. Most of a transformer's parameters live in these. |
nn.Linear |
| Multi-head attention | in_proj_weight [3·d_model, d_model] + out_proj: 4·d_model² + 4·d_model with bias |
Mixes information between positions. The packed weight holds the query, key and value projections; head_dim = embed_dim // num_heads. |
MultiheadAttention.__init__ |
| LayerNorm | weight + bias, each [d_model]: 2·d_model |
Rescales each position's vector to zero mean and unit variance, then applies a learned scale and shift. | LayerNorm.__init__ |
| Logits | [batch, seq, vocab] |
Unnormalized scores for the next token (or the masked token) at each position; softmax turns them into probabilities. | input to CrossEntropyLoss |
PyTorch's own transformer modules default to batch_first=False, so
nn.Transformer expects [seq, batch, d_model] unless you pass
batch_first=True (constructor defaults).
These pages write shapes batch-first, and say so whenever the PyTorch default matters.
Pinned releases
Code links go to one release of each library, so a line range keeps pointing at the right code after the library moves on. When a newer stable release changes a linked file, the pages and the pin move together. Formulas, results and model configurations that come from papers rather than library code cite the paper.
| Library | Release | Commit | Used for |
|---|---|---|---|
| PyTorch | v2.15.0 | 31a77fc9c0a7 |
Tensors, neural networks, training and inference |
| scikit-learn | 1.9.1 | 866c0f51e756 |
Classical models, preprocessing, splits and metrics |
| XGBoost | v3.4.2 | fdf0888beddd |
Gradient-boosted trees |
Pages are static. The few figures computed with a library are produced offline by scripts in this site's repository and committed as small data files; nothing here runs a model.
Pages by area
Mathematical foundations
Vectors, matrices, dot products, gradients, the chain rule, probability, distributions, expectation, Bayes' rule, entropy.
-
Tensors, shapes and broadcasting
intro
What a tensor is, how shapes, strides and views work, and the broadcasting rules every model relies on.
-
Vectors and dot products
intro
Vectors, norms and the dot product as similarity: the operation underneath attention and retrieval.
-
Matrices and matrix multiplication
intro
Matrix multiplication as many dot products, its shape rules, batched matmul, and how to count its FLOPs.
-
Eigenvectors, SVD and low rank
core
Eigenvectors, the SVD and low-rank approximation, and where they show up in ML.
-
LU, QR, Cholesky and matrix norms
core
Solving linear systems and least squares stably, and measuring a matrix with norms.
-
Iterative solvers: conjugate gradient and Krylov methods
advanced
Solving huge or matrix-free linear systems and eigenproblems with nothing but matrix-vector products.
-
Floating point, conditioning and numerical stability
core
Why rounding error grows, which formulas lose accuracy, and the stable rewrites behind logsumexp, losses on logits and streaming variance.
-
Derivatives and gradients
intro
Derivatives, partial derivatives and the gradient, with gradient descent worked step by step.
-
The chain rule
intro
The chain rule from scalars to Jacobians, and why reverse mode is how ML computes gradients.
-
Probability and distributions
intro
Random variables, the common distributions, and conditional and joint probability.
-
Expectation, variance and sampling
intro
Expectation, variance and Monte Carlo estimates, and why minibatch gradients are noisy but unbiased.
-
Bayes' rule and likelihood
core
Bayes' rule, likelihood, maximum likelihood and MAP estimation, with priors as regularizers.
-
Entropy, cross-entropy and KL divergence
core
Entropy, cross-entropy, KL divergence and perplexity, and why cross-entropy is the classification loss.
Core ML concepts
Supervised, unsupervised and self-supervised learning; losses; generalization; bias–variance; overfitting; regularization.
-
Supervised, unsupervised and self-supervised learning
intro
Supervised, unsupervised and self-supervised learning, and what the label is in each.
-
Loss functions
intro
The common losses as negative log-likelihoods, and how to choose one.
-
Generalization
intro
Why a model that fits its training data may still fail, and what makes it generalize.
-
The bias–variance tradeoff
core
The bias–variance decomposition, derived, with learning and validation curves.
-
Overfitting and underfitting
intro
Diagnosing overfitting and underfitting from curves, and the remedies for each.
-
Regularization
core
L1, L2, dropout, early stopping and augmentation: the ways to trade fit for generalization.
Data and evaluation
Splits, leakage, preprocessing, missing data, imbalance, cross-validation, metrics, calibration, uncertainty.
-
Train, validation and test splits
intro
Train, validation and test splits, and when a random split gives the wrong answer.
-
Data leakage
core
How information leaks from test to train, with concrete cases and a checklist to prevent it.
-
Preprocessing and feature scaling
intro
Scaling, encoding and transforming features, and which models care.
-
Missing data
core
Why values go missing, the imputation strategies, and how boosted trees handle missing values natively.
-
Class imbalance
core
Why accuracy misleads on rare classes, and the weighting, resampling and threshold fixes.
-
Cross-validation
core
k-fold and its stratified, grouped and time-series variants, and nested CV for model selection.
-
Classification metrics
intro
The confusion matrix, precision, recall, F1, ROC and PR curves, and choosing a threshold.
-
Regression metrics
intro
MSE, MAE, R² and friends, and how to match the metric to the decision.
-
Calibration
core
When a predicted probability means what it says, and how to fix it when it doesn't.
-
Uncertainty
advanced
Aleatoric and epistemic uncertainty, ensembles, and conformal prediction with guaranteed coverage.
Classical ML
Linear and logistic regression, decision trees, random forests, gradient boosting, SVMs, nearest neighbors, clustering, PCA.
-
Linear regression
intro
Least squares from the normal equations and from gradient descent, plus ridge and lasso.
-
Logistic regression
intro
Log-odds, the sigmoid and the cross-entropy loss: classification as one linear layer.
-
Decision trees
intro
Recursive splitting by Gini or entropy, worked on a toy dataset, and how to stop a tree overfitting.
-
Random forests
core
Bagging and feature subsampling: many decorrelated trees averaged to cut variance.
-
Gradient boosting
core
Boosting as gradient descent in function space, and XGBoost's second-order split gain, derived.
-
Support vector machines
core
The maximum-margin classifier, the hinge loss, and kernels.
-
Nearest neighbors
intro
Predicting from the closest training points, distance metrics, and the curse of dimensionality.
-
Clustering
intro
k-means, DBSCAN and Gaussian mixtures, and how to judge a clustering.
-
Principal component analysis
core
Principal components via the SVD, explained variance, and nonlinear alternatives.
Neural network fundamentals
Layers, activations, backprop, computation graphs, initialization, normalization, optimizers, LR schedules, the training loop.
-
Neurons, layers and the MLP
intro
From one neuron to a multilayer perceptron, and how nn.Module builds one.
-
Activation functions
intro
ReLU, GELU, SiLU, gated units and the rest, with their shapes and derivatives.
-
Backpropagation
core
The backward pass through a two-layer network, with every number shown.
-
Computation graphs and autograd
core
The graph autograd records, how backward walks it, and how to control it.
-
Weight initialization
core
Why weight scale matters, derived, and the Xavier and Kaiming schemes PyTorch uses.
-
Normalization and residual connections
core
The residual stream, BatchNorm, LayerNorm and RMSNorm, pre-norm versus post-norm, and the feed-forward block.
-
Optimizers: SGD to AdamW
core
SGD, momentum, RMSProp, Adam, AdamW and Muon, with a worked Adam step.
-
Learning-rate schedules
core
Warmup, step, cosine and one-cycle schedules, and why the learning rate matters most.
-
The training loop
intro
Cross-entropy loss, AdamW, learning-rate warmup and decay, gradient clipping, and mixed precision.
Model architectures
CNNs, RNNs/LSTMs, Transformers, autoencoders, GNNs, mixture of experts, state-space models, vision transformers.
-
Convolutional networks
core
Convolution as a sliding dot product, output-size arithmetic, pooling, and residual CNNs.
-
RNNs and LSTMs
core
Recurrence, backprop through time, and the gates that let LSTMs remember.
-
The Transformer
core
The full encoder-decoder from Attention Is All You Need, block by block, and how nn.Transformer implements it.
-
Autoencoders
core
Compress, then reconstruct: bottlenecks, denoising, and the latent space.
-
Graph neural networks
advanced
Message passing over graphs: GCN, GraphSAGE and GAT.
-
Vision Transformer
core
ViT: images as sequences of patches, patch embedding as a strided convolution, and the class token.
-
Mixture of experts
advanced
Routing each token to a few of many feed-forward experts: top-k gating, load balancing, total versus active parameters.
-
State-space models
advanced
S4 and Mamba: recurrences that train like convolutions and run in linear time.
Generative modeling
Autoregressive models, VAEs, GANs, diffusion, flow matching.
-
Autoregressive models
core
Generating one piece at a time by the chain rule of probability, trained with teacher forcing.
-
Variational autoencoders
core
The ELBO, derived, and the reparameterization trick that makes it trainable.
-
Generative adversarial networks
core
A generator and a discriminator trained against each other, and how to keep the game stable.
-
Diffusion models
advanced
Learning to undo noise: the forward process, the ε-prediction objective, and DDPM and DDIM sampling.
-
Diffusion U-Net
advanced
Denoising diffusion and the U-Net that predicts the noise: down and up paths, skips, timestep embeddings and attention.
-
Normalizing flows and flow matching
advanced
Normalizing flows, continuous flows, and the flow-matching objective that trains them simply.
Language models
Tokenization, embeddings, positional encoding, attention, encoder and decoder LMs, pretraining, fine-tuning, preference optimization, decoding, KV caching.
-
Tokenization
intro
How text becomes tokens: byte-pair encoding worked on a toy corpus, and why tokenization matters.
-
Embeddings
intro
Embedding tables as lookups, the geometry they learn, and contextual versus static embeddings.
-
Positional encoding
core
How a model that sees a set learns order: sinusoidal, learned and rotary (RoPE) positions.
-
Attention
core
Scaled dot-product and multi-head attention with a tiny numeric example, masks, and cross-attention.
-
Encoder-only models
core
The BERT-style stack: bidirectional attention, padding masks, masked-language-model training and task heads.
-
Decoder-only LLMs
core
The GPT-style stack: causal self-attention blocks, the LM head, generation, and a GPT-2-small parameter count.
-
Pretraining and scaling laws
advanced
Pretraining objectives, compute budgets, and the scaling laws that size a model.
-
Fine-tuning and LoRA
core
Full fine-tuning, instruction tuning, and LoRA's low-rank update, derived.
-
Preference optimization: RLHF and DPO
advanced
Reward models, RLHF with PPO, and DPO's closed-form loss.
-
Decoding and sampling
core
Greedy, beam, temperature, top-k and top-p sampling, and speculative decoding.
-
The KV cache
advanced
Why generation caches keys and values, how big the cache gets, and how MQA and GQA shrink it.
Retrieval and recommendation
Similarity search, vector indexes, ranking, collaborative filtering, two-tower models, RAG.
-
Similarity search
intro
Exact nearest-neighbor search over embeddings, the choice of metric, and lexical baselines.
-
Vector indexes
advanced
Approximate nearest neighbors with IVF, product quantization and HNSW.
-
Learning to rank
core
Pointwise, pairwise and listwise ranking, NDCG, and LambdaMART.
-
Collaborative filtering
core
Recommending from the user–item matrix: neighborhoods and matrix factorization.
-
Two-tower models
core
Separate query and item encoders trained with in-batch negatives, served with a vector index.
-
Retrieval-augmented generation
advanced
Retrieving passages and putting them in the prompt, and how to evaluate each half.
Training systems
GPU execution, precision, batching, distributed training, gradient accumulation, checkpointing, profiling.
-
How a GPU runs a model
core
Kernels, streams, memory bandwidth and the roofline: why some ops are fast and others aren't.
-
Precision and mixed precision
core
fp32, bf16, fp16 and fp8, autocast, and loss scaling.
-
Data loading and batching
intro
Datasets, DataLoaders, collation, padding and packing.
-
Gradient accumulation
core
Simulating a large batch with micro-batches, and the details that make it exact.
-
Distributed training
advanced
Data, sharded, tensor and pipeline parallelism, and memory per GPU worked through.
-
Checkpointing
core
Saving and resuming every piece of training state, and activation checkpointing.
-
Profiling
core
Measuring training correctly, reading a profiler trace, and computing MFU.
Inference and deployment
Quantization, distillation, serving, latency and throughput, monitoring and drift, reproducibility.
-
Quantization
core
Scale and zero point, per-channel quantization, and int8 and int4 for LLMs.
-
Knowledge distillation
core
Training a small student on a large teacher's soft targets.
-
Model serving
core
Exporting a model and serving it with batching on CPU or GPU.
-
Latency and throughput
core
Time to first token, tail latency, batching and Little's law.
-
Monitoring and drift
core
Detecting drift in inputs, predictions and outcomes after deployment.
-
Reproducibility
intro
Seeds, deterministic kernels and versioning: getting the same result twice.
Specialized learning
Reinforcement learning, time series, causal inference, online learning, multimodal models.
-
Reinforcement learning
core
MDPs, Q-learning, policy gradients and PPO.
-
Time series
core
Trend, seasonality, lag features, time-ordered validation and forecasting models.
-
Causal inference
advanced
Confounding, potential outcomes, propensity scores and experiments.
-
Online learning
core
Learning from a stream, regret, and bandits.
-
Multimodal models
advanced
Contrastive image–text pretraining and vision-language models.
Upcoming models
The models an ML engineer should know, from the classics to today's state of the art, oldest first within each tier. Each one has a single-sentence idea and its defining paper. Those with a page here link to it; more pages will follow. Most of the newest models are a Transformer variant, which is why that page comes first.
Classic machine learning
Small, fast, interpretable. Still the right first answer for most tabular data.
-
Linear regression 1805
Fit y = Xw + b by least squares; the closed form and gradient descent agree.
Legendre, 1805 (least squares)
-
Logistic regression 1958
A linear score through a sigmoid, trained with cross-entropy: a one-layer neural network.
Cox, The Regression Analysis of Binary Sequences, 1958
-
Naive Bayes 1960s
Bayes' rule with features assumed independent given the class; a strong text baseline.
Maron, Automatic Indexing, 1961
-
k-nearest neighbours 1967
Predict from the k closest training points; no training, all cost at query time.
Cover and Hart, Nearest Neighbor Pattern Classification, 1967
-
k-means and PCA 1901/1982
Unsupervised workhorses: cluster by nearest centroid; project onto directions of most variance.
Lloyd, Least Squares Quantization in PCM, 1982; Pearson, 1901
-
Support vector machines 1995
The maximum-margin separator, with kernels for non-linear boundaries.
Cortes and Vapnik, Support-Vector Networks, 1995
-
Decision trees and random forests 1984/2001
Recursive splits on features; average many decorrelated trees to cut variance.
Breiman, Random Forests, 2001
-
Gradient-boosted trees (XGBoost, LightGBM) 2016
Add trees one at a time, each fitting the previous ensemble's gradient. Still state of the art on tabular data.
Deep learning foundations
The building blocks every modern model is assembled from.
-
Multilayer perceptron 1986
Stacked linear layers with non-linearities, trained by backpropagation.
Rumelhart, Hinton and Williams, Learning Representations by Back-Propagating Errors, 1986
-
CNNs: LeNet, AlexNet, ResNet 1998-2015
Convolutions share weights across space; residual connections make very deep networks trainable.
He et al., Deep Residual Learning for Image Recognition, 2015
-
RNN, LSTM and GRU 1997/2014
Read a sequence one step at a time, carrying a hidden state; gates fix vanishing gradients.
Hochreiter and Schmidhuber, Long Short-Term Memory, 1997
-
word2vec 2013
Learn word vectors by predicting neighbours; the ancestor of every embedding table.
Mikolov et al., Efficient Estimation of Word Representations in Vector Space, 2013
-
Seq2seq with attention 2014
An encoder RNN, a decoder RNN, and attention over the encoder states: the Transformer's direct ancestor.
-
Autoencoders and VAEs 2013
Compress to a latent code and reconstruct; the VAE makes the latent space a distribution you can sample.
-
GANs 2014
A generator and a discriminator trained against each other.
-
U-Net 2015
A convolutional encoder-decoder with skip connections at every resolution; later the backbone of diffusion.
The transformer era
Attention replaces recurrence, and scale becomes the main lever.
-
Transformer 2017
Encoder-decoder built only from attention and feed-forward blocks.
-
BERT 2018
Encoder-only, bidirectional, pre-trained by filling in masked tokens.
-
GPT-2 and GPT-3 2019/2020
Decoder-only next-token prediction; at scale it learns tasks from the prompt alone.
-
T5 2019
Every NLP task cast as text-to-text on one encoder-decoder.
-
Vision Transformer (ViT) 2020
An image is a sequence of 16x16 patches fed to a plain encoder.
-
DDPM and latent diffusion 2020/2021
Generate by learning to undo noise step by step; do it in a VAE's latent space to make it cheap.
Rombach et al., High-Resolution Image Synthesis with Latent Diffusion Models, 2021
-
CLIP 2021
An image encoder and a text encoder trained so matching pairs have similar embeddings.
Radford et al., Learning Transferable Visual Models From Natural Language Supervision, 2021
-
Chinchilla scaling 2022
For a fixed compute budget, grow parameters and training tokens together (about 20 tokens per parameter).
Hoffmann et al., Training Compute-Optimal Large Language Models, 2022
-
InstructGPT (RLHF) 2022
Fine-tune on demonstrations, then on human preference rankings through a reward model.
Ouyang et al., Training Language Models to Follow Instructions with Human Feedback, 2022
-
Whisper 2022
An encoder-decoder transformer over log-Mel spectrograms, trained on 680,000 hours of audio.
Radford et al., Robust Speech Recognition via Large-Scale Weak Supervision, 2022
Current state of the art
Open-weight models with published architectures. Closed frontier models don't publish theirs, so these pages don't guess at them.
-
Llama 3 2024
The reference dense decoder: RMSNorm, SwiGLU, rotary positions, grouped-query attention.
-
Mixtral 8x7B 2024
Sparse mixture of experts: each token goes to 2 of 8 feed-forward experts.
-
DeepSeek-V3 2024
671B total, 37B active parameters per token; multi-head latent attention shrinks the KV cache.
-
DeepSeek-R1 2025
Reasoning learned with large-scale reinforcement learning on verifiable rewards.
-
Qwen3 2025
Dense and MoE models with switchable thinking and non-thinking modes.
-
Gemma 3 2025
Interleaves local sliding-window and global attention layers to keep long-context memory small.
-
Diffusion transformers (DiT, SD3) 2022/2024
Replace the U-Net with a transformer over latent patches; SD3 trains it with rectified flow.
Esser et al., Scaling Rectified Flow Transformers for High-Resolution Image Synthesis, 2024
-
Segment Anything (SAM) 2023
A promptable segmentation model: ViT image encoder, prompt encoder, light mask decoder.
-
Mamba 2023
A selective state-space model: linear-time sequence mixing, the main alternative to attention.
-
Kimi K2 2025
A 1T-total, 32B-active MoE pre-trained on 15.5T tokens with MuonClip: Muon plus QK-Clip, which rescales query and key weights whenever a head's max attention logit passes a threshold.
-
DeepSeek-V3.2-Exp 2025
DeepSeek Sparse Attention: a small ReLU "lightning indexer" scores earlier tokens and each query attends only to its top-k (2,048) of them.
DeepSeek-AI, DeepSeek-V3.2-Exp: Boosting Long-Context Efficiency with DeepSeek Sparse Attention, 2025 (report in the model's GitHub repository)
-
MiMo-V2-Flash 2026
309B total, 15B active; five 128-token sliding-window layers per global layer with a learnable attention sink, and its multi-token-prediction heads reused as a speculative-decoding draft.
-
DeepSeek-V4.1-Flash 2026
Shrinks the KV cache along all three of its axes: decoder layers reuse the global K/V the middle layer computed (a causal encoder-decoder after YOCO), most attention layers reuse a neighbour's cache and top-k indices, and the main cache is stored in FP4 with one 8-bit scale per 16 channels, about 890 bytes of global KV per token.
DeepSeek-AI, DeepSeek-V4.1-Flash: Pushing the Limits of KV Cache Compression, 2026 (report in the model's Hugging Face repository)