How LLMs Work
Follow a sentence through a large language model: tokens, embeddings, attention, a transformer block, training and sampling. Every piece is computed on numbers small enough to check by hand, then you look at what gets built around the model.
- Advanced
- 4 units, 12 lessons, 151 exercises
- Python, diagrams
- Builds on Math for ML, AI Engineering: NumPy & PyTorch
Unit 01 · 3 lessons
Text to numbers
Turn a string into the tensor a language model actually reads
- 01Tokens
Byte-pair encoding, built by hand
- 02Embeddings
A lookup table that turns ids into meaning
- BOSSOrder matters
From a string to the tensor the model reads
Read the unit guide
A language model never sees letters. A tokenizer cuts text into tokens, pieces that are usually bigger than a character and smaller than a rare word, and replaces each piece with its id: a row number in the vocabulary.
Byte-pair encoding builds that vocabulary from data. Start with single characters (or the 256 possible bytes), count every neighbouring pair, merge the most common pair into one new token, and repeat. Each merge adds exactly one token. Common words end up as one token, rare words as a few pieces, and nothing is ever "unknown" because single characters remain as a fallback.
An id carries no meaning: 6 is not "between" 5 and 7. So the first layer of the model is a lookup table, the embedding matrix, with one row per token and d_model columns. Training moves the rows so that tokens used in similar ways point in similar directions, which you measure with cosine similarity.
A row lookup gives the same vector wherever the token appears, so word order would be invisible. The fix is a second table with one row per position, added to the token embeddings. The number of positions the model was built for is its context window: text beyond it has to be cut.
The whole input pipeline is short: string, token ids, keep the last ones that fit, look up token rows, add position rows. Out comes a tensor of shape [tokens, d_model], and that is all the rest of the model ever sees.
The classic pitfall is thinking in words or letters. Costs, limits and odd failures (miscounting the letters in a word, tripping on a typo) all make sense once you think in tokens.
Unit 02 · 3 lessons
Attention
Compute attention by hand and assemble a transformer block
- 01Self-attention
Queries, keys, values and a weighted mix
- 02Heads and masks
Several attentions at once, and no peeking ahead
- BOSSOne transformer block
Attention, an MLP, and the wiring between them
Read the unit guide
The meaning of a token depends on the tokens around it: "it" needs to find the thing it refers to. Attention is the mechanism that lets every token pull information from the others.
Each token's vector is turned into three vectors by three learned matrices. The query says what this token is looking for, the key says what it contains, and the value is what it hands over. The score between two tokens is the dot product of one's query with the other's key, divided by the square root of the vector size so the scores stay moderate. Softmax turns each row of scores into weights that sum to 1, and the token's new vector is the weighted mix of all the values.
One attention pattern is rarely enough, so a layer runs several heads side by side. Each head works in a slice of d_model with its own weights, and their outputs are concatenated back to d_model. A causal mask sets the score of every later token to minus infinity before the softmax, so a token can only use itself and what came before. Training needs that: the model is learning to predict the next token and must not see it.
A transformer block is attention followed by a small MLP, and each of the two is wrapped the same way: normalise, compute, then add the result to what came in (x = x + f(norm(x))). Attention moves information between tokens; the MLP works on each token alone. The additions form a "residual stream" that every block reads from and writes to.
Because a block returns the same shape it received, [tokens, d_model], blocks stack. A GPT-style model is: token plus position embeddings, N blocks, a final norm, and a linear layer that turns each vector into one score per vocabulary token.
Costs to remember: attention compares every token with every other, so its work grows with the square of the sequence length, and a block's parameter count grows with the square of d_model.
Unit 03 · 3 lessons
Training and generating
See how one task, predict the next token, both trains a model and makes it write
- 01Predict the next token
Logits, cross-entropy and text that labels itself
- 02Scale
Parameters, data, compute, and the stages of training
- BOSSOne token at a time
The generation loop, sampling and the KV cache
Read the unit guide
A language model is trained on one task: given the tokens so far, predict the next one. Text labels itself, because the right answer at every position is simply the token that comes next. No human has to mark anything.
For each position the model outputs logits, one score per vocabulary token. Softmax turns them into probabilities, and the loss is the cross-entropy: minus the log of the probability given to the true next token. Certain and right costs 0; a uniform guess over V tokens costs ln V, which is what an untrained model should show. Thanks to the causal mask, every position of a sequence is a training example in the same forward pass, and the model always reads the true earlier tokens rather than its own guesses (teacher forcing).
Scale is the other ingredient. Compute grows roughly with parameters times tokens processed, and training needs several numbers per parameter (the weight, its gradient, optimizer state), which is why training costs far more than running. Pretraining on huge raw text comes first; fine-tuning continues from those weights on narrower data such as instructions and conversations; preference tuning uses human judgements of which answers are better.
Generation runs the same model in a loop: predict a distribution, pick a token, append it, repeat until a stop token or a length limit. Greedy picking always takes the top token. Sampling draws from the distribution, after temperature has sharpened (below 1) or flattened (above 1) it, and often after top-k or top-p has cut off the unlikely tail.
The KV cache makes the loop affordable. Under a causal mask the keys and values of earlier tokens never change, so they are stored and each new token costs one position of work instead of a full re-read. The prompt still has to be processed once, which is why the first token is the slow one.
The pitfall: "it knows" and "it writes" are the same mechanism. The model always produces a likely next token, whether or not a true one exists.
Unit 04 · 3 lessons
LLMs as systems
Build around a model: context, retrieval, tools and healthy distrust
- 01The context window
One window holds everything the model knows right now
- 02Retrieval and tools
Bring knowledge in, let actions out
- BOSSTrust, but verify
Hallucination, evaluation, injection and cheaper serving
Read the unit guide
A model's weights are frozen once training ends. Everything it knows about your conversation, your documents and your instructions has to be inside one input: the context window. The system prompt, tool descriptions, the conversation so far and the new message all share it, and room must be left for the answer.
The model keeps no memory between calls. Chat apps create the illusion by re-sending the whole history every turn, which is why long chats cost more per message and why something has to be cut or summarised when the window fills. Providers can cache the processed state of a repeated prefix, so keep the stable parts (system prompt, tools) first and the changing parts last.
Retrieval-augmented generation (RAG) gets fresh or private knowledge in without retraining: split documents into chunks, embed them, embed the question, find the nearest chunks and paste them into the prompt. Its ceiling is the retriever: the model cannot read a chunk that was not retrieved.
A model can only emit tokens. A tool call is text in an agreed structure that names a function and its arguments; the program runs it and appends the result to the context. Put that in a loop, where the model sees each result and decides the next step, and you have an agent. Always cap the number of steps.
Fluent is not the same as true. The model produces likely text whether or not a fact backs it, so check what matters: ground answers in retrieved text, test on questions the model has never seen, and score changes with a fixed set of test cases. Treat any text the model reads (web pages, emails, documents) as possibly hostile, because it cannot reliably tell data from instructions; limit what its tools can do.
Serving cost can be cut by quantisation (fewer bits per weight) and distillation (a small model trained to imitate a large one). Choosing a model is a trade between quality, speed and cost for the job in front of you.
Learn How LLMs Work on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.