Review Publically — Header (standalone)
Transformers Explained: How Self-Attention Actually Works
Transformers explained: self-attention diagram
Deep Learning

Transformers Explained: How Self-Attention Actually Works

What query, key, and value actually compute, why multiple attention heads matter, and why this architecture quietly replaced RNN and LSTM everywhere it mattered

Khalid Hussain · · 14 min read · Updated 21 Sep 2026
Quick Answer

A transformer is a neural network architecture that processes an entire sequence at once using self-attention, a mechanism that lets every token directly weigh how relevant every other token is, rather than passing information step by step the way RNNs and LSTMs do. This enables both parallel training on GPUs and direct modeling of long-range dependencies, and it is the architecture behind every major large language model in use today.

If you read the RNN and LSTM guide on this site, you already know the problem transformers were built to solve: sequential models process one time step at a time, which makes them slow to train and prone to losing track of information from many steps back. Transformers solve both problems with one mechanism, self-attention. This guide breaks that mechanism down piece by piece, and includes a from-scratch implementation I built myself that computes real attention weights on a real sentence, not just a diagram of the idea.

Why Transformers Replaced RNNs and LSTMs

An RNN or LSTM processes a sequence one element at a time, carrying a hidden state forward from step to step. That sequential dependency creates two real costs. Training cannot be parallelized across time steps, since step 10 needs the output of step 9. And even with LSTM's gates, information from very early in a long sequence has to survive being passed through dozens or hundreds of intermediate steps to influence a later prediction.

Transformers, introduced by Vaswani et al. in the 2017 paper titled, appropriately, "Attention Is All You Need," remove the sequential dependency entirely [1]. Every token attends to every other token in a single parallel computation. Two tokens 500 words apart interact just as directly as two tokens next to each other, and the entire sequence can be processed simultaneously on a GPU instead of one step at a time.

In Practice

This is not a minor speed optimization. Parallel training across the full sequence is what made it practical to train models on the scale of modern large language models. A sequential architecture processing that much text one token at a time would take an impractical amount of time to train even with the same hardware.

What Is Self-Attention?

Self-attention is the calculation at the center of a transformer. For every token in a sequence, it asks: which other tokens in this same sequence are relevant to understanding this one, and how should information from those tokens be blended in?

Take the sentence "the cat sat on the mat because it was tired." A reader instantly knows "it" refers to "cat," not "mat." Self-attention gives a model a mechanical way to arrive at the same conclusion: when processing the token "it," the mechanism computes a relevance score against every other token in the sentence, and "cat" should end up with a high score if the model has learned what pronouns typically refer to.

Self-attention does not read a sentence left to right and hope earlier context survives. It lets every word look directly at every other word at once and decide for itself what matters.

Query, Key, and Value Explained

The actual computation behind self-attention is built from three vectors derived from each token's embedding, generally referred to by the same names used in a search or lookup system. Like any other neural network layer, this whole calculation is a single step in a larger forward propagation pass, it takes an input, applies a series of matrix operations, and hands the result to the next layer.

Q
QueryWhat this token is looking for. Computed by multiplying the token's embedding by a learned weight matrix, Wq.
K
KeyWhat this token offers to others, used to match against every other token's query. Computed the same way with a separate learned matrix, Wk.
V
ValueThe actual content this token contributes once it is deemed relevant, computed with a third learned matrix, Wv.

The attention weight between two tokens comes from the dot product of one token's query with another token's key, scaled down by the square root of the key dimension to keep the numbers stable, then passed through softmax so all the weights for a given token sum to 1. Those weights are then used to compute a weighted sum of every token's value vector, producing the output for that position.

Q = X @ Wq K = X @ Wk V = X @ Wv scores = (Q @ K.T) / sqrt(d_k) # scaled dot-product weights = softmax(scores) # rows sum to 1 output = weights @ V # weighted blend of values

This is the entire mechanism. Everything else in a transformer, multi-head attention, positional encoding, layer normalization, feedforward layers, exists to make this core calculation more expressive or to stack it into a deep network. Those feedforward layers rely on their own non-linear activation function, typically GELU rather than the classic ReLU, covered in depth in Activation Functions Explained.

