Skip to main content

Guided tour: assembling the GPT (gpt.py)

Embeddings, stacked blocks and the projection to logits

This page is the fourth stop (4 of 5) of the guided tour. The previous tour ended at the output of one block; this page follows how blocks are stacked and how the complete model’s interfaces fit together: input embeddings, repeated blocks, final normalization and the projection to logits. Best read after the configuration and the block. Source: src/llm_lab/foundations/gpt.py.

TipGPT assembly in one minute

The model maps token IDs of shape \((B,T)\) to token embeddings, adds positional embeddings, passes them through the block stack, applies final normalization, and uses an untied output head to produce logits of shape \((B,T,V)\). Prefix-invariance tests check that past positions do not depend on future tokens.

By the end of this tour, you will be able to: - trace one forward pass’s shapes, from (B, T) to (B, T, V); - explain how learned absolute positions are added by broadcasting over the batch; - describe the causality evidence from the prefix-invariance test and the explicit parameter count.

Building: one generator, one fixed order

        self.config = config
        rng = np.random.default_rng(config.seed)
        d = config.embedding_dim

        self.token_embedding: FloatArray = _init_matrix(rng, (config.vocab_size, d))
        self.position_embedding: FloatArray = _init_matrix(
            rng, (config.context_length, d)
        )
        self.blocks = [TransformerBlock(config, rng) for _ in range(config.num_layers)]
        self.ln_f_gamma: FloatArray = np.ones(d, dtype=np.float64)
        self.ln_f_beta: FloatArray = np.zeros(d, dtype=np.float64)
        self.w_head, self.b_head = _init_linear(rng, config.vocab_size, d, 0.02)
  • A single generator walks the whole model in a fixed order (embeddings, blocks in stack order, head): every parameter becomes a deterministic function of the configuration.
  • token_embedding: a (V, d) table — one learned vector per vocabulary entry.
  • position_embedding: a (T, d) table of learned absolute positions, added to the token embeddings.
  • blocks: num_layers blocks, identical in structure, distinct in parameters.
  • The head w_head projects d -> V. It is untied: a separate matrix, distinct from the embedding table (unlike weight tying).
Warning

Differences from GPT-2. The original GPT-2 reuses the token-embedding matrix, transposed, to compute logits: input and output weights are tied. Here, w_head is an independent matrix and has a bias (b_head). There is another initialization difference: GPT-2 initializes its position-embedding table with standard deviation 0.01, whereas this project uses 0.02; token embeddings use 0.02 in both. The project’s reference model is therefore a GPT-style educational model, not an exact GPT-2 reproduction. Its parameter count includes the additional output matrix and bias.

Isolated experiment: verify lookup with NumPy

Before tracing lookup in the complete model, isolate the operation on a small synthetic matrix. These values are pedagogical: they are neither the project’s GPT weights nor learned embeddings. The experiment checks three invariants: the output shape for a batch, identical vectors for repeated IDs, and the absence of a relationship between numerical ID order and geometric distance.

import numpy as np

# Synthetic matrix: V=5 entries, embedding dimension d=2
E = np.array([
    [0.1, 0.0],   # ID 0
    [0.0, 0.2],   # ID 1
    [0.8, -0.1],  # ID 2
    [-0.2, 0.5],  # ID 3
    [0.3, 0.7],   # ID 4
], dtype=np.float64)

# Batch of 2 sequences, each of length T=3
token_ids = np.array([
    [2, 0, 3],
    [1, 2, 4],
])

# Each ID selects one row of E
X = E[token_ids]

assert X.shape == (2, 3, 2)       # (B, T, d)
assert np.array_equal(X[0, 0], E[2])
assert np.array_equal(X[1, 1], E[2])
assert np.array_equal(X[0, 0], X[1, 1])

# Consecutive IDs do not imply geometric proximity
d_2_3 = float(np.linalg.norm(E[2] - E[3]))
d_0_4 = float(np.linalg.norm(E[0] - E[4]))
print(f"X shape: {X.shape}")
print(f"Distance E[2]-E[3]: {d_2_3:.3f} | Distance E[0]-E[4]: {d_0_4:.3f}")

The expected shape is (2, 3, 2). Both occurrences of ID 2 retrieve exactly the same row. The distances are only those of this synthetic matrix: they illustrate that differences between IDs do not determine distances between vectors; they are not measurements from a trained model.

The forward pass: from (B, T) to (B, T, V)

        ids = np.asarray(token_ids)
        # ... full validation before any computation ...
        seq_len = ids.shape[1]
        x = self.token_embedding[ids] + self.position_embedding[:seq_len]
        for block in self.blocks:
            x = block.forward(x)
        x = layer_norm(x, self.ln_f_gamma, self.ln_f_beta)
        return linear(x, self.w_head, self.b_head)
The shape journey: every forward-pass line has its stage
Shape journey through gpt.py: ids cross the blocks and become logits Ids (B, T) index the embedding table (V, d) to give (B, T, d); positions (T, d) are added; the L blocks and the final normalization keep (B, T, d); the w_head projection (d to V) produces the logits (B, T, V). ids(B, T) token_embedding[ids]fancy indexing: one row per id + position_embedding[:T]T rows sliced, broadcast over the batch blocks × Lpré-LN + résidus ln_f(γf, βf) w_headd → V logits(B, T, V) (B, T) (B, T, d) (B, T, d) (B, T, d) (B, T, d) (B, T, V)

Hover over or select a line: the matching stage lights up and the tensor shape reads in the green badge. Keyboard: Tab, Enter to pin, Esc to release.

The shape changes at only two moments: the embedding lookup (ids → d-vectors) and the output projection (d → V). In between, (B, T, d) crosses L blocks and the final normalization unchanged.

token ids parameters (tables, w_head) logits (output) tensor shape

The shape journey, line by line:

  1. Validate first: 2D, integers, non-empty, seq_len <= context_length, ids within [0, V). A named error here beats an indexing crash three lines later.
  2. token_embedding[ids]: fancy indexing with (B, T) ids selects one row of the (V, d) table per id — output (B, T, d).
  3. + position_embedding[:seq_len]: the (T, d) table is sliced to the current length, then broadcast over the batch — every sequence shares the same absolute positions.
  4. The block loop: each block rewrites x; the residual paths inside the blocks guarantee x keeps a copy of its input.
  5. Final normalization then linear: (B, T, d) -> (B, T, V). Position t holds the scores of the token that may follow t.
Tip

Causality is verified, not just declared. The prefix-invariance test runs the model on a prefix, then on that same prefix extended: the earlier positions’ logits must be identical. This is targeted empirical evidence for the tested prefix and configuration, not a proof for every possible input.

Counting parameters: explicit accounting

        return int(sum(array.size for array in arrays))

num_parameters walks every array instead of applying a formula. The test compares the result to an independent count derived from the configuration — per block:

  • 4 (d, d) matrices and their biases (Q, K, V, O);
  • the MLP: (hidden, d), (d, hidden) and their biases;
  • 2 layer-norm parameter pairs.
Warning

Common misconceptions. (1) Position does not enter the model “by magic”: it is added to the token embeddings, in the line above. (2) The model does not output probabilities but logits; turning them into a distribution is a decoding choice (next page).

What the tests verify

tests/unit/test_gpt.py: the expected (B, T, V) shape and finite values; every named validation error; determinism at equal seed (and difference at a different seed); prefix invariance; a parameter count matching the independent formula.

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.

Build path navigation

Connections

Language: Français · English

Supplementary resources Experiment, explore further, and practise the ideas from this lesson.

Further reading