Knowledge Sprint SeriesMT24 Learning

Phase 11 · Sprint 35/90 · Transformers & Vector SpacesVaswani · He · Ba · Xiong · Geva

Inside a Transformer

Attention mixes the words. Most of an encoder layer is not attention, and order must be added.

In short. The two sublayers, skip connections and normalisation, where the weights live, and why position must be added.

Sprint 35 of 90 infographic: Inside a Transformer. Attention mixes the words. Most of an encoder layer is not attention, and order must be added. The full text of the image is on this page.
Full resolution2160 × 2700 PNGPhase summary

The part of the image you are reading lights up. Tap a part to jump to its text.

Fig. 1 in words

One layer, four checks · random weights + tokens, seed 35 · same data as code 05

  1. 1 One layer

    • from the bottom: x · 5 × 16 → LayerNorm → 4-head attention → + → LayerNorm → FFN 16 → 64 → 16 → + → out · 5 × 16
    • skip: a dashed line around each sublayer to its +
  2. 2 Where weights live

    • one base encoder layer: 0.33 · 0.67
    • attention 1 050 624 · FFN 2 099 712
    • base model, my tally: embed 18.9 M · 6 enc 18.9 M · 6 dec 25.2 M
    • total 63.1 M · Table 3: 65 M
    • decoder layer: FFN 0.50 · vocabulary about 37 000
    • big: 214.2 M · Table 3: 213 M
  3. 3 Order blindness

    • x: A B C D E · x[p]: D A E B C
    • largest change after the shuffle
    • no mask, no positions: gap 0.00 · order-blind
    • + sinusoidal positions: gap 2.15 · sees order
    • + causal mask: gap 1.33 · sees order
    • two-way attention alone sees a set
  4. 4 Position waves

    • position 0 to 31 down the side · 16 dimensions · pe(32, 16)
    • +1 · -1 · white 0

01 Two Sublayers Layer

  • Multi-head attention mixes information across tokens
  • A position-wise FFN (512 → 2 048 → 512) works on each token alone
  • The base model stacks N = 6 such layers (Vaswani et al. 2017)

Same shape in and out: that is what lets layers stack.

02 Skip and Normalise Stability

  • Residual: out = x + f(x), so a layer learns only a change (He et al. 2016)
  • LayerNorm rescales each token to mean 0, spread 1, then a learned gain and offset (Ba et al. 2016)
  • 2017 normalised after the add; Pre-LN trains without warm-up (Xiong et al. 2020)

My code is Pre-LN; the original paper was Post-LN.

03 Where Weights Live Count

  • Base encoder layer: attention 1 050 624, FFN 2 099 712, share 0.67; decoder layer 0.50
  • Geva et al. (2021): FFN layers “constitute two-thirds” of the weights and act like key–value memories
  • My total 63.1 M against 65 M in Table 3

The title names the novelty, not the bulk.

04 Order Is Added Position

  • Two-way attention with no positions is order-blind: shuffle gap 0.00
  • Sinusoidal codes break the symmetry (2.15); so does a causal mask (1.33)
  • Causal models without position codes still learn position (Haviv et al. 2022)

2017: “no recurrence and no convolution”, so position is injected.

05 Try It Yourself PYTHON 3.13.16

sprint35_inside_a_transformer.py

import numpy as np
from scipy.special import softmax
rng = np.random.default_rng(35)
n, d, h, dff = 5, 16, 4, 64  # tokens, width, heads, FFN
P = lambda a, b: rng.normal(0, a ** -0.5, (a, b))
Wq, Wk, Wv, Wo = (P(d, d) for _ in range(4))
W1, W2 = P(d, dff), P(dff, d)
def norm(x):  # LayerNorm (gain 1, offset 0)
    m = x.mean(-1, keepdims=True)
    return (x - m) / x.std(-1, keepdims=True)
