Skip to main content

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.

TipNumerical building blocks in one minute

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.

The shape contract of the four gpt_ops.py building blocks
Shape contract of the four gpt_ops.py building blocks, from initialization to activation A generator initializes W (out, in) and a zero bias; the linear projection replaces the last axis of x (..., in) with the output width (..., out); layer normalization acts on the last axis, per position; GELU transforms each activation individually without changing the shape. rng _init_matrix / _init_linear W (out, in) b = (0,) x(..., in) lineary = x @ Wᵗ + b(..., in) → (..., out)the bias broadcasts on the last axis layer_normaxis = -1mean 0, var. ≈1then × γ + β gelu0.5x(1+tanh(…))element-wise output(..., d)

Hover 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.

data flow drawn parameters (W, b) operation

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)
  • rng comes 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.02 is 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 in num_parameters stays 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 as torch.nn.Linear — so both widths are readable in every array’s shape, and the code maps directly onto PyTorch.
  • Why does the bias broadcast? bias has 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.
Tip

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’s d-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.
  • eps inside the sqrt: if a position’s activations were constant, the variance would be zero; eps then keeps the denominator at sqrt(eps) and avoids division by zero. For non-zero variance, the normalized variance is variance / (variance + eps): slightly below 1, but close to 1 when eps is small.
  • gamma and beta are 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, needs erf — 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 about 4.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.
Warning

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.

Build path navigation

Connections

Language: Français · English

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

Further reading