Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The formula sheet

Ten minutes, one page. Nothing here is explained — it is recalled.


Losses

MSE — Gaussian noise / MLE for regression:

MAE — median-seeking, robust to outliers:

Huber — quadratic near zero, linear in the tail; is the switch:

Binary cross-entropy, :

Categorical cross-entropy — one-hot , so only the true class survives:

KL divergence — extra bits from coding with ; asymmetric, :

Cross-entropy = entropy + KL — the identity everything rests on: Minimizing CE over = minimizing KL, since is fixed.

Contrastive (pairwise) — pull positives, push negatives past margin :

Triplet — anchor , positive , negative :

InfoNCE / NT-Xent — softmax over one positive against negatives, temperature : Lower bound on mutual information; small = harder on near-negatives.

Saying it out loud. (The one they ask you to explain: why cross-entropy is the loss for classification.) Cross-entropy is just the negative log-probability your model assigned to the correct answer, averaged over the data — so minimizing it is maximizing likelihood, nothing more exotic than that. The identity that makes it feel principled is that cross-entropy equals the entropy of the true distribution plus the KL divergence from the truth to your model. The entropy term doesn’t depend on your parameters at all, so minimizing cross-entropy is exactly minimizing KL — you’re pushing your predicted distribution onto the real one. The failure mode to name: it’s unbounded below on the wrong side, so a single confidently wrong prediction contributes an enormous loss, which is why label smoothing and gradient clipping exist.


Gradients

Linear regression, , MSE (dropping the 2/n):

Logistic regression, , BCE — the same expression:

Softmax + categorical CE, same again per-example:

Why they coincide. All three are GLMs with the canonical link. Write the likelihood in exponential-family form; the log-partition derivative is exactly the mean , so , and the chain rule to contributes . The link’s derivative cancels the loss’s curvature. Say this in one line: canonical link ⇒ the sigmoid/softmax Jacobian cancels against the cross-entropy denominator, leaving the residual.

Corollary worth knowing. BCE on a sigmoid gives ; MSE on a sigmoid gives — the extra term is why MSE + sigmoid trains badly (saturated units get no gradient).

Normal equation (closed form, when you can afford ):


Activations

Sigmoid, range

Tanh — zero-centered, range

ReLU

Leaky ReLU / PReLU, gradient on the left; fixes dead units.

GELU, = standard normal CDF; tanh approximation:

SiLU / Swish, default:

SwiGLU — the FFN in essentially every current LLM; splits the projection in two: Three matrices, so hidden width is scaled by to keep the parameter count.

Softmax; subtract for stability. Jacobian: Shift-invariant: — hence logits have degrees of freedom.

Temperature. = argmax, = uniform.


Normalization

Common core: , then . Only the axis of changes.

BatchNorm — statistics over the batch dimension, per feature/channel: Train uses batch stats; inference uses running averages. Batch-size dependent, awkward for RNNs/variable-length sequences.

LayerNorm — statistics over the feature dimension, per example: Identical at train and test; no batch coupling. Default in transformers.

RMSNorm — drops the mean subtraction and : Cheaper, empirically equal; used by Llama, Qwen, Gemma, DeepSeek and effectively all current open-weight LLMs.

One-line difference. BatchNorm normalizes across examples for one feature; LayerNorm normalizes across features for one example; RMSNorm is LayerNorm without centering.

Pre-norm vs post-norm — pre-norm () keeps a clean residual path and trains deep stacks without warmup; post-norm is the original and needs warmup. Pre-norm is standard (OLMo is a notable post-norm holdout).

QK-Norm — normalize and before the dot product; now common for training stability at scale.

Saying it out loud. (The one they ask you to explain: BatchNorm versus LayerNorm.) Same formula, different axis — that’s genuinely the whole thing. BatchNorm computes the mean and variance for one feature across all the examples in the batch; LayerNorm computes them for one example across all its features. Everything else follows: BatchNorm couples examples together, so it needs a decent batch size, it behaves differently at train and test because inference uses running averages, and it’s awkward for variable-length sequences. LayerNorm has no batch coupling and is identical in both modes, which is why transformers use it. The named failure mode is the silent BatchNorm bug — fine-tune with the layer left in train mode and it quietly overwrites the running statistics, and nothing errors.


Attention

Scaled dot-product: = mask ( on disallowed positions).

Why . If have i.i.d. zero-mean unit-variance entries, has variance . Unscaled logits grow like , the softmax saturates, and its Jacobian vanishes. Dividing by restores unit variance.

Multi-head heads, each of width :

Complexity — sequence , model width :

  • Scores : time, memory (naive) or with FlashAttention tiling
  • Projections:
  • Crossover: attention dominates once

MQA / GQA — cut the number of KV heads, keep all query heads. MHA: KV heads. GQA: groups, . MQA: . Shrinks the KV cache by with near-zero quality loss. GQA is the current default (Llama-2 70B: 64 query heads, 8 KV heads = 8× cache reduction). MLA (DeepSeek) instead compresses KV into a low-rank latent.

RoPE — rotate by a position-dependent angle so the dot product depends on : Relative position for free; extend context by scaling the base frequency (NTK / YaRN).

Saying it out loud. (The one they ask you to explain: the square root of d-k.) It’s variance control at initialization. If the query and key entries are roughly independent with unit variance, their dot product is a sum over d-k terms, so its variance is d-k and the logits grow like the square root of d-k. Big logits push the softmax toward one-hot, and a saturated softmax has a nearly zero Jacobian, so the gradient dies before training even starts. Dividing by the square root of d-k pulls the logit variance back to one. The number to have ready: at a head width of 64 that’s an 8x reduction in logit scale, and the modern follow-up is QK-Norm, which normalizes the queries and keys directly because the scaling alone stops being enough at frontier scale.


