AI & prompting

What Is a Transformer Model? Attention Explained With a Worked Example

A transformer model is a neural network architecture that processes a whole sequence at once and uses a mechanism called self-attention to let every token weigh how relevant every other token is to it. It was introduced in the 2017 paper "Attention Is All You Need" by eight researchers, and it is the architecture behind today's large language models, including the GPT family.

What problem the transformer solved

Before transformers, language models were mostly recurrent neural networks (RNNs). An RNN reads a sentence one word at a time and carries a running summary forward, so the 50th word can only learn about the 1st through that compressed summary, and the computation can't be parallelised across positions: step 50 has to wait for step 49.

The 2017 paper proposed an architecture "based solely on attention mechanisms", dropping recurrence entirely. Its comparison table puts numbers on the difference, for a sequence of length n and representation size d:

Layer typeWork per layerSequential steps
Self-attentionO(n² · d)O(1)
RecurrentO(n · d²)O(n)

"O(1) sequential steps" is the key line: all positions are processed in parallel, which suits GPUs. The paper's base model trained in about 12 hours on 8 NVIDIA P100 GPUs, and its larger model, trained for about 3.5 days, beat the previous best translation results, including ensembles, with 28.4 BLEU on WMT 2014 English-to-German. The cost is the n² term, which is why very long inputs are expensive; see what a context window is for the practical side of that.

How a transformer processes text, step by step

  1. Tokenise. The text is split into tokens, pieces of words with an ID each. How many tokens is a word shows real counts.
  2. Embed. Each token ID is looked up in a table that maps it to a vector of numbers (512 numbers per token in the original base model).
  3. Add position. Attention by itself has no idea of word order, so position information is added to each vector. The original paper used sine and cosine waves of different frequencies.
  4. Repeat a block N times. Each block has a self-attention layer followed by a small feed-forward network, each wrapped in a residual connection and layer normalisation. The base model stacked 6 blocks in its encoder and 6 in its decoder; modern LLMs stack many more.
  5. Predict. The final vectors are turned into a probability for every token in the vocabulary. A sampler picks the next token, which is where settings like temperature and top-p come in.

Self-attention, with numbers you can check

For each token, the model computes three vectors by multiplying its embedding by three learned weight matrices:

  • Query (Q): what this token is looking for.
  • Key (K): what this token offers to others.
  • Value (V): the information this token passes on if attended to.

The paper defines scaled dot-product attention as:

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

In words: score every pair of tokens by the dot product of one's query with the other's key, divide by the square root of the key size, turn each row of scores into weights that sum to 1 with softmax, and take the weighted average of the values.

Here is a toy example with 3 tokens and vectors of size 2 (d_k = 2, so the divisor is √2 ≈ 1.414). The vectors are made up to keep the arithmetic readable:

Token   Query    Key      Value
A       [1, 0]   [1, 0]   [10, 0]
B       [0, 1]   [0, 1]   [0, 10]
C       [1, 1]   [1, 1]   [5, 5]

For token C, the dot products of its query [1, 1] with the keys of A, B and C are 1, 1 and 2. Divided by 1.414 they become 0.707, 0.707 and 1.414. Softmax turns those into weights:

scores   [0.707, 0.707, 1.414]
weights  [0.248, 0.248, 0.503]      (they sum to 1)
output   0.248·[10,0] + 0.248·[0,10] + 0.503·[5,5] = [5.0, 5.0]

Token A, with query [1, 0], scores A and C equally (0.707 each) and B lower (0), giving weights [0.401, 0.198, 0.401] and output [6.02, 3.98]: it pulls mostly from tokens whose keys match what it's looking for. You can reproduce these figures in a few lines of Python with math.exp.

Why divide by √d_k at all? The paper explains that for large vector sizes the dot products grow large, pushing softmax into regions where its gradients are tiny and learning stalls. Scaling keeps the scores in a workable range.

In a trained model the weight matrices are learned, so attention ends up doing useful things: in "The cat sat because it was tired", the token "it" can learn to put a high weight on "cat".

Multi-head attention

One attention calculation captures one kind of relationship. Transformers run several in parallel, called heads, each with its own Q, K and V weights, and concatenate the results. The original base model used 8 heads of size 64 (8 × 64 = 512, the model width). One head might track which noun a pronoun refers to while another tracks the previous word; the model learns the split during training.

Masking: how a model generates text left to right

When a model generates text, a token must not see tokens that come after it, or training would be trivial cheating. The decoder's self-attention therefore masks out future positions by setting their scores to negative infinity before softmax, which makes their weights zero.

In the toy example, with masking token A can only attend to itself, so its output is just its own value [10, 0]. Token B sees A and B: scores [0, 0.707], weights [0.33, 0.67], output [3.3, 6.7]. Token C still sees all three.

Encoder, decoder and encoder-decoder models

The original transformer had two halves: an encoder that reads the input sentence and a decoder that writes the translation. Later models kept one half or both. Hugging Face's course groups them like this:

TypeAttentionGood forExample
Encoder-onlyEvery token sees every tokenUnderstanding input: sentence classification, named entity recognitionBERT (October 2018)
Decoder-onlyMasked, left to rightGenerating textGPT (June 2018) and today's chat LLMs
Encoder-decoderEncoder full, decoder masked plus attention to the encoderGenerating from an input: translation, summarisationT5, the original transformer

GPT-style chat models are decoder-only. They generate one token, append it to the input, and run again, which is why responses stream out word by word. Encoder-only models suit understanding tasks, such as turning text into vectors for a vector database.

What a transformer is not

A transformer doesn't look things up or store facts in a table. Everything it "knows" is spread across its learned weights, and it produces text by repeatedly predicting a likely next token. That explains both its fluency and its tendency to produce confident errors, covered in why AI hallucinates. The architecture also has no memory between requests: each call starts from the tokens it is given, and nothing else.

Frequently asked questions

Is GPT a transformer model?
Yes. Hugging Face's course describes the original GPT (June 2018) as the first pretrained transformer model and groups GPT-like models as decoder-only, auto-regressive transformers: they generate text one token at a time, each step predicting the next token from the tokens before it.
What is the difference between a transformer and a neural network?
A transformer is a kind of neural network. It is built from the same parts as other networks, such as matrix multiplications, activation functions and layer normalisation, arranged around self-attention layers. The architecture is what makes it a transformer.
Why are transformers expensive to run on long inputs?
Self-attention compares every token with every other token, so its cost per layer grows with the square of the sequence length. Doubling the input length roughly quadruples the attention work, which is one reason long context windows cost more.
Does a transformer remember previous conversations?
No. The model itself has no memory between requests. Each call processes only the tokens it is given, so chat apps resend the earlier conversation as part of the input, which is why long chats use more tokens and eventually hit the context window limit.

Sources