Opens in a new tab
Explainer

How attention helps an AI model connect the words

In brief

Follow a two-server sentence through queries, keys and weighted values, then see what masks, multiple heads and a causal cache change, and what an attention map cannot prove.

11 min read

Is this the right starting point?
Before you read
Comfort with adding and multiplying small numbers. Python is optional; the complete example can be followed on paper.
What you will take away
Explain queries, keys and weighted values, and distinguish attention weights from evidence that an output preserves a condition.
Sources
The old server stays until the new server passes its checks. An original illustration of an invented sentence, not a measured attention map.
On this page6 sections

An AI model works with pieces of text, but the useful meaning often lives between them. Follow one small calculation to see how attention brings those pieces together, and why a longer request asks more of the machine.

Read this invented service note: “Keep the old server until the new server passes its checks.” Now imagine asking an assistant to shorten it for a colleague.

The word “server” appears twice. Both servers matter, but they have different jobs in the sentence. One must stay. The other has something to prove. Lose the little word “until” and a tidy summary can change the plan.

Attention gives a language model a way to bring information from different text positions together while it builds its answer. It calculates how strongly to combine information from the available positions, rather than handling each piece as though it arrived alone. That helps explain how a model can connect a condition near the end of a note with the action near its beginning. It also explains part of the work that grows when a short note becomes a very long conversation.

There is no miniature engineer inside the calculation checking which server is ready. The interesting part is how ordinary arithmetic can make the surrounding words matter.

The same word arrives with different company

Before the model begins, a tokenizer divides the note into pieces called tokens. A token might be a whole word, part of a word or punctuation. We will use whole words when talking about the note, without claiming that a particular tokenizer splits it that way.

Each token starts with a list of numbers, or vector. As it moves through the model, its representation can gather information from positions the model is allowed to use. The two appearances of “server” occupy different places in the note, with different words before them. Their representations can therefore become different even though the printed word is the same. Which directions the model can look matters; we will come back to that before the assistant starts its answer. Google's original Transformer explanation describes this context-building role of self-attention. [7]

To make one attention calculation, learned transformations produce three numerical lists from the representations. One list, the query, is compared with the keys at the available positions. Those comparisons determine how much of each position's value to mix into the result. Keys help decide the proportions; values supply what gets mixed. [6]

The names can sound like a database lookup. Here they are vectors inside the model, not search phrases, document IDs or stored answers. In self-attention, queries, keys and values come from representations of the same sequence. The transformations are learned model parameters. The proportions they produce are calculated for the particular input, so they can change when the note changes. [6]

Those transformations become useful through training. A model tries to predict text it has not been shown, and the mismatch between its predictions and the training text guides adjustments to its parameters. The transformations that make queries, keys and values are among the parameters being adjusted. Repeated across many examples, this can make particular combinations of information useful for prediction. [1]

For our two servers, the useful possibility is that their representations can gather different combinations of information. A real model has many calculations across many layers. We have not inspected one or measured which word it attends to. To see the arithmetic clearly, we can build a tiny example whose numbers are completely ours.

A match becomes a mixture

Put two number cards on the table. Card A carries the value [2, 0]. Card B carries [0, 4]. These are invented numerical values, not measurements of the servers, and their coordinates have no assigned meanings such as “old” or “safe.”

Give the current position a query of [1, 0]. Give A the key [1, 0] and B the key [0, 1]. Compare the query with each key by multiplying corresponding entries and adding them. For A, that is 1 × 1 + 0 × 0 = 1. For B, it is 1 × 0 + 0 × 1 = 0.

That multiply-and-add operation is a dot product. In scaled dot-product attention, the scores are divided by the square root of the number of entries in the query. Our lists contain two numbers, so the scores become about 0.7071 and 0. Scaling moderates the score size as vectors contain more entries, which helps avoid extreme softmax outputs during training. [2]

The next operation, softmax, turns those scores into positive proportions that add to one. It takes the exponential of each score, then divides each result by their total. Here that gives approximately 0.6698 for A and 0.3302 for B. PyTorch's documented attention calculation shows the same sequence: compare, scale, apply any mask, turn scores into proportions, then combine values. [3]

