The Agentic AI Codex
Ch 04 · Neural Networks
Chapter 04 · Theory + Math

Neural Networks — from one neuron to backprop

Everything in deep learning is built on three primitives: a weighted sum, a non-linear activation, and a gradient step. Get those right and the entire transformer stack later becomes a furniture-rearrangement.

4.1 · The artificial neuron

A neuron computes a weighted sum of inputs, adds a bias, and squashes through a non-linearity:

$a = \sigma\!\left(\sum_{i=1}^{n} w_i x_i + b\right)$

x₁ x₂ x₃ w₁ w₂ w₃ Σ + b σ a

The whole field of deep learning is: stack these, train the weights.

4.2 · The Multi-Layer Perceptron (MLP)

Stack neurons in layers; each layer is a matrix multiply + activation:

$\mathbf{h}^{(\ell)} = \sigma\!\left(\mathbf{W}^{(\ell)} \mathbf{h}^{(\ell-1)} + \mathbf{b}^{(\ell)}\right)$

Universal approximation theorem: a single hidden layer with enough neurons can approximate any continuous function. In practice depth works better than width — fewer parameters per quality unit.

4.3 · Activation functions — what each one actually does

Why we need them. A stack of linear layers without activations collapses algebraically to a single linear layer. Activations introduce the bends the network needs to model curves, edges, language — anything non-trivial.

The four most-used activations, drawn

Sigmoid Tanh ReLU GELU

Sigmoid — $\sigma(z) = \dfrac{1}{1+e^{-z}}$

What it does: squashes any real number into $(0, 1)$.

Example: binary-classification output, e.g. "spam vs not spam" probability.

Watch out: saturates for large $|z|$ → tiny gradients ("vanishing gradient").

Tanh — $\tanh(z)$

What it does: like sigmoid but centred at 0, range $(-1, 1)$.

Example: classic RNN hidden states; smoother than sigmoid for symmetric data.

ReLU — $\max(0, z)$

What it does: kills negatives, keeps positives as-is.

Example: the default hidden activation since 2012 — every ResNet, every CNN layer.

Watch out: "dying ReLU" — neurons stuck at 0 forever. Fix: Leaky ReLU, $\max(0.01z, z)$.

GELU — $z \cdot \Phi(z)$

What it does: a smooth, probabilistic version of ReLU.

Example: the activation inside every transformer block of BERT and GPT.

SwiGLU — $\text{Swish}(xW) \odot xV$

What it does: a gated activation; one branch decides "how much" of the other to let through.

Example: feed-forward layers of LLaMA, modern open LLMs.

Softmax — $p_i = \dfrac{e^{z_i}}{\sum_j e^{z_j}}$

What it does: turns a vector of scores into a probability distribution that sums to 1.

Example: final layer of any multi-class classifier; attention weights; LLM next-token distribution.

4.4 · Loss functions

TaskLoss
RegressionMSE: $\frac{1}{n}\sum(y - \hat{y})^2$
Binary classificationBinary cross-entropy: $-y\log\hat{p} - (1-y)\log(1-\hat{p})$
Multi-classCategorical cross-entropy
Embeddings / metric learningContrastive / triplet loss
LLM pre-trainingNext-token cross-entropy

4.5 · The forward pass — worked example

# 2 → 3 → 1 network on a single sample
x = [1.0, 2.0]                 # input
W1 = [[0.1, 0.2],
      [-0.1, 0.3],
      [0.4, -0.5]]              # shape (3, 2)
b1 = [0.0, 0.0, 0.1]

z1 = [W1[i][0]*x[0] + W1[i][1]*x[1] + b1[i] for i in range(3)]
h1 = [max(0, v) for v in z1]        # ReLU

# final layer (3 → 1) ... weighted sum → sigmoid → prediction

4.6 · Backpropagation — the chain rule, organised

Given loss $\mathcal{L}$ and weight $w$ deep in the network, backprop computes $\partial \mathcal{L}/\partial w$ by chaining derivatives layer-by-layer from output back to input.

For a single hidden neuron with output $a = \sigma(z)$, $z = w \cdot x + b$:

