Engineering notes

Attention Is All You Need: From Intuition to Implementation

A step-by-step explanation of tokens, queries, keys, values, masking, and the Transformer—with a small attention implementation you can inspect.

Mohd ShubairJanuary 28, 202610 min read

Updated

When I first encountered the Transformer, the diagram looked more complicated than the idea behind it. The useful starting question was simple: when a model processes one token, how can it decide which other tokens are relevant?

Attention gives it a learned way to combine information from different positions. The Transformer builds a sequence model around that operation, together with positional information, feed-forward layers, and connections that make a deep network trainable.

This guide moves from that intuition to a small implementation. You do not need to memorize the full architecture before understanding what happens inside one attention head.

Reading goal: explain what Q, K, and V do, trace the shape of an attention calculation, and understand why a decoder needs a causal mask.

1. The problem the paper addressed

Earlier sequence models often used recurrent networks. A recurrent layer carries state from one position to the next, which creates a dependency along the sequence. Attention already existed in sequence-to-sequence systems; the 2017 paper did not introduce the first attention mechanism.

Attention Is All You Need, by Vaswani and colleagues, introduced the Transformer architecture for sequence transduction without recurrence or convolution in its core sequence-processing blocks. The original model had an encoder and a decoder and was evaluated on tasks including machine translation.

The distinction matters: the original translation architecture and a modern decoder-only language model share important building blocks, but they are not identical systems.

Why parallelism changed training

During Transformer training, many positions can be processed together through matrix operations. A causal mask can prevent access to future targets while still allowing parallel computation over the supplied sequence.

Autoregressive generation is different. To produce a new response, a model typically generates a token, appends it, and uses that result to generate the next token. Parallel training does not mean that an entire unknown response is generated in one step.

2. Build a small vocabulary first

TermMeaning in this guide
TokenA unit produced by a tokenizer; often a word fragment, punctuation mark, or other symbol
EmbeddingA learned vector associated with a token
Hidden stateA token’s representation after processing by a layer
HeadOne attention calculation using its own projections
LogitsUnnormalized scores before a softmax
Context windowThe sequence capacity supported by a particular model and configuration

A token is not necessarily a whole word. Also, a vector’s individual coordinates do not generally correspond to simple labels such as “animal” or “past tense.” Those labels can be useful teaching analogies, but learned representations are distributed.

3. Start with token representations

Suppose a sequence contains n tokens and each representation has d_model features. We can arrange those representations in a matrix:

text
X: [n, d_model]
Each row represents one token position.
Each column is one learned feature coordinate.

The model also needs information about position. The original Transformer used sinusoidal positional encodings added to the embeddings. Other architectures use different positional methods.

The result is a representation of token content together with positional information. Attention can then use learned projections to decide how information should move between positions.

4. Queries, keys, and values

For one attention head, the model projects the input into three matrices:

text
Q = X Wq queries: [n, d_k]
K = X Wk keys: [n, d_k]
V = X Wv values: [n, d_v]

A useful interpretation is:

  • A query describes what information a position is looking for.
  • A key provides something that can be compared with that query.
  • A value contains information that can contribute to the output.

These are learned numerical projections. They are not literal search questions or database keys. Training adjusts the projection weights so that the operation becomes useful for the objective.

Compare, normalize, combine

For every query, compute a dot product with the available keys. Scale those scores by the square root of the key dimension, apply any mask, then use softmax to form weights.

text
scores = Q Kᵀ / sqrt(d_k) [n, n]
weights = softmax(scores) [n, n], normalized across keys
output = weights V [n, d_v]

Each output row is a weighted combination of value vectors. The scaling helps control the magnitude of the dot products as the dimension grows.

A numerical example

Assume one query produces two scaled scores: 2 and 1. Softmax turns them into approximately 0.731 and 0.269.

text
Scaled scores: [2, 1]
Weights: [0.731, 0.269]
Value A: [10, 0]
Value B: [0, 10]
Weighted result:
0.731 × [10, 0] + 0.269 × [0, 10] ≈ [7.31, 2.69]

These numbers are a worked example, not attention weights measured from a trained model. Their purpose is to show how a position receives a mixture of information rather than selecting exactly one other token.

5. Implement one attention calculation

The following Python example uses only the standard library. It is intentionally small and operates on lists so that the calculation stays visible. Real training uses optimized tensor operations and automatic differentiation.