def mha(x, causal):  # h heads, each of width d / h
    q, k, v = (np.stack(np.split(x @ W, h, 1))
               for W in (Wq, Wk, Wv))
    S = q @ k.transpose(0, 2, 1) / np.sqrt(d // h)
    if causal:  # token i sees tokens 1..i only
        S = np.where(np.tri(len(x)) > 0, S, -np.inf)
    A = softmax(S, axis=-1) @ v
    return np.concatenate(A, 1) @ Wo
def block(x, causal=False):  # pre-LN residual layer
    x = x + mha(norm(x), causal)
    return x + np.maximum(0, norm(x) @ W1) @ W2  # FFN
def pe(n, d):  # sinusoidal positions (Vaswani et al.)
    f = 1e4 ** (np.arange(0, d, 2) / d)  # wavelengths
    a = np.arange(n)[:, None] / f
    s, c = np.sin(a), np.cos(a)  # even, odd columns
    return np.dstack([s, c]).reshape(n, d)
x, p = rng.normal(size=(n, d)), [3, 0, 4, 1, 2]
print("in", x.shape, "-> out", block(x).shape)
gap = lambda a, b: np.abs(a - b).max()  # largest change
xe, xs = x + pe(n, d), x[p] + pe(n, d)
g0 = gap(block(x)[p], block(x[p]))  # no mask, no pos.
g1 = gap(block(xe)[p], block(xs))  # with positions
g2 = gap(block(x, True)[p], block(x[p], True))  # causal
print(f"shuffle gap: plain {g0:.2f} | positions {g1:.2f}"
      f" | causal {g2:.2f}")
y = x.copy(); y[-1] *= -1  # change the last token only
for c in (False, True):
    k = gap(block(x, c)[:-1], block(y, c)[:-1])
    tag = "causal " if c else "two-way"
    print(tag, f"| rows 1-4 change {k:.2f}")
D, F, N, voc = 512, 2048, 6, 37000  # base model, Table 3
att = 4 * D * D + 4 * D  # Q, K, V, O matrices + offsets
ffn = 2 * D * F + F + D  # two dense layers
enc, dec = att + ffn + 4 * D, 2 * att + ffn + 6 * D
print("layer: attention", att, "FFN", ffn,
      f"-> FFN share {ffn / enc:.2f}")
tot = N * (enc + dec) + voc * D  # one shared embedding
print(f"base model {tot / 1e6:.1f} M (Table 3: 65 M)")

Output, as printed on the image

Output printed on the image:
in (5, 16) -> out (5, 16)
shuffle gap: plain 0.00 | positions 2.15 | causal 1.33
two-way | rows 1-4 change 1.79
causal  | rows 1-4 change 0.00
layer: attention 1050624 FFN 2099712 -> FFN share 0.67
base model 63.1 M (Table 3: 65 M)

Run it. sprint35_inside_a_transformer.py · versions, data and steps

Check: 2 099 712 ÷ 3 152 384 = 0.666 · 6 × 7 356 416 + 18 944 000 = 63 082 496 · numpy 2.5.3 · scipy 1.18.1

06 General Notes Practice

  • Causal mask: flip token 5 and rows 1–4 change by 0.00; two-way rows change by 1.79
  • Encoder–decoder for translation, decoder-only for text generation: same layer, different mask
  • Attention cost grows with n²; the FFN grows with n

Next phase: The Complexity Lens.

07 Mini Project Hands-on

  • Stack 6 blocks with and without the skips; compare output norms
  • Move LayerNorm after the add (Post-LN) and repeat
  • Recount the big model (d_model 1 024 and d_ff 4 096)

Check: my tally gives 214.2 M; Table 3 lists 213 M.

R Trusted Sources

  1. Vaswani et al. (2017) Attention Is All You Need, NeurIPS 30
  2. He, Zhang, Ren & Sun (2016) CVPR, 770–778
  3. Ba, Kiros & Hinton (2016) arXiv 1607.06450
  4. Xiong et al. (2020) ICML, PMLR 119, 10524–10533
  5. Geva, Schuster, Berant & Levy (2021) Transformer Feed-Forward Layers Are Key-Value Memories, EMNLP, 5484–5495
  6. Haviv et al. (2022) Findings of EMNLP, 1382–1390

Cite this phase

Tahri, M. (2026). MT24 Learning — Knowledge Sprint Series, Phase 11: Transformers & Vector Spaces (Version 1.0) [Educational resource]. Zenodo. https://doi.org/10.5281/zenodo.23500512

Version DOI 10.5281/zenodo.23500512 · all versions 10.5281/zenodo.23500511 · first published 12 October 2026