Shaf Lab

Transformers

The neural network architecture behind modern language models, built around attention.

A transformer is the neural network architecture behind nearly every modern language model, and many speech and vision models too. It was introduced in 2017 for machine translation and replaced recurrent networks because it processes a whole sequence in parallel instead of one step at a time. Text goes in as tokens, each token becomes a vector, and a stack of identical layers repeatedly refines those vectors until the last layer can predict what comes next.

Each layer has two main parts. Attention lets every position gather information from other positions, so a word can take on meaning from its context. A small feed-forward network then transforms each position on its own. Residual connections and normalization wrap both parts so that deep stacks, often dozens of layers, still train reliably. Almost everything people call model size, such as layer count, hidden width, and number of attention heads, is a setting on this one template.

The design has costs you will meet in practice. Attention compares every token with every other token, so compute grows with the square of the sequence length, which is one reason long context is expensive. Generation is sequential even though training is parallel, so serving a model is mostly a problem of moving weights and cached attention state through memory quickly.

You do not need to implement a transformer to build with one, but knowing its parts explains a lot of everyday behavior: why prompts are counted in tokens, why the start and end of a long prompt get more attention than the middle, why output arrives one token at a time, and why a longer context makes every request slower and pricier.

Next-token prediction

The pretraining task behind language models: predict a probability for every possible next token.

Next-token prediction is the task a language model is pretrained on. Given the tokens so far, the model outputs a probability for every token in its vocabulary, and training adjusts the weights to raise the probability of the token that actually came next in the training text. Repeated over trillions of tokens, this one objective forces the model to pick up grammar, facts, style, and a surprising amount of reasoning, because all of them help predict what comes next.

Generation is the same step in a loop: predict a distribution, choose a token from it, append that token, and predict again. How the token is chosen is a separate decision called decoding. Always taking the most likely token is greedy decoding; sampling with a temperature, or only from the most likely tokens that cover a set share of probability (top-p), adds variety. This is why the same prompt can produce different answers, and why output streams one token at a time.

Assistant models are still next-token predictors at heart. Later training changes which continuations they prefer, but the mechanics of generation do not change, which explains habits like confidently continuing a false premise or drifting when the prompt is ambiguous.

Self-attention

The mechanism that lets each token gather information from the other tokens in the same sequence.

Self-attention lets every token in a sequence look at the other tokens and pull in information from the ones most relevant to it. In "The trophy did not fit in the suitcase because it was too big," attention is how the representation of "it" comes to carry information about "trophy." Every layer of a transformer repeats this, so context builds up layer by layer.

For each token, the model scores its relevance to every other position, turns those scores into weights that sum to one, and takes a weighted blend of the other tokens' content. Because every pair of positions is compared, compute and memory for the score matrix grow with the square of the sequence length. Doubling the prompt roughly quadruples that work, which is a major reason long context is costly and an active area of research into cheaper attention variants.

Query, key, and value

The three vectors each token produces for attention: what it seeks, what it offers, and what it passes on.

Attention gives each token three roles, each produced by multiplying its vector by a learned matrix. The query describes what the token is looking for. The key describes what the token offers to others. The value is the content it hands over if selected. Splitting the roles lets a token search for one kind of information while advertising another.

To update one token, the model compares its query with every key using a dot product, scales the results by the square root of the key size to keep them in a stable range, and applies softmax to turn them into weights. Those weights then blend the value vectors into the token's new representation. Keys and values from earlier tokens can be stored and reused during generation, which is exactly what the KV cache does.

Multi-head attention

Running several smaller attention operations in parallel and combining their results.

Multi-head attention runs several attention operations side by side, each with its own query, key, and value projections on a smaller slice of the vector, and then concatenates their outputs and mixes them with one more projection. A model with a 4,096-wide representation and 32 heads, for example, gives each head 128 dimensions.

Separate heads can specialize. Studies of trained models find heads that track syntax, link pronouns to their referents, attend to nearby positions, or copy repeated patterns, though many heads are hard to interpret. Variants such as grouped-query attention let several query heads share one set of keys and values, which shrinks the KV cache and speeds up generation with little quality loss.

Causal mask

A rule in attention that hides later tokens, so each position can only use what came before it.

A causal mask stops each position in a sequence from attending to positions after it. In practice the attention scores for future positions are set to negative infinity before softmax, so their weights become zero. Each token can draw only on itself and what came before.

The mask is what makes efficient training of a generator possible. A whole training passage can be processed in one parallel pass, with every position learning to predict its next token, without any position peeking at the answer. It also matches how generation works, since future tokens do not exist yet. Models built this way are called decoder-only or causal language models.

Positional encoding

Information added to a transformer so it knows the order of tokens, which attention alone ignores.

Attention by itself treats its input as an unordered set: shuffle the tokens and each one gets the same weights. Positional encoding adds order back. The original transformer added fixed sine and cosine patterns of different frequencies to each token's vector. Later models learned a separate vector for each position, which works well but cannot easily go past the longest position seen in training.

Most current language models use rotary position embedding, or RoPE, which rotates query and key vectors by an angle that depends on position. The dot product between two rotated vectors then depends on how far apart the tokens are rather than where they sit absolutely, which helps models generalize across positions. Other schemes, such as ALiBi, add a penalty that grows with distance. Techniques for extending context length often work by adjusting how these positions are scaled.

Encoder-only, decoder-only, and encoder-decoder

The three transformer layouts: models that understand input, models that generate, and models that do both.

Transformers come in three layouts. Encoder-only models read the whole input at once with no causal mask, so every token sees both sides of its context; they produce representations used for classification, tagging, and embeddings. BERT is the classic text example, and wav2vec 2.0 applies the same idea to speech. Decoder-only models use a causal mask and generate left to right; the GPT and Llama families and most chat models are built this way.

Encoder-decoder models first encode the full input, then a decoder generates output while attending to that encoding through cross-attention. They suit tasks with a clear input and a separate output, such as translation, summarization, and speech recognition; T5 and Whisper are well-known examples. Decoder-only models now dominate general-purpose language work because one simple design scales well and handles any task phrased as text, while encoder-only models remain the workhorses behind embeddings and rerankers.