Skip to content

Courses / GenAI & LLM / Module 1

Module 1: How LLMs actually work: tokens, embeddings, attention, sampling

12 h · theory 5 · hands-on 4 · project 1 · revision 2

You will be able to

  • Explain how text becomes tokens and why token count drives cost and failure modes
  • Describe the decoder-only transformer pipeline from embedding to logits
  • Control generation with temperature, top-k and top-p and predict the effect
  • Implement BPE and softmax sampling from scratch

Capstone increment: Add a token-and-cost estimator utility to the capstone (counts tokens per request, estimates cost per 1,000 queries).

Job-description skills: LLM fundamentals, Transformers, Tokenization · Lab tools: python3.12, tiktoken, numpy

1. The one-sentence model

An LLM is a function that takes a sequence of tokens and returns a probability for every possible next token. Everything else (chat, reasoning, tool use, RAG) is built by calling that function in a loop and choosing what goes into the sequence.

Keep this picture in mind for the whole course. When an answer is wrong, the cause is almost always one of four things: the wrong tokens went in (context), the model's learned probabilities are wrong for this case (model), the way we picked a token from the probabilities was wrong for the task (sampling), or we trusted output we should have checked (system).

Text“The capital of…”TokenizerBPE → token IDsEmbeddingsID → vector + positionN × Transformercausal attention + MLPLogitsone score per tokenSamplertemperature / top-pappend sampled token, repeat until stop token (KV cache avoids recomputing the prefix)
Every LLM call is this loop. Context engineering changes the input; sampling settings change the last box.
Common misconception: LLMs do not look up answers in a database. They produce a probability distribution and we sample from it. That is why the same prompt can give different answers, and why retrieval (Module 5) exists.

2. Tokens: the unit you pay for and the unit that breaks

Models never see characters or words. A tokenizer splits text into sub-word pieces from a fixed vocabulary (about 100k entries for GPT-4-class tokenizers). Byte Pair Encoding (BPE) builds that vocabulary by starting from bytes and repeatedly merging the most frequent adjacent pair.

Three production consequences: you are billed per token, the context window is measured in tokens, and many odd failures (bad arithmetic, miscounting letters, worse performance in Hindi or Telugu than English for the same meaning) trace back to how text was split.

Use the playground below: type a sentence, then step through merges and watch the token count fall. Try English, then the same sentence in Hindi, and compare counts.

BPE playgroundWhat to try: type any text, press Merge, and watch frequent pairs fuse into tokens.
the␣lowest␣newer␣lower␣newest␣the␣low
Characters: 37Bytes: 37Tokens now: 37Compression: 1.00x
Guided experiments
  1. Paste नमस्ते दुनिया नमस्ते. Each Devanagari character is 3 bytes, so the byte count starts far higher than the character count. What does that mean for cost?
  2. Type aaaaaaaa. Why does the token count halve on each merge?
  3. Type a sentence with no repeated words. Why do merges stop early? (A real tokenizer learns merges from a huge corpus, not from your sentence.)
In production: Indic-language text often costs 2-4x more tokens than English for the same meaning on English-heavy tokenizers. Measure this before you quote a price for a multilingual product.

3. Embeddings and the transformer, without the hand-waving

Each token ID is mapped to a vector (an embedding), plus position information. A stack of transformer blocks then updates every vector using two operations: attention, where each position gathers information from earlier positions that are relevant to it, and an MLP, which transforms each vector on its own and is where much of the model's stored knowledge appears to live.

Modern chat models are decoder-only: attention is causal, so position 10 can look at positions 1-9 but not 11. After the last block, the vector at the final position is projected onto the vocabulary to give one score (logit) per token.

Weights are fixed at inference time; only the data flowing through changes. That is why you can't 'teach' a model by chatting with it: you can only change what is in the context.

Tip: Watch the 3Blue1Brown transformer chapter after this section; it is the clearest visual explanation of attention available.

Deep dive

Deep dive: self-attention, step by step

Attention answers one question for every token: which other tokens should I borrow information from, and how much? On its own, “it” in “The cat sat on the mat because it was tired” means almost nothing; after attention, its vector carries much of the meaning of “cat”.

Each token’s vector x is multiplied by three learned matrices to make three new vectors: a query q = xW_Q (what am I looking for?), a key k = xW_K (what do I offer?) and a value v = xW_V (what do I pass on if I’m chosen?). Queries and keys only decide the weights; values are what actually moves between tokens.

  1. Score. For the query token, take the dot product q·k with the key of every token it is allowed to look at. A large dot product means that key matches what the query is looking for.
  2. Scale. Divide every score by √d_k, the square root of the key size. Dot products of longer vectors are larger; without this step the softmax saturates, one token gets almost all the weight and training gradients vanish.
  3. Mask. In a decoder (GPT, Llama, Claude) set the scores of later tokens to −∞, so a token can only use what came before it. This is what lets one training pass learn to predict every next token at once.
  4. Softmax. Turn the row of scores into weights that are positive and add up to 1.
  5. Mix. The token’s output is the weighted sum of the value vectors. For all tokens at once, in matrix form: Attention(Q, K, V) = softmax(QKᵀ / √d_k + mask) V.