Now use those proportions on the value cards:

0.6698 × [2, 0] + 0.3302 × [0, 4] ≈ [1.3395, 1.3210]

The result uses unrounded proportions; the displayed shares are rounded to four decimal places.

A received the larger share, but B did not vanish. The result contains contributions from both. That is the step an illustration showing a spotlight over one word can hide: this form of attention produces a mixture, not simply the label of a winning word.

Two invented value vectors contribute to one output vector. Card A contributes 0.6698 times [2, 0]; card B contributes 0.3302 times [0, 4]. Their sum is approximately [1.3395, 1.3210].
The proportions and vectors belong to this tiny arithmetic example. They are not an attention map from a language model or scores for the service note.

If the query changes to [0, 1], the two comparison scores exchange places. B now gets the larger share, and the mixture changes. The value cards stayed put. What changed was the comparison made from the position doing the asking.

Here is the entire calculation in standard-library Python. It makes no network request, downloads no model and writes no files. Run it with Python 3 to reproduce the arithmetic, not to test language understanding.

from math import exp, sqrt

def attention(query, keys, values):
    scores = [
        sum(q * k for q, k in zip(query, key)) / sqrt(len(query))
        for key in keys
    ]
    largest = max(scores)
    terms = [exp(score - largest) for score in scores]
    proportions = [term / sum(terms) for term in terms]
    mixed = [
        sum(weight * value[column]
            for weight, value in zip(proportions, values))
        for column in range(len(values[0]))
    ]
    return proportions, mixed

keys = [[1.0, 0.0], [0.0, 1.0]]
values = [[2.0, 0.0], [0.0, 4.0]]
for query in [[1.0, 0.0], [0.0, 1.0]]:
    proportions, mixed = attention(query, keys, values)
    print("query", query)
    print("proportions", [round(x, 4) for x in proportions])
    print("mixed", [round(x, 4) for x in mixed])

Subtracting the largest score before the exponentials keeps this calculation numerically well behaved without changing its proportions. The first output is [1.3395, 1.321]; the second is [0.6605, 2.679]. We have deliberately supplied the query, keys and values ourselves. A trained model has learned transformations that produce them, along with much more machinery around this little operation.

A sentence needs more than one mixture

Our two cards reveal one operation. A model also needs room for several relationships to matter at once. Multi-head attention runs several versions of the calculation with different learned transformations, then combines their results. One pair of keys and one mixture do not have to carry the whole sentence. PyTorch's reference implementation shows these parallel calculations and their combined output. [6]

The heads do not come with reliable job labels such as “grammar” or “remember until.” They are learned parts of a larger system. After attention brings information across positions, further learned calculations reshape each position's result. This happens repeatedly in the layered model design called a Transformer, so a later layer receives representations that earlier layers have already changed. Attention is part of that repeating work, not a complete language model by itself. Google's original Transformer explanation follows those changing representations through the model. [7]

Order still matters. “The backup finished before the restart” describes a different sequence from “The restart finished before the backup.” A Transformer is given position information as well as the token representations. The original design added positional encodings to the input vectors. [2] The model has both the words and a way to distinguish where they sit, rather than receiving an unordered bag of them.

The next word is not available yet

When a model generates an answer one token at a time, a position cannot use text that has not been generated. A causal mask prevents attention from looking ahead. For a sequence being processed together, this means each position can use itself and earlier positions, but not later ones. PyTorch's reference calculation excludes those disallowed scores before softmax. [3]

How, then, can the assistant use “until” when it comes after the first server in our note? The note is already supplied before the answer begins. In a model that generates by continuing the supplied sequence, the representation at the end of the input can use the complete note to predict the first answer token. Later answer positions have the note behind them too. The first “server” does not need to look ahead for those later calculations to use both the action and its condition.

Other models process a complete input to produce a representation of it rather than continue it token by token. An encoder is one such input-processing component, and its self-attention can often look both ways. “Attention sees all the words” is therefore too broad. The available positions depend on the model's design and mask. [1]

