Transformer architecture

In one sentence

A decoder-only transformer embeds tokens, runs them through N identical blocks of attention plus MLP joined by residuals, and outputs next-token logits. It trains on all positions in parallel, which is why it beat RNNs.

Analogy: An assembly line of identical stations: every token rides a conveyor belt (the residual stream), and each station reads the belt, consults the other tokens, and adds a small edit before passing it on.

One block = attention + MLP, each added back onto the residual stream; Llama 3 8B stacks 32 of them.

How it works

  • Attention mixes information from earlier tokens into each token; RoPE encodes position by rotating queries and keys.
  • The per-token MLP expands the vector ~3.5–4× and back, holding two-thirds or more of block parameters.
  • Each sublayer adds its output back into the residual stream, which keeps deep stacks trainable.
  • Prefill runs the whole prompt in one parallel pass; decode then needs one full pass per output token.
  • Each decode pass reads all ~16 GB of Llama 3 8B weights: it is bandwidth-bound, so batching matters.

Check yourself

Answer to mark it learned; your answers aren't scored.

Llama 3 8B in bf16 serves a single user on an H100 (~3.35 TB/s). Decode tops out near ~200 tokens/s while the GPU's compute units sit mostly idle. What is the bottleneck?

Go deeper

Full explanation

A transformer is the neural network behind every modern LLM. Chat models are decoder-only: they predict the next token from the ones before it (Encoder vs decoder models (BERT vs GPT)).

One forward pass:

  1. Embed: each token ID becomes a vector of width d_model (4,096 in Llama 3 8B).
  2. Attention sublayer: each token mixes in information from earlier tokens (Self-attention); position enters via RoPE, which rotates queries and keys.
  3. MLP sublayer: a per-token feed-forward network that expands the vector ~3.5–4×, applies a nonlinearity and projects back. It holds two-thirds or more of each block's parameters.
  4. Unembed: a final norm and the LM head produce logits over the vocabulary; Decoding & sampling (temperature, top-p) picks the next token, which is appended for the next pass.

Steps 2–3 form one block, repeated N times (32 in Llama 3 8B). Each sublayer is wrapped as x = x + f(norm(x)): this residual stream, which every block reads and adds to, keeps deep stacks trainable.

Why it beat RNNs: an RNN processes token t after token t−1, so training is sequential. A transformer with a causal mask predicts every position at once with large matrix multiplies, ideal for GPUs; that made training on trillions of tokens practical. Generation is still one token at a time, hence the KV cache.

Code Count where Llama 3 8B's parameters live
pythonCount where Llama 3 8B's parameters live
# Where do a decoder-only transformer's parameters live?
# Llama 3 8B config (from its published config.json)
d, layers, ffn, vocab = 4096, 32, 14336, 128256
n_heads, n_kv_heads = 32, 8          # GQA: 8 K/V heads shared by 32 query heads
head_dim = d // n_heads              # 128

attn = 2 * d * d + 2 * d * n_kv_heads * head_dim  # Wq, Wo full size; Wk, Wv smaller
mlp = 3 * d * ffn                                 # SwiGLU: gate, up, down projections
per_block = attn + mlp                            # norms are negligible
emb = 2 * vocab * d                               # input embeddings + untied LM head

total = layers * per_block + emb
for name, n in [("attention", layers * attn), ("MLP", layers * mlp), ("embed+head", emb)]:
    print(f"{name:11} {n / 1e9:5.2f}B  {n / total:4.0%}")  # ~1.34B, ~5.64B, ~1.05B
print(f"{'total':11} {total / 1e9:5.2f}B")                 # ~8.03B
print(f"MLP share of each block: {mlp / per_block:.0%}")   # ~81%

# Rules of thumb that fall out of the count
print(f"forward pass ≈ {2 * total / 1e9:.0f} GFLOPs per token")  # ~2 x params
print(f"bf16 weights ≈ {2 * total / 1e9:.0f} GB")                # 2 bytes per param
Real example

You send a 2,000-token prompt to Llama 3 8B and get a 300-token answer. Prefill: all 2,000 positions flow through the 32 blocks in one parallel pass, the same trick that makes training fast; it sets time-to-first-token. Decode: each of the 300 output tokens needs its own pass through all 32 blocks, because each depends on the one before. Every pass reads all ~16 GB of bf16 weights from GPU memory, so on an H100 (~3.35 TB/s) a single stream tops out near ~200 tokens/s. Decode is bandwidth-bound, which is why batching and the KV cache matter.

Trade-offs +3 · −3

+ You gain

  • Trains in parallel across the sequence, so it scales with GPUs and data.
  • Any token reaches any earlier token in one step: no long-range fading like RNNs.
  • One generic block, stacked and widened, covers text, code, images and audio.

− You pay

  • Attention cost grows with the square of sequence length.
  • Generation is sequential and memory-bandwidth-bound: one full forward pass per output token.
  • KV cache memory grows with context length × batch size, capping concurrency.

Use it when

It's the default for language, code and most multimodal models. As an architect, use this mental model to reason about cost, latency, GPU memory, MoE, quantization and fine-tuning choices.

Avoid it when

Small tabular or time-series problems where gradient-boosted trees win, or tight edge budgets where a tiny classifier or a regex is enough. Very long streams may favor state-space or hybrid models.

Numbers to know 5
  • Params ≈ 12 × layers × d_model² for a classic block; GPT-3: 12 × 96 × 12,288² ≈ 174B.
  • Llama 3 8B: 32 layers, d_model 4,096, 32 query / 8 KV heads, MLP width 14,336, vocab 128,256.
  • MLPs hold ~2/3 of each block classically; ~81% in Llama 3 8B (SwiGLU + GQA), ~70% of all params.
  • Compute: ~2 × params FLOPs per token forward; ~6 × params per token to train.
  • Weights memory = params × bytes per param: 8B in bf16 ≈ 16 GB.
Common pitfalls 4
  • Picturing the model writing the whole answer at once: every output token is a separate forward pass.
  • Sizing GPUs from weights alone, ignoring KV cache and activations.
  • Using a decoder-only chat model where an encoder (BERT-style) is cheaper and better: embeddings, classification.
  • Assuming quality scales with parameters alone; data quantity and quality matter as much.
Interview questions 2

Answer out loud first, then reveal.

Why did transformers replace RNNs and LSTMs?Show answer

Mainly training parallelism. An RNN computes token t from the hidden state of token t−1, so a 4k-token sequence is 4k sequential steps. A transformer with a causal mask computes all positions in one pass of large matrix multiplies, which is exactly what GPUs are built for, and that made training on trillions of tokens feasible. Attention also gives every token a direct path to every earlier one, so long-range dependencies don't fade. The price is quadratic attention in sequence length, and inference is still sequential, so decode is memory-bandwidth-bound and needs a KV cache.

Where do a model's parameters live, and why should an architect care?Show answer

Mostly in the MLPs: about two-thirds of each block in the classic design and ~81% in Llama 3 8B, with embeddings and LM head around 13%. That explains several choices. Mixture-of-experts replaces exactly that MLP with many experts and routes each token to a few, so total parameters grow while compute per token doesn't. LoRA works best applied to all linear layers, MLPs included, which was a QLoRA finding. And memory math stays simple: parameters × bytes per weight, so 8B in bf16 is ~16 GB before any KV cache.