The neural notebook
The whole path

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

  1. IV-01
    From Fixed Neurons to Learning

    Separate a forward computation, target, loss, gradient and parameter update.

  2. IV-02
    Parameters, Batches and Tensor Shapes

    Translate one-column examples to explicit row-sample batches.

  3. IV-03
    Activations, Derivatives and Saturation

    Compute activation outputs and one-sided derivatives without claiming all points differentiable.

  4. IV-04
    A Trainable MLP Forward Pass

    Calculate all hidden and output values for a trainable multilayer perceptron.

  5. IV-05
    Losses, Targets and Reduction Rules

    Compare squared error, binary cross-entropy and multiclass NLL with declared reduction.

Part II — Learning, Backpropagation and Optimization

  1. IV-06
    Computational Graphs and Local Derivatives

    Associate every graph node with values and local partial derivatives.

  2. IV-07
    Reverse-Mode Chain Rule and Gradient Accumulation

    Compute adjoints in reverse topological order, including fan-out sums.

  3. IV-08
    One Training Step: Hand-Derived Backpropagation

    Derive every parameter gradient of a tiny two-layer net and verify a full update.

  4. IV-09
    Backpropagation Through a Multi-Neuron Layer

    Generalize scalar backward equations to a hidden vector and matrix gradient.

  5. IV-10
    Jacobians, VJPs and Batch Gradients

    Connect component gradients to Jacobian-vector products and sample reductions.

  6. IV-11
    Gradient Checking and Kinks

    Compare central finite differences with independent analytical gradients.

  7. IV-12
    Gradient Descent, SGD and Mini-Batches

    Apply deterministic update rules and compare full-batch versus mini-batch paths.

  8. IV-13
    Momentum, Adam and Optimizer State

    Compute velocity, Adam moments, bias correction and updates by hand.

  9. IV-14
    PyTorch Autograd as an Independent Check

    Relate hand-computed derivatives to framework autograd without hiding them.

  10. IV-15
    Initialization, Regularization and Gradient Pathologies

    Explain activation/gradient magnitude and parameter penalties.

Part III — Embeddings

  1. IV-16
    Token IDs and Embedding Lookup Tables

    Map discrete IDs to selected rows of a learned parameter matrix.

  2. IV-17
    Embedding Geometry and Similarity

    Explore similarities, distances and coordinate-dependent projections.

  3. IV-18
    How Embeddings Learn From Gradients

    Calculate sparse lookup gradients and repeated-index accumulation.

Part IV — Sequence Models

  1. IV-19
    Sequences, Order and Recurrent State

    Define ordered samples, shared recurrent parameters and temporal state.

  2. IV-20
    Recurrent Networks and Backpropagation Through Time

    Unroll a small RNN and differentiate through shared temporal weights.

  3. IV-21
    Long Dependencies and Recurrent Limitations

    Compute Jacobian products to expose vanishing and exploding gradients.

Part V — Self-Attention

  1. IV-22
    Queries, Keys and Values as Projections

    Compute Q, K and V from the same token representations with distinct weights.

  2. IV-23
    Dot-Product Attention Scores and Scaling

    Compute each query-key dot product and its 1/sqrt(d_k) scaling.

  3. IV-24
    Masking and Numerically Stable Softmax

    Apply causal/padding masks then rowwise stable softmax.

  4. IV-25
    Self-Attention: Complete Numerical Trace

    Derive X→Q,K,V→QKᵀ→scale→mask→softmax→AV without gaps.

  5. IV-26
    Causal, Bidirectional and Padding Attention

    Contrast different allowed-key sets using the same real projected tensors.

Part VI — Multi-Head Attention

  1. IV-27
    Separating Attention Heads and Dimensions

    Reshape concatenated projections into named head-specific axes.

  2. IV-28
    Independent Attention Heads

    Execute separate head-specific score, mask, softmax and value paths.

  3. IV-29
    Head Concatenation and Output Projection

    Concatenate real head outputs and apply an explicit output matrix.

Part VII — Transformer Blocks

  1. IV-30
    Residual Connections and Gradient Paths

    Calculate residual addition and its gradient contributions.

  2. IV-31
    Layer Normalization and RMS Normalization

    Compute mean, variance/RMS, epsilon and affine scale parameters.

  3. IV-32
    Position-Wise Feed-Forward Networks

    Apply token-independent MLP operations using shared parameters.

  4. IV-33
    A Complete Transformer Block

    Compose attention, residual, normalization and FFN in order.

