TExcelTAD
Home › Math for Deep Learning & LLMs › The Transformer Block

The Transformer Block

A transformer is a stack of identical blocks, each made of two sublayers: multi-head self-attention, which mixes information between positions, and a position-wise MLP, which processes each position on its own. Each sublayer is wrapped in normalization and a residual connection. This lesson assembles the pieces of the previous lessons into one working pre-norm decoder block in NumPy.

The equations

For a sequence of hidden vectors X∈Rn×dX \in \mathbb{R}^{n \times d}, a pre-norm block computes

X′=X+MHA⁡(Norm⁡(X))X′′=X′+MLP⁡(Norm⁡(X′)),MLP⁡(x)=W2 ϕ(W1x)\begin{aligned} X' &= X + \operatorname{MHA}(\operatorname{Norm}(X)) \\ X'' &= X' + \operatorname{MLP}(\operatorname{Norm}(X')), \qquad \operatorname{MLP}(\mathbf{x}) = W_2\,\phi(W_1\mathbf{x}) \end{aligned}

with causal multi-head attention, LayerNorm or RMSNorm, and an MLP that expands to 4d4d (GELU) or uses SwiGLU with hidden size about 83d\frac{8}{3}d. The residual connections form a "stream" that every sublayer reads from and adds to.

A full decoder-only language model is: token embedding, LL blocks, a final norm, and an output projection to vocabulary logits.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
n, d, h, d_ff = 6, 32, 4, 128
dh = d // h
p = {k: rng.normal(0, 0.02, s) for k, s in
     [("Wq", (d, d)), ("Wk", (d, d)), ("Wv", (d, d)), ("Wo", (d, d)), ("W1", (d, d_ff)), ("W2", (d_ff, d))]}
g1, g2 = np.ones(d), np.ones(d)

def rmsnorm(x, g): return g * x / np.sqrt(np.mean(x**2, -1, keepdims=True) + 1e-6)
def gelu(x): return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
def attention(x):
    q, k, v = (np.reshape(x @ p[w], (n, h, dh)).transpose(1, 0, 2) for w in ("Wq", "Wk", "Wv"))
    s = q @ k.transpose(0, 2, 1) / np.sqrt(dh) + np.triu(np.full((n, n), -1e9), 1)
    a = np.exp(s - s.max(-1, keepdims=True)); a /= a.sum(-1, keepdims=True)
    return (a @ v).transpose(1, 0, 2).reshape(n, d) @ p["Wo"]
def block(x):
    x = x + attention(rmsnorm(x, g1))
    return x + gelu(rmsnorm(x, g2) @ p["W1"]) @ p["W2"]

X = rng.normal(size=(n, d))
Y = block(X)
print("input", X.shape, "-> output", Y.shape)
print("block parameters:", sum(v.size for v in p.values()) + 2 * d, " (12 d^2 + 2d =", 12 * d * d + 2 * d, ")")
print("small init keeps the block near the identity: relative change", round(float(np.linalg.norm(Y - X) / np.linalg.norm(X)), 4))
input (6, 32) -> output (6, 32)
block parameters: 12352  (12 d^2 + 2d = 12352 )
small init keeps the block near the identity: relative change 0.0181

Who does what

  • Attention is the only place where positions exchange information. It is linear in the values, with data-dependent weights.
  • The MLP acts on each position independently, holds about two thirds of the block's parameters, and is often described as the model's key-value memory of facts.
  • Norms keep each sublayer's input well scaled; residuals keep gradients flowing and let each block make small refinements.

Parameter count per block

Ignoring biases and norm gains, attention has 4d24d^2 parameters and a 4d4d MLP has 2⋅4d2=8d22 \cdot 4d^2 = 8d^2, so a block has about 12d212d^2. A SwiGLU MLP has three matrices of size d×83dd \times \frac{8}{3}d, again 8d28d^2. A model with LL blocks has roughly 12Ld212Ld^2 non-embedding parameters (Counting Parameters and FLOPs).

python · try it yourself
configs = {"GPT-2 small": (12, 768, 50257), "GPT-2 XL": (48, 1600, 50257), "a 7B-class model": (32, 4096, 32000)}
for name, (L, d, V) in configs.items():
    blocks = 12 * L * d * d
    emb = V * d
    print(f"{name:16s}: blocks {blocks / 1e6:8.1f}M  + embedding {emb / 1e6:6.1f}M  = {(blocks + emb) / 1e6:8.1f}M")
GPT-2 small     : blocks     84.9M  + embedding   38.6M  =    123.5M
GPT-2 XL        : blocks   1474.6M  + embedding   80.4M  =   1555.0M
a 7B-class model: blocks   6442.5M  + embedding  131.1M  =   6573.5M

GPT-2 small comes out at about 124M, matching its published size; the 7B-class estimate is a little below 7B because Llama-style MLPs are slightly wider than 83d\frac{8}{3}d and the output matrix is not tied.

Encoders, decoders and both

The block above is a decoder block (causal). Encoder blocks (BERT) drop the mask. The original encoder-decoder transformer adds a third sublayer to each decoder block: cross-attention, whose queries come from the decoder and keys and values from the encoder output. Modern LLMs are decoder-only.

In software

  • nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward, norm_first=True) is a pre-norm block; LLM codebases write their own in about 50 lines, like the one above.
  • Llama-style blocks: RMSNorm, RoPE inside attention, GQA, SwiGLU MLP, no biases.
  • Activation memory per block is several n×dn \times d tensors plus attention weights unless FlashAttention is used.

Go further: Building a Transformer Block writes this block in NumPy and in PyTorch, then the next lesson trains a tiny character transformer.

Exercises

Exercise 1: Parameters per block

How many parameters does one block with d=1024d = 1024 have (attention plus 4d4d MLP, no biases)?

Answer

About 12.6M.

Solution

12⋅10242=12,582,91212 \cdot 1024^2 = 12{,}582{,}912.

Exercise 2: Where do positions interact?

Which sublayer would you change to stop position 3 from using information from position 1?

Answer

The attention (its mask).

Solution

The MLP and the norms act on each position separately; only attention mixes positions, so masking A3,1A_{3,1} cuts the information path (in every layer).

Exercise 3: SwiGLU size (code)

A SwiGLU MLP has Wgate,Wup∈Rd×fW_{\text{gate}}, W_{\text{up}} \in \mathbb{R}^{d \times f} and Wdown∈Rf×dW_{\text{down}} \in \mathbb{R}^{f \times d}. Find ff that matches the 8d28d^2 of a 4d4d GELU MLP for d=4096d = 4096, rounded to a multiple of 256.

Answer

f=10,923f = 10{,}923 exactly, about 10,75210{,}752 or 11,00811{,}008 rounded (Llama uses 11,008).

Solution

3df=8d23df = 8d^2 gives f=83df = \frac{8}{3}d.

python · try it yourself
d = 4096
f = 8 * d / 3
print(round(f), 256 * int(f // 256), 256 * (int(f // 256) + 1))
10923 10752 11008

Test yourself

Which sublayer of a transformer block mixes information across positions?

  1. The MLP
  2. Self-attention
  3. LayerNorm
  4. The residual addition

Roughly how many parameters does one transformer block of width dd have?

  1. d2d^2
  2. 4d24d^2
  3. 12d212d^2
  4. d3d^3

In a pre-norm block, the normalization is applied…

  1. after adding the residual
  2. to the input of each sublayer, leaving the residual path untouched
  3. only at the end of the model
  4. to the gradients