aiml

Build a Small Language Model From Scratch

Build a small one-block transformer, then train it and generate text locally.

What is a language model?

A language model learns patterns in text to predict the next token—a unit of text represented by a number. Training compares the model’s scores with the expected next token, then updates its parameters to reduce that error. This course builds those steps before adding attention, position information and a key/value cache.

Begin with the tiny red-to-stop and green-to-go training batch so every intermediate value is visible. Then build a tokenizer and a one-block transformer for the bundled stories, save and resume training, and compare generation with and without a key/value cache. The final tensor bridge checks the existing computation against PyTorch.

Before you start

The examples use a bundled synthetic story corpus and Python’s standard library. Follow the same tokenizer and model through training, checkpointing, generation and a local HTTP service.

Python prerequisites
Read loops and nested lists, write functions, work with dictionaries and JSON, and run a unit test. The labs use Python’s standard library and run on a CPU.
Mathematics prerequisites
Follow basic algebra, multiply and add vector entries, and read probabilities. The examples below introduce the derivatives and logarithms used in the first training step.

Introduced in the course. Embeddings, loss, gradients, attention, transformer blocks, checkpoints, inference and cached generation are explained before you implement them. You do not need prior experience with an ML framework.

Review three numerical examplesDot products, gradient updates and prediction loss
  1. Dot product

    Multiply matching entries, then add. Attention uses this operation to score a query against a key.

    [1, 2] · [3, 4]
    = 1×3 + 2×4 = 11
  2. Gradient update

    The derivative describes local sensitivity. Subtracting the learning rate times that derivative gives one gradient-descent update; a rate that is too large can overshoot.

    L(w) = w²; at w = 2, dL/dw = 4
    new w = 2 − 0.1×4 = 1.6
  3. Prediction loss

    Giving less probability to the correct token produces a larger loss. Lesson 1 connects that loss to parameter gradients.

    −ln(0.5) ≈ 0.693
    −ln(0.1) ≈ 2.303
Course termsShort definitions linked to their worked implementation
Token, token ID and vocabulary

A token is one text unit the model represents. Its token ID is an integer used to select a vocabulary entry. A vocabulary is the fixed set of entries the model can predict.

Explore token, token id and vocabulary →
Vector, matrix, tensor and shape

A vector is a one-dimensional array of numbers; a matrix has rows and columns. Tensor is the general array term. Its shape lists the length of each axis, such as (3, 2) for three rows of two values.

Explore vector, matrix, tensor and shape →
Dot product and matrix multiplication

A dot product multiplies matching vector entries and sums them into one score. Matrix multiplication applies compatible dot products across rows and columns. Matching inner dimensions is required.

Explore dot product and matrix multiplication →
Embedding and parameter

An embedding maps a token ID to a trainable vector. A parameter is a numeric value training adjusts, including embedding entries, weights and biases.

Explore embedding and parameter →
Logit, softmax and probability distribution

A logit is a raw prediction score. Softmax exponentiates a set of scores and normalizes them into nonnegative probabilities summing to one.

Explore logit, softmax and probability distribution →
Loss and cross-entropy

A loss is a numerical penalty used to guide training. For the observed next token here, cross-entropy is the negative natural logarithm of the probability assigned to that token, averaged across scored examples.

Explore loss and cross-entropy →
Derivative, gradient and chain rule

A derivative measures how a quantity changes locally with one input. A gradient collects derivatives with respect to several parameters. The chain rule combines local derivatives through a sequence of operations.

Explore derivative, gradient and chain rule →
Forward pass, backward pass and optimizer

The forward pass computes predictions and loss. The backward pass computes parameter gradients. An optimizer uses those gradients and its update rule to change the parameters.

Explore forward pass, backward pass and optimizer →
Learning rate, batch, step and epoch

The learning rate controls update size. A batch is the group of examples contributing to one update; that update is a step. An epoch is a pass through the training examples.

Explore learning rate, batch, step and epoch →
Training, development and test sets

Training examples determine parameter updates. Development examples guide settings and checkpoint selection. Test examples are reserved for evaluation after those choices.

Explore training, development and test sets →
Causal attention, query, key and value

Each position computes a query that scores allowed keys, then mixes their value vectors. A causal mask prevents it from reading later positions that would reveal the prediction target.