Worked example: the scores for “it” in the tool’s meaning head (d_k = 4, so √d_k = 2)

query(it) = [1.5, 0.9, 0, 0]        features: animal, place, action, grammar
key(cat)  = [3, 0, 0, 0]    q·k = 4.5    ÷ 2 = 2.25    e^2.25 = 9.49
key(mat)  = [0, 3, 0, 0]    q·k = 2.7    ÷ 2 = 1.35    e^1.35 = 3.86
key(it)   = [1, 1, 0, 0]    q·k = 2.4    ÷ 2 = 1.20    e^1.20 = 3.32
5 other earlier words       q·k = 0      ÷ 2 = 0       e^0    = 1.00 each
was, tired (later words)    masked to −∞                weight 0
sum = 9.49 + 3.86 + 3.32 + 5 × 1.00 = 21.67
weights: cat 9.49 / 21.67 = 0.44 · mat 0.18 · it 0.15 · each other word 0.05
Self-attention, one step at a timeClick a word to make it the query: the token asking “which earlier words matter to me?”. The bars show where its attention goes.
Head:

it attends most to cat (44%). Its query looks for [1.5, 0.9, 0, 0] in the features (animal, place, action, grammar).

Key wordKey vectorq·k÷ √d_kmaskedsoftmax weight
The[0, 0, 0, 1]0.000.000.005%
cat[3, 0, 0, 0]4.502.252.2544%
sat[0, 0, 2, 0]0.000.000.005%
on[0, 0, 0, 1]0.000.000.005%
the[0, 0, 0, 1]0.000.000.005%
mat[0, 3, 0, 0]2.701.351.3518%
because[0, 0, 0, 1]0.000.000.005%
it[1, 1, 0, 0]2.401.201.2015%
was[0, 0, 1, 1]0.000.00−∞0%
tired[2, 0, 0, 0]3.001.50−∞0%

Output for it = Σ weight × value: animal 1.47 · place 0.69 · action 0.09 · grammar 0.18. The word’s new vector now carries meaning borrowed from the words it attended to.

The vectors are set by hand with readable features so you can follow the arithmetic; a trained model learns them through its W_Q, W_K and W_V matrices and uses hundreds of unnamed dimensions.

Guided experiments
  1. Click “it”. Which word gets the most weight, and why does “cat” beat “mat”? Compare their key vectors with the query of “it”.
  2. Turn the causal mask off. “it” can now see “tired”. Real decoders can’t do this, so which later word in the sentence does the disambiguating work instead? Click “tired” to see.
  3. Switch to the previous-word head and click several words. Why does a model need a head like this as well as a meaning head? (Hint: word order.)
  4. Set d_k to 512 and untick “Divide by √d_k”. What happens to the weights? Why would almost-one-hot attention make training stall? Tick it again: the result no longer depends on d_k.
Common misconception: Attention weights are not an explanation of the model’s reasoning. They show where one head in one layer read from; the answer comes from dozens of layers and heads combined, plus the MLPs.

Deep dive

Deep dive: multi-head attention and the transformer block

One head can learn only one kind of “looking”. So each layer runs h heads side by side, each with its own W_Q, W_K and W_V of size d × (d/h). One head may track the previous word, another the subject of a verb, another a matching bracket. Their outputs are concatenated and multiplied by W_O to get back to size d.

Attention moves information between tokens. The MLP that follows works on each token on its own: it widens the vector to about 3.5–4× its size, applies a non-linearity and projects it back. Much of a model’s factual knowledge appears to sit in these MLP weights. Around both parts are residual connections (x + f(x)) and normalisation (RMSNorm in Llama), which is what lets 32 or 80 blocks stack and still train.

Attention on its own ignores word order: shuffle the words and every score stays the same. Positions are put back with positional encodings. Most current open models use RoPE, which rotates each query and key by an angle that depends on its position, so the score q·k depends on how far apart two tokens are.

Worked example: the sizes inside Llama 3 8B

hidden size d             = 4,096
blocks (layers)           = 32
query heads h             = 32, so each head is 4,096 / 32 = 128-dimensional
key/value heads           = 8 (grouped-query attention: 4 query heads share one K, V)
MLP inner size            = 14,336 (3.5 × d)
attention scores per head = n × n for n tokens: 8,192 tokens → 67 million scores
Input xtokens × dRMSNormrescale each rowAttentionwords share infoAddx + attention(x)MLPper token, 4× wideAddx + mlp(x)ProjectQ, K, V = xWSplit headsh heads of d/hScoresQKᵀ/√d_k + maskSoftmaxweights per rowMix valuesweights × VConcatthen × W_OOne decoder block (an 8B model stacks 32 of these)Inside the attention boxzoom in
Attention moves information between tokens; the MLP transforms each token on its own. The residual “Add” paths let 32+ blocks stack without the signal fading.
Tip: If you remember one formula, make it softmax(QKᵀ/√d_k)V, and be able to say why each part is there. It is the most common transformer question in interviews.

4. From logits to text: temperature, top-k, top-p

