InterviewKata
AI engineering · Module 01b · Level 1: How AI works

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.

A 5-minute conversation: Sam asks, Priya explains
0:00 / 5:13

1. The idea

A giant mixing desk in a recording studio, with billions of knobs. During training, an engineer adjusts every knob, a tiny bit at a time, until the desk turns any input into a good guess of what comes next. Once training ends, the knobs are glued in place. Every request after that flows through the same fixed desk: nothing is learned while you chat.

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:

Quantitygpt-oss-120bWhat it means
Parameters117 billion in total; 5.1 billion used per tokenMixture of experts: each token only passes through a few of the experts (below)
Layers36Each token's vector is refined 36 times on its way through
Width (residual stream)2,880 numbers per tokenEvery token is represented as a vector of 2,880 numbers inside the model
Attention64 query heads per layer, sharing 8 key/value heads64 different ways of "looking back"; sharing keys and values saves memory
Experts128 per layer; the top 4 are used for each tokenSpecialised sub-networks; a router picks which ones each token needs
Vocabulary201,088 tokensSo the embedding table is 201,088 × 2,880 ≈ 579 million numbers (calculated)
Context131,072 tokensThe 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

One forward pass: token IDs become vectors, 36 layers of attention and experts refine them, and the last vector is turned into a score for every token in the vocabulary. One token is picked, appended, and the pass runs again.

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:

Three loops, not oneThe token loop above produces every token. A reasoning model runs the same loop, but first writes "thinking" tokens (on gpt-oss, on a separate 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 transformerWhat 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 tokenMixture-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 memoryLong 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 trainingThe 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 probabilitiesThe same prompt can give different answers. Low temperature for extraction and code; higher for brainstorming (Module 01).
Precision is a trade-offStoring 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

  1. 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).
  2. Loaded onto accelerators: GPUs (or TPUs) hold the weights in their memory, because every token needs every active weight multiplied, and fast.
  3. 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()))
The honest caveatsThis is a simplified picture: real layers also include normalisation, position encoding (gpt-oss uses RoPE, extended with YaRN for long context) and residual connections that add each layer's output back onto its input. Nobody fully understands what individual weights "mean"; interpretability research is still working on it. And even temperature 0 isn't guaranteed to give identical outputs: batching and floating-point effects on servers can still change the result.

5. The tools in this flow

Checked 1 November 2026. The gpt-oss repository lists the ways to run it.

LayerTool or technologyRole
FrameworkPyTorch (and others such as JAX)Defines the network and runs the matrix maths on GPUs; gpt-oss ships a reference PyTorch implementation
KernelsTriton (GPU), Metal (Apple)Optimised implementations; gpt-oss provides a Triton version for a single GPU and a Metal version for Apple Silicon
Weights formatsafetensors; BF16 and MXFP4 precisionSafe, fast-loading tensor files; fewer bits per weight means less memory
Model librariesHugging Face TransformersLoads weights and tokenizer, applies the chat template, runs generate()
ServingvLLMBatches requests and manages the KV cache with PagedAttention; exposes an OpenAI-compatible API
LocalOllama, LM StudioRun open models on a laptop or workstation; gpt-oss-20b runs within 16 GB of memory
HostedProvider APIs (OpenAI, Anthropic, Google and others)Everything on this page happens on their servers; you see tokens in and tokens out

6. Remember it

Memory hook: "Look up, look back, think, score, pick, repeat"Embedding lookup, attention looks back, the experts think, the output scores every token, sampling picks one, and the loop repeats.
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 deskTransformer
KnobsParameters (weights)
Knobs glued after trainingFixed weights at inference
Channels on the deskThe 2,880-wide vector per token
Effects units chosen per songExperts chosen per token
The output meterLogits 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

"The model learns from our chats"Weights are fixed at inference. Memory features store notes outside the model and paste them into the prompt.
"It searches for the best answer"It samples one token per forward pass. Reasoning and agents add more passes and more loops, not a search over answers.
Judging a model by total parametersMixture-of-experts models compute only a fraction per token; quality depends on training, not size alone.
Forgetting the KV cacheWeights fit, but 50 users with long conversations don't. Budget memory for context, not just for weights.
Expecting temperature 0 to be perfectly repeatableIt's close, but servers can still vary. Design for some variation.

8. Hands-on lab (roadmap week 1)

  1. Read a real config: open config.json for an open model on Hugging Face and find the number of layers, hidden size, attention heads and vocabulary size.
  2. Do the arithmetic: compute its embedding table size and its weight memory in BF16, and compare with the calculator above.
  3. 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.
  4. Feel prefill vs decode: send a long prompt with a short answer, then a short prompt with a long answer. Which takes longer?
  5. Write the sampler: run the sample_next function 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)?

Temperature and max tokens are settings; the vocabulary belongs to the tokenizer.

How many times does the model run to write a 300-token answer?

300 tokens is about 300 passes (plus the prefill of the prompt), each picking one token.

What does attention do?

It's how "it" gets connected to "order"; a causal mask stops it looking at future tokens.

gpt-oss-120b has 117 billion parameters. Roughly how many are computed for each token?

Its router sends each token to 4 of 128 experts per layer.

What do softmax and temperature do to the logits?

Low temperature favours the top token; high temperature spreads the choice.

What is the KV cache for?

It makes each decode step fast, at the cost of GPU memory per token per conversation.

10. Go deeper

ResourceTimeWhy
gpt-oss-120b & gpt-oss-20b model card (OpenAI)30 minA modern production architecture with every dimension published: layers, experts, attention, tokenizer.
gpt-oss repository (OpenAI)20 minReference PyTorch, Triton and Metal implementations you can read.
Attention Is All You Need (Vaswani et al., 2017)45 minThe paper that introduced the transformer.
Efficient Memory Management for LLM Serving with PagedAttention (vLLM, 2023)30 minWhy the KV cache dominates serving, and how paging fixes it.
safetensors (Hugging Face)5 minHow weights are stored safely and loaded fast.
nanoGPT (Andrej Karpathy)an afternoonA small GPT you can read in full and train yourself.