Transformers process every word at once with self-attention
Why did transformers change AI?
In 2017, a team at Google Brain published a paper titled Attention Is All You Need (Vaswani et al., 2017) that quietly launched one of the most consequential shifts in computing history. The paper introduced the transformer, a new neural network architecture that, within a few years, would power ChatGPT, BERT, GPT-4, Gemini, LLaMA, and most of the language models you interact with today.
Before transformers, the dominant approach to processing language was the recurrent neural network (RNN) and its gated cousin, the LSTM. These models read a sentence one word at a time, left to right, passing information forward step by step. The result was slow training, poor handling of long-range dependencies (a word at the start of a 500-word paragraph could barely influence a word at the end), and a ceiling on what sequence models could achieve.
Transformers swept all of that away. The single insight was almost embarrassingly simple: instead of processing tokens in order, let every token in a sequence look at every other token simultaneously, and learn which tokens to pay attention to. This is the self-attention mechanism, and it is the heart of every transformer.
This article walks through that mechanism in three short sections. We will start with the high-level idea and why it matters, then unpack the core concept of self-attention step by step, and close with the key takeaways and what to study next. By the end, you should be able to read transformer code and follow transformer papers with confidence.
What is self-attention in a transformer?
Imagine reading the sentence "The dog chased the cat because it was scared." To understand what it refers to, you have to look back at the noun it could plausibly mean — the dog or the cat. A human does this effortlessly, but a sequence model has to learn the same trick. Self-attention is the mechanism that lets the model do exactly that: for every word in a sentence, it computes a weighted score against every other word, then uses those scores to build a context-aware representation.
Concretely, self-attention works with three learned projections of each input token's embedding, called the query (Q), key (K), and value (V). The names come from information retrieval: think of a search engine. The query is what you are looking for, the key is the label on a document, and the value is the document itself.
The math is straightforward:
- Project. Each input token is multiplied by three learned weight matrices to produce its Q, K, and V vectors.
- Score. For a token i, compute its dot product with the K vector of every other token: this gives a raw relevance score. Then divide by the square root of the embedding dimension (a trick called scaled dot-product attention that keeps gradients stable) and apply a softmax to turn the scores into probabilities that sum to 1.
- Aggregate. Multiply each token's V vector by its attention weight and sum the results. The output is a new representation of token i that has been contextualised by every other token in the sequence.
In vector form, the operation for a single head is:
In practice, transformers don't just run one attention head. They run many in parallel — typically 8, 16, 32, or more — each with its own Q/K/V weight matrices. This is multi-head attention, and the reason is elegant: a single head tends to specialise in one kind of relationship (for example, subject-verb agreement), while different heads can simultaneously learn subject-object links, long-range coreferences, syntactic patterns, and so on. Their outputs are concatenated and projected back to the model dimension, giving the next layer a rich, multi-perspective view of the input.
A few more pieces complete the picture. Because self-attention is permutation-equivariant (it treats input as a set, not a sequence), the model needs positional encodings — vectors added to each token embedding that encode its position in the sequence. The original 2017 paper used fixed sine-and-cosine encodings; modern models often use learned or rotary (RoPE) encodings. Around the attention block, you also find residual connections (the "add" in "add and norm") and layer normalisation, both of which make very deep networks trainable.
Stacking N such blocks — each containing multi-head attention followed by a position-wise feed-forward network, with residuals and normalisation throughout — gives you a full transformer. The original encoder-decoder design is used for tasks like translation, while decoder-only variants (used by GPT-style models) drop the encoder and train the model to predict the next token given everything before it. That simple training objective, scaled up with enough data and compute, is what produces the surprisingly capable systems we see today.
Key Takeaways and What to Learn Next
The transformer is, at its core, a beautifully simple idea: let every token in a sequence look at every other token, and learn how much to look at each one. Everything else — the Q/K/V projections, the multi-head structure, the positional encodings, the residual connections, the deep stacking — is engineering that makes that idea work at scale.
Three things are worth carrying away from this article:
- Attention is the core primitive. Once you understand self-attention, you understand 80% of what makes a transformer tick. The rest of the architecture is there to stabilise, regularise, and scale that one operation.
- Parallelism was the unlock. Unlike RNNs, attention can be computed in parallel across all positions. This is what made it possible to train models on hundreds of billions of tokens — and what made the modern LLM era feasible.
- The same idea generalises. Transformers now dominate not just language but vision (ViT), audio (Whisper), protein folding (AlphaFold), code generation, and robotics. Anywhere data can be tokenised, attention seems to help.
If you want to go deeper, a good next step is to read the original Attention Is All You Need paper (Vaswani et al., 2017) — it is only eight pages and remarkably readable. From there, hands-on implementations like Andrej Karpathy's nanoGPT or the Hugging Face Transformers course let you build and train a small transformer from scratch. Finally, studying scaling laws (Kaplan et al., 2020) explains why bigger transformers keep getting better, which is the deeper story behind the headline-grabbing models you read about every week.
Related stories
- Deep Learning and Neural Architecture
- Hugging Face's 2026 releases are mostly open tools, no flagship model
- Hippocampal neurons' word weights correlate with LLM attention
- Anthropic says Claude Opus 4.7 scores 70% on CursorBench
- Moonshot AI Unveils Kimi K2.5: Open-Source Model with Agent Swarm and Visual Coding
- Moonshot AI releases Kimi K2.5, an open model with agent swarms
More from Teach the Bot
- An AI-written paper clears an ICLR workshop's bar, authors say
- Google says TurboQuant cuts a language model's cache to 3 bits
- NVIDIA releases Nemotron 3 Super, an open 120B-parameter model
- Z.ai releases GLM-5, an open 744-billion-parameter model
- Alibaba releases Qwen3.5, an open 397B model for text and images