Pidoku

The Transformer

Module 10 Lesson 10.i 2h Difficulty 3/5

Prerequisites 10.d, 10.e, 10.f, 10.g, 10.h


Before you start: three words#

WordPlain meaning
Block (or layer)One repeated unit of the model: an attention part and a feed-forward part, each wrapped in a norm and a residual add. A model has L of them (32 for an 8B model, 61–126 for the largest).
Decoder-onlyA transformer that reads tokens left to right and predicts the next one — the design of every current chat model.
LogitsThe raw score the model gives each vocabulary token for “what comes next”; softmax turns them into probabilities (10.g).

1. What is it?#

A transformer is attention (10.h) and a feed-forward network (10.d), stacked with residual connections and normalisation, repeated L times:

                    ┌──────────────────────────┐
   tokens → embed → │  × L transformer blocks  │ → norm → lm_head → logits
                    └──────────────────────────┘

   One block:
        x ──┬─► RMSNorm ─► Attention ─┐
            └───────────────(+)◄──────┘
            │
            ├─► RMSNorm ─► FFN ───────┐
            └───────────────(+)◄──────┘

That is the complete architecture of GPT, Llama, Mistral, Qwen, DeepSeek, Gemma and essentially every production language model. The differences between them are small and can be listed in one table (section 5).


2. Why does it exist?#

It was the first architecture that is at the same time:

  • Expressive — attention lets any token influence any other.
  • Parallel — all positions are computed at once during training and prefill.
  • Scalable — quality improves predictably as parameters and data grow.

Recurrent networks were partly expressive, not parallel, and scaled poorly. Convolutional networks were parallel but needed many layers to connect distant tokens. The transformer had all three, and the field converged on it within about three years of 2017.


3. Simple analogy#

A committee that meets many times.

Each meeting has two phases:

  1. Discussion (attention): every member looks at what every other member currently thinks and updates according to who is relevant to them.
  2. Private reflection (feed-forward): each member thinks over what they heard, alone.

After each phase, members add their update to their previous position instead of replacing it (the residual connection) and calibrate their volume so nobody becomes disproportionately loud (normalisation). Repeat 32–120 times; the final positions are the answer.

The “residual stream” view is more than an analogy: it is how interpretability researchers think about transformers. Each layer reads from the stream, computes something, and writes it back.


4. Tiny example#

A complete, runnable decoder-only transformer — embedding, RMSNorm, RoPE, grouped-query attention with a causal mask, SwiGLU feed-forward, residuals and the output head — using only the standard library:

Go
// transformer.go — a complete decoder-only transformer forward pass, standard library only.
package main

import (
	"fmt"
	"math"
	"math/rand"
)

// Mat is a weight matrix of shape (Out, In), stored row by row.
type Mat struct {
	Out, In int
	W       []float32
}

// Apply computes y = W·x for one vector.
func (m Mat) Apply(x []float32) []float32 {
	y := make([]float32, m.Out)
	for i := range y {
		row := m.W[i*m.In : (i+1)*m.In]
		var s float32
		for j, w := range row {
			s += w * x[j]
		}
		y[i] = s
	}
	return y
}

type Layer struct {
	H, HKV, D                       int // query heads, key/value heads, head dimension
	AttnNorm, FFNNorm               []float32
	Wq, Wk, Wv, Wo, Wgate, Wup, Wdn Mat
}

type Model struct {
	Embed     [][]float32 // (V, d)
	Layers    []Layer
	FinalNorm []float32
	LMHead    Mat // (V, d)
}

func rmsnorm(x, weight []float32) []float32 {
	var ss float32
	for _, v := range x {
		ss += v * v
	}
	inv := float32(1 / math.Sqrt(float64(ss)/float64(len(x))+1e-6))
	y := make([]float32, len(x))
	for i, v := range x {
		y[i] = v * inv * weight[i]
	}
	return y
}

// rope rotates each pair of dimensions of one head's vector by an angle that depends on position.
func rope(x []float32, pos int) {
	D := len(x)
	for i := 0; i < D; i += 2 {
		angle := float64(pos) / math.Pow(10000, float64(i)/float64(D))
		sin, cos := math.Sincos(angle)
		a, b := x[i], x[i+1]
		x[i] = a*float32(cos) - b*float32(sin)
		x[i+1] = a*float32(sin) + b*float32(cos)
	}
}

func silu(x float32) float32 { return x / (1 + float32(math.Exp(float64(-x)))) }

