RecapsKayavak

Kayavak / Recaps / AI and ML Foundations

Recaps · Volume 14A

AI and ML Foundations

The revision sheet of every chapter, on one page: the key ideas, the numbers worth knowing, the pitfalls and the words. Use it before an interview, after a chapter, or to find which chapter to reread. Each title opens its chapter; below each sheet are its exercises, companion and TiffinBox stage, and the misconceptions the companion corrects.

Open the volume

143

AI Foundations

Key ideas

  • AI ⊃ ML ⊃ deep learning ⊃ LLMs (roughly); symbolic AI and search still matter in places.
  • Learning = function approximation from data, judged on unseen data (generalisation).
  • Paradigms: supervised, unsupervised, self-supervised, reinforcement (and semi-supervised, weak supervision).
  • Inductive bias: each learner's built-in assumptions; no free lunch.
  • Bias–variance: too simple (underfit) vs too flexible (overfit); ensembles and regularisation trade between them.
  • Learning curves show whether more data or a better model is the lever.
  • Curse of dimensionality: distance-based reasoning degrades with many irrelevant features.
  • When not to use ML: clear rules, little data, no tolerance for errors, no way to measure success.

Numbers to remember

  • Lab: logistic regression 82.7% vs random forest 95.3% on half-moons.
  • Lab: learning curve 72% at 20 examples → 93% at 200 → flat.
  • A 1,000-example test set measures accuracy to about ±1.5 points (95%).