Explore causal attention, query, key and value →
Transformer block

The layer built here combines attention with a per-position feed-forward network, residual additions and normalization. Position embeddings supply position information to the model.

Explore transformer block →
Checkpoint

A resumable checkpoint preserves parameters and the optimizer, data-order and input identities needed for the next training step. Selected model parameters alone serve a different purpose.

Explore checkpoint →
Training, inference and generation

Training changes model parameters using examples. Inference applies fixed parameters to an input to produce predictions. Text generation repeats inference and token selection, adding each chosen token to the context.

Explore training, inference and generation →
KV cache

A key-value cache retains earlier attention keys and values for one sequence. It avoids recomputing those vectors during inference while keeping the model parameters fixed.

Explore kv cache →

From training inputs to generated text

Stories + tokenizerfixed training inputsTrain transformerupdate parametersCheckpointselected by dev lossInferencegenerate textfixed parameterssame tokenizerStories + tokenizerfixed training inputsTrain transformerupdate parametersCheckpointselected by dev lossInferencegenerate textfixed parametersSame tokenizerload selectedparametersreusevocabulary
Training updates parameters. Inference uses fixed parameters to predict the next token; generation repeats inference and token selection. Lessons 8–10 cover this loop, KV caching and local HTTP serving.

What you'll learn

  • Implement and inspect a training step, tokenizer, causal attention and transformer block.
  • Train on bundled synthetic stories and bind resumable checkpoints to their inputs.
  • Generate text with sampling, compare cached generation and validate a local HTTP interface.
  • Port the one-block transformer to PyTorch and compare outputs and gradients within explicit numerical tolerances.

Lessons

Module 1 · 5 lessons · about 2 hoursTokenization, baselines and transformer blocks

Follow a training update, build a tokenizer and next-token baseline, then add attention and position information.

  1. Build one training step by handRead

    Build a 20-parameter next-token model in plain Python, compute every gradient by hand, check them against finite differences and apply one update.

    25 min readLabQuiz

  2. Build a byte-pair encoding tokenizerRead

    Train a byte-pair encoding tokenizer on a small synthetic story corpus in plain Python, save it as a versioned file and test what it cannot encode.

    25 min readLabQuiz

  3. Build a next-token prediction baselineRead

    Score uniform, unigram and bigram models on held-out stories with cross-entropy, and record the prediction a model that sees one token back cannot make.

    25 min readLabQuiz

  4. Build causal self-attention and inspect intermediate outputsRead

    Implement causal self-attention and its backward pass in plain Python. Inspect intermediate tensors and test that future tokens remain hidden.

    30 min readLabQuiz

  5. Build a transformer block with positional informationRead

    Combine causal attention, normalization, skip paths and a feed-forward network. Add position embeddings and check the complete block’s gradients.

    30 min readLabQuiz

Module 2 · 6 lessons · about 3 hoursTraining, checkpoints and inference

Train and retain the model, generate tokens, cache computation and serve it over HTTP. Then compare its handwritten equations and gradients with a CPU tensor implementation.

  1. Build a small language-model training pipelineRead

    Train a one-block transformer on bundled stories using batches and Adam. Inspect loss and compare it with a bigram baseline on held-out stories.

    30 min readLabQuiz

  2. Build checkpoints and resumable trainingRead

    Save checkpoints bound to training inputs, select parameters by development loss and test that an interrupted run resumes to the same result.

    30 min readLabQuiz

  3. Build text generation with sampling controlsRead

    Generate text from the trained model with greedy choice, temperature and top-k. Define stop rules and compare settings on development openings.

    25 min readLabQuiz

  4. Build a KV cache for LLM generationRead

    Reuse attention keys and values during generation. Test cached and uncached output equivalence, and count the computation avoided by the cache.

    25 min readLabQuiz

  5. Build a local server for the trained modelRead

    Serve the trained model through a validated local HTTP interface. Compare served and direct generation, and evaluate on held-out story tasks.

    30 min readLabQuiz

  6. Compare a handwritten transformer with PyTorchRead

    Port the existing one-block transformer to CPU tensors, then compare logits, loss and every parameter gradient with explicit attention and PyTorch SDPA.

    30 min readLabQuiz