AI & ML Quick Path Progress

All cheat sheets

Part 5 cheat sheet: large language models

How language models work, what they cost, and how to adapt them.

Tokens

  • Text is cut into tokens from a fixed vocabulary; each token becomes an id.
  • Common words stay whole; rarer words split into pieces.
  • Costs, limits and speed are counted in tokens.
The sentence Please refund my broken headphones is shown cut into seven pieces called tokens: Please, refund, my, broken, head, phones and a full stop. Each token has an arrow down to a made-up id number. Common words stay whole, while headphones is split into head and phones. Text: "Please refund my broken headphones." Please 4821 ·refund 9033 ·my 612 ·broken 7455 ·head 1307 phones 5589 . 13 Tokens: pieces of text from the tokeniser's vocabulary (a dot marks a leading space) Token ids: the numbers the model really reads Common words stay whole. A rarer word is split into pieces: here "headphones" became "head" + "phones". Illustrative split and made-up ids. Every tokeniser has its own vocabulary, so real splits and ids differ.
Text is split into tokens from a fixed vocabulary, and each token becomes a number. The split and the ids here are illustrative.

One token at a time

  • The model scores every possible next token, one is chosen and added, and the loop repeats.
  • The chance of a whole text is the chances of its tokens multiplied.
P(w1 w2 w3) = P(w1) x P(w2 given w1) x P(w3 given w1 w2)
The text The capital of France is with an empty slot at the end. A model box reads the text and produces a list of made-up chances for the next token: Paris 0.90, the 0.04, a 0.03, known 0.02. One is picked and placed in the slot, then the loop repeats. Text so far The capital of France is ? Model reads all the text so far Chances for the next token Paris 0.90 the 0.04 a 0.03 known 0.02 … 0.01 pick one 1. The model scores every possible next token. 2. One is chosen (the highest, or at random by chance). 3. It is added to the text, and the loop repeats. Made-up chances. A real model scores its whole vocabulary of tens of thousands of tokens.
The model scores every possible next token, one is chosen and added to the text, and the loop repeats. The chances shown are made up.

Sampling settings

  • Low temperature: sharper and more predictable. High temperature: flatter and more varied.
  • Top-k and top-p drop unlikely tokens before choosing.
  • Softmax turns scores into chances; subtract the largest score first to avoid overflow.
Three small bar charts of the same five next-word scores. At temperature 0.2 refund has 0.92 and replacement 0.08, the others 0. At 1.0 refund 0.51, replacement 0.31, discount 0.11, apology 0.07, banana 0. At 2.0 the bars are flatter: refund 0.37, replacement 0.29, discount 0.17, apology 0.14, banana 0.03. Low temperature 0.2 refund 0.92 replacement 0.08 discount 0.00 apology 0.00 banana 0.00 Sharp: one word dominates Temperature 1.0 refund 0.51 replacement 0.31 discount 0.11 apology 0.07 banana 0.00 Balanced High temperature 2.0 refund 0.37 replacement 0.29 discount 0.17 apology 0.14 banana 0.03 Flat: odd words get a chance The same five next-word scores at three temperatures (the numbers from the executed run in this lesson).
A low temperature makes one word dominate; a high temperature flattens the chances so odd words, like banana, slip in.

Building a model

  • Pretraining: predict the next token on huge text.
  • Instruction tuning: learn from example questions and answers.
  • Preference tuning: learn which answers people prefer.
Three rising steps joined by arrows. Step 1, pretraining: reads huge amounts of text and predicts the next token, learning grammar, facts and patterns of reasoning and code. Step 2, instruction tuning: learns from example questions and good answers, so it follows requests. Step 3, preference tuning: learns which answers people prefer, so it is helpful and safe. 1. Pretraining Reads huge amounts of text and predicts the next token. Learns grammar, facts and patterns of reasoning and code. 2. Instruction tuning Learns from example questions and good answers. Learns to follow requests instead of just continuing text. 3. Preference tuning Learns which answers people prefer. Learns to be helpful and safe. Each stage adds behaviour on top of the one before it. Model builders do these stages. You mostly use the result and add your own documents and checks. Fine-tuning (a later lesson) is the same idea applied again by you, on your own examples.
Each stage adds behaviour on top of the one before. Model builders do these stages; you mostly use the result.

The context window

  • The most text, in tokens, the model can look at in one request.
  • Prompt, documents, conversation and the answer share it.
  • When it is full, text is cut and never seen.
Two horizontal bars. The first shows one request that fits within a limit line: your prompt 20 percent, documents 40, conversation 25 and the model's answer 15, all illustrative. The second shows a request that is too long: the end is cut off beyond the limit and labelled cut text, meaning the oldest or least useful text is removed and the model never sees it. The context window is a desk of limited size Everything the model reads and writes in one request has to fit on it: Your prompt 20% Documents 40% Conversation 25% Answer 15% limit (in tokens) When the text is too long, something has to go: Prompt Documents Conversation Answer cut text ← oldest or least useful text is cut; the model never sees it The percentages are illustrative: the real split changes with every request.
Everything the model reads and writes in one request must fit in the context window. When it is too long, some text is cut and never seen. The percentages are illustrative.

