TExcelTAD

Building a Transformer Block

Attention lets every token read from every other token, but on its own it is a weak layer: it only takes weighted averages of value vectors, it has no idea where a token sits in the sequence, and a stack of bare attention layers is hard to train. A transformer block wraps attention with the three things it lacks: a per-token MLP that does the actual nonlinear computation, residual connections and layer normalisation so that dozens of blocks can be stacked, and positional information added to the input. Every large language model, ViT and speech transformer is a stack of this one block.

This lesson builds the block in NumPy, counts its parameters, and then shows that nn.TransformerEncoderLayer computes exactly the same function once our weights are copied into it. The math background is in The Transformer Block and Positional Encodings.

The pre-norm block

x LayerNorm multi-headattention + LayerNorm MLP: E to 4E,GELU, 4E to E + y residual (identity) residual (identity) one block, shape (B, T, E) in and out sub-layer 1: tokens talk sub-layer 2: each token computes pre-norm: x + f(LN(x)). Post-norm (2017 paper): LN(x + f(x))

A block maps a sequence of shape (B,T,E)(B, T, E) to the same shape, in two sub-layers:

h=x+MHA⁡(LN⁡1(x))tokens exchange informationy=h+W2 GELU⁡(W1LN⁡2(h)+c1)+c2each token on its own\begin{aligned} h &= x + \operatorname{MHA}(\operatorname{LN}_1(x)) && \text{tokens exchange information} \\ y &= h + W_2\, \operatorname{GELU}(W_1 \operatorname{LN}_2(h) + c_1) + c_2 && \text{each token on its own} \end{aligned}
  • Attention mixes across positions; the MLP mixes across features. The MLP is applied to every position independently with the same weights. Its hidden width is usually 4E4E, and with GELU it holds most of the block's parameters.
  • Residuals make each sub-layer learn a correction to xx rather than a whole new representation, and give gradients an identity path through the whole stack (Residual Connections).
  • Pre-norm vs post-norm. The original 2017 transformer normalised after the addition, LN⁡(x+f(x))\operatorname{LN}(x + f(x)). Almost every model since normalises the input of each sub-layer and leaves the residual stream untouched, because that version trains stably without a careful learning-rate warm-up. The price is that the stream is never normalised, so a pre-norm stack ends with one extra LayerNorm before the output head. LayerNorm and RMSNorm covers the normalisation itself; many recent models swap LayerNorm for RMSNorm and GELU for a gated variant (SwiGLU) without changing the structure.

Parameter count. With biases everywhere, as in PyTorch:

Part Weights Biases and scales
attention: WQ,WK,WV,WOW_Q, W_K, W_V, W_O 4E24E^2 4E4E
MLP: E×4EE \times 4E and 4E×E4E \times E 8E28E^2 4E+E4E + E
two LayerNorms (γ\gamma, β\beta) 4E4E
block 12E212E^2 13E13E

So a block has 12E2+13E12E^2 + 13E parameters, independent of the number of heads and of the sequence length. For E=768E = 768 (GPT-2 small, BERT-base) that is about 7.1 million per block; the compute per token is about twice that many multiply-adds plus the attention scores, which grow with TT (Parameter and FLOP Counting).

Positions

Attention treats its input as a set: permute the tokens and the outputs are permuted the same way, nothing else changes. Word order has to be injected, and the simplest way is to add a position vector ptp_t to the token embedding before the first block. Two classic choices:

  • Sinusoidal (fixed, no parameters). Pair up the dimensions; pair ii is a sine and a cosine of the position at frequency ωi=10000−2i/E\omega_i = 10000^{-2i/E}:
pt,2i=sin⁡(t ωi),pt,2i+1=cos⁡(t ωi),ωi=10000−2i/Ep_{t, 2i} = \sin(t\, \omega_i), \qquad p_{t, 2i+1} = \cos(t\, \omega_i), \qquad \omega_i = 10000^{-2i/E}

