What Is Attention in LLMs? Self-Attention Explained Simply
By LatestLLM Editorial · Published · Facts verified · 9 min read
Also called: self-attention, attention mechanism, scaled dot-product attention, multi-head attention, QKV
Before this: Embedding, Dimension
In one line
Attention is the step where each token looks back at the earlier tokens, scores how relevant each one is, and blends in information from the most relevant.
Attention, simply and technically
In plain English
When you read "The trophy didn't fit in the suitcase because it was too big", you know "it" means the trophy. A language model has to work that out too. Attention is the part of the model that lets each word look back over the whole text so far and decide which earlier words are important for understanding it.
For every token, attention gives every earlier token a relevance score, turns the scores into percentages that add up to 100, and mixes in information from the earlier tokens according to those percentages. A model does this many times in parallel and at every layer, each time looking for different kinds of connection: grammar, meaning, names, numbers, or the shape of the conversation.
Think of it like this: Attention works like a student with a highlighter going back over their notes before answering a question. For each new question they skim everything written so far, highlight the few lines that matter most, and base the answer on those. Unlike the student, the model highlights in percentages rather than yes or no, and runs dozens of highlighters at once, each looking for something different.
Everyday example: Working out what "it" refers to
The model is reading the sentence below and has reached the word "it".
Input:
The trophy didn't fit in the suitcase because it was too big.
Output:
Strong attention from "it" to "trophy"; weaker attention to "suitcase"
What it shows: Because "too big" describes something that does not fit, the most useful earlier word for understanding "it" is "trophy". Change the ending to "too small" and a well-trained model shifts its attention to "suitcase".
Technically
Scaled dot-product attention computes softmax(Q K^T / sqrt(d_k)) V. Each token's vector is projected to a query q, a key k and a value v. The score between positions i and j is q_i . k_j / sqrt(d_k); a causal mask sets scores for future positions to minus infinity; a softmax over j turns scores into weights that sum to 1; and the output for i is the weighted sum of the v_j.
Multi-head attention runs h such operations in parallel on smaller projections, 64 heads of 64 dimensions in gpt-oss or 128 heads in DeepSeek-V3, concatenates them and projects back to the model width. Grouped-query attention shares each key-value head across several query heads (gpt-oss: 64 query heads, 8 KV heads) to shrink the cache that decoding must keep.
Technical example: One attention step by hand
A query for "sat" attends to three keys in a 4-dimensional head. Scores are divided by sqrt(4) = 2 and passed through a softmax.
Input:
q = [1, 0, 1, 0]
k(The) = [1, 0, 0, 0]
k(cat) = [1, 0, 1, 0]
k(sat) = [0, 1, 0, 1]
Code (python):
import math
q = [1, 0, 1, 0]
keys = {"The": [1, 0, 0, 0], "cat": [1, 0, 1, 0], "sat": [0, 1, 0, 1]}
d_k = len(q)
scores = {w: sum(a * b for a, b in zip(q, k)) / math.sqrt(d_k) for w, k in keys.items()}
exp = {w: math.exp(s) for w, s in scores.items()}
total = sum(exp.values())
weights = {w: round(e / total, 3) for w, e in exp.items()}
print(scores) # {'The': 0.5, 'cat': 1.0, 'sat': 0.0}
print(weights) # {'The': 0.307, 'cat': 0.506, 'sat': 0.186}
Output:
scores: The 0.5, cat 1.0, sat 0.0
weights: The 0.307, cat 0.506, sat 0.186
What it shows: The key most aligned with the query ("cat") gets about half the weight, but no token gets zero: softmax always spreads some attention. The output is these weights applied to the value vectors.
The problem attention solves
In plain English: Meaning depends on context. "Bank" means something different next to "river" and next to "loan", and a pronoun only makes sense once you find what it refers to. Older AI models read text one word at a time and struggled to remember things from far back. Attention lets the model connect any word directly to any earlier word, however far away.
Technically:
Recurrent networks compress the past into a single fixed-size state, so information from distant positions has to survive many updates. Bahdanau, Cho and Bengio (2014) introduced attention for translation so the decoder could look directly at all encoder states. Vaswani et al. (2017) removed recurrence entirely: in the transformer, attention is the only mechanism that moves information between positions.
Because every pair of positions is connected in one step, the path length between any two tokens is constant, and all positions can be computed in parallel during training. This parallelism is a large part of why transformers scale so well on GPUs.
Go deeper: details for practitioners
- Attention by itself is order-blind: shuffling the keys and values permutes the output identically. Position information is added with positional encodings; most current models rotate queries and keys by position with RoPE.
What is a recurrent neural network?
A network that reads a sequence one step at a time, carrying a hidden state forward. It was the standard for language before transformers.
Queries, keys and values
In plain English: Each token produces three things. A question (the query): what am I looking for? A label (the key): what do I contain? And a message (the value): what will I pass on if chosen? A token's question is compared with every earlier token's label. The better the match, the more of that token's message gets mixed in.
Think of it like this: Queries and keys are like a search box and page titles; values are the page contents you actually read once a title matches.
Technically:
For input X (n x d), Q = X W_q, K = X W_k and V = X W_v with learned projection matrices. Scores S = Q K^T / sqrt(d_k) form an n x n matrix. Dividing by sqrt(d_k) keeps the variance of dot products near 1 as head size grows, so the softmax does not saturate into near one-hot weights with vanishing gradients.
The causal mask enforces that position i only sees positions j <= i, which is what lets a decoder be trained on all positions at once while still generating left to right. The softmax output A is applied as A V, and each head's result is concatenated and multiplied by an output projection W_o.
Go deeper: details for practitioners
- Some models add learned attention sinks, an extra logit in the softmax denominator, so a head can attend to nothing when no earlier token is relevant. gpt-oss uses them; see its architecture guide.
What is softmax?
A function that turns a list of scores into positive weights that add up to 1, giving higher scores exponentially more weight.
What is a causal mask?
A rule that stops each token from attending to tokens after it, so the model cannot peek at the answer during training.
Many heads, many relationships
In plain English: One highlighter can only look for one thing at a time. A model therefore runs many attention heads side by side. Researchers have found heads that track the previous word, heads that link a closing bracket to its opening one, and heads that copy names seen earlier. Nobody programs these roles; they emerge in training.
Technically:
Multi-head attention splits the projection into h heads of dimension d_k, each with its own Q, K and V slices. Heads attend independently and their outputs are concatenated. Interpretability work has identified previous-token heads and induction heads, pairs of heads that implement pattern copying of the form [A][B] ... [A] -> [B], which appear to underpin in-context learning.
Grouped-query attention (Ainslie et al., 2023) keeps many query heads but fewer key-value heads, sharing each KV head across a group. gpt-oss shares 8 KV heads across 64 query heads; Gemma 4 31B uses 16 KV heads for 32 query heads. DeepSeek-V3 keeps 128 heads but caches a compressed latent instead of per-head keys and values.
Everyday example: A head that copies names
The prompt says: "Priya handed the keys to Tom. Later, Tom gave them back to".
Output:
Next word: Priya
What it shows: A copying head notices the earlier pattern of who gave what to whom and points back to the name that fits, so the model can continue the story correctly.
What is an induction head?
An attention pattern that finds an earlier occurrence of the current token and predicts the token that followed it, enabling copying from context.
The cost of attention and how models cut it
In plain English: Because every token looks at every earlier token, doubling the length of a text roughly quadruples the attention work. While writing an answer, the model also keeps a memory of every earlier token's labels and messages, which grows with every token. Long conversations therefore cost more memory and time, and model builders use clever shortcuts to keep this in check.
Technically:
Training-time attention costs O(n^2 d) compute; decoding reuses cached keys and values, making each new token O(n d) but requiring a KV cache of 2 x layers x kv_heads x head_dim values per token. Optimisations target each factor: FlashAttention reorders the computation to avoid materialising the n x n matrix, sliding-window layers cap n per layer, GQA reduces kv_heads, and latent attention compresses what is cached.
Current open models mix these. Gemma 4 alternates local sliding-window layers with periodic global layers, gpt-oss alternates 128-token banded windows with full-attention layers, and DeepSeek-V3 caches a 512-dimensional latent plus a small shared positional key per token.
Go deeper: details for practitioners
- Sparse attention variants go further and pick a subset of earlier tokens per query. DeepSeek-V3.2 adds a lightning indexer that selects the top 2,048 tokens for each query before running full attention on them.
What is a KV cache?
Stored keys and values of all earlier tokens, kept during generation so they do not have to be recomputed for every new token.
Common misconceptions
Myth: Attention weights show exactly why a model gave its answer.
Reality: They show where information was read from in one head of one layer. Many heads and layers combine, so weights alone are a partial and sometimes misleading explanation.
Myth: A model attends to future words when it understands a sentence.
Reality: Decoder LLMs use a causal mask: each token only sees earlier tokens. Understanding of later words is built when those words arrive.
Myth: Attention means the model focuses on one word at a time.
Reality: Softmax gives every visible token some weight, and each head blends many tokens into its output.
Where you'll see this
- Gemma 4 architecture: Gemma 4 alternates sliding-window and global attention layers.
- gpt-oss architecture: gpt-oss combines grouped-query attention, banded windows and learned attention sinks.
- DeepSeek-V3 architecture: DeepSeek-V3 caches a compressed latent with multi-head latent attention.
Key takeaways
- Attention lets every token gather information from earlier tokens, weighted by learned relevance.
- Queries ask, keys advertise and values carry content; relevance is the scaled dot product of query and key, normalised with softmax.
- Many heads run in parallel, each free to specialise in a different kind of relationship.
- Attention cost grows with the square of sequence length and its key-value cache grows linearly, which is why models use grouped heads, sliding windows and latent compression.
Frequently asked questions
What is self-attention?
Attention where the queries, keys and values all come from the same sequence, so each token attends to other tokens of the same text.
Why is attention divided by the square root of the head dimension?
Dot products grow with vector length. Dividing by sqrt(d_k) keeps scores in a range where the softmax still spreads attention and gradients stay healthy.
What is the difference between multi-head and grouped-query attention?
Multi-head gives every query head its own key and value head. Grouped-query attention shares key-value heads across groups of query heads to save memory.
Why are long prompts slower?
Attention compares every token with every earlier token, so the prompt-processing work grows with the square of its length, and the cache grows with every token.
Is attention the same as a transformer?
No. Attention is one component; a transformer block combines attention with normalisation, a feed-forward network and residual connections.
Sources
Facts last verified November 23, 2026.
- Vaswani et al.: Attention Is All You Need (arXiv)
- Bahdanau, Cho and Bengio: Neural Machine Translation by Jointly Learning to Align and Translate (arXiv)
- Ainslie et al.: GQA, Training Generalized Multi-Query Transformer Models (arXiv)
- Dao et al.: FlashAttention (arXiv)
- Olsson et al.: In-context Learning and Induction Heads (Transformer Circuits)