// block runs one transformer layer over a sequence x of shape (S, d).
func block(x [][]float32, p *Layer) [][]float32 {
	S, d := len(x), len(x[0])
	h, hkv, D := p.H, p.HKV, p.D

	// ---- attention ----
	q, k, v := make([][]float32, S), make([][]float32, S), make([][]float32, S)
	for s := range x {
		xn := rmsnorm(x[s], p.AttnNorm)
		q[s], k[s], v[s] = p.Wq.Apply(xn), p.Wk.Apply(xn), p.Wv.Apply(xn) // (h·D), (hkv·D), (hkv·D)
		for i := 0; i < h; i++ {
			rope(q[s][i*D:(i+1)*D], s)
		}
		for i := 0; i < hkv; i++ {
			rope(k[s][i*D:(i+1)*D], s)
		}
	}
	scale := float32(1 / math.Sqrt(float64(D)))
	for s := 0; s < S; s++ {
		out := make([]float32, d)
		for head := 0; head < h; head++ {
			kv := head / (h / hkv) // GQA: several query heads share one key/value head
			qs := q[s][head*D : (head+1)*D]

			// scores against every position t <= s (the causal mask: the future is never read)
			att := make([]float32, s+1)
			maxScore := float32(math.Inf(-1))
			for t := 0; t <= s; t++ {
				kt := k[t][kv*D : (kv+1)*D]
				var dot float32
				for i := range qs {
					dot += qs[i] * kt[i]
				}
				att[t] = dot * scale
				maxScore = max(maxScore, att[t])
			}
			var sum float32
			for t := range att { // softmax, stable form
				att[t] = float32(math.Exp(float64(att[t] - maxScore)))
				sum += att[t]
			}
			for t := range att { // weighted sum of the values
				vt, w := v[t][kv*D:(kv+1)*D], att[t]/sum
				for i := range vt {
					out[head*D+i] += w * vt[i]
				}
			}
		}
		o := p.Wo.Apply(out)
		y := make([]float32, d)
		for i := range y {
			y[i] = x[s][i] + o[i] // residual
		}
		x[s] = y
	}

	// ---- feed-forward ----
	for s := range x {
		xn := rmsnorm(x[s], p.FFNNorm)
		gate, up := p.Wgate.Apply(xn), p.Wup.Apply(xn)
		for i := range gate {
			gate[i] = silu(gate[i]) * up[i]
		}
		dn := p.Wdn.Apply(gate)
		for i := range dn {
			x[s][i] += dn[i] // residual
		}
	}
	return x
}

// forward returns the logits for every position: shape (S, V).
func forward(ids []int, m *Model) [][]float32 {
	x := make([][]float32, len(ids))
	for s, id := range ids {
		x[s] = append([]float32{}, m.Embed[id]...) // (S, d)
	}
	for i := range m.Layers {
		x = block(x, &m.Layers[i])
	}
	logits := make([][]float32, len(ids))
	for s := range x {
		logits[s] = m.LMHead.Apply(rmsnorm(x[s], m.FinalNorm)) // (V,)
	}
	return logits
}

// ---- random weights so the program runs on its own ----

func randMat(out, in int) Mat {
	m := Mat{out, in, make([]float32, out*in)}
	for i := range m.W {
		m.W[i] = float32(rand.NormFloat64()) * 0.05
	}
	return m
}

func ones(n int) []float32 {
	v := make([]float32, n)
	for i := range v {
		v[i] = 1
	}
	return v
}

func main() {
	const V, d, h, hkv, D, ff, L = 100, 64, 8, 2, 8, 128, 2
	m := &Model{FinalNorm: ones(d), LMHead: randMat(V, d)}
	for i := 0; i < V; i++ {
		m.Embed = append(m.Embed, randMat(1, d).W)
	}
	for i := 0; i < L; i++ {
		m.Layers = append(m.Layers, Layer{h, hkv, D, ones(d), ones(d),
			randMat(h*D, d), randMat(hkv*D, d), randMat(hkv*D, d), randMat(d, h*D),
			randMat(ff, d), randMat(ff, d), randMat(d, ff)})
	}
	logits := forward([]int{5, 17, 42, 8}, m)
	fmt.Println("logits shape:", len(logits), "x", len(logits[0])) // 4 x 100
}

That is a Llama-style block. Everything else is stacking, the embedding and the final head. Project 04 turns this into a working inference engine.