Fast pairs change every position, slow pairs over thousands of positions, like the hands of a clock. Because sin⁡asin⁡b+cos⁡acos⁡b=cos⁡(a−b)\sin a \sin b + \cos a \cos b = \cos(a - b), the dot product ps⋅pt=∑icos⁡((s−t) ωi)p_s \cdot p_t = \sum_i \cos((s - t)\, \omega_i) depends only on the distance s−ts - t.

  • Learned (an nn.Embedding(max_len, E) table, or an nn.Parameter of shape (max_len, E), trained with the rest). Simple and works well, used by BERT, GPT-2 and ViT; but it has no row for positions beyond max_len seen in training.

Modern LLMs mostly use rotary embeddings (RoPE), which rotate the query and key vectors by a position-dependent angle inside every attention layer instead of adding anything to the input; the same "depends only on the distance" property then holds for the attention scores themselves. The example checks the properties above and that positions break the permutation symmetry.

python · try it yourself
import numpy as np

def sinusoidal(T, E):
    pos = np.arange(T)[:, None]                       # (T, 1)
    i = np.arange(0, E, 2)[None, :]                   # even dimensions 0, 2, 4, ...
    angle = pos / 10000 ** (i / E)                    # (T, E/2)
    pe = np.zeros((T, E))
    pe[:, 0::2] = np.sin(angle)
    pe[:, 1::2] = np.cos(angle)
    return pe

pe = sinusoidal(64, 16)
print("PE[1, :6]:", np.round(pe[1, :6], 3).tolist())
print("every row has norm sqrt(E/2):", np.allclose(np.linalg.norm(pe, axis=1), np.sqrt(8)))
# similarity depends on the distance only, not on the position itself
print("PE[5].PE[8] =", round(float(pe[5] @ pe[8]), 4), " PE[40].PE[43] =", round(float(pe[40] @ pe[43]), 4))
print("dot with position 10, distances 0..5:", [round(float(pe[10] @ pe[10 + k]), 2) for k in range(6)])

# Without positions, self-attention is permutation equivariant.
def softmax(z):
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

def self_attention(x, Wq, Wk, Wv):
    q, k, v = x @ Wq, x @ Wk, x @ Wv
    return softmax(q @ k.T / np.sqrt(q.shape[1])) @ v

rng = np.random.default_rng(0)
T, E = 6, 16
x = rng.normal(size=(T, E))
Wq, Wk, Wv = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(3))
perm = np.array([3, 0, 5, 1, 4, 2])
out = self_attention(x, Wq, Wk, Wv)
print("no positions: f(x[perm]) == f(x)[perm]:", np.allclose(self_attention(x[perm], Wq, Wk, Wv), out[perm]))
xp = x + pe[:T]
outp = self_attention(xp, Wq, Wk, Wv)
print("with positions:", np.allclose(self_attention(x[perm] + pe[:T], Wq, Wk, Wv), outp[perm]))
PE[1, :6]: [0.841, 0.54, 0.311, 0.95, 0.1, 0.995]
every row has norm sqrt(E/2): True
PE[5].PE[8] = 5.5431  PE[40].PE[43] = 5.5431
dot with position 10, distances 0..5: [8.0, 7.49, 6.37, 5.54, 5.56, 6.14]
no positions: f(x[perm]) == f(x)[perm]: True
with positions: False

Each row has norm E/2=8\sqrt{E/2} = \sqrt{8} because every sine-cosine pair contributes sin⁡2+cos⁡2=1\sin^2 + \cos^2 = 1. The dot product of positions 5 and 8 equals that of 40 and 43 (5.5431): only the distance 3 matters. It falls from 8 at distance 0 but not monotonically (5.54 at distance 3, 5.56 at distance 4), so it is a rough similarity, not a clean distance measure. Without positions, permuting the input permutes the output exactly; with them added, it doesn't.

The block in NumPy

The block below follows the equations line by line: layer norm with the biased variance and ϵ=10−5\epsilon = 10^{-5} (as PyTorch), multi-head attention with biases on all four projections, and the exact GELU xΦ(x)x \Phi(x) written with scipy.special.erf. The optional memory argument turns self-attention into cross-attention: queries from x, keys and values from another sequence. That is all a decoder needs beyond the encoder block.

