AI basics › How LLMs work
What is a transformer? How the model behind LLMs works
What a transformer is, how self-attention lets tokens borrow meaning from one another, how BERT and GPT differ, and where it falls short, with code I ran.
If you’ve looked into how ChatGPT and other AI chatbots work, the word transformer has probably come up within the first few paragraphs. It hides in model names too, and the T in BERT stands for Transformers. Yet the explanation often stops at “the architecture behind LLMs,” which may leave you without a clear picture of what it actually does.
A transformer is a neural network architecture that researchers at Google introduced in 2017, in a paper called Attention Is All You Need. At its center is self-attention, a way for each token in a sentence to decide how much to draw on each of the other tokens and blend their information into its own. A token is the small piece of text a model reads, often a word or part of one. The design was first made for translation, yet today many large language models (LLMs) are built on it. OpenAI, for one, describes GPT-4 in its technical report as a Transformer-based model pre-trained to predict the next token. That’s why the word comes up almost every time LLMs do.
Self-attention, or tokens looking at each other
In the sentence “The animal didn’t cross the street because it was too tired,” the word “it” means the tired animal. Change “tired” to “wide,” though, and the sentence is now about a street that was too wide, so “it” points to the street instead. Google used this very pair of sentences in its 2017 post introducing the transformer. It explained that when the model processes “it,” attention picks out both nouns, and how much goes to each changes with the answer the model chose in each sentence.
Self-attention is what does that work. At every layer, each token gives every token, itself included, a score for how relevant it is. It turns those scores into weights that add up to 1, then mixes the information of all the tokens in those proportions to form its new representation. So after attention, the vector for “it” carries part of the meaning of “animal.” A vector here is the list of numbers a model uses to hold a token’s meaning, also called an embedding.
Query, key, and value
To produce those scores, each token needs three vectors called the query, the key, and the value. Think of a search. The query is what you type, the key is the label on each document, and the value is the content of the document you find. So a token’s query describes what it’s looking for, its key describes what it can offer, and its value is the information it actually hands to other tokens. All three are made by multiplying the token’s embedding by three different weight matrices, and those weights are what the model learns in training.
The calculation then takes three steps. First, it takes the dot product of the query with each key, which means multiplying the numbers in matching positions and adding them up, and the result grows as the two vectors point the same way. Next, it divides those results by the square root of how many numbers each vector holds. The authors suspected that with many numbers the dot products grow too large and the learning signal becomes tiny. Finally, a function called softmax turns the scores into weights that add up to 1, and those weights mix the values. The paper calls the whole process scaled dot-product attention.
Computing attention by hand with NumPy
Let’s follow the process with NumPy. The material is a four-token phrase, a small red ball, and to keep the result easy to read, I set the vectors by hand instead of training them. The first number in each query and key means “describes something” and the second means “is a thing,” so the adjectives look for a thing and “ball” looks for words that describe it. The three numbers in each value stand for size, color, and object.
import numpy as np
tokens = ["a", "small", "red", "ball"]
# Q/K axes: [describes something, is a thing]
Q = np.array([[0, 2], [0, 2], [0, 2], [2, 0]], dtype=float) # what each token looks for
K = np.array([[0, 0], [2, 0], [2, 0], [0, 2]], dtype=float) # what each token offers
V = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=float) # [size, color, object]
def attention(Q, K, V, causal=False):
scores = Q @ K.T / np.sqrt(K.shape[1]) # how well each query matches each key
if causal: # decoder style: no looking at later tokens
scores[np.triu_indices(len(scores), k=1)] = -np.inf
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True) # softmax: each row adds up to 1
return weights, weights @ V
def show(weights):
print("query \\ key" + "".join(f"{t:>7}" for t in tokens))
for t, row in zip(tokens, weights):
print(f"{t:>11}" + "".join(f"{w:7.2f}" for w in row))
weights, out = attention(Q, K, V)
show(weights)
print("new 'ball' [size, color, object]:", out[3].round(2))
query \ key a small red ball
a 0.05 0.05 0.05 0.85
small 0.05 0.05 0.05 0.85
red 0.05 0.05 0.05 0.85
ball 0.03 0.47 0.47 0.03
new 'ball' [size, color, object]: [0.47 0.47 0.03]
Each row shows how one token splits its attention across the four tokens, and every row adds up to 1. The tokens “a,” “small,” and “red” are looking for a thing, and only the key of “ball” offers one, so all three give “ball” 0.85. Meanwhile, “ball” gives 0.47 each to “small” and “red,” and that’s how it gains the size and color information in the last line. Its own object information nearly disappeared, but a real model adds the attention output back onto the original vector through what’s called a residual connection, so the token keeps what it started with.
With causal=True, every score for a later token becomes minus infinity before softmax, so its weight is exactly 0 and no token can look ahead.
weights, out = attention(Q, K, V, causal=True)
show(weights)
query \ key a small red ball
a 1.00 0.00 0.00 0.00
small 0.50 0.50 0.00 0.00
red 0.33 0.33 0.33 0.00
ball 0.03 0.47 0.47 0.03
Now “a” sees only itself, and “small” and “red,” which can no longer see “ball,” spread their attention evenly over the tokens before them. Only “ball,” at the very end, sees the whole phrase, and this is what happens on the decoder side of a transformer.
Many heads, word order, and stacked layers
The table above is the work of a single attention head. A real model runs several heads side by side, each with its own weights, and joins their results. This is called multi-head attention, and the original paper used 8 heads. Nobody decides which relationship each head handles, though. The roles divide up on their own during training.
Attention also has a weakness, which is that it doesn’t know word order. Swap “small” and “red” in the example and the row for “ball” comes out exactly the same, because the calculation only compares vectors and never looks at positions. That’s why a transformer adds position information to the embeddings before the first layer. The original paper used a fixed pattern of sine and cosine waves, while BERT and GPT-2 learn a separate vector for each position. As a result, the lengths these two models can handle are fixed at 512 and 1,024 tokens.
And one layer is made of attention plus a small feed-forward network applied to each token separately. The original paper stacked 6 of these layers in its encoder and 6 in its decoder, while BERT-base and the smallest GPT-2 stack 12 each.
Encoder, decoder, and the BERT and GPT families
The model in the original paper had two halves. In the encoder, which reads the source sentence, every token can see every other token. The decoder, on the other hand, writes the translation one token at a time and sees only the encoder’s output and the tokens it has already written, hiding the words that come later with the mask you just saw.
In 2018 the two halves went their separate ways. Google’s BERT kept only the encoder and learned by guessing hidden words from the context on both sides. That’s why it suits understanding tasks such as classifying text or finding an answer in a passage. OpenAI’s first GPT paper kept only the decoder, training a 12-layer decoder-only transformer as a language model that predicts what comes next, and many of today’s chat models follow this line. Hugging Face’s LLM Course also notes that most modern LLMs use the decoder-only architecture, and adds that models such as T5 and BART use both halves for tasks like translation and summarization.
I wanted to see this difference in real models. So I gave the same phrase to bert-base-uncased, with about 110M parameters, and to the smallest GPT-2, with 124M, and measured the share of attention that goes to later tokens.
import torch
from transformers import AutoModel, AutoTokenizer
for name in ["google-bert/bert-base-uncased", "openai-community/gpt2"]:
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name, attn_implementation="eager")
inputs = tok("a small red ball", return_tensors="pt")
with torch.no_grad():
att = torch.cat(model(**inputs, output_attentions=True).attentions)
# att: (layers, heads, query, key); above the diagonal means "a later token"
later = att.triu(diagonal=1).sum(dim=-1).mean().item()
print(f"{name}: {att.shape[0]} layers x {att.shape[1]} heads, later-token share {later:.2f}")
google-bert/bert-base-uncased: 12 layers x 12 heads, later-token share 0.55
openai-community/gpt2: 12 layers x 12 heads, later-token share 0.00
att holds 12 layers of 12 heads each, 144 attention tables in all. In BERT, an average of 0.55 of each token’s attention goes to tokens after it, while GPT-2 puts no weight at all on a later token in any of its 144 tables. When I looked closer, though, about 0.52 of BERT’s 0.55 was going to [SEP], a special token BERT adds at the end of the sentence.
How it differs from an RNN
Before the transformer, tasks like translation mostly relied on recurrent neural networks (RNNs), and the original paper set them aside and kept only attention. An RNN reads a sentence one token at a time and passes a summary of everything so far to the next step, and the paper points out that this structure rules out parallel computation within a single training example. A transformer, by contrast, computes attention for all tokens at once, which suits GPUs that handle many calculations at the same time. Following the paper’s own comparison, here’s how the two line up.
| RNN | Transformer | |
|---|---|---|
| How it reads a sentence | One token at a time, in order | All tokens at once |
| Parallel training within a sentence | Hard | Easy |
| Two distant words | Linked through many steps | Linked in one step |
| Cost as the text gets longer | Proportional to length | Proportional to length squared |
Because any two tokens are linked directly, the paper explains, relationships between distant words become easier to learn. Still, each new token depends on the ones before it, so when writing an answer, a decoder still moves one token at a time.
Beyond text, images and more
Self-attention only needs a sequence of vectors, so its material doesn’t have to be words. The Vision Transformer (ViT), introduced by Google researchers in 2020, cuts an image into small patches, such as 16 by 16 pixels, and feeds them to a transformer as if they were tokens. The paper reports that ViT, pre-trained on large amounts of data, approached or beat the best convolutional networks of the time while needing substantially less compute to train.
When it fits and when it doesn’t
Transformers fit well when there’s plenty of data and hardware that can compute in parallel, and when distant parts of the input relate to each other. They also make it easy to pre-train one large model and adapt it to many tasks, and the BERT paper reports fine-tuning it for a wide range of tasks by adding just one output layer.
The best-known limit comes from the attention table. Since every token is compared with every token, 1,000 tokens means 1,000,000 scores per head in each layer, and doubling the length makes four times as many. The paper’s comparison also lists this cost as growing with the square of the length, and it’s a big reason long contexts are expensive. That’s why people have come up with approaches such as FlashAttention, which computes exactly the same attention with fewer reads and writes to GPU memory, and the sparse attention that the Hugging Face course above introduces.
Small datasets call for care too. The ViT paper explains that transformers lack assumptions convolutional networks hold about images, such as nearby pixels being related, so they don’t generalize well when data is scarce. In that case, fine-tuning an already trained transformer or using a simpler model may serve you better.
Where to start
If you’re new to this, I’d suggest copying the NumPy example above and changing the vectors or the order of the tokens. Once that feels familiar, you might try the same calculation with PyTorch’s scaled_dot_product_attention. When I gave it the vectors from the example, it returned the same results with is_causal both on and off. For the overall structure, you can continue with the Transformer Architectures chapter of the Hugging Face LLM Course. I ran these examples on October 27, 2026, on a Mac’s CPU with Python 3.13.12, NumPy 2.5.4, PyTorch 2.14.1, and Transformers 5.20.2.
AI tools helped with the research for this post.