Originally published on Medium.
We call it attention. We visualize it with colorful heatmaps. But what is actually happening inside a neural network when one word attends to another? The answer is more interesting than you might think.
Imagine asking an AI model to complete this sentence:
"The animal didn't cross the street because it was too..."
What does it refer to? The animal? The street?
To answer correctly, the model needs to connect information across different parts of the sentence. It needs to retrieve something it encountered earlier, understand how the pieces relate, and use that information to predict what comes next.
This is where attention comes in.
If you've spent any time reading about modern language models, you've probably encountered the term attention. It appears everywhere: research papers, technical discussions, architecture diagrams, and almost every explanation of how transformers work.
The original Transformer paper even made it the centerpiece of its title: Attention Is All You Need.
But here's something I've always found interesting: we talk about attention constantly, yet we don't always understand what an individual attention head is actually doing.
Most explanations show a heatmap of colored lines connecting words, tell us that the model is "paying attention" to important tokens, and move on.
That visualization is useful, but it can also create the wrong mental model.
Attention isn't quite the same as human attention. A language model isn't consciously focusing on certain words while ignoring others.
A better way to think about it is this:
Attention is an information-routing mechanism.
It determines which tokens can send information to other tokens, how much information gets transferred, and how different pieces of a sequence influence one another.
And once you understand that, some fascinating things about language models start to make sense.
Let's unpack it.
1. First, what actually happens when a model pays attention?
A transformer processes text as a sequence of tokens. A token might be an entire word, part of a word, or even a punctuation mark.
Each token is represented by a vector: essentially, a collection of numbers encoding information about that token and its context.
But a token doesn't operate in isolation.
Consider:
"The dog chased the ball because it was excited."
To understand the sentence, the model needs to establish relationships between different tokens. The word it needs information about the earlier words to build an appropriate representation.
Attention provides a mechanism for doing this.
For every token, the model creates three different representations:
- Query (Q): What information am I looking for?
- Key (K): What information do I have that another token might need?
- Value (V): What information should I actually send?
Think of it as a search engine operating inside the neural network.
Imagine you're searching through a collection of documents. Your search query is compared against the descriptions of those documents. The most relevant documents contribute more information to your final result.
Attention works similarly.
Each token produces a query, compares it against the keys of other tokens, and uses the resulting scores to determine how much information to retrieve from their values.
Mathematically, this is expressed as:
[
\text{Attention}(Q,K,V)=
\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V
]
You don't need to memorize this equation to understand the idea.
The important parts are:
- The query-key comparison determines which tokens are relevant to one another.
- Softmax converts the scores into weights that sum to one.
- Those weights determine how much information is collected from each token's value.
The result is an updated representation of the token.
In other words, a token doesn't simply look at another token. It retrieves a learned transformation of the information that token carries.
And this distinction matters.
The model learns the query, key, and value transformations during training. Nobody explicitly tells it that a pronoun should search for its antecedent or that a verb should retrieve information about its subject.
Those behaviors emerge because learning to predict language rewards useful information-routing patterns.
Attention is essentially a learned communication system between tokens.
But if every token only had one attention mechanism, the model would have a serious limitation.
It would have to use the same information-routing strategy for everything.
That's why transformers have multiple attention heads.
2. Why do transformers need multiple attention heads?
Consider everything a model might need to understand in a single sentence.
It might need to:
- Identify the relationship between a subject and its verb.
- Determine which noun a pronoun refers to.
- Retrieve information from a previous sentence.
- Recognize a repeated pattern.
- Connect a word to something that appeared much earlier in the sequence.
These are different information-retrieval problems.
One attention mechanism would have to combine all these relationships into a single operation.
Multi-head attention gives the model a way around this.
Instead of having one attention mechanism, the transformer runs several attention heads in parallel. Each head has its own query, key, and value projections.
This means different heads can learn different ways of routing information.
Their outputs are then combined to produce an updated representation.
A useful analogy is a research team.
Imagine several researchers examining the same document. One focuses on grammatical relationships, another tracks recurring patterns, and another retrieves relevant information from earlier sections.
They examine the same material, but they are looking for different things.
Attention heads work in a somewhat similar way.
And this leads to one of the most interesting discoveries in transformer interpretability:
Attention heads often develop surprisingly specialized behaviors, even though nobody explicitly assigns them those jobs.
3. What do individual attention heads actually learn?
When researchers began investigating trained transformers, they discovered that attention heads were not simply performing interchangeable operations.
Some heads learned recognizable patterns of behavior.
Here are a few particularly interesting examples.
A. Heads that track grammatical relationships
Some attention heads consistently connect words that have specific grammatical relationships.
For example, a head might connect a determiner to its noun, a verb to its direct object, or a preposition to the noun it governs.
In the sentence:
"The scientist discovered a new planet."
A syntactic head might learn to connect discovered with scientist or planet.
Nobody explicitly programmed this head to understand grammar.
It emerged because grammatical relationships provide useful information for predicting language.
Clark and colleagues explored these behaviors in their 2019 paper, What Does BERT Look At?.
B. Induction heads: How models learn patterns from examples
This is probably one of my favorite discoveries in transformer interpretability.
In 2022, researchers at Anthropic, including Chris Olah and colleagues, described a mechanism called induction heads.
These heads help explain an important aspect of in-context learning: a model's ability to recognize and continue patterns from examples provided in its prompt.
Consider this sequence:
"apple ... banana ... apple ..."
If the model has already encountered the pattern:
"apple ... banana"
it can use that previous occurrence to predict that banana might follow the second apple.
An induction head helps implement this behavior.
It essentially performs two operations:
- It identifies an earlier occurrence of the current token.
- It retrieves the token that followed that earlier occurrence.
This is a surprisingly simple mechanism, but its implications are significant.
It provides a concrete example of how a transformer can learn to recognize patterns in context without having a separately programmed algorithm for every possible pattern.
Researchers also found that induction heads emerge during training in a recognizable phase change, and that disrupting them can impair in-context learning.
If you're interested in understanding how models acquire capabilities during training, this is an excellent place to start.
Paper: In-context Learning and Induction Heads.
C. Attention sinks: The head that keeps looking at the beginning
Not every attention head behaves in a way that immediately makes sense.
Researchers discovered that some heads consistently assign substantial attention to the first token in a sequence, regardless of what that token represents.
At first, this seems strange.
Why would a model repeatedly attend to the first token when the information it needs might be somewhere else?
The explanation is surprisingly practical.
Attention weights must sum to one. Sometimes a head needs somewhere to direct attention weight even when no particular token is relevant. The first token can serve as a convenient destination for that excess weight.
This behavior became known as an attention sink.
It is more than an interesting observation. It has practical consequences for models that process long, continuously growing sequences.
The 2023 paper Efficient Streaming Language Models with Attention Sinks showed how retaining the initial tokens alongside a recent window of tokens can help maintain stable generation in streaming settings.
D. Some attention heads are surprisingly unnecessary
Here's another interesting finding.
Not every attention head contributes meaningfully to a model's performance.
Voita and colleagues demonstrated in 2019 that many heads could be removed with little impact on model quality, while a smaller subset carried much more important functionality.
This tells us something important about how neural networks learn.
They don't necessarily develop perfectly efficient internal architectures. Training can produce redundancy, specialization, and behaviors that overlap.
Sometimes multiple heads perform similar functions. Sometimes a head is important only for particular inputs.
This is also why researchers study head pruning as a potential model-compression technique.
The bigger picture is that attention heads are not a collection of identical components.
They can develop specialized roles, and understanding those roles gives us a window into the internal organization of transformers.
If you want to see some of this yourself, BertViz is a good place to start. It lets you load a model like BERT, type in a sentence, and inspect what each head in each layer is actually attending to. The syntactic heads and the attention sinks are both visible there, in real models, not just in papers.
4. Here's the problem: Do attention maps actually explain what a model is thinking?
If you've ever seen a transformer visualization, you've probably encountered an attention heatmap.
It typically shows tokens along the horizontal and vertical axes, with brighter regions indicating stronger attention weights.
These visualizations can be fascinating.
You might see a word attending strongly to another word several positions away and immediately conclude that you've discovered the model's reasoning process.
But there's a problem.
Seeing where a model directs attention is not the same as understanding why it makes a prediction.
This question sparked a significant debate in machine learning research.
In 2019, Jain and Wallace published Attention is not Explanation.
Their argument was that attention weights should not automatically be treated as explanations of model predictions.
They demonstrated that substantially different attention distributions could sometimes produce similar predictions. They also found that attention weights did not always align with other measures of feature importance.
Wiegreffe and Pinter responded with Attention is not not Explanation, arguing that attention can still provide meaningful explanations under appropriate conditions.
Both sides raised important points.
The practical lesson is more nuanced than simply declaring attention useful or useless.
An attention weight tells us how much a token's value contributes to another token's attention output.
But the value itself is not simply the original word. It is a learned transformation of the token's representation, which already contains information accumulated through previous layers.
Furthermore, the attention output is only one part of the computation that determines the model's final prediction.
A token can receive substantial attention without making a decisive contribution to the final output. Conversely, a relatively small contribution can matter significantly depending on the surrounding computation.
This is why interpreting attention requires more than looking at heatmaps.
Researchers increasingly investigate circuits: connected computational pathways involving multiple attention heads and other components across different layers.
For example, the induction-head mechanism is not simply one head operating independently. It involves multiple components working together to identify previous occurrences and retrieve the associated continuation.
The distinction is important.
A heatmap tells you something about information routing.
A circuit-level investigation attempts to explain how multiple operations combine to produce a particular behavior.
And ideally, that explanation should survive an intervention: if you disrupt the proposed mechanism, does the behavior change in the way your hypothesis predicts?
That is a much stronger standard of evidence.
5. Attention has limitations, and they affect the models we use every day
Attention is powerful, but its design comes with practical limitations.
Two are particularly important.
The computational cost of looking at everything
In standard full self-attention, every token can compare its query against the keys of every other token.
For a sequence of length (N), this produces an attention matrix with (N \times N) entries.
The computational cost therefore grows quadratically with sequence length:
[
O(N^2)
]
What does this mean in practice?
If you double the sequence length, the attention computation grows approximately fourfold.
If you increase it by a factor of ten, the number of token-to-token comparisons grows by a factor of one hundred.
This is one reason why extending context windows has been such an important engineering challenge.
Researchers have explored several approaches to address this, including:
- Sliding-window attention, which restricts attention to nearby tokens.
- Grouped-query attention, which shares key and value representations across groups of query heads.
- More efficient attention implementations that reduce memory movement and improve hardware utilization.
The goal is to make models process longer sequences without making inference prohibitively expensive.
Having a large context window doesn't mean a model can use all of it
This is perhaps an even more interesting limitation.
In 2023, Liu and colleagues published Lost in the Middle.
They investigated how language models retrieve information from long contexts and discovered a striking pattern.
Models often performed better when relevant information appeared near the beginning or end of the input, while performance deteriorated when that information was placed somewhere in the middle.
Think about that for a moment.
A model might technically accept a context containing 100,000 tokens, but that doesn't guarantee it can reliably retrieve and use every relevant piece of information within those tokens.
The distinction between having access to information and effectively using information is fundamental.
A large context window is not necessarily a large usable memory.
And this is an important reminder that architectural capabilities and actual model behavior are not always the same thing.
6. What changes when we move from language models to diffusion and multimodal models?
This is where attention becomes particularly interesting to me.
Much of our understanding of attention heads and their specialized behaviors comes from studying autoregressive transformers.
These models generate text sequentially, predicting one token after another.
But not every model generates information that way.
Attention in diffusion language models
Diffusion language models approach generation differently.
Rather than generating a sequence strictly from left to right, they start with a noisy or partially masked sequence and progressively refine it over multiple denoising steps.
This changes the information-routing problem.
In a conventional autoregressive transformer, causal attention prevents a token from accessing future tokens.
In a typical bidirectional diffusion language model, tokens can attend to information on both sides of the sequence.
There is no fixed left-to-right generation process governing every attention operation.
That raises some fascinating questions.
Do the same specialized attention heads emerge in diffusion language models?
Can we identify equivalents of induction heads when generation happens through iterative refinement rather than sequential prediction?
How do attention patterns change as the model moves from an initially noisy sequence toward a coherent sentence?
Are different heads responsible for different stages of denoising?
These are not merely architectural questions. They are questions about how information is represented, retrieved, and transformed during generation.
We understand considerably less about the internal circuits of diffusion language models than we do about their autoregressive counterparts.
For researchers interested in mechanistic interpretability, this creates an interesting opportunity.
Attention in multimodal models
Now consider a model that receives both text and an image.
Suppose you give it a picture of a red car parked beside a blue building and ask:
"What color is the car on the left?"
The model needs to connect language with visual information.
This introduces another important mechanism: cross-attention.
Unlike self-attention, where tokens exchange information within the same sequence, cross-attention allows representations from one modality to retrieve information from another.
For example, text tokens can attend to image patches.
The word red might retrieve information from the image region containing the car, while building might retrieve information from a different region.
This creates an opportunity to investigate whether a model is genuinely grounding language in visual information or relying on misleading correlations.
One question I find particularly interesting is whether different attention heads specialize in different visual properties.
For example:
- Are some heads more responsible for spatial relationships?
- Do others primarily carry color information?
- Are object identity and spatial localization handled by the same heads?
- How does this information move between visual and textual representations?
In my own work on multimodal interpretability, these are the kinds of questions I find worth investigating.
The interesting part isn't simply identifying which image patches receive the most attention.
It's understanding what information is being transferred, how it is transformed, and whether that information actually contributes to the model's final behavior.
That distinction brings us back to the central question of this article: understanding attention means understanding information flow, not just visualizing it.
7. Why should we care about what attention heads are doing?
It might seem like a fairly narrow research question.
After all, why spend so much time studying individual components of a neural network when we could simply focus on improving the model's performance?
I think there are several reasons.
First, understanding attention helps us understand model behavior.
When a model fails to retrieve information, makes an incorrect prediction, or struggles with a long context, we need ways to investigate the internal computation responsible.
Attention is one of the mechanisms through which information moves inside transformers. Understanding its behavior gives us an important starting point.
Second, it helps us move beyond surface-level explanations.
A model producing the correct answer doesn't necessarily mean we understand how it arrived there.
If we want to make meaningful progress in mechanistic interpretability, we need explanations that go beyond plausible-looking visualizations.
We need hypotheses, experiments, and interventions that reveal which internal components actually contribute to a behavior.
Third, understanding these mechanisms could help us build better architectures.
The limitations of attention have motivated research into more efficient ways of processing long sequences, managing memory, and routing information.
Understanding what existing attention heads do, and where they struggle, can help inform the design of future architectures.
And finally, as models become increasingly multimodal, the question becomes even more important.
We are no longer interested only in how models connect words to other words.
We want to understand how they connect language, images, audio, spatial information, and eventually more complex representations of the world.
That requires a much deeper understanding of information flow inside neural networks.
Final thoughts: Attention is not the same as understanding
There's something fascinating about attention.
At its mathematical core, it is a relatively straightforward operation: compare vectors, calculate weights, and combine information.
Yet when this operation is repeated across dozens of layers and multiple attention heads, the resulting system can learn grammatical relationships, recognize patterns, retrieve information from context, and support surprisingly sophisticated behavior.
Nobody explicitly programs each head to perform these specialized functions.
They emerge through training.
But we should be careful not to confuse discovering a pattern with understanding the entire mechanism behind it.
A colorful attention map is a starting point, not a complete explanation. Identifying a specialized head is interesting, but understanding how that head contributes to a larger computational circuit is far more valuable.
And perhaps that's the bigger lesson of mechanistic interpretability:
If we want to understand what neural networks are doing, we need to move beyond what their outputs look like and investigate the computations that produce them.
The more we understand how information flows through these systems, the closer we get to understanding how their capabilities emerge, where their limitations come from, and how we might build better ones.
That's what makes studying attention heads so interesting to me. We're not just studying a mathematical operation. We're trying to understand the internal mechanisms of systems that are becoming increasingly capable.
And there is still a lot we don't know.
References and further reading
If you want to explore the research behind this article, these are excellent starting points:
- Attention Is All You Need (Vaswani et al., 2017). The original Transformer paper.
- What Does BERT Look At? (Clark et al., 2019). An investigation of attention-head specialization.
- Analyzing Multi-Head Self-Attention (Voita et al., 2019). Specialized heads and attention pruning.
- Attention is not Explanation (Jain and Wallace, 2019). Why attention weights should not automatically be treated as explanations.
- A Mathematical Framework for Transformer Circuits (Elhage et al., 2021). A foundational exploration of transformer circuits.
- In-context Learning and Induction Heads (Olsson et al., 2022). How induction heads help explain in-context learning.
- Lost in the Middle (Liu et al., 2023). How language models use information in long contexts.
- Efficient Streaming Language Models with Attention Sinks (Xiao et al., 2023). Understanding attention sinks and efficient streaming generation.
If you enjoyed this article, follow along as I explore transformers, diffusion models, multimodal learning, and mechanistic interpretability. There is a lot happening beneath the surface of modern AI, and I think it's worth understanding.




