AI & LLMs

The Attention Mechanism Explained: How It Works, Where It's Used, and Why It Matters

How attention works in plain language and simple maths — queries, keys, values, self-attention, multi-head — with NumPy code, real use cases and benefits.

Key takeaways

  • Attention lets a model decide, for every piece of its input, which other pieces matter most — and blend their information accordingly.
  • It works with three learned views of each token: a query (what am I looking for?), a key (what do I offer?) and a value (what information do I pass on?).
  • Attention is the core of the transformer, which powers ChatGPT, Claude, Google Translate, modern search, speech recognition and many vision models.
  • Its main benefits are long-range understanding, parallel training, flexibility across data types and partial interpretability. Its main cost is that compute and memory grow with the square of the input length.

If you have used ChatGPT, Google Translate or a modern voice assistant, you have used attention. It is the idea that turned neural networks from good pattern-matchers into systems that can follow long documents, translate idioms and write code. Yet it is often explained either with hand-waving or with a wall of equations.

This article sits between the two. It builds the intuition first, then shows the actual formula with a small NumPy implementation you can run, and finishes with real use cases, benefits and limits. If you want the bigger picture of where attention fits among machine-learning methods, read Machine Learning vs Deep Learning vs Transformers first.

The problem attention solved

Before attention, the standard way to process language was a recurrent neural network (RNN or LSTM). It reads a sentence one word at a time and squeezes everything it has seen into a single memory vector. That design has two weaknesses:

  • Forgetting. Information from early words must survive many steps to reach later ones. In long sentences and documents, it fades.
  • A bottleneck. In early translation systems, the whole source sentence was compressed into one fixed-size vector before the translation began. Long sentences simply didn't fit.

Around 2014–2015, researchers working on machine translation (Bahdanau, Cho and Bengio, followed by Luong and colleagues) added a simple fix: when producing each translated word, let the model look back at all the source words and focus on the relevant ones. Translation quality on long sentences jumped. In 2017 the paper "Attention Is All You Need" went further and built an entire architecture — the transformer — out of attention alone, removing recurrence entirely.

The intuition: a smart lookup

Consider this sentence:

"The bank approved the loan because it had a strong credit record."

What does "it" refer to? Most readers link it to "the bank", though grammatically it could also be "the loan". Either way, to understand "it" you attend to other words — weighting "bank" and "loan" heavily and ignoring words like "the" and "because".

Attention gives a model the same ability. A helpful analogy is a library search:

  • You arrive with a query: the question you want answered.
  • Every book has a key: its title and catalogue tags, which say what it is about.
  • Every book has a value: its actual content.

You compare your query with every key, decide how relevant each book is, and read a weighted mix of the most relevant contents. Unlike a normal search that returns one best match, attention blends many sources at once, in proportion to their relevance — and it learns, during training, how to form good queries and keys.

The maths, step by step

Each token (a word or word-piece) starts as a vector — its embedding. The model multiplies it by three learned weight matrices to get three new vectors: a query Q, a key K and a value V. Then:

  1. Score: compare each query with every key using a dot product. A high score means "this token is relevant to me".
  2. Scale: divide the scores by √dk (the square root of the key length). Without this, scores grow large in high dimensions and the next step becomes too "peaky" to train well.
  3. Normalise: apply softmax across each row, turning scores into weights that are positive and add up to 1.
  4. Blend: multiply the weights by the values. Each token's output is a weighted average of all the value vectors.

Written compactly, this is the famous formula:

Attention(Q, K, V) = softmax( Q · Kᵀ / √d_k ) · V

Try it in NumPy

Here is the whole mechanism in about 15 lines of plain NumPy:

import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)      # numerical stability
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

def scaled_dot_product_attention(Q, K, V, mask=None):
    d_k = Q.shape[-1]
    scores = Q @ K.T / np.sqrt(d_k)              # how well each query matches each key
    if mask is not None:
        scores = np.where(mask, scores, -1e9)    # block positions we must not see
    weights = softmax(scores, axis=-1)           # each row sums to 1
    return weights @ V, weights

# Toy example: 4 tokens, each an 8-dimensional embedding
rng = np.random.default_rng(0)
tokens = ["the", "bank", "approved", "it"]
X = rng.normal(size=(4, 8))

