Technopedia

The technologist’s encyclopedia

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.

residual (skip) connections tokens x LayerNorm multi-head self-attention + LayerNorm feed-forward MLP + out One transformer layer: each sub-block is preceded by a LayerNorm and wrapped in a residual connection. Stack L such layers.
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 LL 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 x1=[1,0]x_1 = [1, 0], x2=[0,1]x_2 = [0, 1], x3=[1,1]x_3 = [1, 1], and a single attention head with identity projections (WQ=WK=WV=IW_Q = W_K = W_V = I, d=2d = 2). For position 1:

  1. Scores: q1⋅kj=x1⋅xjq_1 \cdot k_j = x_1 \cdot x_j gives [1,0,1][1, 0, 1].
  2. Softmax: softmax([1,0,1])≈[0.422,0.155,0.422]\text{softmax}([1, 0, 1]) \approx [0.422, 0.155, 0.422].
  3. Attention output: 0.422 x1+0.155 x2+0.422 x3=[0.845,0.538]0.422\,x_1 + 0.155\,x_2 + 0.422\,x_3 = [0.845, 0.538] — a blend of all three value vectors, weighted by relevance.
  4. Residual: x1+output=[1.845,0.538]x_1 + \text{output} = [1.845, 0.538] — 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 VV classes as a VV-dimensional vector with a single 1; wasteful for large vocabularies. Embeddings: a learned dense vector ec∈Rde_c \in \mathbb{R}^d per token; the table is a V×dV \times d 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 PE(pos,2i)=sin⁡(pos/100002i/d)PE(pos, 2i) = \sin(pos / 10000^{2i/d}) (fixed, extrapolates) or learned (flexible, limited to training length).

Outputs. Sigmoid: σ(z)=1/(1+e−z)\sigma(z) = 1/(1+e^{-z}) maps a scalar to (0,1)(0,1); used for binary classification and LSTM gates. Softmax: softmax(z)i=ezi/∑jezj\text{softmax}(z)_i = e^{z_i} / \sum_j e^{z_j} 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: f(x)=WLσ(⋯σ(W1x+b1)⋯ )f(x) = W_L \sigma(\cdots \sigma(W_1 x + b_1)\cdots); the transformer’s position-wise FFN is a 2-layer MLP with dff≈4dd_{ff} \approx 4d. ReLU: max⁡(0,x)\max(0, x); GELU and SiLU are smooth variants that train better. CNN: yi=∑jWi−jxjy_i = \sum_j W_{i-j} x_j with shared weights — translation invariance plus local connectivity builds a hierarchy of spatial features. RNN / LSTM: recurrent state ht=f(ht−1,xt)h_t = f(h_{t-1}, x_t); the LSTM’s cell state ct=ft⊙ct−1+it⊙c~tc_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t, ht=ot⊙tanh⁡(ct)h_t = o_t \odot \tanh(c_t) with input/forget/output gates lets it remember over long distances. Residual connections: y=F(x)+xy = F(x) + x let gradients reach early layers, enabling very deep stacks. Self-attention: Attn(Q,K,V)=softmax(QKT/dk) V\text{Attn}(Q, K, V) = \text{softmax}(QK^T / \sqrt{d_k})\,V; multi-head attention runs hh heads in parallel and concatenates them. KV cache: during autoregressive generation, cached keys/values cut per-token cost from O(t2)O(t^2) to O(t)O(t).

Source: Attention Is All You Need introduces the layer traced above.

Example problem

A single attention head has identity projections and d=2d = 2. The sequence is x1=[1,0]x_1 = [1, 0], x2=[0,1]x_2 = [0, 1]. Compute the attention weights for position 1 and the attention output at that position.

Solution

Scores: q1⋅k1=1q_1 \cdot k_1 = 1, q1⋅k2=0q_1 \cdot k_2 = 0. Softmax: [e1/(e1+e0), e0/(e1+e0)]=[2.718/3.718, 1/3.718]≈[0.731,0.269][e^1/(e^1+e^0),\ e^0/(e^1+e^0)] = [2.718/3.718,\ 1/3.718] \approx [0.731, 0.269]. Output: 0.731 x1+0.269 x2=[0.731,0.269]0.731\,x_1 + 0.269\,x_2 = [0.731, 0.269]. After the residual add: x1+output=[1.731,0.269]x_1 + \text{output} = [1.731, 0.269].

Loss

The loss function L(y^,y)\mathcal{L}(\hat{y}, y) 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.

loss parameter value local min global min convex: one minimum non-convex: many minima
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 z=[1.0,2.0,0.5]z = [1.0, 2.0, 0.5] for three classes; the true label is class 2. Softmax gives y^=[0.186,0.506,0.309]\hat{y} = [0.186, 0.506, 0.309]. The cross-entropy against the one-hot target y=[0,1,0]y = [0, 1, 0] is L=−log⁡(0.506)≈0.681\mathcal{L} = -\log(0.506) \approx 0.681. The gradient with respect to the logits is y^−y=[0.186,−0.494,0.309]\hat{y} - y = [0.186, -0.494, 0.309]: 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): L=1n∑i(y^i−yi)2\mathcal{L} = \frac{1}{n}\sum_i (\hat{y}_i - y_i)^2. Used for regression. The gradient is proportional to the residual, so large errors dominate the update; sensitive to outliers.