Multi-Head Attention: Why One Attention Pattern Isn't Enough

A single attention calculation can only learn one type of relationship between tokens at a time. Real language has multiple overlapping relationships in the same sentence at once: grammatical structure, pronoun reference, subject-verb agreement, topical relevance. Multi-head attention runs several independent attention calculations in parallel, each with its own Wq, Wk, and Wv matrices, then concatenates the results and projects them back down to the model's working dimension.

Each head is free to specialize in a different pattern during training. In a fully trained large model, research on attention visualization has found heads that specialize in tracking syntactic dependencies, others that track coreference, and others that appear to track less interpretable statistical patterns.

Positional Encoding: Giving Attention a Sense of Order

Self-attention has a structural blind spot: comparing every token to every other token simultaneously means the calculation itself has no inherent notion of which token came first. Shuffle the words in a sentence and, without any additional information, self-attention would treat it identically.

The original transformer solves this by adding a positional encoding vector to each token's embedding before the first attention layer, built from sine and cosine functions at different frequencies for each dimension. Nearby positions end up with similar encodings and distant positions end up with different ones, giving the model a consistent, learnable signal for relative and absolute position without requiring the sequential processing that made RNNs slow.

Why Sine and Cosine Specifically

Sinusoidal functions were chosen because they let the model generalize to sequence lengths it has not seen during training and because the encoding for any position can be expressed as a linear function of the encoding for a nearby position, which makes relative position easy for the model to learn to use.

Encoder-Only vs. Decoder-Only: BERT vs. GPT

AspectEncoder-Only (BERT-style)Decoder-Only (GPT-style)
Attention directionUnrestricted, sees the full sequence both directionsMasked, each position only sees earlier positions
Training objectivePredict masked tokens using full contextPredict the next token from what came before
Best forClassification, question answering, embeddingsText generation, chat, autoregressive tasks
ExamplesBERT and its derivativesGPT-family and most modern chat-oriented LLMs

The original 2017 transformer paper actually used both an encoder and a decoder together for machine translation. Most of the architectures people encounter day to day now pick one side or the other, encoder-only for understanding tasks, decoder-only for generation, depending on what the task needs.

Real-World Applications of Transformers

  • Large language models: the architecture behind every major chat and text-generation model in production today
  • Machine translation: the original use case the architecture was designed for
  • Text classification and question answering: encoder-only models like BERT variants remain a strong default
  • Computer vision: Vision Transformers (ViT) apply the same self-attention mechanism to image patches instead of words
  • Protein structure prediction and scientific modeling: attention over sequences generalizes well beyond natural language

Building Self-Attention From Scratch: What the Numbers Actually Show

Most explanations of self-attention, including good ones, describe query, key, and value conceptually and stop there. Very few show the mechanism actually computed on a real example with real numbers. So before writing this article, I implemented scaled dot-product attention, multi-head attention, and sinusoidal positional encoding entirely in NumPy, then ran it on a real sentence.

Self-Attention From Scratch (NumPy)
View on GitHub →

Sentence: "the cat sat on the mat because it was tired." The question: when the model processes the word "it," does the attention mechanism correctly identify "cat" as the most relevant token?

Methodology, Disclosed Honestly

This demo has no training corpus, so the embeddings for "it" and "cat" were deliberately constructed to be similar, the way a trained embedding layer would eventually learn from real co-occurrence patterns. Every attention weight computed after that point is real, nothing in the softmax or attention math is hand-set to force the result.

0.1884
Attention weight: "it" → "cat" (highest in row)
2 heads
Produced visibly different attention patterns
10 tokens
Full sentence processed in parallel
Self-attention weights for every token pair in the sentence, computed from the from-scratch implementation
Self-attention weights for every token pair in the sentence, computed from the from-scratch implementation
The same input processed by two separate attention heads, producing two different weight distributions
The same input processed by two separate attention heads, producing two different weight distributions
Positional encoding values across all 10 token positions and 8 embedding dimensions
Positional encoding values across all 10 token positions and 8 embedding dimensions