python
import math
def attention(queries, keys, values, causal=False):
if not keys or len(keys) != len(values):
raise ValueError("Provide one value vector per key")
if not queries or not keys[0] or not values[0]:
raise ValueError("Vectors must not be empty")
key_dim = len(keys[0])
value_dim = len(values[0])
if any(len(row) != key_dim for row in queries + keys):
raise ValueError("Queries and keys must share a dimension")
if any(len(row) != value_dim for row in values):
raise ValueError("Value dimensions must match")
if causal and len(queries) != len(keys):
raise ValueError("This causal example expects self-attention")
outputs, all_weights = [], []
for position, query in enumerate(queries):
count = position + 1 if causal else len(keys)
scores = [
sum(q * k for q, k in zip(query, key)) / math.sqrt(key_dim)
for key in keys[:count]
]
# Subtracting the maximum makes softmax more stable.
exponentials = [math.exp(score - max(scores)) for score in scores]
total = sum(exponentials)
weights = [value / total for value in exponentials]
output = [
sum(weight * value[column]
for weight, value in zip(weights, values[:count]))
for column in range(value_dim)
]
outputs.append(output)
all_weights.append(weights + [0.0] * (len(keys) - count))
return outputs, all_weights
q = [[1.0, 0.0], [0.0, 1.0]]
k = [[1.0, 0.0], [0.0, 1.0]]
v = [[10.0, 0.0], [0.0, 10.0]]
output, weights = attention(q, k, v, causal=True)
assert output[0] == v[0] # The first position cannot read the second.
assert weights[0][1] == 0.0
assert all(abs(sum(row) - 1.0) < 1e-9 for row in weights)
print([[round(value, 3) for value in row] for row in output])

Read the assertions before changing the example. They capture two useful invariants: forbidden positions receive zero weight, and each valid attention row sums to one.

This function does not implement learned projections, batching, padding masks, dropout, or gradients. It demonstrates the attention operation after Q, K, and V have already been constructed.

6. Why causal masking matters

In next-token training, the model must not use a token that appears after the position it is predicting from. Otherwise, training would expose information that is unavailable during generation.

text
Allowed key positions for each query position:
key 0 key 1 key 2
query 0 yes no no
query 1 yes yes no
query 2 yes yes yes

A common tensor implementation assigns forbidden score entries negative infinity before softmax. Their resulting probability is zero. Be careful with padding: a row with no allowed keys needs explicit handling, since a softmax over only negative infinities can produce invalid values.

An encoder’s self-attention can use the full available input sequence. Decoder self-attention applies a causal constraint. In an encoder–decoder model, cross-attention uses decoder queries and encoder keys and values.

7. Put attention inside a Transformer block

Attention moves information between positions. A feed-forward network then transforms the representation at each position. Residual connections provide paths around sublayers, while normalization helps manage the scale of intermediate activations.

Multi-head attention performs several attention calculations with separate projections, concatenates their results, and applies an output projection. Heads can learn different useful patterns, but it is too simplistic to label every head permanently as “grammar,” “meaning,” or “pronoun resolution.”

ArchitectureTypical information flowCommon task shape
Encoder-onlyInput positions can use the supplied contextRepresentation and classification
Decoder-onlyPositions attend under a causal constraintNext-token generation
Encoder–decoderA decoder also attends to encoded inputInput-to-output sequence tasks

Layer placement, normalization, activation functions, and positional methods vary across implementations. Learning the original block is a starting point, not a description of every model called a Transformer.

8. Understand training and inference separately

During next-token training, known token sequences supply the targets. The model predicts distributions over the vocabulary, and the training loss compares those predictions with the expected tokens. Optimization changes the model parameters.

During ordinary inference, those parameters stay fixed. The application selects tokens from the output distribution using a decoding strategy. Temperature and sampling affect selection; they do not teach the model new facts by updating its weights.

A key–value cache reuses previously computed keys and values during autoregressive decoding. This saves repeated work, while the stored cache consumes memory as the sequence grows. Retrieval, prompt history, and weight updates are separate mechanisms and should not all be described as “memory.”

9. What later improvements change

Several later techniques address different limitations. They are useful to distinguish because they do not solve the same problem.

Rotary positional embeddings

RoFormer describes rotary positional embeddings, commonly called RoPE. The method applies position-dependent rotations to representations used in attention, allowing relative position to affect their interaction. It is a positional method; it does not make arbitrary context lengths reliable by itself.

FlashAttention

FlashAttention reorganizes exact attention computation to reduce costly memory traffic. It is an implementation improvement, not a replacement of attention with a different semantic operation. It does not change standard dense attention’s quadratic pairwise computation into linear computation.

Grouped-query attention

Grouped-query attention, or GQA, lets groups of query heads share key and value heads. This reduces key–value storage relative to a corresponding multi-head setup and offers a useful inference tradeoff. The quality and speed of a complete model still depend on its architecture, training, and hardware.

10. Common misunderstandings

  • “Attention is an explanation.” Attention weights show one internal operation. They do not automatically establish why a model produced a particular answer.
  • “More context guarantees better answers.” A larger supported window provides capacity. Relevant retrieval, clear instructions, and evaluation still matter.
  • “Every modern language model uses the original architecture.” Models change blocks and may use other sequence-processing designs.
  • “A tutorial’s speedup applies to my machine.” Performance claims require a defined workload, implementation, hardware, and measurement method.

What I would learn next

First, run the small function and inspect how its weights change when you alter a query or key. Next, implement the same operation with a tensor library and compare its output on identical inputs. Then add learned projections, multiple heads, and a padding mask.

That sequence makes each abstraction earn its place. The large model becomes easier to understand once you can trace how a single position collects information from the rest of a sequence.

Further reading

Share this article

Found it useful? Sharing helps others discover it too.

Code blocks and navigation by Rare UI.