Inside the transformer
The tokenizer hands the model a list of numbers (Module 01a). What happens next produces one new token, every time, and then starts again. This module opens the box: what parameters and weights are, how a token ID becomes a vector, how attention lets each token look at the others, how the model picks the next token, how many times it loops, and how the weights are stored and served. The example throughout is OpenAI's open-weight gpt-oss-120b, because its design is published, so every number here can be checked.
- Sam Once the tokenizer hands the model a list of numbers, what actually happens inside?
- Priya The model runs those numbers through a fixed network and produces one new token. Then it appends that token and runs again. We'll use OpenAI's open-weight gpt-oss-120b as the example, because its design is published, so every number can be checked.
- Priya Picture a giant mixing desk with billions of knobs. During training, every knob is nudged until the desk turns any input into a good guess of what comes next. Then the knobs are glued in place. Every request flows through the same fixed desk; nothing is learned while you chat.
- Sam So the knobs are the parameters?
- Priya Yes, the parameters, also called weights: the numbers learned in training. gpt-oss-120b has 117 billion of them, but only 5.1 billion are used for each token. It has 36 layers, represents each token as 2,880 numbers, and has a vocabulary of 201,088 tokens.
- Sam Walk me through one pass.
- Priya Look up: each token ID picks one row of the embedding table, a vector of 2,880 numbers. Look back: attention lets each token gather information from earlier ones. Think: a router sends each token to 4 of 128 expert networks. That pair, attention then experts, repeats 36 times. Score: the last vector becomes a score, a logit, for every one of the 201,088 tokens. Pick: softmax turns scores into probabilities, temperature and top-p shape them, and one token is sampled.
- Sam How does attention know that "it" means "order"?
- Priya Each token gets a query, a key and a value from learned matrices. The score between two tokens is one's query times the other's key. After softmax, "it" puts most of its weight on "order", and its new vector mixes in that token's value. A mask stops it looking at future tokens, and 64 heads look for different kinds of link at once.
- Priya Your turn. To write a 300-token answer, how many times does the model run?
- Priya About 300 forward passes, one per output token, plus one parallel pass over the prompt. It doesn't search for the best answer; it commits to one token at a time.
- Sam Then how does it ever stop?
- Priya When it samples a stop token, like call for a tool or return for a finished answer, or when it hits your max tokens limit. A reasoning model runs the same loop but writes thinking tokens first, so higher effort means more passes. And an agent wraps another loop around it: tool call, your app runs the tool, the result goes back in, and the model runs again.
- Sam What can I try?
- Priya A sampling playground: five made-up scores for the next word after "Your order is". Move temperature and top-p and watch the probabilities change, then sample ten times. And a memory calculator: pick gpt-oss-120b or 20b and a precision, and see the memory for the weights and for the KV cache across many conversations.
- Sam Why does this matter at work?
- Priya Output tokens cost more and take longer than input, because input is read in one parallel pass but output is one pass per token. Mixture-of-experts models are cheaper to run than their size suggests. Every token in every conversation needs KV-cache memory, which limits long contexts and many users. The model doesn't learn from your chats. And quantization, storing weights in fewer bits, is how gpt-oss-120b fits on one 80 gigabyte GPU.
- Sam And how are the weights stored and served?
- Priya As tensors in safetensors files, safe to load and fast. They're loaded onto GPUs, and a server like vLLM batches users and manages the KV cache in pages; its authors report two to four times higher throughput.
- Sam Which tools are involved?
- Priya PyTorch to define and run the network, with optimised kernels like Triton. safetensors files, in BF16 or 4-bit precision. Hugging Face Transformers to load a model and generate. vLLM to serve it. Ollama or LM Studio to run it locally; gpt-oss-20b fits in sixteen gigabytes. Or a provider's API, where all of this happens on their servers.
- Sam The memory hook?
- Priya Look up, look back, think, score, pick, repeat.
- Sam Common mistakes?
- Priya Believing the model learns from your chats. Believing it searches for the best answer. Judging a model by total parameters. Forgetting KV-cache memory. And expecting temperature zero to be perfectly repeatable.
- Sam And the lab?
- Priya Read a real model's config and find its layers, width, heads and vocabulary. Calculate its memory. Run a small open model locally and measure time to first token and tokens per second. Compare a long prompt with a long answer. And run the sampling function at different temperatures.
1. The idea
Parameters are those knobs: the numbers the model learned in training. People say weights for the same thing (strictly, weights are the multipliers inside the parameter matrices, and biases are the smaller rest). Hyperparameters are design choices fixed before training: how many layers, how wide each vector is, how many attention heads. gpt-oss-120b, from its model card:
| Quantity | gpt-oss-120b | What it means |
|---|---|---|
| Parameters | 117 billion in total; 5.1 billion used per token | Mixture of experts: each token only passes through a few of the experts (below) |
| Layers | 36 | Each token's vector is refined 36 times on its way through |
| Width (residual stream) | 2,880 numbers per token | Every token is represented as a vector of 2,880 numbers inside the model |
| Attention | 64 query heads per layer, sharing 8 key/value heads | 64 different ways of "looking back"; sharing keys and values saves memory |
| Experts | 128 per layer; the top 4 are used for each token | Specialised sub-networks; a router picks which ones each token needs |
| Vocabulary | 201,088 tokens | So the embedding table is 201,088 × 2,880 ≈ 579 million numbers (calculated) |
| Context | 131,072 tokens | The most tokens it can attend to at once (Module 02) |
The design is the transformer, introduced in 2017 in "Attention Is All You Need" by Vaswani and colleagues at Google: a network "based solely on attention mechanisms", which is what lets it learn from huge amounts of text in parallel.
2. How it works
Attention: each token looks back at the others
Attention is how a token gathers meaning from the tokens before it. To understand "it" in "Where is my order A-1042? It was due yesterday", the model has to connect "it" to "order".
Mixture of experts: only part of the model runs for each token
The generation loop: how far does it go?
A common belief is that the model searches through possible answers for the best one. It doesn't. It runs one forward pass per output token, picks one token, appends it, and runs again, until it produces a stop token or hits a length limit. A 300-token answer is 300 passes. Step through it:
analysis channel), so it spends more passes before the answer: that's what higher reasoning effort buys. An agent loop wraps the whole thing: when the model writes a tool call and stops, your application runs the tool, adds the result to the conversation, and starts the model again (Module 07, case study C02).3. Try it yourself
How the next token is picked
After the last layer, the model gives every token in the vocabulary a score (a logit). Softmax turns the scores into probabilities. Temperature sharpens or flattens them; top-p keeps only the most likely tokens that together reach probability p. These five scores are made up, for the text "Your order is".
How much memory does a model need?
Weights take parameters × bytes per parameter. On top of that, every token in every active conversation needs a KV cache entry in each layer (the keys and values attention keeps, so earlier tokens aren't recomputed). Pick a model and precision.
4. Why it matters at work
| Fact about the transformer | What it means for you |
|---|---|
| Input is read in one parallel pass (prefill); output is written one pass per token (decode) | Output tokens are slower and cost more than input tokens. Long answers drive latency more than long prompts. |
| Only active parameters are computed per token | Mixture-of-experts models are cheaper and faster to run than their total size suggests: gpt-oss-120b computes 5.1B of 117B parameters per token. |
| Every token in every conversation needs KV-cache memory | Long contexts and many users are limited by GPU memory, not just by the model's context window. Serving systems like vLLM exist largely to manage this memory. |
| Weights are fixed after training | The model doesn't learn from your chats. Anything it should know goes in the prompt (Module 02), retrieval (Module 15) or fine-tuning (Module 03a). |
| The next token is sampled from probabilities | The same prompt can give different answers. Low temperature for extraction and code; higher for brainstorming (Module 01). |
| Precision is a trade-off | Storing weights in fewer bits (quantization) cuts memory and cost, usually with a small quality loss. gpt-oss ships its expert weights in 4-bit MXFP4 so the 120B model fits on one 80 GB GPU. |
How weights are stored and served
- On disk: weights are saved as named tensors (matrices) in safetensors files, a format designed to be safe to load (unlike Python pickle, it can't run code) and fast (zero-copy). gpt-oss stores its expert weights in MXFP4 and the rest in BF16 (16-bit).
- Loaded onto accelerators: GPUs (or TPUs) hold the weights in their memory, because every token needs every active weight multiplied, and fast.
- Served: an inference server batches many users' requests together and manages the KV cache. vLLM's PagedAttention stores the cache in pages, like an operating system's virtual memory, and its authors report 2–4× higher throughput than earlier systems.
The sampling step in code
import numpy as np
def sample_next(logits, temperature=1.0, top_p=1.0, rng=np.random.default_rng()):
# Pick the next token ID from the model's scores for every token in the vocabulary.
if temperature == 0: # greedy: always the highest score
return int(np.argmax(logits))
z = logits / temperature # <1 sharpens, >1 flattens
p = np.exp(z - z.max()); p /= p.sum() # softmax: scores -> probabilities
order = np.argsort(p)[::-1] # most likely first
keep = np.cumsum(p[order]) - p[order] < top_p # smallest set reaching top_p
p_kept = np.zeros_like(p); p_kept[order[keep]] = p[order[keep]]
return int(rng.choice(len(p), p=p_kept / p_kept.sum()))
5. The tools in this flow
Checked 1 November 2026. The gpt-oss repository lists the ways to run it.
| Layer | Tool or technology | Role |
|---|---|---|
| Framework | PyTorch (and others such as JAX) | Defines the network and runs the matrix maths on GPUs; gpt-oss ships a reference PyTorch implementation |
| Kernels | Triton (GPU), Metal (Apple) | Optimised implementations; gpt-oss provides a Triton version for a single GPU and a Metal version for Apple Silicon |
| Weights format | safetensors; BF16 and MXFP4 precision | Safe, fast-loading tensor files; fewer bits per weight means less memory |
| Model libraries | Hugging Face Transformers | Loads weights and tokenizer, applies the chat template, runs generate() |
| Serving | vLLM | Batches requests and manages the KV cache with PagedAttention; exposes an OpenAI-compatible API |
| Local | Ollama, LM Studio | Run open models on a laptop or workstation; gpt-oss-20b runs within 16 GB of memory |
| Hosted | Provider APIs (OpenAI, Anthropic, Google and others) | Everything on this page happens on their servers; you see tokens in and tokens out |
6. Remember it
How this hook works: what “Look up, look back, think, score, pick, repeat” means
What the slogan means, word by word
- “Look up”
- Each token ID selects a row of the embedding table: a vector of 2,880 numbers.
- “look back”
- Attention: each token gathers information from the tokens before it.
- “think”
- The feed-forward network, in gpt-oss 4 of 128 experts, transforms each token's vector. Repeated over 36 layers.
- “score, pick”
- The final vector becomes a logit for every vocabulary token; softmax, temperature and top-p choose one.
- “repeat”
- Append the token and run again: one forward pass per output token, using the KV cache.
Why this picture fits: it's the actual order of operations in a forward pass, and it makes clear there's no search: just one pick per pass.
The story → the concept
| Mixing desk | Transformer |
|---|---|
| Knobs | Parameters (weights) |
| Knobs glued after training | Fixed weights at inference |
| Channels on the desk | The 2,880-wide vector per token |
| Effects units chosen per song | Experts chosen per token |
| The output meter | Logits over the vocabulary |
The trap it saves you from
Believing the model plans a whole answer or searches for the best one. It commits to one token at a time; good answers come from training, instructions, reasoning tokens and the loops around it.
7. Common mistakes
8. Hands-on lab (roadmap week 1)
- Read a real config: open
config.jsonfor an open model on Hugging Face and find the number of layers, hidden size, attention heads and vocabulary size. - Do the arithmetic: compute its embedding table size and its weight memory in BF16, and compare with the calculator above.
- Run a model locally: run gpt-oss-20b (or another small open model) with Ollama or LM Studio. Measure time to the first token and tokens per second.
- Feel prefill vs decode: send a long prompt with a short answer, then a short prompt with a long answer. Which takes longer?
- Write the sampler: run the
sample_nextfunction above on made-up logits at temperatures 0.2, 1 and 1.5 and count the picks.
9. Self-check quiz
What are a model's parameters (weights)?
How many times does the model run to write a 300-token answer?
What does attention do?
gpt-oss-120b has 117 billion parameters. Roughly how many are computed for each token?
What do softmax and temperature do to the logits?
What is the KV cache for?
10. Go deeper
| Resource | Time | Why |
|---|---|---|
| gpt-oss-120b & gpt-oss-20b model card (OpenAI) | 30 min | A modern production architecture with every dimension published: layers, experts, attention, tokenizer. |
| gpt-oss repository (OpenAI) | 20 min | Reference PyTorch, Triton and Metal implementations you can read. |
| Attention Is All You Need (Vaswani et al., 2017) | 45 min | The paper that introduced the transformer. |
| Efficient Memory Management for LLM Serving with PagedAttention (vLLM, 2023) | 30 min | Why the KV cache dominates serving, and how paging fixes it. |
| safetensors (Hugging Face) | 5 min | How weights are stored safely and loaded fast. |
| nanoGPT (Andrej Karpathy) | an afternoon | A small GPT you can read in full and train yourself. |