Lesson 01 How LLMs Work
Theme:
Lesson 01 · Slide 1

How LLMs Work

A ground-up look at the technology powering modern AI assistants — from probability distributions to transformer architectures.

Learning Objectives

Lesson 01 · Slide 2

What is a Language Model?

At its core, a language model assigns a probability distribution over the next token given all previous tokens. Training on trillions of tokens from books, code, and web text compresses world knowledge into a function that can continue any sequence plausibly.

Next-Token Prediction Intuition

Given the prefix "The capital of France is", the model assigns probabilities like:

Continuation tokenApproximate probability
Paris~94%
Lyon~2%
a~1.5%
(anything else)<2.5% combined

Chaining this prediction step-by-step produces coherent text — or code, or JSON, or poetry.

Notes: Emphasise that the model has no memory between calls — each call is stateless. The "conversation" is maintained by re-sending the full history each time.
Lesson 01 · Slide 3

Tokens: The Unit of LLMs

Models don't read characters or words — they read tokens, sub-word pieces produced by a learned vocabulary (typically 50–100 K entries).

Word → Tokens

  • hello → 1 token
  • tokenization → 2 tokens
  • supercalifragilistic → ~6 tokens
  • 1 token ≈ ¾ of an English word on average

Why It Matters

  • API pricing is per-token (input + output)
  • Context window is measured in tokens
  • Non-English text uses more tokens per word
  • Code is token-dense — estimate carefully

Counting Tokens with tiktoken

import tiktoken

enc = tiktoken.get_encoding("cl100k_base")  # Claude / GPT-4 family proxy

text = "Hello, how many tokens is this sentence?"
tokens = enc.encode(text)
print(f"{len(tokens)} tokens: {tokens}")
# → 9 tokens: [9906, 11, 1268, 1690, 11460, 374, 420, 11914, 30]
Notes: tiktoken uses cl100k_base as a proxy for Claude. Anthropic uses its own tokenizer but counts are close enough for cost estimation.
Lesson 01 · Slide 4

The Transformer (Plain English)

Every modern LLM is built on the transformer architecture. Here is the data flow at inference time:

Input text → tokenise → embedding lookup (token + position) → stack of attention + FFN layers → logits over vocabulary → sample next token → repeat

Self-Attention in One Sentence

For each token, attention asks: "which other tokens in this context are most relevant for predicting what comes next?" and weights their representations accordingly.

Decoder-Only Architecture

Claude, GPT-4, Llama, Mistral — all decoder-only. They use causal masking so each position can only attend to earlier positions, making autoregressive generation efficient.

Lesson 01 · Slide 5

Context Windows

The context window is the maximum number of tokens a model can process in a single call — both input and output combined.

ModelContext windowApprox. pages
Claude Haiku 3.5200 K tokens~500 pages
Claude Sonnet 4200 K tokens~500 pages
GPT-4o128 K tokens~320 pages
Gemini 1.5 Pro1 M tokens~2 500 pages

Cost Implications

Input tokens are priced per-million. Sending a 100 K-token document on every turn costs money — cache or chunk when possible.

Lost-in-the-Middle Warning

Research shows LLMs recall information placed at the beginning and end of long contexts better than content in the middle. Put critical instructions at the top or bottom.

Lesson 01 · Slide 6

Temperature & Sampling

Temperature scales the logit distribution before softmax. Low = peaked distribution (safe). High = flat distribution (creative/risky).

temperature = 0

Always picks the highest-probability token. Deterministic. Best for: code, structured data, factual Q&A.

temperature = 0.7

Balanced creativity and coherence. Best for: summarisation, drafting, general chat.

temperature = 1.0+

High diversity, occasional incoherence. Best for: brainstorming, creative writing, generating varied options.

top_p (nucleus) sampling

Keep the smallest token set whose cumulative probability ≥ p. top_p=0.9 is a popular default. Don't set both temperature and top_p simultaneously.

Lesson 01 · Slide 7

Demo

Live walkthrough of the concepts from this lesson using demo/tokenizer_demo.py.

Demo Steps

  1. Open demo/tokenizer_demo.py in your editor
  2. Run the script on 3 different strings: a short English sentence, a code snippet, and a non-English phrase
  3. Observe token counts and token IDs — note the difference between English and other languages
  4. Modify the temperature parameter and re-run the same creative prompt at 0, 0.7, and 1.2
  5. Compare the three outputs — note that temperature=0 is identical on every run
Notes: Open tokenizer_demo.py, run on 3 strings, then show temperature comparison. Point out that temperature=0 gives the same result every time while 1.2 varies on each run.

📥 Demo Files

⬇ tokenizer_demo.py
Lesson 01 · Slide 8

Lab & Homework

Lab Exercises

  1. Token Counter — encode 5 different text samples with tiktoken; record token counts and observe patterns (code vs prose vs non-English)
  2. Temperature Comparison — call Claude 3 times with the same creative prompt at temperatures 0, 0.7, and 1.2; document the differences
  3. Context Window Budget — given a 200 K context, calculate how many tokens remain for output after inserting a 50-page document (assume 250 words/page, 0.75 tokens/word)

Homework Tasks

  1. Read the tiktoken README. Explain in your own words why different encodings (cl100k_base vs p50k_base) exist and when you'd choose each.
  2. Find a paragraph in a language other than English. Count its tokens and compare the ratio of tokens-to-words versus English text. What does this mean for multilingual app costs?
  3. Research "lost in the middle" (Liu et al., 2023). Summarise the key finding in 2–3 sentences and describe one practical strategy to mitigate it.
1 / ?