Read the program in this order: block first (one layer: the attention half, then the feed-forward half, each with its residual add), then forward (embed → layers → norm → head), then main, which builds a tiny random model with 8 query heads sharing 2 KV heads.


5. Technical explanation#

The whole model#

Go
// The whole model is this loop (from the program above):
func forward(ids []int, m *Model) [][]float32 {
	x := embed(ids, m)                  // (S, d)   one table lookup per token
	for i := range m.Layers {
		x = block(x, &m.Layers[i])      // (S, d)   same shape in, same shape out
	}
	return lmHead(finalNorm(x, m), m)   // (S, V)   one score per vocabulary entry
}

Eight lines. Every language model you have used is this, with particular weights and a few architectural choices.

Pre-norm versus post-norm#

Post-norm (2017 original):   x = Norm(x + Sublayer(x))
Pre-norm (nearly all since): x = x + Sublayer(Norm(x))

Pre-norm won because it trains stably at depth: the residual path stays a clean identity, so the signal flows through 80+ layers without normalisation interfering. (A few models, such as Gemma 2 and 3 and OLMo 2, add a second norm after each sublayer as well.)

Inference consequence: with pre-norm the residual stream itself is never normalised, so its values grow through the network and late layers can hold large activations. That matters for FP16’s limited range (10.k) and for activation quantization (13.d).

What differs between models#

ChoiceOptionsInference impact
NormalisationLayerNorm / RMSNorm (± QK-norm)minor: kernel cost, stability
Norm positionpre / post / bothactivation sizes
Position encodinglearned / sinusoidal / RoPE (+ scaling) / ALiBi / none in some layersRoPE limits prefix reuse; scaling sets usable context
Attention typeMHA / GQA / MQA / MLAmajor: KV-cache size (12.g)
Attention spanfull / sliding window / interleaved / sparse / linear (hybrid)major: how fast the KV cache grows
Attention extrassinks, logit soft-cappingkernel support needed
FFN activationGELU / SiLU / gatedminor
FFN typedense / MoE (with shared experts)major: active vs total parameters (14.g)
Extra headsmulti-token prediction (MTP)free draft model for speculative decoding (13.o)
Weight tyingyes / nomemory
Biasespresent / absentminor

The three bold rows decide your serving economics. When someone says “we’re switching to model X”, ask about those first.

Limiting attention span#

Mistral 7B popularised sliding-window attention: each layer attends only to the last W tokens.

Full attention:      token 10,000 attends to tokens 0..10,000       KV cache grows forever
Sliding window (W):  token 10,000 attends to tokens 5,905..10,000   KV cache CAPPED at W = 4,096

The serving benefit is enormous: that layer’s KV memory stays bounded however long the context. The cost is that distant information can only arrive indirectly, through a chain of layers.

Current models usually interleave layer types so most of the cache is bounded while a few layers keep a global view. Gemma 3 uses five sliding-window layers (window 1,024) for every global one; gpt-oss alternates sliding-window and full layers. Hybrid models go further and replace most attention layers with linear-attention layers that keep a fixed-size state (24.b). For an engine, each of these means managing several kinds of cache in one model (17.i).

Counting everything#

Parameters     ≈ L · (2·d² + 2·d·d_kv + 3·d·d_ff) + V·d (+ V·d if untied)     dense, GQA
FLOPs/token    ≈ 2 · (active parameters) + 4 · L · S · d                       S = context so far
KV bytes/token ≈ 2 · L · h_kv · d_head · bytes per number                       standard attention

Here d_kv = h_kv · d_head. Apply the three formulas to any config.json and you know the model’s serving profile before downloading it. Practise until it is automatic. For MoE models use the active parameters for FLOPs and the total for memory; for MLA and hybrid models the KV formula changes (12.g, 17.i).


6. Under the hood#

One token through Llama 3.1 8B during decode, with 2,000 tokens already in the cache (16-bit weights and KV; FLOPs and bytes per layer):

1.  input_ids = [15496]                                   1 token
2.  embedding lookup → x (1, 4096)                        8 KB read from a ~1 GB table
3.  For each of the 32 layers:
      a. RMSNorm                         read/write 8 KB
      b. q_proj  (1,4096)@(4096,4096)    33.6 MFLOP,  33.6 MB of weights read
      c. k_proj  (1,4096)@(4096,1024)     8.4 MFLOP,   8.4 MB
      d. v_proj                           8.4 MFLOP,   8.4 MB
      e. RoPE on q and k                 negligible
      f. append the new k and v          4 KB written to the cache
      g. attention over 2,001 positions  32.8 MFLOP,   8.2 MB of KV read
      h. o_proj                          33.6 MFLOP,  33.6 MB
      i. residual add
      j. RMSNorm
      k. gate, up, down                  352 MFLOP,  352 MB of weights read
      l. residual add
