Transformer Architecture and Attention Explained

How transformers and self-attention work, explained without heavy maths, with a NumPy attention example.

Last Updated:

Module 2 · Lesson 1 of 5 · Beginner

Transformer Architecture and Attention Explained

How transformers and self-attention work, explained without heavy maths, with a NumPy attention example.

Almost every modern language model and embedding model is a transformer, the neural network architecture introduced in the 2017 paper Attention Is All You Need by Vaswani and colleagues. You do not need to build transformers to build RAG systems, but understanding them explains context windows, token limits, why embeddings capture meaning, and why long prompts cost more. This lesson explains the architecture without heavy mathematics, with a small NumPy example of attention.

What you will learn

  • The main parts of a transformer: embeddings, attention, feed-forward layers
  • How self-attention lets each token use information from other tokens
  • The difference between encoder, decoder and encoder-decoder models
  • What this means for RAG: context windows, cost and embeddings

Prerequisites

The big picture

  1. Tokenise the text into tokens.
  2. Embed each token as a vector, and add information about its position.
  3. Pass the vectors through a stack of identical transformer blocks. Each block has:
    • a self-attention layer, where every token gathers information from other tokens, and
    • a feed-forward layer, which transforms each token's vector on its own.
  4. The final vectors are used for the task: predicting the next token (LLMs) or summarising the meaning of the text (embedding models).

Large models stack dozens of blocks; each block refines the token vectors with more context and more abstract features.

Self-attention, intuitively

In "The bank raised the interest rate", the meaning of "bank" depends on "interest rate". Self-attention lets the vector for "bank" look at all other tokens and pull in information from the relevant ones. Each token produces three vectors:

  • a query: what am I looking for?
  • a key: what do I contain?
  • a value: what information do I pass on?

The attention score between two tokens is the dot product of one token's query with the other's key. Scores are turned into weights with softmax, and each token's new vector is the weighted sum of all value vectors.

Attention in 15 lines of NumPy

attention_demo.py
import numpy as np

rng = np.random.default_rng(0)
tokens = ["the", "bank", "raised", "interest", "rates"]
d = 8                                        # vector size (real models use thousands)
X = rng.standard_normal((len(tokens), d))    # token embeddings (normally learned)

Wq, Wk, Wv = (rng.standard_normal((d, d)) for _ in range(3))   # learned in a real model
Q, K, V = X @ Wq, X @ Wk, X @ Wv

scores = Q @ K.T / np.sqrt(d)                # scaled dot-product attention
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)   # softmax: each row sums to 1
output = weights @ V                         # each token: weighted mix of all values

print("attention of 'bank' over the tokens:")
for tok, w in zip(tokens, weights[1]):
    print(f"  {tok:9} {w:.2f}")
attention of 'bank' over the tokens:
  the       0.05
  bank      0.12
  raised    0.31
  interest  0.38
  rates     0.14

With random weights the numbers are arbitrary; in a trained model, the learned matrices make "bank" attend to words that disambiguate it. Real transformers run many attention heads in parallel, each learning different relationships (syntax, coreference, topic).

Encoders, decoders and both

TypeAttentionUsed forExamples
Encoder-onlyEach token sees all tokensUnderstanding: embeddings, classification, rerankingBERT, embedding models such as BGE and E5, cross-encoders
Decoder-onlyEach token sees only earlier tokensGenerating text token by tokenGPT, Claude, Llama, Qwen, Mistral
Encoder-decoderEncoder reads input, decoder generates outputTranslation, summarisationT5, BART

In a RAG system, you typically use encoder models to embed and rerank, and a decoder model to write the answer.

Why this matters for RAG

  • Context windows: attention compares tokens with each other, so the cost of processing grows with input length. Models are trained for a maximum length: the context window.
  • Long prompts cost more and take longer: every retrieved chunk adds tokens that must be processed (and billed).
  • Embeddings capture context: because of attention, a token's vector depends on its neighbours, which is why sentence embeddings represent meaning, not just words.
  • Embedding input limits: many encoder models accept 512 tokens; longer text is truncated (Token-Based Chunking).
  • Positional effects: models do not use all positions equally well, one cause of the "lost in the middle" effect (Lost in the Middle).

Key takeaways

  • Transformers process token vectors through stacked attention and feed-forward layers.
  • Self-attention lets each token weigh and combine information from other tokens using queries, keys and values.
  • Encoder models embed and rerank; decoder models generate text.
  • Attention explains context windows, prompt costs and why embeddings capture meaning.

Frequently asked questions

Do I need to understand the maths to build RAG?

No. The intuition in this lesson is enough to make good engineering decisions.

Are all LLMs transformers?

Nearly all major ones are transformer-based, sometimes with variations such as mixture-of-experts layers or alternative attention schemes for long contexts.

Practice exercises

  1. Change the demo so token 3 attends only to earlier tokens (a causal mask, as in decoder models).
  2. Count the tokens of a typical RAG prompt and estimate how much of it is retrieved context.

Related tutorials