Build a small GPT
A guided practical path without disproportionate mathematical prerequisites
This path guides you through an existing small decoder-only GPT: inspect its configuration and numerical building blocks, trace the Transformer block and assembled model, then run the generation loop. LLM Lab uses small, inspectable models to teach mechanisms, not to reproduce production-scale capabilities. The tested reference code lives in src/llm_lab/foundations/; each of the five tours includes exercises with worked answers. You can use these tours to guide your own construction, but reading and running the reference is not evidence that you built it independently. Familiarity with Python and basic NumPy is useful; consult the linked concept pages for the mathematics and shapes as needed.
The path follows the reference code’s dependencies through five tours: configuration, numerical operations, the Transformer block, GPT assembly, and generation. Each stage connects code to tensor shapes, tests, and an observable result. It inspects and verifies a small inference model; the complete data, training, and evaluation pipeline remains outside the implemented scope.
You can start Build independently of the Theory / Understand path. Consult concept pages as needed. The progression below follows code dependencies and results you can run and verify.
By the end of this path, you will be able to: - place the five modules of the reference code and their order of construction; - run the reference code and its tests, then verify each available milestone’s observable result (tensor shapes, causality, generation loop); - explain why a randomly initialized GPT can demonstrate generation mechanics without learned language quality.
The code, in construction order
The tours follow a useful reading order, not a complete dependency list. For example, the block also uses attention.py, and generation imports the optional decoding filters. The source links show the actual imports; separating the minimal inference path from optional extensions remains future work.
- The configuration (
gpt_config.py): name and validate the model’s dimensions before any computation. - The numerical building blocks (
gpt_ops.py): initialization, linear projection, layer normalization, GELU. - The Transformer block (
transformer_block.py): multi-head causal attention, MLP and residuals, in pre-LN order. - Model assembly (
gpt.py): embeddings, stacked blocks, projection to logits. - Generation (
generate.py): the autoregressive loop — pick a token, append it to the context, repeat.
The model, assembled
After the setup below1, run this complete example with uv run --locked python example.py. It uses a synthetic vocabulary and returns token IDs, not decoded text (see “Generate first, train later”):
import numpy as np
from llm_lab.foundations import GPT, GPTConfig, generate
config = GPTConfig(
vocab_size=50, # V: embedding-table rows, logits per position
context_length=32, # T: positions processed in one pass
embedding_dim=32, # d: residual-stream width, divisible by num_heads
num_heads=4, # H: attention heads
num_layers=2, # stacked blocks
mlp_hidden_dim=64, # MLP hidden width
seed=0, # same seed, same parameters
)
model = GPT(config)
parameter_count = model.num_parameters()
assert parameter_count == 21426
print("Parameters:", parameter_count)
prompt = np.array([1, 2, 3])
greedy_ids = generate(model, prompt, max_new_tokens=8)
sampled_ids = generate(
model, prompt, max_new_tokens=8, greedy=False,
temperature=0.8, rng=np.random.default_rng(42),
)
print("Greedy IDs:", greedy_ids)
print("Sampled IDs:", sampled_ids)For this configuration, the expected count is 21,426 parameters. Each output contains the three prompt IDs followed by eight generated IDs; the two calls start from the same prompt. The reference code is pure NumPy (float64): readability first, speed later.
Build and verify at each milestone
At each milestone:
- Understand the mechanism: the linked concept page explains it — consult it when the question arises rather than beforehand.
- Build and verify: trace or implement the operation, make a prediction, and check it against the worked exercise and reference tests. The tours do not require you to write a full GPT from scratch.
- Deepen as needed: tensors and the mathematical chain of training are references for shapes and gradients. Training also requires data, a loss and an update procedure; understanding gradients alone is not sufficient.
- Practice: try the questions in the relevant tour before opening its answers, or choose an available exercise.
Try a tour and check its evidence
Start with the configuration exercise: predict whether the two width/head-count combinations are accepted, then compare your answer with the explanation. After the setup below, run uv run --locked pytest --no-cov -q tests/unit/test_gpt_config.py and inspect what the tests actually check. Continue with the exercises and linked tests in the operations, block, model, and generation tours. --no-cov disables the whole-project coverage gate for this single-file run; the full test command below retains it. A passing test covers its stated cases; it does not establish independent construction or language quality.
Generate, score and train: three uses of the same computation
The same predictive computation maps a context to a conditional distribution over the next token. This shared distribution serves three distinct uses: generation selects a token and feeds it back into the context; scoring measures the probability assigned to an observed token; training compares predictions with targets, computes a loss and its gradients, then updates parameters. Scoring and validation use fixed parameters: they do not trigger an optimizer step. The panorama details this distinction between learning and inference.
The path explores generation first. A randomly initialized GPT has no learned language behavior to rely on: its shapes, causal mask and generation loop can be checked without demonstrating useful text. The example above returns IDs from a synthetic vocabulary; interpreting them as text would require a compatible tokenizer. This separation motivates the learning milestones: preparing training examples, optimizing a loss with gradients — of which only the loss computations exist today (losses.py). The generation loop itself is detailed in Generating text: inference step by step.
The Build path separates model implementation from the infrastructure that executes it. Once a training loop works locally, a managed GPU can be used as an on-demand accelerator: Hugging Face Jobs recipe (EN/FR). The external repository illustrates this method; it is not an integrated LLM Lab training implementation and does not verify the project’s G8/G9 milestones.
Build milestones
Before moving to the next step, produce or verify the indicated result; concept pages supply the mechanism, not proof that the code exists. The G0–G9 identifiers are those of the versioned build plan; G2 (training data) is a parallel branch: required before training, not for generation.
| Step | What you build | Result to verify | To understand | Code status |
|---|---|---|---|---|
| 0 · G0. Define the model | The scope: a decoder-only GPT predicting the next token | Place this model among LLM families and Transformer architectures | LLM panorama, GPT and Transformer, history as context | Conceptual |
| 1 · G1. Prepare text input | Encoding and decoding a prompt with the tokenizer | Encode then decode a short text; identify the effect of special tokens and tokenizer version | Text and data, Unicode, tokenization | Conceptual — no validated tokenizer pipeline |
| 2 · G3. Represent tokens | Embedding lookup and positional information | Trace shapes from [B, L] to [B, L, D] and name each axis |
Embedding space, position; optional deep dives: RoPE, sinusoidal encoding | Reference — inside gpt.py; tour: model |
| 3 · G4. Build and verify attention | Q/K/V projections, score computation, softmax, causal mask and value aggregation | Verify attention weights, normalization over permitted keys and weighted value aggregation; test that future positions are excluded | Q/K/V, attention, causal masking; optional deep dive: attention score scaling | Reference — attention.py for the mask and single-head primitive; the attention sublayer in transformer_block.py for Q/K/V projections and heads; tour: attention section |
| 4 · G5. Build the block and assemble GPT | Complete the pre-LN block: attention, position-wise MLP, residual paths and normalization; stack blocks in GPT, then add final normalization and the output head | Verify the block preserves (B, T, d), then trace (B, T, d) → (B, T, V) and the model parameter count |
Transformer, tensors as reference | Reference — TransformerBlock.forward and GPT.forward; tour: block recipe and model assembly |
| 5 · G6. Predict and select | Turning logits into a distribution, then the decoding rule | Distinguish logits from probabilities; explain greedy or sampled selection | Logits, probabilities, generation step by step; optional deep dive: advanced decoding strategies | Reference — inside generate.py; tour: generation |
| 6 · G7. Generate before training | The autoregressive loop with random parameters, a new-token bound and a sliding context window | Run the loop on token IDs; verify max_new_tokens and window sliding; note the absence of an EOS/early-stopping rule |
Generation step by step; optional deep dive: LLM computational complexity | Reference — generate.py and tests; no KV cache or EOS rule; no published checkpoint is loaded (see G9) |
| Data branch · G1b. Prepare the corpus and tokenizer | A traceable, eligible corpus, explicit splits, and a tokenizer that is fitted then frozen | Check provenance, deduplication, split hygiene and tokenizer consistency | Corpus preparation; tokenizer design/evaluation as optional depth | Conceptual plan available; complete loading, provenance, deduplication and split-audit pipeline not implemented |
| Data branch · G2. Create training examples | Context windows, shifted targets, batches and masks built from token streams | Build a window and its shifted target; test alignment, boundaries and leakage | Training examples; tensors as reference | Partial — sliding windows and shifted targets are tested in training_examples.py; full packing, padding, batching and masks remain to be built |
| 7 · G8. Train and validate | Compute loss on training targets, backpropagate and update parameters; measure validation separately with fixed parameters | Reproduce an update on a training batch; verify that a validation batch computes scores without calling the optimizer | Cross-entropy, loss, gradients; optional deep dive: mathematical training chain | Partial — losses.py (cross_entropy_from_logits, cross_entropy_gradient); no complete loop, optimizer, automated validation runner or checkpoint |
| 8 · G9. Verify the implementation | Compare an implementation with a compatible reference (same architecture, tokenizer, weights and preprocessing) | Check configuration, parameter coverage and numerical outputs with explicit tolerances; explain discrepancies | GPT and Transformer, generation | Reference — gpt2_weights.py loads GPT-2-format parameters; test_gpt2_reference_parity.py compares logits, layer-by-layer hidden states and greedy generation with Hugging Face GPT-2 under identical random weights (tolerance 1e-10 in float64, 1e-5 in float32). Tokenizer out of scope (IDs supplied); published GPT-2 weights not loaded yet |
| Cross-cutting · E1. Evaluate the task | Evaluate performance and limitations for a specific task on suitable data | Compare against a baseline under an explicit protocol; analyze errors, uncertainty and metric limitations | Experimental evaluation | Method available — no complete evaluation of a trained GPT |
For the G4 causality check, inspect test_prefix_invariance_future_tokens_do_not_change_earlier_logits in the model tests: it compares a prefix with a longer sequence under the same model. The NumPy reference has no train/eval mode switch. This test covers that prefix-extension case; it does not prove causality for every possible input.
For a first G2 check, take token IDs [5, 6, 7, 8] and a context length of 3: predict the input window and its one-token-shifted target. The worked training-example lesson explains the convention; compare your answer with test_corpus_of_context_length_plus_one_yields_one_window in the reference tests. Run the file with uv run --locked pytest --no-cov -q tests/unit/test_training_examples.py. It does not test a complete corpus or data-splitting pipeline.
These criteria are learning objectives: an available page, a hand-checkable example, an automated test and a reproducible run are different levels of evidence.
To continue
- Exercises and practice: apply the milestones to exercises, separately from conceptual questions.
- Hugging Face — Building a model card: document intended uses, limitations, data, training procedure, and evaluation results for a shared model.
- Versioned build plan: prerequisites, expected evidence, dependencies and validation criteria for each milestone.
An educational project, not industrial-scale training. The small randomly initialized GPT makes transformations and errors inspectable; it does not reproduce the data volumes, compute resources or performance of a production LLM.
Footnotes
Install Python 3.12+ and uv, clone the repository (
git clone https://github.com/JM-Brun/llm-lab.gitthencd llm-lab), and sync withuv sync --locked --dev. For the full test suite, also install the site-test dependencies withuv pip install --python .venv/bin/python -r docs/requirements-tokenizer-example.txtanduv pip install --python .venv/bin/python -r docs/requirements-history-validation.txt, then runuv run --locked pytest. Reinstall those requirements after a fresh sync, as explained in the contributor guide. Save the example in a file namedexample.pyat the repository root. The five tour test files aretest_gpt_config.py,test_gpt_ops.py,test_transformer_block.py,test_gpt.pyandtest_generate.py;test_attention.py,test_training_examples.pyandtest_losses.pycover additional primitives.↩︎