# Learned projection matrices (random here; trained in a real model)
W_q, W_k, W_v = (rng.normal(size=(8, 8)) for _ in range(3))
Q, K, V = X @ W_q, X @ W_k, X @ W_v

output, weights = scaled_dot_product_attention(Q, K, V)
print("output shape:", output.shape)
for tok, row in zip(tokens, weights):
    print(f"  {tok:>9}", np.round(row, 2))

Running it prints:

output shape: (4, 8)
        the [0.57 0.   0.43 0.01]
       bank [1. 0. 0. 0.]
   approved [0.17 0.36 0.46 0.01]
         it [0.05 0.35 0.04 0.56]

Each row shows how much one token attends to each of the four tokens, and every row adds up to 1. Because the weight matrices here are random rather than trained, these particular patterns mean nothing linguistically. In a trained model, these weights are exactly what learns that "it" should look at "bank" or "loan". The output keeps the same shape as the input — four tokens, eight numbers each — but every token's vector now contains information gathered from the others.

The main types of attention

Self-attention

Queries, keys and values all come from the same sequence, so every token looks at every other token in its own sentence. This is how a transformer builds context-aware meanings: the vector for "bank" ends up different in "river bank" and "bank loan".

Cross-attention

Queries come from one sequence and keys and values from another. In translation, each word being generated (the query) attends to the source sentence (keys and values). The same idea connects text to images in image-generation models, and a spoken-audio encoding to the text being transcribed in speech recognition.

Masked (causal) attention

When a model generates text one token at a time, it must not peek at future tokens during training. A causal mask blocks every position after the current one. Adding a mask to the example above:

causal = np.tril(np.ones((4, 4), dtype=bool))   # lower-triangular: only self and earlier tokens
_, w_causal = scaled_dot_product_attention(Q, K, V, mask=causal)
        the [1. 0. 0. 0.]
       bank [1. 0. 0. 0.]
   approved [0.17 0.36 0.47 0.  ]
         it [0.05 0.35 0.04 0.56]

Now the first token can only attend to itself, and no token puts weight on anything after it. Every GPT-style model — including the chat assistants you use — relies on this mask.

Multi-head attention

One attention pattern can capture only one kind of relationship at a time. Transformers therefore run several attention heads in parallel, each with its own Q, K and V matrices, then combine their outputs. In trained models, different heads tend to specialise — some track nearby words, some link pronouns to nouns, some follow syntax. It is like having several readers each looking for something different in the same text.

Positional information

Attention on its own treats input as an unordered set: "dog bites man" and "man bites dog" would look the same. Transformers fix this by adding positional encodings to the embeddings (fixed sine waves in the original paper; learned or rotary position embeddings in many modern models), so word order is part of what attention sees.

Where attention is used

AreaWhat attention doesExamples
Chat assistants and LLMsCausal self-attention over the conversation and documentsChatGPT, Claude, Gemini, Llama
Machine translationCross-attention aligns target words with source wordsGoogle Translate, DeepL, Nepali–English translators
Search and retrievalBuilds context-aware embeddings for semantic search and re-rankingWeb search, RAG systems, e-commerce search
Summarisation and document Q&ARelates questions to the right passages in long textsContract review, policy assistants, meeting notes
Speech recognitionText output attends to audio featuresWhisper, voice assistants, call-centre transcription
Computer visionImage patches attend to each other (Vision Transformers)Document and ID scanning, medical imaging, quality inspection
Image and video generationCross-attention connects the text prompt to image regionsText-to-image and text-to-video models
Code assistantsLinks a function call to its definition far away in the fileCoding copilots, code review tools
Recommendations and time seriesWeights relevant past events in a user's history or a signalProduct and content recommenders, demand forecasting
ScienceRelates distant elements of a sequence or structureProtein-structure prediction, genomics

A banking and fintech example

Imagine a support system for a bank or wallet in Nepal. A customer writes: "I sent Rs 5,000 to my brother yesterday from the app, the money left my account, but he says he hasn't received it." An attention-based model:

  • connects "it" and "the money" back to "Rs 5,000";
  • links "he" to "my brother" and "hasn't received" to the transfer;
  • classifies the case as a failed or pending transfer rather than a login or balance question, and extracts the amount and date;
  • in a RAG setup, attends to the paragraph of the bank's policy about pending transfers to draft an accurate reply.

