Guided tour: GPT configuration (gpt_config.py)
Where every model dimension gets a name and a validation
This page is the first stop (1 of 5) of the guided tour of the reference code: the smallest file of the package, the one that defines what the model is before any other file defines what it does. Every code excerpt is commented line by line; the full source lives in src/llm_lab/foundations/gpt_config.py.
The configuration names the dimensions that determine model shapes and groups their constraints in an immutable object. Construction-time validation rejects inconsistent combinations early, with a message identifying the field, before a numerical operation produces a harder-to-diagnose shape error.
By the end of this tour, you will be able to: - name every configuration dimension and what it determines elsewhere in the model; - map each field to the tensor shapes it controls; - explain why validation fails early with a named message instead of late with a shape error.
The file’s role in the module family
The reference implementation is split into five modules, in reading order:
| Module | Contents | Tour page |
|---|---|---|
gpt_config.py |
dimensions, their names, their validation | this page |
gpt_ops.py |
numerical building blocks (init, projection, normalization, GELU) | next |
transformer_block.py |
one complete pre-LN Transformer block | block |
gpt.py |
the assembled model: embeddings, blocks, output | model |
generate.py |
the autoregressive decoding loop | generation |
Isolating configuration in one small immutable object has three pedagogical benefits: one definition site (every surprising dimension has a name here), errors at construction time (instead of a broadcasting crash mid-forward-pass), and reproducibility (two identically configured models are identical).
The declaration: a frozen dataclass
@dataclass(frozen=True)
class GPTConfig:@dataclassgenerates the constructor: no need to write six assignments by hand.frozen=Truemakes the object immutable. The configuration is read everywhere and written nowhere: “did something mutate the config mid-run?” becomes a guarantee instead of a debugging session. Any accidental assignment raisesFrozenInstanceErrorimmediately.
The seven fields, one by one
vocab_size: int
context_length: int
embedding_dim: int
num_heads: int
num_layers: int
mlp_hidden_dim: int
seed: int = 0GPTConfig field livesHover over or select a field: the diagram dims everywhere except the places this field determines. Keyboard: Tab to browse, Enter to pin, Esc to release.
One full forward pass: ids become d-dimensional vectors, cross L blocks, and leave as V logits. Select a field to see the shape it controls.
| Field | Role | What it determines elsewhere |
|---|---|---|
vocab_size (V) |
vocabulary size | rows of the embedding table; number of logits per position |
context_length (T) |
maximum positions per pass | rows of the position table; width of the sliding generation window |
embedding_dim (d) |
residual-stream width | must be divisible by num_heads: each head owns d/H contiguous columns |
num_heads (H) |
number of attention heads | multi-head attention = H independent single-head attentions over slices |
num_layers |
depth (stacked blocks) | scales W_O and fc2 only; Q/K/V and fc1 keep 0.02 |
mlp_hidden_dim |
MLP hidden width | GPT-2 uses 4 * d; here the value is explicit, hence visible and changeable |
seed |
initialization seed | inference is deterministic; the seed controls only the initial draws |
Why does seed: int = 0 have a default? The other six dimensions describe the architecture; the seed describes an experiment. A default lets you build the model without thinking about it, then change it and observe that only the parameter values change — never the shapes, never the mechanics.
The validation: fail early, with a name
def __post_init__(self) -> None:
dimensions = {
"vocab_size": self.vocab_size,
"context_length": self.context_length,
"embedding_dim": self.embedding_dim,
"num_heads": self.num_heads,
"num_layers": self.num_layers,
"mlp_hidden_dim": self.mlp_hidden_dim,
}
for name, value in dimensions.items():
if type(value) is not int or value <= 0:
raise ValueError(f"{name} must be a positive integer")
if type(self.seed) is not int or self.seed < 0:
raise ValueError("seed must be a non-negative integer")
if self.embedding_dim % self.num_heads != 0:
raise ValueError("embedding_dim must be divisible by num_heads")Line by line:
__post_init__runs automatically at the end of the generated constructor: the last moment when the caller still knows which value is wrong.- The
dimensionsdict ties each value to its field name; without it, this would be six near-identical checks. - The type check is explicit: an
intannotation does not validate a value at runtime. Only Python integers are accepted; positive floats, including16.0, and booleans are rejected before reaching NumPy. raise ValueError(f"{name} ..."): the message names the culprit ("vocab_size must be a positive integer") instead of a distantshapes not aligned.- The seed is validated too: it must be a non-negative integer, matching the
default_rngcontract. - The divisibility check stands apart: multi-head attention slices the residual stream into
Hequal parts ofd/Hcolumns. Adthat does not divide would make the split impossible — the failure would otherwise surface as a shape error in the middle of the first forward pass.
Common misconception. context_length is not “the maximum output size”. It is the number of positions the model can process in one pass; generation can produce longer sequences by sliding the window (see the generate.py tour).
What the tests verify
tests/unit/test_gpt_config.py checks this file’s promises: non-integer, zero or negative dimensions are rejected with the right message, divisibility is enforced, negative, non-integer or boolean seeds are rejected, the object is genuinely immutable (FrozenInstanceError), and the seed defaults to 0.
Exercises
The questions for this tour and their worked answers are collected on its dedicated practice page. Try them before opening the answers: they check the stated outcomes without duplicating the prompts in the walkthrough.
Connections
- Next stop: building-block operations (
gpt_ops.py).
Supplementary resources Experiment, explore further, and practise the ideas from this lesson.
Further reading
- Concept page: GPT and the Transformer — the architecture these dimensions parametrize.
- Back to the path: Build a small GPT — the path that motivates this code.
- Source:
gpt_config.py· Tests:test_gpt_config.py.