Pitfalls

  • Judging models by training accuracy.
  • Assuming deep learning beats everything (tabular data often favours tree ensembles).
  • Collecting more data when the learning curve is flat (or tuning models when it's still rising).
  • Framing a problem as ML when a rule or a heuristic would do.
  • Ignoring label noise that caps achievable accuracy.

Glossary

  • Inductive bias: assumptions that let a learner generalise.
  • Bias / variance: systematic error / sensitivity to the training sample.
  • Bayes error: the lowest error any model could achieve on the data.
  • Learning curve: performance vs amount of training data.
  • Self-supervised learning: labels derived from the data itself.

144

Python for AI

Key ideas

  • Python orchestrates; native code computes: NumPy, pandas, PyTorch, JAX run array operations in C/C++/CUDA.
  • Vectorise: whole-array operations, broadcasting, einsum; avoid per-element Python loops.
  • Memory layout: contiguous arrays, strides, views vs copies; in-place operations.
  • dtypes: float64 for analysis, float32 default for models, bf16/fp16 for training speed, int8/int4 for inference; accumulate in higher precision.
  • Environments: uv/venv, lockfiles, pinned versions; notebooks for exploration, packages and scripts for anything repeated.
  • Reproducibility: seeds everywhere, deterministic algorithms, versioned data and code, recorded configs.
  • Typing and testing ML code: type hints, shape checks, small unit tests on data transforms.

Numbers to remember

  • Lab: NumPy ≈55–100× faster than Python loops for these tasks.
  • float32 ≈ 7 significant digits; float16 max 65,504; bfloat16 has float32's range.
  • Lab: naive float32 running sum of 10⁷ × 0.1 was 8.8% off; pairwise sum 0.00001% off.

Pitfalls

  • Python loops over rows of large arrays or data frames.
  • Silent dtype upcasting or downcasting (int overflow, float16 overflow).
  • Accumulating losses or statistics in low precision.
  • Unseeded randomness; unpinned dependencies; notebooks as the only record.
  • Accidental copies of large arrays doubling memory.

Glossary

  • Broadcasting: combining arrays of compatible shapes without copying.
  • Vectorisation: expressing computation as whole-array operations.
  • bfloat16: 16-bit float with an 8-bit exponent.
  • Pairwise summation: adding numbers in a tree to limit rounding error.
  • Lockfile: exact versions of all dependencies.

145

Linear Algebra

Key ideas

  • Vectors as data points and directions; dot product = |a||b|cos θ; cosine similarity; norms L1, L2, L∞.
  • Matrices as linear maps; matrix multiplication composes maps; shapes (m×n)(n×p) → (m×p).
  • Identity, inverse, transpose, determinant (volume scaling; zero means information lost).
  • Rank: number of independent directions; low rank = hidden low-dimensional structure.
  • Eigenvectors/eigenvalues: directions a matrix only scales; SVD for any matrix: UΣVᵀ.
  • PCA = SVD of centred data; Eckart–Young: truncated SVD is the best low-rank approximation.
  • In ML: layers are matrix multiplies; attention is dot products; embeddings live in vector spaces; LoRA is a low-rank update.
  • Compute: matmul ≈ 2n³ FLOPs; high arithmetic intensity; batching to use hardware well.

Numbers to remember

  • Lab: five hidden factors → five large singular values (≈350–430) then ≈11.5.
  • Lab: rank 5 kept error at 0.13 with 2.7% of the numbers.
  • Lab: 2048×2048 float32 matmul ≈ 120 GFLOP/s on 2 CPU cores.

Pitfalls

  • Shape mistakes hidden by broadcasting.
  • Cosine similarity on unnormalised, unscaled features.
  • Inverting matrices explicitly instead of solving linear systems (np.linalg.solve).
  • Ignoring conditioning (nearly singular matrices amplify errors).
  • Assuming element-wise operations are cheap at scale (memory-bound).

Glossary

  • Span / basis: all combinations of vectors / a minimal set spanning a space.
  • Orthogonal: perpendicular (dot product zero).
  • Singular value: stretch factor along a principal direction.
  • Condition number: ratio of largest to smallest singular value.
  • Arithmetic intensity: FLOPs per byte moved.

146

Calculus

Key ideas

  • Derivative = rate of change; partial derivatives per input; gradient = vector of partials, direction of steepest ascent.
  • Chain rule: derivative of a composition = product of local derivatives; backpropagation applies it in reverse through the computational graph.
  • Autograd (reverse-mode automatic differentiation): exact gradients for all parameters at about the cost of one extra pass.
  • Jacobian (vector → vector derivatives), Hessian (second derivatives, curvature).
  • Gradient descent stability: lr < 2/λ_max for quadratics; condition number slows convergence.
  • Optimisers: SGD, momentum, Adam/AdamW; learning-rate warm-up and decay.
  • Gradient health: vanishing/exploding gradients; fixes: ReLU-family activations, careful initialisation, normalisation, residual connections, gradient clipping.
  • Key derivatives: softmax + cross-entropy gradient = p − y.

Numbers to remember

  • Lab: best finite-difference step ≈ 1e-5 in float64; h = 1e-12 lost 4 digits.
  • Lab: valley with curvatures 2 and 20 diverged above lr 0.1.
  • Lab: 30 sigmoid layers → gradient 1.8e-25; ReLU + He init → ≈6.

Pitfalls

  • Learning rate tuned on one batch size or model size and reused elsewhere.
  • Forgetting to zero gradients between steps (they accumulate in PyTorch).
  • Computing gradients through code you meant to treat as constant (use detach/no_grad).
  • Sigmoid/tanh in deep stacks without normalisation or residuals.
  • Ignoring exploding gradients (use clipping, check norms).

Glossary

  • Computational graph: operations recorded for backpropagation.
  • Learning-rate schedule: changing the step size over training.
  • Gradient clipping: capping the gradient norm.
  • Condition number: ratio of largest to smallest curvature.
  • He / Xavier initialisation: variance-preserving weight scales for ReLU / tanh.

147

Probability and Statistics

Key ideas

  • Random variables and distributions: Bernoulli, binomial, categorical, Poisson, uniform, normal, multivariate normal; expectation, variance, covariance.
  • Conditional probability and Bayes' theorem: posterior ∝ likelihood × prior; base rates matter.
  • Law of large numbers and CLT: sample means converge; their spread is σ/√n and their distribution ≈ normal.
  • Estimation: maximum likelihood (cross-entropy loss is negative log-likelihood); MAP and regularisation as priors.
  • Uncertainty: standard errors, confidence intervals (Wald, Wilson, bootstrap), credible intervals.
  • Testing: p-values, power, sample size, multiple comparisons, optional stopping.
  • Information: entropy, cross-entropy, KL divergence (used for losses and distillation).

Numbers to remember

  • 95% CI ≈ ±1.96 standard errors; for a proportion, SE = √(p(1−p)/n).
  • Lab: peeking every 100 users raised false positives from ~5% to 31%.
  • Lab: 99%/99% detector at 0.5% prevalence → 33% precision.
  • Accuracy on 1,000 test examples: about ±1.7–1.9 points.

Pitfalls

  • Treating small accuracy differences as real without error bars.
  • Peeking, early stopping on significance, and reporting the best of many tries.
  • Base-rate neglect; evaluating on balanced data and deploying on imbalanced.
  • Assuming normality for heavy-tailed metrics.
  • Confusing p-values with the probability a hypothesis is true.

Glossary

  • Standard error: spread of an estimate across samples.
  • Power: probability of detecting a real effect of a given size.
  • Likelihood: probability of the data under given parameters.
  • KL divergence: how one distribution differs from another.
  • Bootstrap: estimating uncertainty by resampling the data.

148

Classical Machine Learning

Key ideas

  • Setup: features X, target y; train/validation/test or cross-validation; always a baseline.
  • Linear regression (least squares, normal equations), logistic regression (log loss), regularisation (L2 ridge, L1 lasso, elastic net).
  • k-NN (distance-based, scale-sensitive), SVM (maximum margin, kernels), naive Bayes.
  • Trees (greedy splits by impurity), random forests (bagging + feature subsampling, lower variance), gradient boosting (XGBoost, LightGBM, CatBoost: sequential error correction).
  • Unsupervised: k-means, hierarchical clustering, DBSCAN, PCA.
  • Pipelines: preprocessing fitted inside CV folds; categorical encoding; missing-value handling.
  • Model selection: CV, nested CV, hyperparameter search; error bars and paired comparisons.
  • On tabular data, tuned gradient-boosted trees are the usual strongest baseline.

Numbers to remember

  • Lab: majority baseline 62.7%; scaled logistic regression 97.9% ± 1.4; XGBoost 97.7% ± 0.9.
  • Lab: scaling lifted k-NN from 93.2% to 96.5%.
  • Lab: diabetes R² ≈ 0.42–0.49 for every model.

Pitfalls

  • No baseline; reporting the best of many tries as the expected performance.
  • Fitting scalers or encoders on the full dataset before splitting.
  • Forgetting to scale for distance/gradient models.
  • Over-tuning on small datasets; ignoring fold-to-fold variance.
  • Assuming deep learning will beat boosted trees on tables.

Glossary

  • Bagging: training models on bootstrap samples and averaging.
  • Boosting: adding models sequentially to correct residual errors.
  • Kernel trick: computing similarities in an implicit high-dimensional space.
  • Impurity (Gini, entropy): measure trees reduce when splitting.
  • Nested CV: CV inside CV, separating tuning from evaluation.

149

ML Evaluation

Key ideas

  • Confusion matrix: TP, FP, FN, TN; accuracy, precision, recall, specificity, F1/Fβ.
  • Thresholds from costs and capacity; curves (ROC, precision–recall) and their areas for threshold-free comparison; PR-AUC for rare positives.
  • Calibration: reliability diagrams, Brier score, log loss; Platt scaling and isotonic regression.
  • Regression metrics: MAE, RMSE, MAPE (and its traps), R²; quantile loss for forecasts.
  • Ranking metrics: precision@k, recall@k, MAP, NDCG, MRR.
  • Protocol: train/validation/test; CV; splits by time and group; one-shot test set; error bars; slice analysis (by segment, region, device).
  • Leakage: target leakage, train–test contamination, preprocessing leakage, temporal leakage.
  • Offline vs online: offline metrics must predict business outcomes; confirm with A/B tests.

Numbers to remember

  • Lab: always-negative model 98.87% accurate, 0% recall.
  • Lab: ROC-AUC 0.863 vs PR-AUC 0.183 on 1.1% positives.
  • Lab: a post-outcome feature lifted 68.7% to 96.4%; duplicates lifted 82.0% to 94.8%.

Pitfalls

  • Accuracy on imbalanced data; ROC-AUC alone for rare events.
  • Default 0.5 thresholds; thresholds tuned on the test set.
  • Random splits for time series or grouped data.
  • Features unavailable at prediction time.
  • Ignoring slices where the model fails badly.
  • Treating calibration as optional when probabilities drive decisions.

Glossary

  • Fβ: weighted harmonic mean of precision and recall (β > 1 favours recall).
  • Brier score: mean squared error of probabilities.
  • Reliability diagram: predicted vs observed frequency per bin.
  • NDCG: ranking quality weighting top positions more.
  • Slice analysis: evaluating metrics separately for subgroups.

150

Data Engineering for AI

Key ideas

  • Data-centric ML: quality, coverage, consistency and labels often matter more than the model.
  • Ingestion: databases (CDC), events, files, APIs, web; point-in-time correctness (features "as of" prediction time).
  • Cleaning: types, units, outliers, missing values (and why they're missing), deduplication.
  • Labelling: guidelines, multiple annotators, agreement metrics, active learning, weak supervision, label auditing.
  • Validation: schemas, ranges, distributions, drift (covariate, label, concept), skew between training and serving.
  • Features: feature stores for consistent training/serving computation; offline and online stores.
  • Versioning and lineage: data versions (DVC, lakeFS, Delta/Iceberg time travel), recorded transforms, reproducible datasets.
  • Privacy and governance: consent, PII handling, retention, access controls.

Numbers to remember

  • Lab: 10% random label noise cost 5.4 points; halving clean data cost 2.1.
  • Lab: a unit change in one input raised MAE from 12.4 to 86.3 with no error raised.
  • Lab: exact hashing found 0 of 2 near-duplicate pairs that 3-gram Jaccard found (0.81, 0.72).

Pitfalls

  • Trusting labels without auditing; systematic annotator errors.
  • Features computed differently in training and serving.
  • Validation only at training time, never at serving time.
  • Random splits that put duplicates or the same entity on both sides.
  • Building training sets with information from after the prediction time.
  • No dataset versions, so results can't be reproduced.

Glossary

  • Concept drift: the relationship between inputs and target changes.
  • Covariate shift: input distribution changes, relationship stays.
  • PSI: population stability index, a drift score.
  • Point-in-time join: joining features as they were at each event's time.
  • Weak supervision: labels from heuristics and noisy sources, combined statistically.

151

Deep Learning

Key ideas

  • Perceptron → MLP: linear map + nonlinearity, stacked; universal approximation (wide enough nets approximate any continuous function, depth makes it efficient).
  • Activations: ReLU, GELU/SiLU (modern), sigmoid/tanh (gates, outputs); softmax for class probabilities.
  • Losses: cross-entropy (classification), MSE/MAE/Huber (regression).
  • Backpropagation: chain rule in reverse; cost ≈ 2× the forward pass.
  • Optimisation: SGD with momentum, Adam/AdamW; mini-batches; learning-rate schedules.
  • Initialisation and normalisation: He/Xavier; batch norm, layer norm; residual connections.
  • Regularisation: weight decay, dropout, data augmentation, early stopping.
  • Generalisation in over-parameterised nets: benign overfitting, double descent, implicit regularisation of SGD.

Numbers to remember

  • Lab: XOR 50% linear → 100% with 8 hidden ReLUs.
  • Lab: digits 97.2% with no hidden layer, 87.2% with a 4-unit bottleneck, 98.1% with 256 units.
  • An MLP layer d → h has d·h + h parameters.

Pitfalls

  • No nonlinearity between layers.
  • Bottleneck layers too narrow for the information needed.
  • Bad initialisation (vanishing or exploding signals, dead ReLUs).
  • Judging tiny accuracy differences on small test sets.
  • Training without a validation set for early stopping and tuning.

Glossary

  • Representation learning: learning features rather than hand-crafting them.
  • Logits: pre-softmax scores.
  • Epoch: one pass over the training data.
  • Dropout: randomly zeroing activations during training.
  • Double descent: test error falling again as models grow past the interpolation point.

152

PyTorch

Key ideas

  • Tensors: dtype, device, shape, strides; views vs copies; .contiguous(), reshape vs view.
  • Autograd: dynamic graph recorded on the forward pass; requires_grad, backward(), .grad accumulation, no_grad, detach.
  • Modules: nn.Module, parameters and buffers, state_dict, train()/eval() modes.
  • Training loop: forward → loss → zero_grad → backward → step; validation each epoch; checkpointing; early stopping; LR schedulers.
  • Data: Dataset, DataLoader (batching, shuffling, workers, pinned memory).
  • Speed: GPU placement, mixed precision (torch.autocast, bf16), torch.compile, profiling (torch.profiler).
  • Scale: DDP and FSDP for distributed training; gradient accumulation; activation checkpointing.

Numbers to remember

  • Lab: AdamW 1e-3 reached 97.8% validation accuracy in 30 epochs where SGD 0.01 reached 92.0%.
  • Lab: validation loss bottomed at epoch 87 while training loss kept falling to 0.0002.

Pitfalls

  • Forgetting zero_grad() (gradients accumulate).
  • Evaluating in train mode; forgetting no_grad (memory blow-up).
  • Tensors on different devices; dtype mismatches.
  • In-place ops breaking autograd; modifying views unintentionally.
  • Saving whole model objects instead of state_dicts.
  • Data loading as the hidden bottleneck.

Glossary

  • Stride: elements to skip per step along a dimension.
  • Buffer: non-trained state in a module (e.g. batch-norm running mean).
  • state_dict: mapping of parameter and buffer names to tensors.
  • Autocast: automatic mixed precision context.
  • DDP / FSDP: data-parallel / fully sharded data-parallel training.

153

Neural Architectures

Key ideas

  • Inductive bias: architecture encodes assumptions; the right bias needs less data.
  • CNNs: convolution (weight sharing, locality), stride, padding, pooling, receptive fields; output size ⌊(n + 2p − k)/s⌋ + 1; equivariance vs invariance; aliasing from downsampling.
  • Residual connections (ResNet) and normalisation (batch, layer, RMS) make deep networks trainable.
  • RNNs, LSTMs, GRUs: recurrence for sequences; gating against vanishing gradients; sequential computation limits parallelism.
  • Attention and Transformers: all-pairs interactions, parallel over positions, positional information added explicitly (chapter 154).
  • Other families: GNNs (graphs), autoencoders and VAEs, diffusion models (generation), mixture-of-experts layers.
  • Augmentation teaches invariances the architecture lacks.

Numbers to remember

  • Lab: a 1-pixel shift dropped an MLP from 97.5% to 12.4%; the CNN (1/7 the parameters) kept 97.2% at 2 px.
  • Lab: odd shifts dropped the CNN to 52–57% (stride-2 pooling aliasing).
  • Two 3×3 convs = 5×5 receptive field; three = 7×7.

Pitfalls

  • Flattening images into MLPs for vision tasks.
  • Assuming CNNs are perfectly shift-invariant.
  • Shape errors from kernel/stride/padding arithmetic.
  • Deep stacks without residuals or normalisation.
  • Using recurrent models where parallel attention would train far faster.

Glossary

  • Receptive field: input region influencing one output unit.
  • Pooling: downsampling by max or average over neighbourhoods.
  • Residual connection: adding a layer's input to its output.
  • Layer norm / RMSNorm: per-example normalisation used in Transformers.
  • Mixture of experts: routing each token to a few of many sub-networks.

154

Transformers

Key ideas

  • Embeddings turn tokens into vectors; positional information via learned/sinusoidal embeddings or rotary embeddings (RoPE) applied to queries and keys.
  • Scaled dot-product attention: softmax(QKᵀ/√d)V; masks for causality and padding.
  • Multi-head attention: several heads on lower-dimensional projections, concatenated and projected.
  • Block: (pre-)layer norm → attention → residual add → layer norm → MLP (GELU/SwiGLU) → residual add.
  • Decoder-only (GPT-style, causal) vs encoder-only (BERT, bidirectional) vs encoder–decoder (T5, translation).
  • Cost: O(n²·d) attention, O(n·d²) MLP; parameters ≈ 12·d² per block plus embeddings.
  • Efficiency variants: FlashAttention, KV cache, grouped-query / multi-query attention, sliding-window and sparse attention, mixture of experts.

Numbers to remember

  • Lab: unscaled attention at d = 1024 put 0.966 weight on one key; scaled stayed ≈ 0.25.
  • Lab: a causal mask gave exactly 0.0 change in earlier outputs.
  • Lab: n = 4,096 score matrix = 67 MB per head (float32).
  • GPT-2 small ≈ 124 M parameters (12 blocks × 7.1 M + 38.6 M embeddings).

Pitfalls

  • Missing or off-by-one causal masks (training looks great, generation fails).
  • Forgetting the √d scale; softmax in low precision without max-subtraction.
  • Padding tokens attended to (missing padding mask).
  • Underestimating attention memory at long context.
  • Confusing encoder (bidirectional) and decoder (causal) use cases.

Glossary

  • Query / key / value: what a position asks for / offers as a label / offers as content.
  • Residual stream: the running sum of block outputs passed through the network.
  • RoPE: rotary position embedding, encoding relative position by rotating Q and K.
  • GQA: grouped-query attention; several query heads share one key/value head.
  • Context length: maximum tokens the model attends over.

155

Tokenization

Key ideas

  • Tokens are vocabulary entries; models consume and emit token IDs; cost, latency and context are measured in tokens.
  • Granularity: characters (long sequences), words (huge vocabularies, unknown words), subwords (the compromise).
  • Algorithms: BPE (merge frequent pairs), WordPiece (likelihood-based merges, BERT), Unigram (prune a large vocabulary probabilistically, SentencePiece).
  • Byte-level vocabularies guarantee any text is encodable (byte fallback); decoding needs care with partial UTF-8.
  • Normalisation (Unicode NFKC, case, whitespace) and pre-tokenisation (splitting on spaces, digits, punctuation) shape results.
  • Special tokens: beginning/end of text, padding, chat role markers, tool-call markers.
  • Effects: multilingual inflation, irregular number splits, whitespace/case sensitivity, glitch tokens from rare vocabulary entries.

Numbers to remember

  • Lab: vocab 512 → 32,768 cut held-out tokens from 132,943 to 57,303 (3.43 → 1.48 tokens/word).
  • Lab: a Hindi sentence took 164 tokens vs 23 for English (8,192 vocab, English-trained).
  • English prose ≈ 4 characters per token with large production tokenizers.

Pitfalls

  • Estimating cost or context in words or characters instead of tokens.
  • Using a tokenizer trained on one language or domain for another.
  • Mismatched tokenizer and model (IDs mean different things).
  • Breaking multi-byte characters when streaming.
  • Prompt formats with inconsistent spaces or special tokens.

Glossary

  • Vocabulary: the set of tokens a model knows.
  • Merge rule: a learned pair-to-token rule in BPE.
  • Byte fallback: encoding unknown characters as raw bytes.
  • Fertility: tokens per word for a language.
  • Special token: a reserved token with control meaning.

156

Large Language Models

Key ideas

  • Pipeline: tokenizer → embeddings → decoder-only Transformer → logits → softmax → decoding.
  • Objective: next-token cross-entropy over huge corpora (self-supervised); perplexity = e^loss; compare across tokenizers in bits per byte/character.
  • Context window: maximum tokens attended; cost grows with length (attention O(n²), KV cache memory O(n)).
  • Inference: prefill (process the prompt in parallel) then decode (one token at a time, reusing the KV cache); decode is memory-bandwidth-bound.
  • Behaviour: models predict plausible continuations; hallucination is fluent text unsupported by facts; knowledge is frozen at the training cut-off.
  • After pre-training: instruction tuning and preference optimisation turn a text predictor into an assistant (chapter 158).
  • Sanity checks: initial loss ≈ ln V; loss falls smoothly; validation tracks training.

Numbers to remember

  • Lab: 2.2 M parameters, 1.76 M tokens, 10 minutes on 2 CPU cores: validation loss 7.65 → 4.23 (perplexity 68.5, 2.11 bits/char).
  • Lab: bigram baseline 4.985; unigram 6.519.
  • Lab: default N(0,1) embeddings with tied weights gave an initial loss of 126.5.

Pitfalls

  • Comparing per-token losses across different tokenizers.
  • Treating fluent output as factual.
  • Skipping the initial-loss sanity check.
  • Repeating a small dataset for many epochs (memorisation).
  • Ignoring KV-cache memory when planning context length and batch size.

Glossary

  • Autoregressive: generating one token at a time conditioned on previous ones.
  • Perplexity: exponentiated average cross-entropy.
  • Prefill / decode: prompt processing / token-by-token generation phases.
  • KV cache: stored keys and values of previous tokens.
  • Hallucination: confident output not grounded in facts or sources.

157

LLM Decoding

Key ideas

  • Decoding turns next-token distributions into text; it's separate from the model and has large effects.
  • Greedy: deterministic, repetitive, loops; beam search: high-likelihood but bland for open-ended text.
  • Sampling with temperature (sharpen/flatten), top-k (fixed count), top-p (cumulative mass), min-p (relative threshold); applied in that order in most implementations.
  • Penalties: repetition, frequency and presence penalties.
  • Constrained decoding for grammars and JSON schemas; logit bias for steering specific tokens.
  • Speed: KV cache, batching, speculative decoding, quantisation (Volume 15).
  • Reproducibility: seeds, but batching and hardware can still change results; temperature 0 isn't always bit-exact on GPUs.

Numbers to remember

  • Lab: greedy distinct-2 0.73 with 9% repeated 4-grams; T = 1.5 own-loss 6.27 (near random).
  • Lab: at T = 1.0 the model's loss on its own samples (4.21) ≈ its validation loss (4.23).
  • Common defaults: T 0.7–1.0, top-p 0.9–0.95; T ≈ 0 for extraction.

Pitfalls

  • High temperature for factual or structured tasks.
  • Greedy for long open-ended text (loops).
  • Parsing free-form text when constrained decoding is available.
  • Assuming temperature 0 guarantees identical outputs across runs and hardware.
  • Over-penalising repetition so needed words (names, terms) can't repeat.

Glossary

  • Logit: pre-softmax score.
  • Nucleus sampling: top-p sampling.
  • Beam width: number of partial sequences kept in beam search.
  • Speculative decoding: draft-then-verify generation.
  • Constrained decoding: masking invalid tokens at each step.

158

The Foundation-Model Lifecycle

Key ideas

  • Pre-training: data mixtures, deduplication and filtering; compute C ≈ 6·N·D FLOPs; scaling laws; compute-optimal ≈ 20 tokens per parameter (Chinchilla); many models now "over-train" smaller models for cheaper inference.
  • Post-training: SFT on demonstrations; preference optimisation (RLHF with reward models and PPO; DPO and variants); safety training; reasoning training with verifiable rewards.
  • Evaluation: benchmarks (and contamination risks), human and model-graded evals, red-teaming, task-specific evals.
  • Adaptation ladder: prompting → retrieval → adapters (LoRA, QLoRA) → full fine-tuning → continued pre-training.
  • LoRA: frozen W plus trainable low-rank BA (B starts at zero); small checkpoints; many adapters per base model; QLoRA trains adapters over a quantised base.
  • Forgetting and overfitting are the main fine-tuning risks; mix in general data, stop early, evaluate both domain and general skills.
  • Distillation and quantisation produce smaller, cheaper models for serving (Volume 15).

Numbers to remember

  • Lab: at one learning rate, bigger models were worse; at a lower rate, loss fell with size (5.588 → 4.753).
  • Lab: full fine-tuning −0.148 domain loss, +0.316 general; LoRA r=8 −0.050, +0.126 with 4.5% of parameters.
  • Training FLOPs ≈ 6 × parameters × tokens.

Pitfalls

  • Fine-tuning to add facts that change (use retrieval).
  • Comparing model sizes with one shared, untuned learning rate.
  • Evaluating only on the target domain and missing forgetting.
  • Benchmark scores inflated by training-data contamination.
  • Training on data you don't have rights to or that contains personal data.

Glossary

  • SFT: supervised fine-tuning on demonstrations.
  • RLHF / DPO: preference optimisation with a reward model and RL / directly from preference pairs.
  • LoRA / QLoRA: low-rank adapters / adapters over a 4-bit quantised base model.
  • Catastrophic forgetting: losing prior abilities during fine-tuning.
  • Data contamination: test items present in training data.