Skip to content
MLG 033 Transformers episode artwork

Feb 9, 2025 42 min

MLG 033 Transformers

from Machine Learning Guide

A transformer is attention plus multilayer perceptrons: each token's query, key and value let it weigh every other token, and dropping recurrence lets training run in parallel, at a cost that grows with the square of the context window. Also covers RNNs and vanishing gradients, multi-head attention, positional encodings, masking and where to learn transformers. Links Notes and resources at ocdevel.com/mlg/33 Join the free MLG group: listen to my other AI shows, ask me questions, and talk with other listeners What is a transformer? A transformer is a neural network built from attention layers and multilayer perceptrons (MLPs), introduced in Attention Is All You Need (Vaswani et al., 2017). It is the architecture behind large language models (LLMs) (MLG 034). It reads every token of its input at once, where a recurrent neural network (RNN) reads one step at a time. Context-free vs context-aware A plain MLP scores each row in isolation: a house from its bedrooms and bathrooms, a freight load from its weight, miles, rate and origin. That is context-free. Attention makes it context-aware, letting each row or token be modified by the others. A dispatcher's loads compete for one truck's capacity and route. In "The blue trophy didn't fit on the shelf because it was too big", "trophy" should take in "blue", and "it" should point to the trophy, not the shelf. A static word2vec embedding (MLG 022) gives a homonym like "close" one vector in every context. RNNs, vanishing gradients and the origin of attention An RNN passes a hidden state from step to step, predicting the next token and updating a running summary of the sequence (MLG 022, MLG 023). It has two separate problems over long sequences. The vanishing-gradient problem is gradients shrinking as they backpropagate through many steps during training. The other is the fixed-size hidden state losing information. LSTM and GRU cells address both. Attention was first added to RNN encoder-decoders for machine translation (Bahdanau et al., 2014), letting each decoder step weigh every encoder state of the source sentence. The remaining limit was speed: an RNN computes step by step, so training can't be spread across a GPU in parallel. Attention Is All You Need dropped the recurrence and kept attention. Context window and quadratic cost A transformer works over a fixed context window: the prompt plus the tokens generated so far. Self-attention compares every token with every other, so its compute and memory grow with the square of the context length. Attention's learned parameters (the query, key and value matrices) don't grow with context length; only a learned position table, as in BERT and GPT-2, does. In exchange, training and reading the prompt run in parallel. Generation stays sequential: the model emits one token, appends it to the context and runs again. Query, key and value Learned weight matrices project each token's embedding into a query, a key and a value vector. Attention(Q, K, V) = softmax(Q·Kᵀ / √d_k) · V d_k = key dimension Query: what a token is looking for, as "trophy" looks for its modifiers. Key: what each token offers to be matched on, as "blue" and "it" do. Value: what each token contributes once matched. Query-key dot products measure the match and are not capped at 1. Scaling by √d_k and a softmax turn them into attention weights that sum to 1 for each token. Each token's output is the weighted sum of the value vectors, which moves "trophy" toward "blue trophy". A weight near 0 leaves out that token's contribution. The weights form a tokens × tokens matrix. Attention heads, multi-head attention and transformer blocks Attention mechanism: the operation above, in general. Attention head: one instance of it, with its own query, key and value weights. Multi-head attention: several heads in parallel, each projecting the full embedding into its own smaller subspace, so each can learn a different relationship. Their outputs are concatenated and projected. Transformer block: multi-head attention followed by an MLP (feed-forward) layer, each wrapped in a residual connection and layer normalization. A transformer stacks many blocks. 3Blue1Brown's chapter How might LLMs store facts shows how MLP layers can hold a fact, drawing on Google DeepMind's Fact Finding study of factual recall. Locating and Editing Factual Associations in GPT (Meng et al., 2022) traces much factual recall to mid-layer MLPs. Self-attention vs cross-attention In self-attention a sequence attends to itself. In cross-attention one sequence attends to another: in an encoder-decoder translator, the tokens of the translation being written attend to the encoder's representation of the source sentence. Positional encodings and causal masking Attention ignores word order, so each token gets position information. The original Transformer added fixed sinusoidal encodings, BERT and GPT-2 learned theirs, and most current LLMs use rotary position embeddings (RoPE), which rotate queries and keys by position. Causal masking stops each token from attending to later tokens. That lets a model train on a whole sentence at once without seeing the token it is predicting. Where to learn transformers 3Blue1Brown's neural networks series, above all Transformers, the tech behind LLMs and Attention in transformers, step-by-step. Most of the teaching is in the animations, so watch rather than listen. The paper, Attention Is All You Need. Jay Alammar's The Illustrated Transformer. Next: MLG 034, on LLMs: scaling laws, mixture of experts, RLHF and chain of thought.

Episode details come from the podcast's RSS feed.

Embed this episode

Ready to play

MLG 033 Transformers

0:00 42:20

No transcript yet.

Requests help us decide what to transcribe next.

Frequently asked questions

How long is this episode of Machine Learning Guide?

This episode is 42 minutes long.

When was this Machine Learning Guide episode published?

This episode was published on February 9, 2025.

Can I download this Machine Learning Guide episode?

Yes. Use the download control on the episode player to save the publisher-provided media file.