AI Engineering · Module 02
How LLMs work: what builders need to know
- Lessons
- 12
- Free
- 2
- Reading
- ~2 h
Your progress
0 / 12 lessons done
Sign in to trackLessons
- Next-token prediction: how an LLM writes textFreeMost surprises in an AI feature trace back to how the model writes: answers that change between runs, slow long replies, text cut off mid-sentence, a confident number that was never in the input. Once you see the loop, you can predict each of them.
- Embeddings: turning words into numbers with meaningSearch by meaning, grouping similar messages and handing a model the right documents all start with embeddings. Knowing what the numbers are and how they are compared tells you when that search will find the right thing and when it will miss.
- Attention: how the model decides what to focus onEvery prompt you send is read through attention. It explains why long prompts take more work, why a detail in the middle of a long input can be missed, and why the order of a long prompt is worth testing.
- Transformers: the architecture in one pictureModel size shows up in every bill and every latency number you see. Knowing what is inside a model tells you why a larger one costs more for each token, and why you can’t read a hosted model’s size from its price.
- Training stages: pretraining, tuning and feedbackEvery time a prompt works, a model refuses, a model doesn’t know last month’s news or a new version writes longer answers, you are seeing the result of a training stage. Knowing which stage caused it tells you which fix is yours to make.
- KV cache and prompt caching: reusing earlier workMost AI features send the same long instructions on every call. Placing one cache breakpoint correctly can cut that part of the bill by about nine tenths; placing it wrongly makes every call cost more than no caching at all, with no error to warn you.
- Quantization: running models in less memoryThe first question about any open model you want to run is whether it fits on the GPUs you can rent. Quantization often decides the answer, and with it the hardware bill.
- Mixture of experts: large models that run fastMany open-weight models now list two parameter counts. Read the wrong one and you rent GPUs that can’t load the model, or skip a model that would have been fast enough.
- Reasoning effort: paying for extra thinkingEvery call to a thinking model has an effort level, set by you or by a default. It moves cost and wait on every call, and it is the first setting to check when a feature thinks more than its task needs.
- Hallucinations: why models state false thingsFreeEvery feature that summarizes, answers or drafts will sometimes state something nobody said. The call succeeds, the checks pass and the sentence reads well, so you only catch it if you designed for it.
- Under the hood: queries, keys and valuesModel docs, inference servers and pricing pages talk about heads, KV cache memory and why long prompts are slow. This arithmetic is what all of those words refer to.
- Under the hood: how decoding picks each tokenEvery token a model writes is chosen by a decoding rule. Knowing that rule tells you which settings to tune when you run an open-weight model, and why on the Claude API you get consistency from prompts, schemas and checks instead.
Practise with
No tools or paper guides for this module yet.
Terms this module teaches 57
Open glossaryActive parameters
The parameters a mixture-of-experts model uses for one token: the shared parts plus the experts the router picked. It decides the work per token.
Adaptive thinking
A mode in which the model decides on each request whether to think before answering and for how long. The effort setting steers it, but no level guarantees a thinking block.
Attention
The step inside a language model that lets each token look at earlier tokens, weight them by relevance and mix in what they carry, so its meaning reflects its context.
Attention head
One of several attention steps that run side by side in a layer, each computing its own weights, so different heads can track different relations between tokens.
Attention weight
The share of one token’s attention given to another token. A token’s weights over the tokens it can see add up to 100%, and they are computed fresh for every input.
Autoregressive generation
Writing text one token at a time, where each new token is chosen from a prediction based on all the tokens before it, including the ones the model has just written.
Base model
A language model straight out of pretraining. It knows a lot of language and facts but continues text instead of following instructions.
Cache breakpoint
A mark on a block of a prompt, set with cache_control on the Claude API, that ends the prefix the provider stores and looks up for prompt caching.
Cache read
Input tokens a provider takes from a stored prompt prefix instead of processing them again, billed at a fraction of the normal input price and reported as cache_read_input_tokens on the Claude API.
Cache write
Input tokens a provider processes and stores as a prompt prefix for later requests, billed above the normal input price and reported as cache_creation_input_tokens on the Claude API.
Causal mask
The rule in a text-writing model that each token may attend only to itself and earlier tokens. Scores for later tokens are set to minus infinity before softmax, so they get weight 0.
Constitutional AI
A training method from Anthropic in which an AI judge, following a written list of principles, gives the feedback on harmful outputs instead of human labels. It uses self-critique and revision, then reinforcement learning from AI feedback.
Decode phase
The phase of a model request after prefill, in which the model writes one output token per step, each step running one new token and reading the KV cache.
Decoding
The rule that picks one token from the model’s probability list at each step, for example always the most likely token or a draw weighted by probability.
Dense model
A model that uses all of its parameters for every token, as opposed to a mixture-of-experts model.
Dot product
Multiply two lists of numbers position by position and add the results. It is large when the two vectors point the same way, so attention uses it to score how well a key fits a query.
Embedding dimension
How many numbers an embedding model returns for each text. More numbers leave room for more kinds of difference in meaning, but take more storage.
Embedding model
A model that reads text and returns an embedding instead of writing text. It is called through its own API, separate from a text-generating model API.
End-of-sequence token
A special token that marks the end of a model’s output. When the model picks it, generation stops.
Expert (mixture of experts)
One of the several feed-forward blocks in a mixture-of-experts layer. It runs only for the tokens the router sends to it.
Factuality hallucination
A hallucination that is false about the world, such as an invented policy, date or library function, usually filled in from patterns the model learned in training.
Faithfulness hallucination
A hallucination that the text given to the model does not support or contradicts, such as a summary claim that no message makes.
Feed-forward block
The step in each transformer layer that works on each token’s row alone: it widens the row, applies a simple non-linear rule and narrows it back. It holds about two thirds of a standard layer’s parameters.
Greedy decoding
A decoding rule that always writes the most likely next token; the same scores always give the same output, but long outputs can repeat themselves.
Hallucination
Output that states something false or unsupported as if it were true, often fluently, because the model writes likely text rather than looking facts up.
Instruction tuning
Training a pretrained model further on example conversations, each a request and a good answer, so it learns to answer requests. Also called supervised fine-tuning.
Knowledge cutoff
The date after which a model’s training text has little or nothing, so the model doesn’t know about later events. Providers list it per model.
KV cache
Memory where a model keeps the attention results of tokens it has already processed, so each new token it writes doesn’t recompute them.
Language model
A program trained on very large amounts of text that writes text and can follow instructions written in plain language.
Logit
The raw score a language model gives each token in its vocabulary at one step; it can be any number, and a higher score means a more likely token.
Memory bandwidth
How many bytes a chip can read from its memory each second. When a model writes one token at a time for one request, it usually limits the speed.
Mixture of experts (MoE)
A model design where each layer has several feed-forward blocks, called experts, and a router sends each token to only a few of them. Only part of the model runs for each token.
Model snapshot
One fixed version of a model behind a model id. Behaviour under the id doesn’t change; a new version gets a new id.
Next-token prediction
What a language model does at each step of writing: given all the tokens so far, it gives every possible next token a probability, so one can be picked.
Parameter (model)
One learned number in a model’s weights. A model’s size is usually given as its parameter count.
Preference training
Training a model on judgements of which of two answers is better, from people or from an AI model, so it gives the answers judges prefer and declines some requests.
Prefill
The first phase of a model request, in which the model processes all input tokens at once and fills the KV cache before it can produce the first output token.
Pretraining
The first and most expensive training stage: next-token prediction on a very large amount of text. It gives a model knowledge and fluency, and fixes its knowledge cutoff.
Prompt caching
A provider feature that stores the processed start of a prompt so later requests that begin with the same text read it from the cache at a lower price.
Quantization
Storing a model’s weights in fewer bits than it was trained with, such as 8 or 4 instead of 16, so it needs less memory. The rounding can lower quality, so it is checked with an eval.
Quantization scale
One number stored for a group of quantized weights. Each weight is kept as a small integer, and multiplying it by the scale gives back a value close to the original.
Query, key and value
Three vectors attention makes from each token by multiplying its embedding by three learned matrices. The query says what the token looks for, the key lets other tokens’ queries score it, and the value is what it hands over when picked.
Reasoning effort
A request setting that controls how much a model thinks before it answers. Higher effort usually means more thinking tokens, a higher bill and a longer wait.
Reinforcement learning from human feedback (RLHF)
Preference training in which people rank a model’s answers, a reward model learns from the rankings, and reinforcement learning trains the model to score higher.
Residual stream
The running representation inside a transformer: one row of numbers per token that every layer reads and adds its results to, keeping the same shape from bottom to top.
Reward model
A model trained on many comparisons of answers to give any answer a score. Preference training uses the score to update the main model.
Router (mixture of experts)
A small learned network in each mixture-of-experts layer that scores the experts for a token and picks the few that will process it.
Sampling (language models)
A decoding rule that draws the next token at random, weighted by each token’s probability, so different runs can write different text.
Softmax
A function that turns a list of scores into probabilities that are all positive and add up to 1; higher scores get larger probabilities.
Temperature
A decoding setting that divides every score before softmax: below 1 it makes the most likely token win more often, above 1 it spreads probability across more tokens.
Thinking tokens
Tokens a model writes as reasoning before its answer. They are billed as output tokens and count toward the output limit, even when you don’t see them.
Top-k sampling
A decoding rule that keeps only the k most likely next tokens and samples among them, dropping every less likely token.
Top-p (nucleus sampling)
A decoding setting that keeps only the smallest set of most likely tokens whose probabilities add up to at least p, then samples from that set.
Total parameters
Every parameter in a model, all experts included. It decides how much memory the weights need.
Transformer
The model design behind today’s large language models, built from layers of attention and other steps, introduced in the 2017 paper “Attention Is All You Need”.
Vector
An ordered list of numbers. In AI engineering, an embedding is stored and compared as a vector.
Vocabulary (language models)
The fixed list of tokens a language model can read and write. At each step the model gives every token in this list a probability of coming next.