Contents
Follow the Parts in order, or return to a mechanism you want to inspect. Planned chapters remain visible while their source is being authored.
Part I — Neural Network Foundations
- IV-01From Fixed Neurons to Learning
Separate a forward computation, target, loss, gradient and parameter update.
- IV-02Parameters, Batches and Tensor Shapes
Translate one-column examples to explicit row-sample batches.
- IV-03Activations, Derivatives and Saturation
Compute activation outputs and one-sided derivatives without claiming all points differentiable.
- IV-04A Trainable MLP Forward Pass
Calculate all hidden and output values for a trainable multilayer perceptron.
- IV-05Losses, Targets and Reduction Rules
Compare squared error, binary cross-entropy and multiclass NLL with declared reduction.
Part II — Learning, Backpropagation and Optimization
- IV-06Computational Graphs and Local Derivatives
Associate every graph node with values and local partial derivatives.
- IV-07Reverse-Mode Chain Rule and Gradient Accumulation
Compute adjoints in reverse topological order, including fan-out sums.
- IV-08One Training Step: Hand-Derived Backpropagation
Derive every parameter gradient of a tiny two-layer net and verify a full update.
- IV-09Backpropagation Through a Multi-Neuron Layer
Generalize scalar backward equations to a hidden vector and matrix gradient.
- IV-10Jacobians, VJPs and Batch Gradients
Connect component gradients to Jacobian-vector products and sample reductions.
- IV-11Gradient Checking and Kinks
Compare central finite differences with independent analytical gradients.
- IV-12Gradient Descent, SGD and Mini-Batches
Apply deterministic update rules and compare full-batch versus mini-batch paths.
- IV-13Momentum, Adam and Optimizer State
Compute velocity, Adam moments, bias correction and updates by hand.
- IV-14PyTorch Autograd as an Independent Check
Relate hand-computed derivatives to framework autograd without hiding them.
- IV-15Initialization, Regularization and Gradient Pathologies
Explain activation/gradient magnitude and parameter penalties.
Part III — Embeddings
- IV-16Token IDs and Embedding Lookup Tables
Map discrete IDs to selected rows of a learned parameter matrix.
- IV-17Embedding Geometry and Similarity
Explore similarities, distances and coordinate-dependent projections.
- IV-18How Embeddings Learn From Gradients
Calculate sparse lookup gradients and repeated-index accumulation.
Part IV — Sequence Models
- IV-19Sequences, Order and Recurrent State
Define ordered samples, shared recurrent parameters and temporal state.
- IV-20Recurrent Networks and Backpropagation Through Time
Unroll a small RNN and differentiate through shared temporal weights.
- IV-21Long Dependencies and Recurrent Limitations
Compute Jacobian products to expose vanishing and exploding gradients.
Part V — Self-Attention
- IV-22Queries, Keys and Values as Projections
Compute Q, K and V from the same token representations with distinct weights.
- IV-23Dot-Product Attention Scores and Scaling
Compute each query-key dot product and its 1/sqrt(d_k) scaling.
- IV-24Masking and Numerically Stable Softmax
Apply causal/padding masks then rowwise stable softmax.
- IV-25Self-Attention: Complete Numerical Trace
Derive X→Q,K,V→QKᵀ→scale→mask→softmax→AV without gaps.
- IV-26Causal, Bidirectional and Padding Attention
Contrast different allowed-key sets using the same real projected tensors.
Part VI — Multi-Head Attention
- IV-27Separating Attention Heads and Dimensions
Reshape concatenated projections into named head-specific axes.
- IV-28Independent Attention Heads
Execute separate head-specific score, mask, softmax and value paths.
- IV-29Head Concatenation and Output Projection
Concatenate real head outputs and apply an explicit output matrix.
Part VII — Transformer Blocks
- IV-30Residual Connections and Gradient Paths
Calculate residual addition and its gradient contributions.
- IV-31Layer Normalization and RMS Normalization
Compute mean, variance/RMS, epsilon and affine scale parameters.
- IV-32Position-Wise Feed-Forward Networks
Apply token-independent MLP operations using shared parameters.
- IV-33A Complete Transformer Block
Compose attention, residual, normalization and FFN in order.
Part VIII — Positional Information
- IV-34Why Position Matters to Attention
Demonstrate that attention without positional signals is permutation equivariant.
- IV-35Learned and Sinusoidal Position Embeddings
Compute additive position vectors and compare parameterized and fixed schemes.
- IV-36Rotary Position Embeddings (RoPE)
Rotate paired query/key feature coordinates by positional angles.
Part IX — Tokenization
- IV-37From Unicode Text to Token IDs
Distinguish characters, code points, UTF-8 bytes and vocabulary IDs.
- IV-38Subwords and Vocabulary Trade-Offs
Compare character, byte and subword granularity on sample texts.
- IV-39Byte-Pair Encoding: A Full Merge Trace
Perform deterministic byte-level BPE training and encoding step by step.
Part X — Language Modeling
- IV-40Autoregressive Next-Token Prediction
Form a causal conditional distribution p(x_t|x_<t).
- IV-41Teacher Forcing and Shifted Targets
Align input and target token positions in a causal training example.
- IV-42Cross-Entropy, NLL and Perplexity
Compute token NLL, sequence loss, average and perplexity.
- IV-43End-to-End Tiny Language-Model Objective
Connect token IDs, embeddings, causal block, logits, and shifted loss.
Part XI — Autoregressive Inference
- IV-44Prefill and Single-Token Decode
Distinguish processing a prompt from subsequent decoding calls.
- IV-45From Logits to the Next Token
Calculate greedy selection and deterministic tie resolution.
- IV-46Temperature, Top-k and Nucleus Sampling
Apply temperature and filtering in a declared order.
- IV-47Complete Autoregressive Generation Trace
Generate a short sequence with inspectable logits and deterministic RNG.
Part XII — KV Cache
- IV-48Keys, Values and the Cache Invariant
Identify which per-layer past tensors a decoder can reuse.
- IV-49Cached Versus Uncached Decoding
Independently compute cached and full-prefix outputs for each step.
- IV-50KV Cache Memory, Latency and Invalidation
Calculate cache footprint and demonstrate relevant invalidations.
Part XIII — Training Language Models
- IV-51Training Data, Packing and Causal Boundaries
Turn short documents into training chunks and loss masks.
- IV-52Language-Model Training Steps and Batches
Calculate token losses, reduced gradients and one optimizer update.
- IV-53Checkpoints and Reproducible Resumption
Explain exact trainable and RNG state needed to resume.
- IV-54Scaling Limits and Generalization
Distinguish capacity, compute, data quality and evaluation uncertainty.
Part XIV — Fine-Tuning and Alignment
- IV-55Pretraining, Fine-Tuning and Transfer
Compare which model parameters/data/objectives change in adaptation.
- IV-56Low-Rank Adaptation (LoRA)
Derive W+alpha/r·BA and compute gradients and trainable counts.
- IV-57Preference Data and Optimization Objectives
Define scored/ranked pairs and a transparent preference loss.
- IV-58Alignment, Safety and Evaluation Limits
Distinguish training objectives, evaluation proxies and observed behavior.
Part XV — Modern LLM Architectures
- IV-59Decoder-Only Transformer Anatomy
Locate embeddings, repeated blocks, output head and causal decoding.
- IV-60Encoder, Decoder and Cross-Attention Variants
Contrast bidirectional encoders, causal decoders and cross-attention.
- IV-61Multi-Query and Grouped-Query Attention
Explain query-head to key/value-head mappings and memory tradeoffs.
- IV-62Mixture-of-Experts Routing
Compute router scores, top-k dispatch and gated expert outputs.
- IV-63Quantization and Numerical Approximation
Quantize small weight tensors and measure reconstructed output error.
- IV-64Inference Systems: Throughput and Latency
Reason about prefill, decode, batching and memory-bound tradeoffs.
- IV-65Evaluating LLMs, Leakage and Reliability
Examine evaluation design, leakage, calibration and uncertainty.
- IV-66From Text to Output: Full-Stack LLM Capstone
Trace text → bytes/BPE → embeddings → positioned block → logits → decode.