Architecture · Foundations
How GPT-Style Language Models Work: The Transformer Architecture
The short answer
Models like GPT, Claude and Gemini are decoder-only transformers. Text is split into tokens, each token becomes a vector, and a deep stack of identical blocks lets every token gather information from the tokens before it through self-attention, then transform it with a feed-forward network. The final layer scores every possible next token; the model picks one, appends it, and repeats.
By Maitreya Kulkarni · Updated · 12 min read
01 · The architecture
What Is Inside A Decoder-Only Transformer?
A pipeline that runs once per generated token. The prompt is tokenised and embedded, flows through a stack of blocks that each apply masked self-attention and a feed-forward network, and comes out as a probability for every token in the vocabulary. The chosen token is appended to the input and the loop runs again.
NX-AR-01 · Architecture
Inside a decoder-only transformer
- Outside world
- Data & integration
- AI agent
- System of record
- L1
Input
(Outside world)Prompt
“Write a haiku about rain”
. Hands work to: Tokenizer.
Passes down: text - L2
Tokenise
(Data & integration)Tokenizer
Text → sub-word token IDs (BPE)
. Hands work to: Token embeddings, Positions.
Passes down: token IDs - L3
Embed
(Data & integration)Token embeddings
Each ID → a learned vector
. Hands work to: Masked self-attention.Positions
Rotary position encoding
. Hands work to: Masked self-attention.
Passes down: vectors - L4
Attention
(AI agent)Masked self-attention
Each token reads earlier tokens
. Hands work to: Feed-forward network.KV cache
Past keys and values, reused
. Hands work to: Feed-forward network.
Passes down: context-mixed vectors - L5
Feed-forward
(AI agent)Feed-forward network
Dense MLP or mixture of experts
. Hands work to: Vocabulary scores.
Passes down: final hidden state - L6
Output
(System of record)Vocabulary scores
Linear layer + softmax
Sampling
Temperature, top-p
Next token
Appended to the input
. Hands work to: Token embeddings.
02 · Tokens
What Is A Token, And Why Does It Matter?
A token is the unit a model reads and writes: usually a word or a piece of one. Everything about a model's limits and costs is counted in tokens, so understanding them explains a lot of model behaviour.
Sub-word tokenisation
Byte-pair encoding splits text into frequent fragments, so common words are one token and rare ones several. Roughly, an English word averages a little over one token.
The context window
The maximum number of tokens the model can attend to at once: the prompt, any documents and the reply together.
Cost and speed
APIs charge per input and output token, and generation time grows with output length, which is why concise prompts and outputs matter.
Odd behaviour explained
Models struggle to count letters or reverse words because they see tokens, not characters.
03 · Self-attention
What Does Self-Attention Actually Do?
It lets every token decide which earlier tokens matter to it and pull in their information. Each token produces a query, and every token offers a key and a value; the query is compared with all the keys, and the values are blended in proportion to how well they match.
Queries, keys and values
Three learned projections of each token's vector. Attention weights come from query–key similarity; the output is a weighted sum of values.
Many heads
Multi-head attention runs this in parallel with different projections, so different heads can track syntax, references or facts.
The causal mask
In a decoder, a token may only attend to tokens before it, which is what lets the model be trained to predict the next one.
Long contexts
Rotary position encodings, grouped-query attention and other refinements keep attention accurate and affordable over very long inputs.
04 · Training
How Is A Model Like GPT Trained?
In stages. Pre-training teaches the model language and knowledge by predicting the next token across a huge corpus. Post-training then turns that raw predictor into a helpful assistant, with supervised examples and reinforcement learning from feedback.
Pre-training
Next-token prediction over trillions of tokens of text and code. This is where almost all of the compute, and the model's knowledge, comes from.
Supervised fine-tuning
Training on curated instruction–response pairs, so the model follows instructions rather than just continuing text.
Preference tuning
Reinforcement learning from human or AI feedback (RLHF, RLAIF) or direct preference optimisation shapes tone, helpfulness and safety.
Reasoning training
Reinforcement learning on tasks with checkable answers, such as maths and code, teaches models to think step by step before answering.
05 · Inference
What Happens When You Send A Prompt?
Two phases. In prefill, the model processes the whole prompt in parallel and caches its keys and values. In decode, it generates one token at a time, each step reusing the cache, until it emits a stop token or hits a limit.
Prefill and decode
Prefill is compute-bound and fast per token; decode is memory-bound and sets the speed you see as tokens per second.
Sampling
Temperature and top-p decide how adventurous the choice of next token is: low for extraction, higher for creative work.
Speed tricks
Speculative decoding drafts several tokens with a small model and verifies them in one pass of the large one.
Mixture of experts
Many frontier models route each token through a few of many expert networks, adding capacity without running every parameter every time.
06 · For builders
What Does This Mean For Building AI Products?
That a model only knows what is in its weights and its context window. Good AI products are mostly about putting the right information in front of the model, constraining what it can do, and measuring the result.
| Property | Consequence | What we do about it |
|---|---|---|
| Knowledge is frozen at training | ConsequenceIt doesn't know your data or recent events | What we do about itRetrieval over your sources (RAG) |
| Output is sampled | ConsequenceAnswers vary and can be wrong | What we do about itStructured outputs, validation, evals |
| Context is finite and priced | ConsequenceLong prompts are slow and costly | What we do about itContext engineering, caching, small models for easy steps |
| It predicts text, not actions | ConsequenceIt can't act on its own | What we do about itTools and agents with permissions |
The ecosystem
OpenAI
Claude
Gemini
Llama
Mistral
Hugging Face
PyTorch
NVIDIA
Sources and further reading
- [1]Vaswani et al., Attention Is All You Need (2017)
- [2]Radford et al., Language Models are Unsupervised Multitask Learners (GPT-2, 2019)
- [3]Brown et al., Language Models are Few-Shot Learners (GPT-3, 2020)
- [4]Ouyang et al., Training language models to follow instructions with human feedback (2022)
- [5]Su et al., RoFormer: Rotary Position Embedding (2021)
- [6]Jay Alammar, The Illustrated Transformer