python · try it yourself
import numpy as np
from scipy.special import erf

def softmax(z):
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

def layer_norm(x, g, b, eps=1e-5):
    mu = x.mean(axis=-1, keepdims=True)
    var = x.var(axis=-1, keepdims=True)              # biased variance, as PyTorch
    return g * (x - mu) / np.sqrt(var + eps) + b

def gelu(x):                                         # exact GELU: x * Phi(x)
    return 0.5 * x * (1 + erf(x / np.sqrt(2)))

def mha(x, p, h, mask=None, memory=None):
    B, T, E = x.shape
    src = x if memory is None else memory            # cross-attention: keys/values from memory
    split = lambda z: z.reshape(B, -1, h, E // h).transpose(0, 2, 1, 3)
    q, k, v = split(x @ p["Wq"] + p["bq"]), split(src @ p["Wk"] + p["bk"]), split(src @ p["Wv"] + p["bv"])
    s = q @ k.transpose(0, 1, 3, 2) / np.sqrt(E // h)
    if mask is not None:
        s = np.where(mask, s, -np.inf)
    o = (softmax(s) @ v).transpose(0, 2, 1, 3).reshape(B, T, E)
    return o @ p["Wo"] + p["bo"]

def block(x, p, h, mask=None):
    x = x + mha(layer_norm(x, p["g1"], p["b1"]), p, h, mask)                         # attention sub-layer
    return x + gelu(layer_norm(x, p["g2"], p["b2"]) @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"]   # MLP sub-layer

def init_block(E, rng, hidden=None):
    hidden = hidden or 4 * E
    n = lambda *s: rng.normal(0, 0.1, s)
    return {"Wq": n(E, E), "Wk": n(E, E), "Wv": n(E, E), "Wo": n(E, E),
            "bq": n(E), "bk": n(E), "bv": n(E), "bo": n(E),
            "g1": 1 + n(E), "b1": n(E), "g2": 1 + n(E), "b2": n(E),
            "W1": n(E, hidden), "c1": n(hidden), "W2": n(hidden, E), "c2": n(E)}

rng = np.random.default_rng(0)
B, T, E, h = 2, 5, 16, 4
p = init_block(E, rng)
x = rng.normal(size=(B, T, E))
y = block(x, p, h)
print("in", x.shape, "-> out", y.shape)
print("y[0, 0, :5]:", np.round(y[0, 0, :5], 4).tolist())
n_params = sum(v.size for v in p.values())
print("parameters:", n_params, " 12E^2 + 13E =", 12 * E * E + 13 * E)

# A causal block: changing the last token cannot change earlier outputs.
causal = np.tril(np.ones((T, T), dtype=bool))
x2 = x.copy(); x2[:, -1] += 5.0
ya, yb = block(x, p, h, causal), block(x2, p, h, causal)
print("causal: first 4 positions unchanged:", np.allclose(ya[:, :4], yb[:, :4]), " last changed:", not np.allclose(ya[:, 4], yb[:, 4]))

# Cross-attention: 3 decoder positions attend to 7 encoder positions.
memory = rng.normal(size=(B, 7, E))
z = rng.normal(size=(B, 3, E))
print("cross-attention output:", mha(z, p, h, memory=memory).shape)
in (2, 5, 16) -> out (2, 5, 16)
y[0, 0, :5]: [-2.5923, 0.2019, 1.3822, 0.4116, 0.5268]
parameters: 3280  12E^2 + 13E = 3280
causal: first 4 positions unchanged: True  last changed: True
cross-attention output: (2, 3, 16)

The parameter count agrees with the formula: 12⋅162+13⋅16=328012 \cdot 16^2 + 13 \cdot 16 = 3280. With a causal mask, perturbing the last token changes only the last output: no information flows backwards in time, which is the property a language model's training relies on. The cross-attention call returns one vector per decoder position (3), each a mixture of the 7 encoder positions.

The same block in PyTorch

nn.TransformerEncoderLayer is this block, but its defaults are not the ones above: it is post-norm unless norm_first=True, uses ReLU unless activation="gelu", has dropout 0.1 (on the attention weights, inside the MLP and on both residual branches), a hidden width of 2048 whatever EE is, and expects (T, B, E) unless batch_first=True. The recorded example (CPU, float64) sets all five, copies the NumPy weights in (nn.Linear stores weights as (out, in), so every matrix is transposed; the attention's in_proj_weight stacks WQW_Q, WKW_K, WVW_V by rows) and compares, with and without a causal mask.

python · try it yourself
import numpy as np
from scipy.special import erf
import torch
from torch import nn

def softmax(z):
    e = np.exp(z - z.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

def layer_norm(x, g, b, eps=1e-5):
    mu = x.mean(axis=-1, keepdims=True)
    var = x.var(axis=-1, keepdims=True)              # biased variance, as PyTorch
    return g * (x - mu) / np.sqrt(var + eps) + b

def gelu(x):                                         # exact GELU: x * Phi(x)
    return 0.5 * x * (1 + erf(x / np.sqrt(2)))

def mha(x, p, h, mask=None, memory=None):
    B, T, E = x.shape
    src = x if memory is None else memory            # cross-attention: keys/values from memory
    split = lambda z: z.reshape(B, -1, h, E // h).transpose(0, 2, 1, 3)
    q, k, v = split(x @ p["Wq"] + p["bq"]), split(src @ p["Wk"] + p["bk"]), split(src @ p["Wv"] + p["bv"])
    s = q @ k.transpose(0, 1, 3, 2) / np.sqrt(E // h)
    if mask is not None:
        s = np.where(mask, s, -np.inf)
    o = (softmax(s) @ v).transpose(0, 2, 1, 3).reshape(B, T, E)
    return o @ p["Wo"] + p["bo"]

def block(x, p, h, mask=None):
    x = x + mha(layer_norm(x, p["g1"], p["b1"]), p, h, mask)                         # attention sub-layer
    return x + gelu(layer_norm(x, p["g2"], p["b2"]) @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"]   # MLP sub-layer

def init_block(E, rng, hidden=None):
    hidden = hidden or 4 * E
    n = lambda *s: rng.normal(0, 0.1, s)
    return {"Wq": n(E, E), "Wk": n(E, E), "Wv": n(E, E), "Wo": n(E, E),
            "bq": n(E), "bk": n(E), "bv": n(E), "bo": n(E),
            "g1": 1 + n(E), "b1": n(E), "g2": 1 + n(E), "b2": n(E),
            "W1": n(E, hidden), "c1": n(hidden), "W2": n(hidden, E), "c2": n(E)}

rng = np.random.default_rng(0)
B, T, E, h = 2, 5, 16, 4
p = init_block(E, rng)
x = rng.normal(size=(B, T, E))

layer = nn.TransformerEncoderLayer(d_model=E, nhead=h, dim_feedforward=4 * E, dropout=0.0,
                                   activation="gelu", batch_first=True, norm_first=True, dtype=torch.float64)
t = lambda a: torch.tensor(a, dtype=torch.float64)
with torch.no_grad():                                 # nn.Linear stores W with shape (out, in): transpose
    layer.self_attn.in_proj_weight.copy_(t(np.concatenate([p["Wq"].T, p["Wk"].T, p["Wv"].T])))
    layer.self_attn.in_proj_bias.copy_(t(np.concatenate([p["bq"], p["bk"], p["bv"]])))
    layer.self_attn.out_proj.weight.copy_(t(p["Wo"].T)); layer.self_attn.out_proj.bias.copy_(t(p["bo"]))
    layer.linear1.weight.copy_(t(p["W1"].T)); layer.linear1.bias.copy_(t(p["c1"]))
    layer.linear2.weight.copy_(t(p["W2"].T)); layer.linear2.bias.copy_(t(p["c2"]))
    layer.norm1.weight.copy_(t(p["g1"])); layer.norm1.bias.copy_(t(p["b1"]))
    layer.norm2.weight.copy_(t(p["g2"])); layer.norm2.bias.copy_(t(p["b2"]))
layer.eval()
with torch.no_grad():
    y_t = layer(t(x)).numpy()
    mask = nn.Transformer.generate_square_subsequent_mask(T, dtype=torch.float64)
    y_tc = layer(t(x), src_mask=mask, is_causal=True).numpy()
causal = np.tril(np.ones((T, T), dtype=bool))
print("encoder layer matches NumPy block:", np.allclose(y_t, block(x, p, h), atol=1e-10))
print("with causal mask:", np.allclose(y_tc, block(x, p, h, causal), atol=1e-10))
print("causal mask row 2:", mask[1].tolist())
print("parameters:", sum(q.numel() for q in layer.parameters()), "(NumPy:", sum(v.size for v in p.values()), ")")

default = nn.TransformerEncoderLayer(d_model=E, nhead=h, batch_first=True)
print("defaults: activation =", default.activation.__name__, " dropout =", default.dropout.p,
      " dim_feedforward =", default.linear1.out_features, " norm_first =", default.norm_first)

E = 512
enc = nn.TransformerEncoderLayer(E, 8, dim_feedforward=4 * E, batch_first=True)
dec = nn.TransformerDecoderLayer(E, 8, dim_feedforward=4 * E, batch_first=True)
count = lambda m: sum(q.numel() for q in m.parameters())
print(f"E = 512 encoder layer: {count(enc):,}  (12E^2 + 13E = {12 * E * E + 13 * E:,})")
print(f"E = 512 decoder layer: {count(dec):,}  (16E^2 + 19E = {16 * E * E + 19 * E:,})")
torch.manual_seed(0)
memory = torch.randn(2, 7, E)
tgt = torch.randn(2, 3, E)
print("decoder output:", tuple(dec(tgt, memory).shape))
encoder layer matches NumPy block: True
with causal mask: True
causal mask row 2: [0.0, 0.0, -inf, -inf, -inf]
parameters: 3280 (NumPy: 3280 )
defaults: activation = relu  dropout = 0.1  dim_feedforward = 2048  norm_first = False
E = 512 encoder layer: 3,152,384  (12E^2 + 13E = 3,152,384)
E = 512 decoder layer: 4,204,032  (16E^2 + 19E = 4,204,032)
decoder output: (2, 3, 512)

The layer and the NumPy block agree to 10−1010^{-10}, with and without the mask, and both have 3280 parameters. generate_square_subsequent_mask builds the float version of the causal mask (0 where allowed, −∞-\infty above the diagonal); passing is_causal=True as well is a hint that lets PyTorch use a faster kernel. The last lines confirm the formulas at the classic size E=512E = 512: 3,152,384 parameters per encoder layer, and 4,204,032 per decoder layer, which adds a cross-attention sub-layer (4E2+4E4E^2 + 4E) and a third LayerNorm (2E2E), giving 16E2+19E16E^2 + 19E.

Encoder, decoder, decoder-only

Stack Blocks contain Mask Used for
Encoder self-attention + MLP padding only: every token sees the whole input understanding a whole input: BERT, ViT, sentence embeddings
Decoder (encoder-decoder) causal self-attention + cross-attention to the encoder output + MLP causal (and padding) sequence to sequence: the original translation model, T5, Whisper
Decoder-only causal self-attention + MLP (an encoder block with a causal mask) causal language models: GPT, Llama; the next lesson trains one

In cross-attention the decoder's states provide the queries and the encoder's output (called the memory) provides keys and values, so the weight matrix has shape Tdec×TencT_{\text{dec}} \times T_{\text{enc}}. A decoder-only model is built with nn.TransformerEncoderLayer plus a causal mask, not with nn.TransformerDecoderLayer, which always expects a memory. Tokenizers, pretraining objectives and large-model fine-tuning belong to NLP, Transformers & LLM Fine-Tuning.

Pitfalls

  • Library defaults are not the modern recipe. Post-norm, ReLU, dropout 0.1 and dim_feedforward=2048 are PyTorch's defaults for backwards compatibility. A model compared with a paper, or with your own NumPy code, must set them explicitly, as above.
  • Dropout makes outputs random in training mode. With the default dropout, two forward passes in model.train() give different results; comparisons and inference need model.eval() (or dropout=0.0).
  • No final LayerNorm after a pre-norm stack. nn.TransformerEncoder(layer, num_layers, norm=nn.LayerNorm(E)) adds it; forgetting it leaves the head reading an unnormalised residual stream whose scale grows with depth.
  • Positions added twice, or not at all. Add them once, to the input embeddings (for RoPE: inside attention, never to the input). A model without them runs fine and simply cannot tell "dog bites man" from "man bites dog".
  • Learned positions beyond max_len. Indexing the table at position max_len raises an index error; feeding longer sequences needs a bigger table (and training on such lengths).
  • The hidden width is not 4E4E by default in nn.TransformerEncoderLayer: pass dim_feedforward=4 * E if you want the standard ratio, otherwise a small model gets a huge MLP.

Practice

  1. How many parameters does a 12-block encoder with E=768E = 768 have, without embeddings? And how many does one extra cross-attention sub-layer add per block?
Answer

Per block 12⋅7682+13⋅768=7,077,888+9,984=7,087,87212 \cdot 768^2 + 13 \cdot 768 = 7{,}077{,}888 + 9{,}984 = 7{,}087{,}872; times 12 is 85,054,46485{,}054{,}464, about 85 million (BERT-base has about 110 million with its embeddings). A cross-attention sub-layer adds 4E2+4E=2,362,3684E^2 + 4E = 2{,}362{,}368 plus a LayerNorm of 2E=15362E = 1536.

  1. In the NumPy block, replace pre-norm by post-norm. Write the two lines of block.
Answer
python
x = layer_norm(x + mha(x, p, h, mask), p["g1"], p["b1"])
return layer_norm(x + gelu(x @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"], p["g2"], p["b2"])

With norm_first=False in PyTorch this matches nn.TransformerEncoderLayer too.

  1. The sinusoidal dot product p10⋅p10+kp_{10} \cdot p_{10+k} was 8.0 for k=0k = 0. Why exactly 8, and what would it be for E=64E = 64?
Answer

At distance 0 every pair contributes cos⁡0=1\cos 0 = 1, and there are E/2E/2 pairs: 8 for E=16E = 16, 32 for E=64E = 64.

  1. You train a learned-position model on sequences of length 128 and want to run it on length 200. What breaks, and what are your options?
Answer

The position table has 128 rows, so positions 128 to 199 have no vector (an index error, or garbage if you pad the table with untrained rows). Options: truncate or slide a window of 128; extend the table (for example by interpolating the learned vectors) and fine-tune on longer sequences; or use a scheme that extrapolates better, such as RoPE or ALiBi, from the start.

Test yourself

In a pre-norm block, what is the first sub-layer's output?

  1. LN⁡(x+MHA⁡(x))\operatorname{LN}(x + \operatorname{MHA}(x))
  2. x+MHA⁡(LN⁡(x))x + \operatorname{MHA}(\operatorname{LN}(x))
  3. MHA⁡(LN⁡(x))\operatorname{MHA}(\operatorname{LN}(x))
  4. LN⁡(MHA⁡(x))\operatorname{LN}(\operatorname{MHA}(x))

How many parameters does a transformer block with E=16E = 16, a 4E4E MLP and biases everywhere have?

  1. 12⋅162=307212 \cdot 16^2 = 3072
  2. 3280
  3. 4096
  4. It depends on the number of heads

Which setting is NOT a default of nn.TransformerEncoderLayer?

  1. dropout=0.1
  2. activation ReLU
  3. norm_first=True
  4. dim_feedforward=2048

What does cross-attention take from the encoder?

  1. The queries
  2. The keys and the values
  3. Only the values
  4. The causal mask

Why does a transformer need positional information?

  1. Without it the softmax overflows
  2. Self-attention is permutation equivariant: reordering the tokens just reorders the outputs
  3. To reduce the number of parameters
  4. Because LayerNorm removes the order