Learning Paradigms and Models §
Neural networks are parametric models trained by gradient descent to map data to predictions. Their design is governed by five orthogonal axes: architecture (the blocks and connections that define the function), loss (the scalar objective that defines “good”), data (the paradigm that supplies the learning signal: unsupervised, supervised, or reinforcement), training (the loop that evaluates and updates the model at scale), and evaluation (the measurement of whether the model generalizes beyond its training data). This page is relevant whenever a system must adapt to data, discover structure, or make sequential decisions.
Authoritative sources
Architecture §
The architecture of a neural network is the composition of blocks (linear maps, nonlinearities, convolutions, attention) wired together with input representations (embeddings, tokenization) and output heads (softmax, sigmoid, linear). The architecture determines the function class the model can express; the loss and data determine which function in that class is selected.
Details
Step 1 — What one layer computes. A transformer layer applies two sub-blocks, each wrapped in a residual connection: multi-head self-attention, where tokens exchange information with each other, followed by a position-wise feed-forward MLP, where each token is transformed independently. Layer normalization stabilizes the activations before each sub-block. Stacking such layers, with positional information added at the input, gives the full model.
Step 2 — A concrete trace: one token through one layer. Take a sequence of three tokens with embeddings , , , and a single attention head with identity projections (, ). For position 1:
- Scores: gives .
- Softmax: .
- Attention output: — a blend of all three value vectors, weighted by relevance.
- Residual: — the original token enriched with information from the other tokens.
The feed-forward sub-block then transforms this vector independently, and the next layer repeats the process on the whole sequence.
Reference — the blocks at a glance.
Inputs. One-hot encoding: a categorical variable with classes as a -dimensional vector with a single 1; wasteful for large vocabularies. Embeddings: a learned dense vector per token; the table is a matrix and lookup is a row selection; co-occurring tokens end up with nearby vectors. Tokenization (BPE): iteratively merge the most frequent adjacent character pairs, balancing vocabulary size against sequence length. Positional encoding: transformers have no inherent order, so a position signal is added — sinusoidal (fixed, extrapolates) or learned (flexible, limited to training length).
Outputs. Sigmoid: maps a scalar to ; used for binary classification and LSTM gates. Softmax: maps a vector to a probability distribution; used for multiclass heads and language-model outputs. Pooling: max preserves salient features, min preserves the weakest signal, average smooths; used in CNNs to reduce spatial resolution and to produce fixed-size sentence representations.
Blocks. MLP: ; the transformer’s position-wise FFN is a 2-layer MLP with . ReLU: ; GELU and SiLU are smooth variants that train better. CNN: with shared weights — translation invariance plus local connectivity builds a hierarchy of spatial features. RNN / LSTM: recurrent state ; the LSTM’s cell state , with input/forget/output gates lets it remember over long distances. Residual connections: let gradients reach early layers, enabling very deep stacks. Self-attention: ; multi-head attention runs heads in parallel and concatenates them. KV cache: during autoregressive generation, cached keys/values cut per-token cost from to .
Source: Attention Is All You Need introduces the layer traced above.
Example problem
A single attention head has identity projections and . The sequence is , . Compute the attention weights for position 1 and the attention output at that position.
Solution
Scores: , . Softmax: . Output: . After the residual add: .
Loss §
The loss function is the scalar that gradient descent minimizes; it encodes what “good” means for a given task. The choice of loss determines the geometry of the optimization landscape and the statistical properties of the learned model.
Details
Step 1 — What a loss does. The loss compresses “how wrong the model is on this example” into one differentiable number. Gradient descent then follows the slope of the average loss downhill. Two consequences follow: the loss must be differentiable (or subdifferentiable) in the model’s outputs, and its shape matters — a convex loss has a single basin, while a deep network’s loss surface is non-convex, full of local minima and saddle points that SGD nevertheless navigates well in practice.
Step 2 — A concrete example: cross-entropy for a 3-class prediction. A classifier outputs logits for three classes; the true label is class 2. Softmax gives . The cross-entropy against the one-hot target is . The gradient with respect to the logits is : push class 2 up, push the others down, in proportion to how wrong each was.
Reference — the losses in common use.
Mean squared error (MSE): . Used for regression. The gradient is proportional to the residual, so large errors dominate the update; sensitive to outliers.
Cross-entropy: . Used for classification; the negative log-likelihood of the true label. With softmax the gradient is , which vanishes when correct and grows when wrong.
Perplexity: . The geometric mean number of choices the model “considers” per token; used to compare language models.
KL divergence: . The information lost when approximates ; used in VAEs, distillation, and GAN variants.
Weight decay (L2 regularization): adds to the loss, shrinking weights toward zero. AdamW applies the decay directly to parameters (“decoupled”).
Knowledge distillation: the student matches both hard labels and the teacher’s softened outputs: . The temperature softens the teacher’s distribution so the student learns its “dark knowledge” (relative probabilities of incorrect classes).
Source: Distilling the Knowledge in a Neural Network introduces the distillation loss and the temperature scaling.
Example problem
A model predicts for a 3-class problem whose true class is 1. Compute the cross-entropy loss and the gradient with respect to the logits.
Solution
nats. The gradient is : the correct class logit should increase, the others decrease.
Data §
The data paradigm determines how the learning signal is structured. Three paradigms exist, distinguished by what the environment provides: unsupervised (raw data, no labels), supervised (input–label pairs), and reinforcement (sequential rewards from an environment). The paradigm dictates the loss, the architecture constraints, and the training loop.
Details
Step 1 — The paradigm is the signal. Before choosing an architecture or a loss, ask what the environment gives you. If you only have raw data, the model must invent its own supervision (structure: clusters, axes of variance, compressed codes, generative fidelity). If you have labels, the loss can compare the prediction to the truth directly. If an agent must act and only receives delayed rewards, the model must trade off exploration and long-term return. Everything downstream — loss, architecture, evaluation — follows from this choice.
Step 2 — Unsupervised learning. Each method targets a different notion of “structure”.
Clustering (k-means): partition points into groups by minimizing within-cluster variance:
The algorithm alternates between assigning each point to the nearest centroid and recomputing centroids as cluster means; it converges to a local optimum in finite steps. Try it interactively:
PCA: find the orthonormal basis that maximizes projected variance. Eigendecompose the covariance matrix ; the top- eigenvectors span the maximum-variance subspace. Used for dimensionality reduction, denoising, and visualization; it is the linear special case of an autoencoder.
Autoencoders: a network with a bottleneck learns a compressed representation by minimizing reconstruction error . Being nonlinear, it captures manifold structure that PCA misses; variational autoencoders add a probabilistic prior on for generative modeling. (GANs and diffusion models push the same generative idea further: GANs train a generator against a discriminator in a minimax game, and diffusion models learn to reverse a gradual noising process.)
Step 3 — Supervised learning. Given a dataset , the model is trained to minimize a loss by gradient descent.
Regression: the target is continuous; the standard loss is mean squared error (see the Loss section above). Applications: price prediction, demand forecasting, sensor calibration.
Classification: the target is a discrete label; the loss is categorical cross-entropy (see the Loss section above), with a sigmoid head for the binary case and a softmax head for the multiclass case. Applications: image labeling, spam detection, medical diagnosis.
Sequence labeling: one label per input token — named-entity recognition, part-of-speech tagging, speech recognition — typically an RNN or transformer with a per-position classification head.
Step 4 — Reinforcement learning. An agent in a Markov Decision Process learns a policy to maximize expected cumulative reward . The Bellman equation links a state’s value to its successors. Policy gradient (REINFORCE) directly ascends ; actor-critic adds a value function to reduce variance. When the agent must also plan, tree search over the state graph is used — see Graphs for the underlying search algorithms (best-first search, MCTS-style playouts, A*).
Source: Reinforcement Learning: An Introduction covers MDPs, Bellman equations, and policy gradients in depth.
Example problem
Run one full k-means iteration on the 1-D points with and initial centroids , . What are the new centroids, and has the algorithm converged after a second iteration?
Solution
Assignment: each point goes to the nearest centroid: (distances 0, 1, 2 vs 8, 7, 6) and (distances 1, 0 vs 7, 6).
Update: , .
Second iteration: assignments are unchanged ( still nearest to 2, still nearest to 8.5), so the centroids no longer move: the algorithm has converged to a local optimum.
Training §
Training a neural network means running a loop: sample a mini-batch, run the forward pass to compute predictions and loss, run the backward pass to get gradients, and update the parameters. Everything else — batching strategy, learning-rate schedules, distributed execution — exists to make this loop converge faster and scale further. The calculus of how gradients are computed (chain rule, automatic differentiation, backpropagation) is covered in Optimization and differentiation; this section focuses on the loop itself.
Details
Step 1 — The training loop. One iteration is: (1) draw a mini-batch of examples; (2) forward pass — apply the network to the batch and evaluate the loss; (3) backward pass — propagate the loss gradient back through the computation graph to every parameter; (4) update — move each parameter a small step against its gradient. Repeat until the loss stops improving. The backward pass is exactly the chain rule applied in reverse topological order over the graph recorded during the forward pass; the formulas and the automatic-differentiation machinery live in the Optimization and differentiation topic linked above.
Step 2 — Batching and stochastic gradient descent. Computing the gradient over the whole dataset (“full batch”) is exact but expensive; computing it over one example is noisy. The mini-batch (typically 32–4096 examples) sits in the sweet spot: gradients are averaged over enough examples to be informative, and the batch is large enough to use GPU matrix multiplication efficiently. The noise of small batches is not purely a cost — it helps escape sharp minima.
Step 3 — Learning-rate schedules. The step size is the single most important hyperparameter. Schedules shape it over time: step decay (drop by 10× at milestones), cosine decay (smoothly anneal to zero), warmup (ramp up over the first few hundred steps, essential for large transformers, whose early training is unstable). Adaptive optimizers (Adam, AdamW) give each parameter its own effective step size based on gradient statistics.
Step 4 — Initialization. The first forward pass must neither saturate nonlinearities nor explode activations. Xavier initialization scales weights by ; He initialization by for ReLU networks. Bad initialization shows up immediately: the loss does not decrease in the first hundred steps.
Step 5 — Training at scale. A single dense layer is a matrix product, and GPUs execute thousands of such products in parallel, which is why deep learning took off with GPU hardware. When a model no longer fits on one device, the training loop itself is distributed: data parallelism replicates the model and splits the batch, pipeline parallelism splits the layers across devices, and tensor parallelism splits individual weight matrices. These are distributed-systems problems (see the Distributed systems topic) layered on top of the same loop.
Source: Deep Learning, chapter 8 (Optimization for Training Deep Models) covers batching, learning rates, and initialization.
Example problem
A scalar two-layer network computes with . Given , , , target , and learning rate : compute the loss, both gradients, and the updated weights after one training step.
Solution
Forward: , , , .
Backward: . Then , so . And ; since the ReLU passes the gradient through, and , so .
Update: , . The new prediction is — it overshot the target, a reminder that the gradient is only valid infinitesimally, which is why small learning rates (or schedules) matter.
Evaluation and Generalization §
A model is useful only if it performs well on data it has not been trained on. Generalization measures that gap; the machinery of evaluation — splits, curves, and model selection — tells you whether your model has learned the task or merely memorized the training set.
Details
Step 1 — The split. Hold data out in three roles. The training set fits the parameters . The validation set is untouched by gradient descent but is looked at: it selects hyperparameters, sets the learning-rate schedule, and decides when to stop. The test set is touched exactly once, at the end, to report the final number — every peek at it is a form of fitting.
Step 2 — Overfitting and underfitting. The generalization gap is validation performance minus training performance. Underfitting: both losses are high — the model lacks capacity or training time; add capacity, train longer, or improve features. Overfitting: training loss keeps dropping while validation loss flattens and rises — the model is memorizing noise; add data, add regularization (weight decay, dropout), or stop earlier. The learning-curve diagram above shows the canonical signature: the two curves diverge after the early-stopping point.
Step 3 — Model selection. Given the validation curve, choose the checkpoint with the lowest validation loss (early stopping). For hyperparameters (learning rate, depth, weight decay ), run the same training with several values and pick by validation performance — never by training performance, which always favors the most overfit model. When data is scarce, k-fold cross-validation rotates the validation role across splits and averages, giving a lower-variance estimate at times the training cost.
Step 4 — Reading curves in practice. Noisy validation loss is normal; compare smoothed curves. A validation loss that plateaus early while training loss falls slowly suggests the learning rate is too small or the model too small. A validation loss that spikes suggests the learning rate is too large. Curves are the model’s vital signs: most debugging in deep learning is curve reading.
Source: Deep Learning, chapter 5 (Machine Learning Basics) formalizes the generalization gap, cross-validation, and the bias-variance trade-off.
Example problem
A model is trained for 6 epochs with validation losses and training losses . Which epoch should you deploy, and what is happening after it?
Solution
Deploy the epoch-4 checkpoint: validation loss is minimal there (). After epoch 4 the training loss keeps falling () while validation loss rises (): the model has begun to overfit, memorizing training examples that do not transfer. Early stopping at epoch 4 (or stronger regularization) is the fix.
Quiz §
Problem: You design a transformer-based language model with embedding dimension , 8 attention heads, 4 layers, feedforward hidden dimension , and vocabulary size . (a) Compute the number of parameters in a single transformer layer (multi-head attention + position-wise feedforward + two layer norms; ignore positional encoding and the embedding/output matrices). (b) The model is trained with cross-entropy loss. If the validation perplexity is 8.0, what is the cross-entropy loss per token? (c) You distill the model into a smaller student with temperature and mixing weight . Write the combined distillation loss.
Solution
(a) A single transformer layer contains:
- Multi-head self-attention: four weight matrices (): parameters.
- Position-wise feedforward: two matrices (, ): parameters.
- Two layer norms: each has a scale and a bias vector of length : parameters.
Total: parameters per layer.
(b) Perplexity is defined as , so the cross-entropy loss per token is nats.
(c) The combined distillation loss is:
Substituting and :
The coefficient multiplying the KL term is the combined product — the mixing weight times the squared temperature, not alone. The temperature softens the teacher’s distribution (which shrinks the KL term’s magnitude), the factor compensates for that softening, and the weight balances the hard-label and soft-label contributions equally.