4.  Final RMSNorm
5.  lm_head (1,4096)@(4096,128256)       1.05 GFLOP,  1.05 GB of weights read
6.  softmax over 128,256 logits, sample one token
──────────────────────────────────────────────────────────────
Total: ~16 GFLOPs,  ~15.3 GB read (15.0 GB weights + 0.26 GB KV)
On an H100 (989 TFLOP/s, 3.35 TB/s):
   compute 0.016 ms, memory 4.6 ms  →  MEMORY-BOUND by about 280x

That trace is Module 2 made concrete. Notice where the bytes are: 15 GB of weights and a quarter of a gigabyte of KV. At batch 1 with 2k tokens of context, weights dominate completely. Batch 64 users together and the weights are read once for all of them; give each user 32k tokens of context and the KV reads overtake the weights. That shift is what Module 12 is about.


7. Performance implications#

  • The feed-forward blocks dominate FLOPs and weight bytes (about 65–75% in a dense model). Quantize them first; make them MoE if you are designing the model.
  • Attention dominates at long context, through KV reads.
  • The LM head is about 7% of decode cost and produces a large tensor.
  • Norms and residual adds are about 1% of FLOPs but around 10% of time when unfused.
  • The layer count sets the kernel-launch count: 80 layers × ~10 kernels = 800 launches per token. At ~5 µs each that is 4 ms of CPU overhead per token. CUDA graphs remove it (5.f, 13.k).

8. Production implications#

  • Read the config before deploying. config.json gives num_hidden_layers, hidden_size, num_attention_heads, num_key_value_heads, head_dim, intermediate_size, vocab_size, max_position_embeddings, rope_theta, rope_scaling, sliding_window and, for MoE, num_experts and num_experts_per_tok. Everything in section 5 follows from them.
  • New architectures break kernels. A new attention variant may not have a fused kernel in your engine yet and may silently fall back to a slow path. Engines publish day-0 support for major model releases for exactly this reason.
  • Sliding windows change your capacity model completely: bounded KV means much higher concurrency.
  • Mixed layer types complicate the KV manager: different layers need different cache sizes (17.i).

9. Common mistakes#

Assuming all transformers are alike. GQA versus MHA is an 8x difference in the main capacity constraint.

Ignoring rope_theta and rope_scaling. Long-context models change them; the wrong values degrade output at long positions with no error message.

Forgetting sliding_window when computing KV memory: you over-provision by 10x, or under-provision if you assume a window that is not there.

Using parameter count as a proxy for serving cost. An MoE with 400B total and 40B active parameters computes like a 40B model and needs memory like a 400B one.

Not checking whether your engine has an optimised kernel for the architecture.


10. Hands-on exercise#

A. Make it real. Extend the program in section 4 to load the weights of a small real model (for example a 0.5–1B open model in safetensors format) and check that your logits match Hugging Face Transformers’ to within 1e-3. This is Project 04, and it is the most valuable exercise in this material.

B. Config archaeology. Download config.json for five open models, including one MoE and one with sliding-window layers. For each compute the parameters, FLOPs per token, KV bytes per token, and the memory for weights plus KV at 8k context and batch 32. Which is cheapest to serve? Is it the smallest?

C. Trace the bytes. Redo the section 6 trace for a model and batch size of your choice and compare the total with a measured decode step.

D. Sliding window. Compute the KV memory of a 32k-token request with and without a 4,096-token window on every layer, then with Gemma 3’s 5:1 pattern. What happens to the number of users that fit?

E. Ablate. In your implementation from A, remove the causal mask, then RoPE, then the residual connections, one at a time. Generate text with each and describe what breaks and why.


11. Interview questions#

  1. Draw a transformer block and label every operation.
  2. What are pre-norm and post-norm, and why did pre-norm win?
  3. List five choices that differ between current LLMs, ranked by inference impact.
  4. What is sliding-window attention, and what does interleaving it with full layers do to your capacity model?
  5. Given a config.json, compute the parameters, FLOPs per token and KV bytes per token.
  6. Why are the feed-forward blocks the first target for quantization?
  7. How many kernel launches per token does an 80-layer model need, and why does that matter?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in