Skip to content

Loading index.

Enter to openEsc to close

A Mental Model for Transformer Attention

A mental model for attention based on queries, keys, values, scaling, masking, and multi-head structure.

Dilawar Hussain · 5 min read

Attention is often described as a complicated operation. The useful mental model is simpler: attention is a learned lookup with soft matches.

You have a query. You compare it with a set of keys. The comparison produces weights. You use those weights to combine values. The model learns what to put in the queries, keys, and values so that the lookup supports the task.

Queries, keys, and values

Start with a sequence of token representations. Each position produces three vectors:

  • Query: what this position is looking for.
  • Key: what this position offers for matching.
  • Value: what this position contributes if it is selected.

The comparison between a query and a key is a dot product. A larger dot product means a stronger match. The softmax turns the matches into weights that sum to one. The output is a weighted sum of the values.

In matrix form:

Q=XWQ,K=XWK,V=XWVQ = XW_Q, \qquad K = XW_K, \qquad V = XW_V

The model learns the projection matrices WQW_Q, WKW_K, and WVW_V. The input XX is the same sequence, but each position gets a different view depending on which projection is used.

Scaled dot-product attention

The core operation is:

Attention(Q,K,V)=softmax(QK⊤dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

Read it from the inside out:

  1. QK⊤QK^\top compares every query with every key.
  2. Dividing by dk\sqrt{d_k} keeps the logits from growing too large.
  3. Softmax turns the logits into attention weights.
  4. Multiplying by VV mixes the values according to those weights.

Without scaling, large dot products push softmax into a nearly one-hot state. The model then has very little gradient signal for the positions that were not selected.

A tiny example

Suppose a sequence has three positions and the model uses one head with dimension two. The query for position 2 is compared with three keys. The raw scores might be:

[1.2, 4.8, 0.3]

After scaling and softmax, the weights might become:

[0.03, 0.95, 0.02]

The output for position 2 is mostly the value from position 1, with small contributions from the others. The model learned that position 1 is the useful match for this query. In a real model, the scores come from learned projections, not from hand-picked numbers.

Example 1

One query, two equally aligned keys

A single head uses . The query is , the keys are and , and the values are and . Compute the attention output for this query.

Solution

  1. Score each key with a dot product:

  2. Divide by . Both scores stay at zero, so the scale does not change them here.

  3. Apply softmax. Two equal logits give equal weights, because :

  4. Mix the values with those weights:

Answer

The output is . When two keys match the query equally, attention returns the mean of their values.

Multi-head attention

One attention head can represent one kind of relationship. Multi-head attention runs several heads in parallel. Each head has its own projections, so one head can track local syntax while another tracks a longer dependency.

The outputs are concatenated and projected again:

MultiHead(Q,K,V)=Concat(head1,…,headh)WO\mathrm{MultiHead}(Q, K, V) = \mathrm{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)W_O

What each head learns matters more than the count. If you debug a model, inspect heads separately before you inspect the merged output.

Causal masking

In a decoder, a position must not attend to future positions. A causal mask sets those scores to negative infinity before softmax. After softmax, the future positions receive zero weight.

The mask is what turns a general attention block into an autoregressive model. Without it, the model could see the answer it is supposed to predict.

What attention is not

Attention is not a full explanation of a model's reasoning. The weights show a pattern of matching, but they do not prove why the final token was chosen. The model also has feed-forward layers, residual connections, and normalization that shape the output.

Attention is also not a database. It does not store facts in a way that can be queried with perfect recall. It is a learned mixing operation that runs at every layer.

Debugging attention

When an attention model behaves badly, check these in order:

  1. Tokenization. Are the tokens what you think they are?
  2. Positions. Are position encodings aligned with the sequence?
  3. Mask. Is the causal mask applied before softmax?
  4. Scaling. Is the scale factor present and correct?
  5. Heads. Does one head dominate, or are the heads collapsed?
  6. Residual path. Is the attention output added back correctly?

Most implementation bugs are in one of these places, not in the mathematical idea.

Attention bugs rarely stay inside one block. If the model also calls tools or runs a loop, the agent guide covers the control flow around it. If you want another example of a numerical pipeline with convergence checks, DFT for developers makes the same assumptions explicit.

Summary

Attention is a soft lookup. Queries ask, keys advertise, values contribute, and softmax decides how much each value matters. Scaling keeps the weights trainable, masking enforces causality, and multiple heads let the model represent different relationships at once. The mental model is simple enough to debug, and it is accurate enough to guide implementation.

References

  1. 1Attention Is All You NeedarXiv, 2017
  2. 2The Illustrated TransformerJay Alammar, 2018
  3. 3Stanford CS224N lecture notesStanford University

Questions

Why divide by the square root of the key dimension?
The dot product grows with dimension. Scaling keeps the logits in a range where softmax does not saturate too early, which makes gradients more stable.
Does attention explain why a model made a choice?
Not by itself. Attention weights show where a query matched keys, but they are not a complete causal explanation of the output.
What does a causal mask do?
It prevents a position from attending to future positions. This is what makes autoregressive generation possible.

How this was checked. Sources are linked, calculations are shown, and corrections are logged. Read the editorial policy.

Dilawar Hussain

Lecturer in chemistry, researcher, and web developer

Lecturer at PIEAS. I write about AI and agentic systems, software and operating systems, computational chemistry and physics, research practice, and the tools I use to teach and build.

About

One email, the week's new articles.

Double opt-in, one message per week, unsubscribe in every email.

From the same cluster

LLMs

Keep reading

Cite this article

APA

Hussain, D. (2026). A Mental Model for Transformer Attention. Dilawar Hussain. https://dilawarhussain.net/r/DH00002

BibTeX

@misc{dh00002,
  author = {Hussain, Dilawar},
  title = {A Mental Model for Transformer Attention},
  year = {2026},
  publisher = {Dilawar Hussain},
  url = {https://dilawarhussain.net/r/DH00002},
  note = {Reference ID DH00002}
}
Share

Comments

0

Sign in to join the discussion.

Loading comments.