Regularization

L2 / ridge; gradient adds ; shrinks smoothly, never exactly zero; = Gaussian prior (MAP).

L1 / lasso; subgradient ; corners of the ball ⇒ exact zeros ⇒ feature selection; = Laplace prior.

Elastic net; sparsity plus grouping of correlated features (L1 alone picks one arbitrarily).

Dropout — keep probability . Train: with (inverted dropout — scale at train). Inference: identity, no scaling. Original formulation instead multiplied by at test; every framework now does the inverted version.

Label smoothing — target . Caps logit margins, improves calibration, hurts if you later distill from the model.

Weight decay vs L2. Identical for plain SGD (up to a factor of the LR). Not identical for adaptive optimizers: L2 goes into the gradient and gets divided by , so large-gradient weights get decayed less. AdamW decouples it — decay applied directly to :

Early stopping — approximately L2 for linear models; the effective .


Optimizers

SGD

Momentum, then ; effective step .

Nesterov — evaluate the gradient at the look-ahead point :

AdaGrad, ; LR decays monotonically to zero.

RMSProp — fix AdaGrad’s decay with an EMA:

Adam — momentum on both moments, with bias correction: Defaults , , . Bias correction exists because biases early estimates toward zero; without it the first steps are far too small (and means the bias lasts ~1000 steps).

AdamW — Adam with decoupled weight decay (above). Standard for transformers.

LR schedules — linear warmup then cosine decay to ~10% of peak is the transformer default; warmup exists because early Adam variance estimates are noisy.

Gradient clipping, typically .


Metrics

weights recall; common when misses are costly.

ROC-AUC — area under TPR-vs-FPR; equals . Invariant to class balance — which is exactly why it misleads at extreme imbalance: FPR barely moves when TN is enormous, so a useless model still scores 0.9.

PR-AUC / average precision. Baseline = positive class prevalence, not 0.5. Use this when positives are rare and you care about them.

Accuracy misleads at any imbalance (99% negatives ⇒ 99% by predicting nothing).

Calibration — Brier score ; ECE = weighted mean over bins. A model can rank perfectly (AUC 1.0) and be badly calibrated.

Regression (can go negative); RMSE punishes outliers, MAE does not; MAPE explodes near .

Ranking, NDCG = DCG / ideal DCG. MRR = mean of .


Probability and statistics

Bayes, i.e. posterior likelihood prior.

MLE. MAP. MAP = MLE + regularizer; Gaussian prior ⇒ L2, Laplace prior ⇒ L1. As the prior washes out and MAP → MLE.

Bias–variance (squared loss, expectation over training sets): is label noise — no model reduces it. The clean decomposition holds for squared loss; for 0-1 loss it is only approximate.

Entropy; max at uniform, .

Cross-entropy.

Mutual information.

Perplexity; the effective branching factor.

Jensen–Shannon — symmetric, bounded: , .

CLT; standard error .

Covariance / correlation; zero correlation independence (except jointly Gaussian).

Sigmoid ↔ logit, inverse of . Logistic regression coefficients are log-odds ratios.


Scaling and inference cost

Chinchilla — for fixed compute , loss is minimized when and scale together: Epoch AI’s 2024 replication showed the paper’s fitted constants were off, but the ~20:1 policy survives. In practice deployed models are trained far past this (inference cost dominates lifetime cost, so you over-train a smaller model).

Loss form.

Parameter count, decoder-only transformer, layers, width (dense, ignoring embeddings): ( for QKVO, for a MLP; SwiGLU with hidden lands in the same place.) Embeddings add (and another if untied) — non-negligible for small models.

FLOPs

  • Forward: per token (one multiply-add per parameter)
  • Backward: per token
  • Training: FLOPs per token, so
  • Attention adds per token — ignorable until is comparable to
  • MoE: use active parameters for FLOPs, total parameters for memory

Memory, training — fp16 weights + fp16 grads + Adam states fp32 (+ fp32 master copy ) bytes per parameter, before activations.

KV cache (per sequence): The leading 2 is K and V. Multiply by batch size. fp16 = 2 bytes, fp8 = 1, int4 = 0.5. With GQA, — that ratio is the savings.

Inference regimes — prefill is compute-bound ( attention, parallel); decode is memory-bandwidth-bound (one token at a time, must re-read all weights + KV cache). Hence batching, paged KV (vLLM), and speculative decoding.

Rules of thumb — serving a model in fp16 needs bytes of weights; int8 ; int4 , plus KV cache, plus ~20% overhead.

Saying it out loud. (The one they ask you to explain: where the compute goes.) Training costs about six FLOPs per parameter per token — two forward and four backward, because the backward pass computes gradients with respect to both activations and weights. Multiply by parameters and tokens and you have the whole training budget in one expression, which is why labs can price a run before starting it. Chinchilla then says that for a fixed budget you want roughly twenty tokens per parameter, though Epoch AI’s 2024 replication showed the paper’s fitted constants were off even while the twenty-to-one policy held. The tradeoff nobody in a real job forgets: Chinchilla only optimizes training compute, and inference cost scales with parameters and not tokens — so you deliberately over-train a smaller model, often to hundreds of tokens per parameter, and pay in training efficiency for permanently cheaper serving.