The result: "it" attends to "cat" with a weight of 0.1884, the highest weight in that row, out of ten tokens including "it" itself. Watching that number come out of an actual matrix multiplication, rather than reading that transformers "can resolve pronoun references," made the mechanism concrete in a way no diagram had for me.

The two-head comparison was equally instructive. With identical input, the two heads produced clearly different weight distributions purely from having separate random Wq, Wk, and Wv matrices, which is the mechanical reason multiple heads can specialize in different relationship types once trained on real data.

Conclusion: One Mechanism, Most of Modern AI

Self-attention is a comparatively simple calculation, a scaled dot product and a softmax, and yet stacking it into multiple heads and multiple layers produced the architecture behind nearly every major AI system built since 2018. Understanding query, key, and value as real matrix operations, not just a search-engine metaphor, is what makes it possible to reason about why transformers behave the way they do, rather than treating them as an unexplainable black box.

If you have not already, the RNN and LSTM guide on this site is the natural companion piece, since it covers exactly the sequential limitations that self-attention was built to remove.

Frequently Asked Questions

What is a transformer model in simple terms?

A transformer is a neural network architecture that processes sequences, like sentences, by letting every element look directly at every other element at once through a mechanism called self-attention, instead of processing them one step at a time the way older RNN and LSTM networks did.

What is self-attention?

Self-attention is a calculation that lets every token in a sequence weigh how relevant every other token is to understanding it, then blends information from the most relevant tokens into its own representation. It is called self-attention because the queries, keys, and values all come from the same input sequence.

What are query, key, and value in attention?

Query, key, and value are three vectors computed from each token's embedding. The query represents what a token is looking for, the key represents what a token offers to others, and the value represents the actual content a token contributes once it is deemed relevant.

Why do transformers use multiple attention heads?

A single attention head can only learn one type of relationship pattern between tokens. Running several attention heads in parallel, each with its own learned projections, lets the model capture multiple kinds of relationships at once and combine all of them into a richer representation.

What is positional encoding and why is it needed?

Self-attention has no built-in sense of word order, since it compares every token to every other token simultaneously. Positional encoding adds a pattern of values, typically based on sine and cosine functions, to each token's embedding so the model can distinguish position 1 from position 5.

What is the difference between BERT and GPT?

BERT is an encoder-only transformer that looks at an entire sequence at once in both directions, strong for understanding tasks. GPT is a decoder-only transformer that predicts the next token using only earlier tokens, suited to generating text.

Why did transformers replace RNNs and LSTMs?

RNNs and LSTMs process a sequence one time step at a time, which limits training speed and makes long-range dependencies harder to learn. Transformers process an entire sequence in parallel through self-attention, which trains faster and lets any two tokens interact directly regardless of distance.

What is the difference between encoder-only and decoder-only transformers?

An encoder-only transformer processes the full input at once with unrestricted attention in both directions, suited to understanding tasks. A decoder-only transformer uses masked attention so each position can only attend to earlier positions, suited to generating text autoregressively.

Are transformers used in image models too?

Yes. Vision Transformers (ViT) apply the same self-attention mechanism to images by splitting an image into fixed-size patches and treating each patch like a token in a sequence, which has proven competitive with convolutional neural networks on many benchmarks.

References
  1. Vaswani, A. et al. (2017). Attention Is All You Need. NeurIPS.
  2. IBM. What Is a Transformer Model?
  3. Devlin, J. et al. (2018). BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. arXiv.
  4. Dosovitskiy, A. et al. (2020). An Image Is Worth 16x16 Words: Transformers for Image Recognition at Scale (Vision Transformer). arXiv.
  5. Review Publically (2026). RNN vs LSTM Explained: How Neural Networks Learn Sequences.
  6. Review Publically (2026). Self-Attention From Scratch, Built With NumPy (GitHub).

Khalid Hussain

Founder of Review Publically. MSc in Computer Science, Google Advanced Data Analytics certified. Hands-on with Python, Pandas, NumPy, Seaborn, and Scikit-learn, including building models from scratch to understand them beyond the library level.

Founder, Review Publically MSc Computer Science