Part VIII — Positional Information

  1. IV-34
    Why Position Matters to Attention

    Demonstrate that attention without positional signals is permutation equivariant.

  2. IV-35
    Learned and Sinusoidal Position Embeddings

    Compute additive position vectors and compare parameterized and fixed schemes.

  3. IV-36
    Rotary Position Embeddings (RoPE)

    Rotate paired query/key feature coordinates by positional angles.

Part IX — Tokenization

  1. IV-37
    From Unicode Text to Token IDs

    Distinguish characters, code points, UTF-8 bytes and vocabulary IDs.

  2. IV-38
    Subwords and Vocabulary Trade-Offs

    Compare character, byte and subword granularity on sample texts.

  3. IV-39
    Byte-Pair Encoding: A Full Merge Trace

    Perform deterministic byte-level BPE training and encoding step by step.

Part X — Language Modeling

  1. IV-40
    Autoregressive Next-Token Prediction

    Form a causal conditional distribution p(x_t|x_<t).

  2. IV-41
    Teacher Forcing and Shifted Targets

    Align input and target token positions in a causal training example.

  3. IV-42
    Cross-Entropy, NLL and Perplexity

    Compute token NLL, sequence loss, average and perplexity.

  4. IV-43
    End-to-End Tiny Language-Model Objective

    Connect token IDs, embeddings, causal block, logits, and shifted loss.

Part XI — Autoregressive Inference

  1. IV-44
    Prefill and Single-Token Decode

    Distinguish processing a prompt from subsequent decoding calls.

  2. IV-45
    From Logits to the Next Token

    Calculate greedy selection and deterministic tie resolution.

  3. IV-46
    Temperature, Top-k and Nucleus Sampling

    Apply temperature and filtering in a declared order.

  4. IV-47
    Complete Autoregressive Generation Trace

    Generate a short sequence with inspectable logits and deterministic RNG.

Part XII — KV Cache

  1. IV-48
    Keys, Values and the Cache Invariant

    Identify which per-layer past tensors a decoder can reuse.

  2. IV-49
    Cached Versus Uncached Decoding

    Independently compute cached and full-prefix outputs for each step.

  3. IV-50
    KV Cache Memory, Latency and Invalidation

    Calculate cache footprint and demonstrate relevant invalidations.

Part XIII — Training Language Models

  1. IV-51
    Training Data, Packing and Causal Boundaries

    Turn short documents into training chunks and loss masks.

  2. IV-52
    Language-Model Training Steps and Batches

    Calculate token losses, reduced gradients and one optimizer update.

  3. IV-53
    Checkpoints and Reproducible Resumption

    Explain exact trainable and RNG state needed to resume.

  4. IV-54
    Scaling Limits and Generalization

    Distinguish capacity, compute, data quality and evaluation uncertainty.

Part XIV — Fine-Tuning and Alignment

  1. IV-55
    Pretraining, Fine-Tuning and Transfer

    Compare which model parameters/data/objectives change in adaptation.

  2. IV-56
    Low-Rank Adaptation (LoRA)

    Derive W+alpha/r·BA and compute gradients and trainable counts.

  3. IV-57
    Preference Data and Optimization Objectives

    Define scored/ranked pairs and a transparent preference loss.

  4. IV-58
    Alignment, Safety and Evaluation Limits

    Distinguish training objectives, evaluation proxies and observed behavior.

Part XV — Modern LLM Architectures

  1. IV-59
    Decoder-Only Transformer Anatomy

    Locate embeddings, repeated blocks, output head and causal decoding.

  2. IV-60
    Encoder, Decoder and Cross-Attention Variants

    Contrast bidirectional encoders, causal decoders and cross-attention.

  3. IV-61
    Multi-Query and Grouped-Query Attention

    Explain query-head to key/value-head mappings and memory tradeoffs.

  4. IV-62
    Mixture-of-Experts Routing

    Compute router scores, top-k dispatch and gated expert outputs.

  5. IV-63
    Quantization and Numerical Approximation

    Quantize small weight tensors and measure reconstructed output error.

  6. IV-64
    Inference Systems: Throughput and Latency

    Reason about prefill, decode, batching and memory-bound tradeoffs.

  7. IV-65
    Evaluating LLMs, Leakage and Reliability

    Examine evaluation design, leakage, calibration and uncertainty.

  8. IV-66
    From Text to Output: Full-Stack LLM Capstone

    Trace text → bytes/BPE → embeddings → positioned block → logits → decode.