The restriction also makes earlier work reusable. Once the note has been processed, appending an answer token puts nothing new on the earlier positions' allowed side. In an ordinary causal Transformer, their layer-by-layer results can therefore stay put, including the keys and values calculated from them. A key-value cache, usually shortened to KV cache, retains those intermediate results. The new token adds its own layerwise work, while its attention still reads the available keys and values. This follows from the causal dependency and the attention calculation above.

For that reuse, the prefix, its positions and how those positions are encoded must stay the same, as must the model parameters and causal mask. We are assuming repeatable internal calculations, so doing the same earlier work again would give the same result. Editing the note or changing those conditions is a different case and can invalidate the cached work. An encoder looking both ways does not have this same guarantee when new text is added.

The cache is keeping intermediate numerical work, not a checked summary of the note. If the application left “until the new server passes its checks” out of the request, caching cannot restore it. The context-window guide follows that earlier question: what text did the application actually send?

A longer note changes the work behind the answer

There is a cost to connecting positions. In a straightforward dense attention calculation over a complete input, the number of query-key pairings grows roughly with the square of its token count. Double the sequence length and the pairings grow about fourfold. That does not promise four times the whole-request latency: other calculations, hardware, batching and the implementation matter.

Picture the comparisons as a large table, with one row for each query and one column for each key. A straightforward implementation can write that full table to memory on the graphics processing unit, or GPU, and read it back for later calculations. Moving those numbers takes work too.

FlashAttention arranges the calculation in blocks, keeping more of the immediate work in small, fast memory close to the computing units. It makes fewer trips to the GPU's larger memory and avoids storing the full attention table there. It still computes exact attention rather than skipping word pairs to approximate the result. This is a change in how the work is arranged, not a promise that a long request costs the same as a short one. The original FlashAttention paper explains that memory-traffic tradeoff. [4]

During cached generation, each new query still has to work with the keys and values available to it. Retaining more of those vectors takes more storage. For the same architecture and storage precision, longer retained sequences or more simultaneous requests expand that cache. The exact size depends on the model and cache strategy. This is why a model file fitting in memory is only the beginning of a serving-capacity question. The inference guide separates input processing, generation and the wait a person experiences.

Return to the short note. An assistant might produce a concise answer that preserves both servers and the condition between them. It might also produce a confident sentence that loses the condition. An attention visualization can show something about the internal mixing; on its own it does not establish why the final answer was produced or whether it is correct. Research by Jain and Wallace demonstrated that limitation for the attention-based NLP models they studied. [5]

The useful check here is visible in the text: does the summary still say the old server stays until the new one passes its checks? Attention helps make those connections possible. The answer is where we find out whether this request kept them.

Sources and example scope

  1. Google's introduction to Transformer models, read November 5, 2026. Used for context-sensitive representations, training and directional attention.
  2. Vaswani and colleagues, Attention Is All You Need, sections 3.1–3.5. Used for scaling the scores and supplying position information.
  3. PyTorch 2.15 scaled dot-product attention documentation. Used for the scale, mask and mixing sequence; the cache-reuse argument is derived from those fixed causal dependencies. The small Python example above is original, framework-free teaching code.
  4. Dao and colleagues, FlashAttention, 2022. Used for exact tiled attention and GPU-memory traffic, without repeating its benchmark results as current performance promises.
  5. Jain and Wallace, Attention is not Explanation, 2019. Its results concern the systems studied, not an exhaustive finding about every modern model.
  6. PyTorch 2.15 MultiheadAttention documentation. Used for queries, keys, values, their learned transformations and the parallel calculations with a combined output.
  7. Google Research, Transformer: A Novel Neural Network Architecture for Language Understanding, 2017. Used for repeated mixing and further transformation of representations, not its historical benchmark claims.

The service notes, number cards and visual are constructed teaching examples. The arithmetic was checked locally. No language model, production service, attention-map experiment or user study was run for this article.

Sources & context

Sources linked in this article. Read alongside the author’s analysis; a citation does not independently verify a publisher’s claims.

Report an error or outdated detail

Keep reading

Where to go next