$\dfrac{\partial \mathcal{L}}{\partial w} = \underbrace{\dfrac{\partial \mathcal{L}}{\partial a}}_{\text{from above}} \cdot \underbrace{\sigma'(z)}_{\text{local}} \cdot \underbrace{x}_{\text{input}}$

input x layer 1 layer 2 loss L forward → ← backward (gradients)

Modern libraries (PyTorch, JAX, TensorFlow) implement autograd: you write the forward pass; the framework builds a computation graph and back-propagates automatically.

4.7 · Optimizers — what each one really does

Every optimizer answers the same question: given the gradient, how big a step should I take and in what direction?

SGD (Stochastic Gradient Descent)

Rule: $w \leftarrow w - \eta \nabla \mathcal{L}$.

Intuition: walk downhill, one mini-batch at a time. Pure and simple.

Example: training a ResNet on ImageNet, often with momentum + cosine schedule.

SGD + Momentum

Rule: $v \leftarrow \beta v + \nabla \mathcal{L};\; w \leftarrow w - \eta v$.

Intuition: a ball rolling down a valley keeps moving past flat spots — fewer oscillations, faster convergence.

RMSProp

What it adds: divides the learning rate by a moving average of recent gradient magnitudes, so each parameter gets its own effective step size.

Example: RNN training, where some parameters get rare but huge gradients.

Adam / AdamW

What it adds: Momentum (first moment) + RMSProp (second moment) + bias correction. AdamW decouples weight decay correctly.

Example: the default optimizer for nearly every transformer trained since 2018.

Lion

What it adds: uses only the sign of the moving-average gradient — half Adam's memory, often matches it.

Example: large-scale pretraining where saving GPU memory matters.

Learning-rate schedules

  • Warmup: ramp from 0 → $\eta$ over the first few hundred steps (avoids instability).
  • Cosine decay: gradually anneal $\eta$ toward zero. Standard for LLM pretraining.
  • One-cycle: small → big → small. Pop-classic for vision fine-tunes.

4.8 · Regularization that actually helps

  • Dropout — randomly zero a fraction (e.g. 0.1) of activations each step.
  • Weight decay — L2 penalty on weights, baked into AdamW.
  • Label smoothing — soften one-hot targets to prevent over-confidence.
  • Early stopping — track validation loss; stop when it stops improving.
  • Data augmentation — cheap data multiplier (flips, crops, paraphrases).

4.9 · Initialization & normalization — small details, huge impact

TrickWhy
Xavier / Glorot initKeeps variance stable across layers for tanh/sigmoid.
Kaiming / He initTuned for ReLU.
BatchNormNormalizes activations across the batch. Smoother training in vision.
LayerNormNormalizes across features per sample. Standard in transformers.
RMSNormLighter LayerNorm variant used in LLaMA.
Residual connections$y = x + f(x)$. Lets gradients flow through deep networks.

4.10 · Evaluating a neural network

A neural network is just a function. We evaluate it like any other ML model — but with two extras to watch: the loss curves (which expose under/overfitting visually) and the head-specific metrics (classification head ≠ regression head ≠ embedding head).

The four loss-curve shapes you must recognise

Healthy epochs → Underfit both stuck high Overfit val curls back up Diverging LR too high solid = train loss · dashed = validation loss

Train / validation / test — the three splits

SplitUsed forTouched how often?
Train (~70–80%)Update weights via backprop.Every batch.
Validation (~10–15%)Tune hyperparameters, early stopping, model selection.Once per epoch.
Test (~10–15%)Final, unbiased estimate of generalisation.Exactly once, at the very end.

K-fold cross-validation is the small-data alternative: split into $K$ folds and rotate validation through each, averaging scores.

Metrics by head — match the metric to the output

MetricWhat it tells you
Accuracy, Top-1 / Top-5Fraction correct; for many-class problems, allow the true label to be in top-k predictions.
Cross-entropy (val loss)Same loss used for training; track per-epoch.
Precision / Recall / F1 / ROC-AUC / PR-AUCFull classification suite from Ch 3. Macro-average for multi-class.
Calibration / ECEAre predicted probabilities trustworthy? Reliability diagram.
Confusion matrixDiagnose which classes the model confuses.
MetricWhat it tells you
MAE, MSE, RMSEAverage error magnitude.
R² / Adjusted R²Variance explained.
MAPE / SMAPEPercentage error for cross-scale comparison.
Quantile / Pinball lossFor prediction-interval models.
MetricWhat it tells you
Hamming lossFraction of wrong labels across all classes per sample.
Subset accuracy (exact match)1 only if every label is correct — strict.
Label-wise Precision / Recall / F1Compute per label, average (macro / micro / weighted).
mAP (mean Average Precision)Mean of per-label AP — standard for object detection.
MetricWhat it tells you
Cosine similarity / distanceGeometric quality of learned embeddings.
Recall@k / MRRDoes the right neighbour appear in the top-k of an anchor?
Triplet / contrastive lossTraining loss that doubles as quality proxy on held-out triplets.
Alignment / UniformityWang & Isola (2020) diagnostics for contrastive learning.
Don't confuse loss with metric
The loss is what you minimise during training (must be differentiable). The metric is what you report to humans (need not be differentiable). Cross-entropy is the loss; accuracy and F1 are the metrics. They usually move together — but not always.

4.11 · A training-loop checklist

  1. Start with a tiny model on a tiny subset — confirm it can overfit a few batches. If not, the loss or shape is wrong.
  2. Sanity-check input/output ranges; normalize inputs to roughly zero mean and unit variance.
  3. Print or log: loss, gradient norm, parameter norm — every step at first.
  4. Use a learning-rate finder to bracket a reasonable range.
  5. Hold out a validation set; monitor it; early stop.
  6. Fix all seeds you care about; document them.
  7. Save checkpoints often. Resume-friendly code earns you weeks of life back.

4.12 · Self-check

Q1 · Why do networks need non-linear activations?
For speed
Without them a deep network is equivalent to one linear layer
To save memory
To make the loss differentiable
Q2 · What does backprop compute?
Predictions on the training set
∂L/∂w for every weight
The validation accuracy
The next weight update