Cross-entropy: L=−∑i∑cyi,clog⁡y^i,c\mathcal{L} = -\sum_i \sum_c y_{i,c} \log \hat{y}_{i,c}. Used for classification; the negative log-likelihood of the true label. With softmax the gradient is y^−y\hat{y} - y, which vanishes when correct and grows when wrong.

Perplexity: PPL=exp⁡(LCE)PPL = \exp(\mathcal{L}_{CE}). The geometric mean number of choices the model “considers” per token; used to compare language models.

KL divergence: DKL(P∥Q)=∑xP(x)log⁡P(x)Q(x)D_{KL}(P \| Q) = \sum_x P(x) \log \frac{P(x)}{Q(x)}. The information lost when QQ approximates PP; used in VAEs, distillation, and GAN variants.

Weight decay (L2 regularization): adds λ∥θ∥2\lambda \|\theta\|^2 to the loss, shrinking weights toward zero. AdamW applies the decay directly to parameters (“decoupled”).

Knowledge distillation: the student fθf_\theta matches both hard labels and the teacher’s softened outputs: L=α⋅CE(y^,y)+(1−α)⋅T2⋅DKL(pϕ/T∥pθ/T)\mathcal{L} = \alpha \cdot \text{CE}(\hat{y}, y) + (1-\alpha) \cdot T^2 \cdot D_{KL}(p_\phi / T \| p_\theta / T). The temperature TT 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 y^=[0.7,0.2,0.1]\hat{y} = [0.7, 0.2, 0.1] for a 3-class problem whose true class is 1. Compute the cross-entropy loss and the gradient y^−y\hat{y} - y with respect to the logits.

Solution

L=−ln⁡(0.7)≈0.357\mathcal{L} = -\ln(0.7) \approx 0.357 nats. The gradient is y^−y=[0.7−1, 0.2, 0.1]=[−0.3, 0.2, 0.1]\hat{y} - y = [0.7 - 1,\ 0.2,\ 0.1] = [-0.3,\ 0.2,\ 0.1]: 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.

What signal does the environment provide? raw data, no labels input-label pairs rewards for actions Unsupervised find structure in raw data k-means, PCA, autoencoders Supervised map inputs to labels regression, classification Reinforcement act to maximize reward policy gradient, value functions
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 nn points into kk groups by minimizing within-cluster variance:

min⁡{C1,…,Ck}∑j=1k∑x∈Cj∥x−μj∥2\min_{\{C_1,\ldots,C_k\}} \sum_{j=1}^{k} \sum_{x \in C_j} \|x - \mu_j\|^2

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 Σ=UΛUT\Sigma = U \Lambda U^T; the top-kk 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 x→z→x^x \to z \to \hat{x} with a bottleneck zz learns a compressed representation by minimizing reconstruction error ∥x−x^∥2\|x - \hat{x}\|^2. Being nonlinear, it captures manifold structure that PCA misses; variational autoencoders add a probabilistic prior on zz 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 {(xi,yi)}i=1n\{(x_i, y_i)\}_{i=1}^{n}, the model fθf_\theta is trained to minimize a loss L(fθ(xi),yi)\mathcal{L}(f_\theta(x_i), y_i) by gradient descent.

Regression: the target yy is continuous; the standard loss is mean squared error (see the Loss section above). Applications: price prediction, demand forecasting, sensor calibration.

Classification: the target yy 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 (S,A,P,R,γ)(S, A, P, R, \gamma) learns a policy π(a∣s)\pi(a|s) to maximize expected cumulative reward Vπ(s)=E[∑tγtR(st,at)]V^\pi(s) = \mathbb{E}[\sum_t \gamma^t R(s_t, a_t)]. The Bellman equation Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVπ(s′)]V^\pi(s) = \sum_a \pi(a|s) \sum_{s'} P(s'|s,a)[R(s,a,s') + \gamma V^\pi(s')] links a state’s value to its successors. Policy gradient (REINFORCE) directly ascends ∇J(θ)=E[∇log⁡πθ(a∣s)⋅Gt]\nabla J(\theta) = \mathbb{E}[\nabla \log \pi_\theta(a|s) \cdot G_t]; 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 {1,2,3,8,9}\{1, 2, 3, 8, 9\} with k=2k = 2 and initial centroids c1=1c_1 = 1, c2=9c_2 = 9. What are the new centroids, and has the algorithm converged after a second iteration?

Solution

Assignment: each point goes to the nearest centroid: {1,2,3}→c1\{1, 2, 3\} \to c_1 (distances 0, 1, 2 vs 8, 7, 6) and {8,9}→c2\{8, 9\} \to c_2 (distances 1, 0 vs 7, 6).

Update: c1=(1+2+3)/3=2c_1 = (1+2+3)/3 = 2, c2=(8+9)/2=8.5c_2 = (8+9)/2 = 8.5.

