Guided tour: building-block operations (gpt_ops.py)
Initialization, linear projection, normalization and GELU, line by line
This page is the second stop (2 of 5) of the guided tour. This file gathers the operations every Transformer block repeats: weight initialization, linear projection, normalization and activation. Keeping them out of the model classes has two benefits: each operation is testable alone, and the model files read like architecture. Full source: src/llm_lab/foundations/gpt_ops.py.
The module isolates four operations reused by the model: initialize weights, apply a linear projection with an explicit shape convention, normalize each position along the last axis with an epsilon term, and apply the tanh approximation of GELU. Testing them separately makes their shapes and behavior verifiable before assembling the network.
By the end of this tour, you will be able to: - predict each operation’s output shape (linear, layer_norm, gelu) without running it; - explain why weights start small at initialization; - justify layer norm’s axis=-1 convention and the tanh approximation of GELU.
One convention for the whole package: float64
FloatArray = NDArray[np.float64]The whole package exchanges float64 arrays: results stay exact enough to hand-check on paper; the speed cost is irrelevant at reference scale.
gpt_ops.py building blocksHover over or select an operation to locate it in the chain. Keyboard: Tab to browse, Enter to pin, Esc to release.
Four operations, one shared contract: batch axes pass untouched, only the last axis is transformed — by a projection, a normalization, or an activation. This contract is what makes the block’s shapes predictable.
Initializing: drawing small weights
def _init_matrix(
rng: np.random.Generator,
shape: tuple[int, int],
std: float = 0.02,
) -> FloatArray:
return np.asarray(rng.normal(0.0, std, shape), dtype=np.float64)rngcomes from the caller: the model creates one generator from the seed and hands it around — that is what makes the whole model’s initialization reproducible from a single seed.std=0.02is the GPT-2 convention: small weights keep initial activations near the embedding scale, so the first pass neither saturates nor explodes. A convention, not a law.
def _init_linear(
rng: np.random.Generator,
out_features: int,
in_features: int,
std: float,
) -> tuple[FloatArray, FloatArray]:
weight = _init_matrix(rng, (out_features, in_features), std)
bias = np.zeros(out_features, dtype=np.float64)
return weight, bias- The weight has shape
(out, in)with a zero bias: at initialization the layer is a pure linear map with no learned shift. The parameter count innum_parametersstays honest.
Projecting: y = x @ W^T + b
def linear(x: FloatArray, weight: FloatArray, bias: FloatArray) -> FloatArray:
return np.asarray(x @ weight.T + bias, dtype=np.float64)- Why transpose? The weight is stored
(out, in)— the same convention astorch.nn.Linear— so both widths are readable in every array’s shape, and the code maps directly onto PyTorch. - Why does the bias broadcast?
biashas shape(out,); NumPy adds it to the last axis of the product, which is exactly the output axis. The same line works for(in,),(B, T, in), or any number of leading batch axes.
Shape rule to remember: x of shape (..., in) and weight of shape (out, in) give (..., out). Every projection in the block follows this contract.
Normalizing: layer norm per position
mean = x.mean(axis=-1, keepdims=True)
variance = x.var(axis=-1, keepdims=True)
normalized = (x - mean) / np.sqrt(variance + eps)
return np.asarray(normalized * gamma + beta, dtype=np.float64)axis=-1: the statistics cover each position’sd-dimensional vector, independent of batch and sequence — that is what makes the operation per-position, unlike batch normalization.keepdims=True: mean and variance keep shape(..., 1)and broadcast back over the embedding axis with no reshaping.epsinside the sqrt: if a position’s activations were constant, the variance would be zero;epsthen keeps the denominator atsqrt(eps)and avoids division by zero. For non-zero variance, the normalized variance isvariance / (variance + eps): slightly below 1, but close to 1 whenepsis small.gammaandbetaare the affine parameters applied after normalization. In a trained model they are learned; here they are initialized to identity (ones and zeros) and remain fixed, because this module does not implement training.
Activating: approximate GELU
inner = math.sqrt(2.0 / math.pi) * (x + 0.044715 * x**3)
return np.asarray(0.5 * x * (1.0 + np.tanh(inner)), dtype=np.float64)- The exact definition,
x * Phi(x)with the normal CDF, needserf— absent from base NumPy (SciPy would be required). - The tanh approximation is the one GPT-2 used: on the test grid
[-3, 3], its maximum absolute error against the exact definition is about4.73 × 10⁻⁴; it is the formula learners meet in real GPT-2 source code. - Unlike ReLU, GELU is smooth: near zero, a small negative input passes with a small weight instead of being clipped to exactly zero.
Common misconceptions. (1) Layer norm is not batch norm: it uses no statistic of the batch or the sequence. (2) GELU is not “a universally better ReLU”: it is a GPT-style convention, chosen here precisely because GPT-2 uses it.
What the tests verify
tests/unit/test_gpt_ops.py checks each promise: linear equals the manual x @ W.T + b and broadcasts the bias; layer_norm normalizes then rescales, with zero mean and near-unit variance under the identity affine; gelu(0) = 0 and the approximation stays within 1e-3 of the exact erf definition; initialization is reproducible at equal seeds.
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
- Previous stop: GPT configuration (
gpt_config.py) — the dimensions used here. - Next stop: the Transformer block (
transformer_block.py) — which consumes these blocks.
Supplementary resources Experiment, explore further, and practise the ideas from this lesson.
Further reading
- Concept pages: GPT and the Transformer, tensors and shapes.
- Back to the path: Build a small GPT.
- Source:
gpt_ops.py· Tests:test_gpt_ops.py.