Prefill and decode

  • Prefill reads the prompt at once (limited by arithmetic); decode writes one token at a time (limited by memory speed).
  • Time to first token (TTFT) is the wait for the first piece; inter-token latency (ITL) is the average gap after that.
A timeline. A wide box for prefill reads the whole prompt at once, then eight small boxes for decode, one token at a time. A bracket under prefill is time to first token, and a bracket between two decode boxes is inter-token latency. One request, over time Prefill reads the whole prompt at once t1 t2 t3 t4 t5 t6 t7 t8 limited by arithmetic speed Decode: one token at a time, limited by memory speed TTFT: the wait for the first token ITL: the gap between tokens Made-up example from the API lesson: first token after 0.5 s (TTFT), then a token every 0.05 s (ITL). A long prompt makes TTFT worse; a busy or large model makes ITL worse. Boxes are not to scale. Every real system differs; measure yours.
Prefill reads the prompt at once and sets the wait for the first token; decode writes one token at a time and sets the pace. The example times are made up.

Size and memory

  • Layer parameters grow with width squared; the word table adds vocabulary times width.
  • Weights memory is parameters times bytes each (2 bytes at 16 bits).
  • Full training needs about 16 bytes per parameter before activations.
training memory = parameters x 16 bytes (before activations)
training work = 6 x parameters x tokens
A bar for about 16 bytes per parameter in full training with the AdamW optimiser: weights 2 bytes, gradients 2 bytes and optimiser state 12 bytes, before activations. Below it, an 8-billion-parameter model needs about 128 gigabytes of training state, and a bar marks that one 80 gigabyte GPU holds only part of it, so it does not fit. Memory per parameter: full training with AdamW 2 bytes 2 bytes 12 bytes Weights Gradients Optimiser state: AdamW keeps extra numbers per weight about 16 bytes per parameter, before activations (a common mixed-precision breakdown: 2 + 2 + 12 bytes) An 8-billion-parameter model, full fine-tuning: 8 billion × 16 bytes = about 128 GB of training state one 80 GB GPU does not fit Activations (saved for the backward pass) come on top. LoRA and QLoRA cut this memory far more than the other tools.
Full training needs about 16 bytes per parameter before activations: 8 billion parameters is about 128 GB, more than one 80 GB GPU. LoRA and QLoRA cut this a lot.

Fine-tuning

  • Prompt first, add RAG for facts, fine-tune only for style, format or a narrow task.
  • LoRA freezes the model and trains two thin matrices; QLoRA also stores the frozen model in 4-bit.
  • DPO learns from chosen and rejected answers.
LoRA parameters = rows x rank + rank x columns
A large square labelled frozen, 10,000 numbers, 100 by 100. Beside it, plus a tall thin rectangle of 100 by 2 times a wide thin rectangle of 2 by 100, which are the only parts trained. A box says LoRA trains 100 times 2 plus 2 times 100, which is 400 numbers, or 4 percent of 10,000. One layer of a model: a grid of 100 × 100 weights frozen 10,000 numbers 100 × 100 + 100 × 2 × 2 × 100 → LoRA trains only the two thin pieces: 100 × 2 + 2 × 100 = 400 numbers, which is 4% of 10,000 The big grid stays frozen. The two thin pieces are the "adapter": a small file that holds what was learned. QLoRA does the same and also stores the frozen layer in 4-bit numbers to save memory. The numbers are the lesson's example. In a real model the layers are thousands wide, so the share is far below 4%.
LoRA leaves the big layer frozen and trains two thin pieces next to it: 400 numbers instead of 10,000 in the lesson's example. QLoRA also stores the frozen layer in 4-bit.

Running locally and evaluating

  • Quantisation stores weights in fewer bits: smaller and faster, with a small quality loss to measure.
  • Test on your own task, not only public benchmarks; beware contamination.
On the left, a smooth rising line next to a staircase that follows it with only a few levels. On the right, three bars for the memory of an 8-billion-parameter model: 16 GB at 16 bits, 8 GB at 8 bits and 4 GB at 4 bits. Rounding to fewer levels smooth values (grey) → a few steps (green) Memory for 8 billion weights 16-bit 16 GB 8-bit 8 GB 4-bit 4 GB Smaller files and faster loading, with a small quality loss to measure. Memory numbers are from the lesson's executed run. Real quantisation schemes group weights and treat outliers carefully.
Rounding weights to fewer levels shrinks the model, with a small quality loss to measure. The memory numbers are from the lesson's run.