Second iteration: assignments are unchanged ({1,2,3}\{1,2,3\} still nearest to 2, {8,9}\{8,9\} 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.

forward pass: compute predictions and loss x layer 1 (W1) h layer 2 (W2) y loss L dL/dW2 dL/dW1 backward pass: gradients flow from the loss to every parameter
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 1/nin1/\sqrt{n_{in}}; He initialization by 2/nin\sqrt{2/n_{in}} 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 y^=W2⋅h\hat{y} = W_2 \cdot h with h=ReLU(W1⋅x)h = \text{ReLU}(W_1 \cdot x). Given x=2x = 2, W1=1W_1 = 1, W2=2W_2 = 2, target y=6y = 6, and learning rate 0.10.1: compute the loss, both gradients, and the updated weights after one training step.

Solution

Forward: z=W1x=2z = W_1 x = 2, h=ReLU(2)=2h = \text{ReLU}(2) = 2, y^=W2h=4\hat{y} = W_2 h = 4, L=(y^−y)2=4L = (\hat{y} - y)^2 = 4.

Backward: ∂L/∂y^=2(y^−y)=−4\partial L/\partial \hat{y} = 2(\hat{y} - y) = -4. Then ∂y^/∂W2=h=2\partial \hat{y}/\partial W_2 = h = 2, so ∂L/∂W2=−8\partial L/\partial W_2 = -8. And ∂L/∂h=∂L/∂y^⋅W2=−8\partial L/\partial h = \partial L/\partial \hat{y} \cdot W_2 = -8; since z=2>0z = 2 > 0 the ReLU passes the gradient through, and ∂z/∂W1=x=2\partial z/\partial W_1 = x = 2, so ∂L/∂W1=−16\partial L/\partial W_1 = -16.

Update: W2←2−0.1×(−8)=2.8W_2 \leftarrow 2 - 0.1 \times (-8) = 2.8, W1←1−0.1×(−16)=2.6W_1 \leftarrow 1 - 0.1 \times (-16) = 2.6. The new prediction is y^=2.8×ReLU(2.6×2)=14.56\hat{y} = 2.8 \times \text{ReLU}(2.6 \times 2) = 14.56 — 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.

loss training epochs early stopping overfitting: validation loss rises again training loss validation loss
Details

Step 1 — The split. Hold data out in three roles. The training set fits the parameters θ\theta. 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 λ\lambda), 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 kk splits and averages, giving a lower-variance estimate at kk 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 [2.1,1.4,1.0,0.9,0.95,1.15][2.1, 1.4, 1.0, 0.9, 0.95, 1.15] and training losses [2.0,1.3,0.8,0.4,0.15,0.05][2.0, 1.3, 0.8, 0.4, 0.15, 0.05]. Which epoch should you deploy, and what is happening after it?

Solution

Deploy the epoch-4 checkpoint: validation loss is minimal there (0.90.9). After epoch 4 the training loss keeps falling (0.4→0.050.4 \to 0.05) while validation loss rises (0.9→1.150.9 \to 1.15): 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 d=512d = 512, 8 attention heads, 4 layers, feedforward hidden dimension dff=2048d_{ff} = 2048, and vocabulary size V=32 000V = 32\,000. (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 T=4T = 4 and mixing weight α=0.5\alpha = 0.5. Write the combined distillation loss.

Solution

(a) A single transformer layer contains:

Total: 1 048 576+2 097 152+2 048=3 147 7761\,048\,576 + 2\,097\,152 + 2\,048 = 3\,147\,776 parameters per layer.

(b) Perplexity is defined as PPL=exp⁡(LCE)PPL = \exp(\mathcal{L}_{CE}), so the cross-entropy loss per token is LCE=ln⁡(8)≈2.079\mathcal{L}_{CE} = \ln(8) \approx 2.079 nats.

(c) The combined distillation loss is:

L=α⋅CE(y^,y)+(1−α)⋅T2⋅DKL ⁣(pϕT  ∥  pθT)\mathcal{L} = \alpha \cdot \text{CE}(\hat{y}, y) + (1-\alpha) \cdot T^2 \cdot D_{KL}\!\left(\frac{p_\phi}{T} \;\Big\|\; \frac{p_\theta}{T}\right)

Substituting α=0.5\alpha = 0.5 and T=4T = 4:

L=0.5⋅CE(y^,y)+8⋅DKL ⁣(pϕ4  ∥  pθ4)\mathcal{L} = 0.5 \cdot \text{CE}(\hat{y}, y) + 8 \cdot D_{KL}\!\left(\frac{p_\phi}{4} \;\Big\|\; \frac{p_\theta}{4}\right)

The coefficient 88 multiplying the KL term is the combined product (1−α)⋅T2=0.5×16=8(1-\alpha) \cdot T^2 = 0.5 \times 16 = 8 — the mixing weight times the squared temperature, not T2T^2 alone. The temperature softens the teacher’s distribution (which shrinks the KL term’s magnitude), the T2T^2 factor compensates for that softening, and the (1−α)(1-\alpha) weight balances the hard-label and soft-label contributions equally.