Shaf Lab

Transformers

Transformers are the architecture behind almost every language model you will use. The training task is simple: given the tokens so far, assign a probability to every possible next token, pick one, append it, and repeat. That loop is all generation is. The interesting part is how the model decides.

Self-attention lets every token look at every other token and pull in what matters. A pronoun can absorb context from the noun it refers to. Each token plays three roles: a query for what it is looking for, a key for what it offers, and a value for the content it will hand over. Comparing queries to keys produces weights, and those weights blend the values into a new representation. Running several of these operations side by side, each on a smaller slice of the vector, is multi-head attention. Different heads tend to pick up different relationships, such as grammar, reference, or nearness in the sentence.

Attention by itself ignores word order, so position has to be added. Fixed wave patterns, learned vectors, and rotation-based schemes such as RoPE are all ways to do that. For models that generate left to right, a causal mask hides future tokens so a position can only use what came before it. That is what makes a model decoder-style, and it is why a generating model is not allowed to peek at the answer during training.

The same blocks can be wired three ways. Encoder-only models read the whole input at once and label each position, as BERT does. Decoder-only models generate left to right, as GPT and Llama do. Encoder-decoder models read an input first and then generate from it, as T5 and Whisper do. When you pick a model, you are picking one of these layouts and the jobs it is good at.