Logits become probabilities through softmax. Temperature divides the logits before softmax: below 1 sharpens the distribution toward the top token, above 1 flattens it. Top-k keeps only the k most likely tokens; top-p (nucleus) keeps the smallest set whose probabilities add up to p.

Use the sampler below. Experiment 1: set temperature to 0.1 and sample 50 times. Why do you almost always get the same token? Experiment 2: set temperature to 2.0. What happens to the low-probability tokens? Experiment 3: keep temperature at 1.5 but set top-p to 0.5. Why does output become sensible again?

Rules of thumb for production: extraction, classification and code use temperature 0-0.3; drafting and brainstorming use 0.7-1.0; never rely on temperature 0 for exact reproducibility across providers, because batching and hardware make it non-deterministic.

Next-token samplerPrompt: “The capital of France is …”. Change the dials, edit the logits, then sample.
TokenLogit (editable)Probability after softmax → filtersSampled
Paris
86.4%
0
Lyon
7.1%
0
France
4.3%
0
the
1.6%
0
Berlin
0.6%
0
banana
0.1%
0
Last: none yet
Guided experiments
  1. Temperature 0.1, sample 50. Why is it almost always “Paris”?
  2. Temperature 2.0, sample 50. How often does “banana” appear now, and why is that dangerous in production?
  3. Keep temperature 2.0, set top-p to 0.5. Which tokens survive, and why does output become sensible again?
  4. Raise “Lyon” to 6.0. With two equal logits, what does temperature 0.1 do?
In production: If a JSON-extraction endpoint randomly breaks 2% of the time, check temperature first, then switch to schema-constrained output (Module 2).

5. Context windows and the generation loop

Generation is a loop: run the model, sample a token, append it, repeat until a stop token or the length limit. Each new token needs a forward pass, which is why output tokens cost more and take longer than input tokens. The KV cache stores attention keys and values for the prefix so it isn't recomputed every step.

The context window caps input plus output. Long windows are not free: cost grows with length, and models recall information in the middle of very long contexts less reliably than at the start or end. Good systems put less, better-chosen context in, which is the whole point of RAG.

Hands-on: coding window

The coding window and the full VS Code lab are available after you sign in.

Sign in to code

Labs

Lab 1.1: Finish the tokenizer

Complete decode() in the BPE starter so that decode(encode(text)) == text for any UTF-8 string, including Hindi and emoji. Add a test.

Expected: Round-trip test passes for 'hello', 'नमस्ते दुनिया' and '🚀 launch'.

Lab 1.2: Token cost estimator (capstone increment)

In the full lab (JupyterHub), use tiktoken to count tokens for 20 sample questions plus a 1,500-token context. Write estimate_cost(input_tokens, output_tokens, price_in, price_out) and report cost per 1,000 queries.

Expected: A table of token counts per question and a cost-per-1,000-queries figure, committed as capstone/src/utils/cost.py with a unit test.

Lab 1.3: Sampling experiment

Run the same factual question 20 times at temperature 0.0, 0.7 and 1.5 against a local Ollama model. Count distinct answers and wrong answers at each setting.

Expected: A short table and a one-paragraph conclusion on which temperature you'd use for a support bot and why.

Go deeper

Videos

Further reading

  • Paper Attention Is All You Need · Vaswani et al., NeurIPS 2017. The paper that introduced the transformer. Read sections 3.1–3.5 for attention, multi-head attention and positional encodings.
  • Article The Illustrated Transformer · Jay Alammar. The classic picture-by-picture walk through queries, keys, values and multi-head attention.
  • Interactive Transformer Explainer · Polo Club of Data Science, Georgia Tech. Runs a real GPT-2 in your browser: type a prompt and inspect every attention head and the next-token probabilities.
  • Interactive LLM Visualization · Brendan Bycroft. A 3-D walk through every matrix multiplication of a small GPT, one step at a time.
  • Article The Illustrated GPT-2 · Jay Alammar. Decoder-only models specifically: masked self-attention and how generation reuses earlier tokens.
  • Paper RoFormer: Enhanced Transformer with Rotary Position Embedding · Su et al., 2021. Where RoPE comes from; the positional method most current open models use.

GitHub repositories

Checkpoint quiz

1. Why does the same prompt sometimes produce different answers?
2. Raising temperature from 0.7 to 1.5 will…
3. A model fails to count the letters in 'strawberry'. The most likely root cause is…
4. Why do output tokens usually cost more than input tokens?
5. Top-p = 0.9 means…
6. Why does attention divide the scores by √d_k?
7. In a decoder-only model, what does the causal mask do?

Interview questions

  1. Walk me through what happens between sending a prompt and receiving the first token.
  2. Why might a multilingual chatbot cost more per query in Telugu than in English? How would you measure and reduce it?
  3. When would you set temperature to 0, and why is that still not fully deterministic?
  4. What is the KV cache and how does it affect latency and memory?
  5. Explain causal attention to a backend engineer in two minutes.

Ask the professor

Sign in to ask questions about this module.

Discussion

Community discussion appears here once giscus is configured (see README).