Older keyword rules would see "account" and "app" and might route the message to the wrong team. Attention lets the system understand the whole sentence, not just its words.

Benefits of attention

  1. Long-range understanding. Any token can connect to any other token in one step, however far apart they are. Information no longer has to survive a long chain, so models handle long sentences, documents and code far better.
  2. Parallel training. RNNs process one step after another. Attention compares all positions at once with matrix multiplication, which GPUs do extremely fast. This is the practical reason today's large models could be trained at all.
  3. Context-aware meaning. The same word gets different representations in different contexts ("bank" by a river vs. a bank loan), which improves search, classification and translation.
  4. Flexibility across data types. The mechanism doesn't care whether tokens are words, image patches, audio frames, table cells or amino acids. One architecture now serves text, vision, speech and multimodal models.
  5. Transfer learning. Attention-based models pre-trained on huge datasets learn general knowledge that transfers to new tasks with little data. You can fine-tune or prompt instead of starting from scratch.
  6. Partial interpretability. Attention weights can be visualised to see which inputs a model focused on. They are not a complete explanation of a decision, but they are a useful debugging signal — for example, checking whether a complaint classifier is looking at the complaint or at a polite greeting.
  7. Better results on hard tasks. Translation, summarisation, question answering and code generation all improved sharply once attention-based models replaced earlier approaches.

Limitations to know

  • Quadratic cost. Every token compares itself with every other token, so compute and memory grow with the square of the input length. Doubling a document's length roughly quadruples the attention cost, which is why long context windows are expensive.
  • Data and compute hungry. Training attention-based models from scratch needs very large datasets and GPUs. Most teams should fine-tune or use existing models.
  • Attention is not full explanation. High attention weight doesn't prove a token caused the output. Use proper explainability methods for regulated decisions such as lending.
  • Position needs help. Without positional encodings, word order is lost; how well a model handles very long positions depends on the encoding it uses.
  • Language coverage. Models are only as good as their training data. For lower-resource languages like Nepali, test carefully — see NLP for the Nepali language.

How engineers are making attention cheaper

  • Memory-efficient kernels such as FlashAttention compute exactly the same result while moving far less data through GPU memory, making long inputs much faster.
  • Sparse and local attention lets each token attend only to a window of nearby tokens plus a few global ones, instead of everything.
  • Grouped-query and multi-query attention share key and value heads across query heads, which shrinks memory use during text generation.
  • KV caching stores keys and values of earlier tokens during generation so they aren't recomputed for every new word.
  • Retrieval (RAG) avoids stuffing whole document collections into the context: retrieve the few relevant passages, then attend over those.

Using attention in your own projects

You rarely implement attention by hand outside of learning. In practice:

  • For text classification, search or extraction: fine-tune a pre-trained encoder such as BERT or a multilingual model like XLM-R with the Hugging Face transformers library.
  • For chat, drafting and document Q&A: use an LLM through an API or a local model, combined with good prompts and retrieval.
  • For custom models: PyTorch provides torch.nn.MultiheadAttention and torch.nn.functional.scaled_dot_product_attention, which use optimised kernels where available.
  • For structured tabular data: attention is usually not the first tool — gradient-boosted trees are faster, cheaper and easier to explain.

Implementing the NumPy version above once, though, is the best way to make the idea stick. Try changing the number of tokens, printing the scores before the softmax, or adding a second head.

Summary

Attention answers one simple question for every piece of input: what else here should I pay attention to? By scoring queries against keys and blending values, it gives models direct access to context anywhere in the input, trains efficiently in parallel, and works across text, images, audio and more. That single idea is the engine behind transformers and today's AI assistants. Its cost grows quickly with input length, which is why so much current engineering goes into making it faster — but the core formula has stayed the same since 2017.

Spotted an error or have a question about this article? Send me a message — corrections are applied and noted with an updated date. See the editorial policy.

Keep reading

More articles you may find useful.

All articles