Module 02: Projects
Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.
All six projects run locally and free, and none needs an API key. One stretch project has an optional extension that uses API keys, marked as such.
First time? Create a project with uv init llm-basics && cd llm-basics, then add each project's packages with its uv add line (package names only, so you get the newest releases; the lessons' Setup sections say which versions their outputs were produced with) and run scripts with uv run python file.py.
Starter: Tokenizer explorer#
Goal: Build a command-line tool that shows how different tokenizers split the same text, and estimates what that text would cost to send to a model.
What you'll practise:
- Loading OpenAI tokenizers with
tiktokenand open-model tokenizers with Hugging Facetransformers(lesson 02.2, Part 5) - Seeing where token boundaries fall, including spaces, numbers, code and non-English text (Part 9)
- Measuring the "token tax" on other languages (Part 8)
- Turning token counts into cost estimates (10.2)
Prerequisites: lesson 02.2 (Parts 1 to 7 are enough). No API key and no GPU.
Setup: uv add tiktoken transformers (or pip install tiktoken transformers)
Steps:
-
Read the input. Write
explore.py, which reads text from a file passed as an argument, or from standard input if no file is given. -
Load at least four tokenizers. Use
tiktoken.get_encoding("o200k_base")andtiktoken.get_encoding("cl100k_base")for OpenAI. For open models, useAutoTokenizer.from_pretrained(...)withopenai-community/gpt2,Qwen/Qwen2.5-0.5B-Instructandgoogle-bert/bert-base-uncased. -
Print a comparison table. For each tokenizer, show the token count, the characters per token and the words per token.
-
Show the split. Print the text with a visible separator between tokens (for example
|), so you can see where each tokenizer cuts. Decode each token ID separately to get its text. For byte-level tokenizers, explain in a comment why some tokens show up as�on their own (2.6). -
Try a test set. Run the tool on at least six inputs:
- a paragraph of English prose
- a Python function
- a JSON object
- a list of numbers and dates
- a sentence in a language you speak other than English
- a line of emoji
Save the outputs.
-
Add a cost estimate. Add an option
--price-per-million <dollars>that prints the input cost of the text for each tokenizer. Keep prices as inputs to the tool, not hard-coded values. Prices change, and lesson 02.9, 6.12 explains how to look up current ones. -
Write up what you found. Note which inputs were most expensive per character and why. Then compare your measured words-per-token figures with the rules of thumb in 7.1.
Hints:
- For user-supplied text, call
enc.encode(text, disallowed_special=())so a file that mentions<|endoftext|>doesn't crash the tool (4.2). For Hugging Face tokenizers, usetok(text, add_special_tokens=False)["input_ids"]so[CLS]and[SEP]aren't counted. - Words per token is
len(text.split()) / tokens, which is meaningless for Chinese and Japanese (no spaces). Say so in your write-up rather than hiding the number. - To show the split, decode IDs one at a time. A lone
�is a fragment of a multi-byte character, not a bug. - Cost is
tokens * price_per_million / 1_000_000. The point of the project is to compare the tokenizers, so use one price for all of them. - Expect
o200k_baseto be the most compact on most inputs, GPT-2 and BERT to be the worst on code and non-English text, and the emoji line to cost far more tokens than characters.
Done when:
- The tool prints a comparison table and the token-by-token split for any input text, using at least four tokenizers.
- You've run it on all six inputs and saved the results.
- Your write-up explains at least three differences you observed, such as numbers splitting differently, the extra cost of a non-English language, or BERT's lowercasing and
##pieces, each with a link to the lesson section that explains it.
Extensions: Add a --max-tokens N option that truncates the text to N tokens without cutting a word in half (7.4). Or render the split as coloured HTML, like OpenAI's online tokenizer page.
Starter: Sampling playground#
Goal: Run the same prompt through a small local model with different sampling settings, and build an intuition for what temperature, top-p, top-k and min-p actually do.
What you'll practise:
- Generating text with
model.generate()and a chat template (lesson 02.5, Part 1) - Temperature, top-k, top-p and min-p (Part 3)
- Seeds and reproducibility (3.10, Part 7)
- Measuring diversity instead of eyeballing it
Prerequisites: lesson 02.5, Parts 1 to 3, and lesson 02.2, 4.3 for chat templates. No API key; a laptop CPU is enough.
Setup: uv add torch transformers. The model is Qwen/Qwen2.5-0.5B-Instruct (about 1 GB), which runs on a laptop CPU. Apple-silicon Macs can use device="mps" for speed.
Steps:
- Write a helper. Create
playground.pywith a functiongenerate(prompt, **sampling). It should apply the model's chat template, callmodel.generate(..., do_sample=True, max_new_tokens=60, **sampling), and return only the new text. - Turn off the hidden default. Pass
top_k=0explicitly whenever you aren't testing top-k. Withdo_sample=True, Transformers otherwise appliestop_k=50silently (3.3). - Sweep temperature. Use one creative prompt (for example "Write a one-line slogan for a coffee shop") and one factual prompt (for example "What is the capital of Australia?"). For each, generate 10 samples at temperatures 0.2, 0.7, 1.0 and 1.5, with a fixed seed per sample (
torch.manual_seed(i)). - Sweep the truncation samplers. At temperature 1.0, compare
top_p0.5 / 0.9 / 1.0,top_k5 / 50, andmin_p0.05 / 0.2. - Measure, don't eyeball. For each setting, count how many of the 10 outputs are distinct, and compute the average output length. For the factual prompt, also count how many answers are correct.
- Compare with greedy decoding. Run greedy decoding (
do_sample=False) and confirm it gives the same output every time. - Write up what you found. Summarize the results in a table. Recommend settings for a creative task and for a factual or extraction task, and compare your recommendations with the lesson's recommended settings by task.
Hints:
- Build the prompt with
tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt", return_dict=True)and decode onlyout[0, inputs["input_ids"].shape[1]:]so the prompt isn't echoed. - "Temperature 0" is greedy decoding (
do_sample=False), nottemperature=0.0with sampling on. - Judge "distinct" by comparing normalized strings (lower-cased, stripped), or near-identical outputs will look different.
- A small 0.5B model will get some factual answers wrong even at low temperature. That is a finding, not a bug in your code.
Done when:
playground.pyreproduces any run exactly when given the same seed.- Your results table covers every setting in steps 3–6 for both prompts.
- Your write-up explains, with examples from your own outputs, why high temperature produces more errors on the factual prompt, and what top-p or min-p changes at high temperature.
Extensions: Print the top 10 next-token probabilities at each temperature to see the distribution flatten (2.2). Or add repetition and frequency penalties and test them on a prompt that tends to loop (3.8).
Starter: Semantic search with a threshold-calibration report#
Goal: Build a small semantic search over documents you write yourself, then measure where to set the "no good match" threshold for your model and your data, and write it up as a short calibration report.
What you'll practise:
- Embedding documents and queries with
sentence-transformersand ranking by cosine similarity (lesson 02.3, 5.6, 4.4) - Reading similarity scores, and why no threshold is universal (4.6)
- Catching silent truncation of long documents (5.7)
- Choosing a cut-off from measured data rather than intuition, the way you'd tune any classifier
Prerequisites: lesson 02.3, Parts 4 and 5. No API key; a laptop CPU is enough.
Setup: uv add sentence-transformers numpy (sentence-transformers installs PyTorch and Transformers for you). The model is all-MiniLM-L6-v2 (about 90 MB), which runs on a laptop CPU. First time? Run uv init llm-basics && cd llm-basics first, then run scripts with uv run python file.py.
Steps:
- Write a corpus. Create
docs.jsonlwith 40–60 short documents from one domain you know (a product's help centre, a course FAQ, your team's runbooks), one JSON object per line with anidand atext. - Build the index. Write
search.py, which embeds every document once withnormalize_embeddings=True, saves the vectors with NumPy, and reloads them on the next run instead of re-embedding. - Search. Add
search(query, k=3), which embeds the query and returns the topkdocument IDs with their scores, as in 5.6. - Write a labelled query set. Create
queries.jsonlwith at least 30 queries: 20 that one document answers (record itsid), including some paraphrases that share few words with the answer, and 10 that nothing in the corpus answers but that sound related. - Look at the distributions. For every query, record the top-1 score and whether the top-1 document is the right one. Print the scores of answerable and unanswerable queries side by side (or plot them as two histograms). How much do they overlap?
- Sweep the threshold. For thresholds from 0.20 to 0.80 in steps of 0.05, compute two rates: the share of answerable queries whose correct answer is returned above the threshold, and the share of unanswerable queries correctly rejected (top-1 score below the threshold). Print them as a table.
- Check for truncation. Add one document longer than the model's maximum input length, put its key fact at the end, and show that a query about that fact fails. Fix it by splitting long documents into chunks (5.7).
- Write the calibration report. In
REPORT.md, include the sweep table, the threshold you chose, the trade-off it makes (missed answers vs false matches), the queries that still fail, and why your number wouldn't transfer to another model or corpus.
Hints:
- Save with
np.save("vectors.npy", emb)and keep the document IDs in the same order in a separate file. Refuse to load vectors if the model name stored beside them differs (7.5). - For the sweep, the "answerable" rate at threshold t is the share of answerable queries whose top-1 is correct and scores at least t. The "rejected" rate is the share of unanswerable queries whose top-1 score is below t. The two rates pull in opposite directions, which is the whole point of the report.
- Write the unanswerable queries so they sound related (the same product, a feature that doesn't exist), or the task is too easy.
- Ten unanswerable queries is a small sample, so describe your threshold as an estimate and say how you would collect more.
Done when:
search.pyanswers a query from the cached index without re-embedding the corpus.- The report contains the threshold sweep for at least 30 labelled queries and justifies one chosen threshold with numbers from the sweep.
- The truncation case is demonstrated and fixed.
Extensions: Repeat the calibration with intfloat/e5-small-v2, using its query: and passage: prefixes (10.3), and show that its best threshold is different (and that its vectors can't be mixed with MiniLM's, 7.5). Or store the vectors as int8 and measure what that does to accuracy and file size (10.2).
Starter: Model config inspector#
Goal: Build a command-line tool that reads any open model's config.json from Hugging Face, without downloading the weights, and estimates its parameter count, its memory for weights and KV cache, and its context window.
What you'll practise:
- Reading the fields of a real
config.jsonand handling different naming schemes (lesson 02.4, 7.5) - Counting parameters from the config (7.6) and converting them into memory at different precisions (lesson 02.1, 4.4)
- Estimating KV-cache memory for a given context length and batch size (lesson 02.4, 11.4)
- Telling the configured context window apart from what you'll actually get when you self-host (lesson 02.7, 2.4, lesson 02.4, 5.6)
Prerequisites: lesson 02.1, 4.4 (optional lesson, read just that section) and lesson 02.4, Parts 5 to 7 and 11. No API key and no model download.
Setup: uv add huggingface_hub. Download a config with json.load(open(hf_hub_download(repo_id, "config.json"))); it's a few kilobytes. Use ungated models such as Qwen/Qwen2.5-0.5B, Qwen/Qwen3-8B, HuggingFaceTB/SmolLM2-135M-Instruct and openai-community/gpt2 (Llama and Gemma repositories need a Hugging Face login and an accepted licence).
Steps:
- Fetch the config. Write
inspect_model.py, which takes a repo ID as an argument and loads itsconfig.json. - Normalize the field names. Map each family's names onto one set: for example GPT-2's
n_layer,n_embd,n_headandn_positions. Use an explicithead_dimwhen the config gives one, and otherwisehidden_size / num_attention_heads. If the config nests the language model undertext_config, read from there. Fail with a clear message for fields you can't find, rather than guessing. - Count the parameters. Reuse the function from 7.6, and print the share in embeddings, attention and MLP. Check your tool on
Qwen/Qwen2.5-0.5B: it must print 494,032,768. - Estimate weight memory. Print the memory needed for the weights at FP32, BF16, INT8 and 4-bit (lesson 02.1, 4.4).
- Estimate the KV cache. Using the formula in 11.4, print the KV-cache size per token, and in total at 4,096 tokens, 32,768 tokens and the model's maximum context, for a batch size you pass as an option.
- Report the context window. Print
max_position_embeddings(or the family's equivalent) and any RoPE scaling entry (rope_scaling, orrope_parametersin Transformers 5), with a note that the model card and your inference server's settings decide what you actually get (lesson 02.7, 2.4). - Answer a sizing question. Add
--gpu-gb N --context T --batch Boptions that print whether the weights plus the KV cache fit in N GB, and the largest batch that would. - Compare four models. Run the tool on four models of different sizes and families and save the outputs.
Hints:
- GPT-2 uses
n_layer,n_embd,n_head,n_positionsand has no KV-head field (treat it as multi-head attention). Qwen3 setshead_dimexplicitly. Some configs nest the language model undertext_config. - Qwen2.5 adds bias terms to the Q, K and V projections, which is why the lesson's
count_paramshas aqkv_biasswitch. Without it your Qwen2.5-0.5B count will be a little low. - Weights only: BF16 is 2 bytes per parameter. A sensible sizing answer for an 8B model on a 24 GB GPU at 32,768 tokens: about 16 GB of BF16 weights plus about 4.3 GB of KV cache for one conversation fits with a few GB to spare, but only one conversation does. At 8-bit weights the batch limit rises. Say that real serving also needs memory for activations and the engine itself.
- Models with
layer_types,sliding_windowor MLA need the notes in 11.4, 12.1 (GQA and MLA) and 12.3; it is fine for the core tool to flag them as "estimate not valid" rather than guess.
Done when:
- The tool prints parameter count, weight memory at four precisions, KV-cache estimates and the context window for any of your four models, without downloading weights.
- The Qwen2.5-0.5B parameter count is exact, and your write-up explains any model where your count differs from the model card, and why.
- The sizing question gives a sensible answer for a 24 GB GPU and an 8B model at 32,768 tokens.
Extensions: Cross-check your parameter count against the Hub's own metadata with huggingface_hub.get_safetensors_metadata(repo_id).parameter_count. Or add mixture-of-experts support, reporting total and active parameters for a model such as openai/gpt-oss-20b (lesson 02.1, 4.6), or sliding-window layers, which cap the KV cache in those layers (lesson 02.4, 12.3).
Stretch: Handwritten digit recognizer from scratch#
Goal: Build and train a 2-layer neural network that recognizes handwritten digits, using NumPy only (no ML frameworks). Use scikit-learn's built-in 8×8 digits dataset. This extends the XOR network from lesson 02.1 to a real task with ten classes.
What you'll practise:
- The forward pass, softmax and cross-entropy loss (3.6, 5.1)
- Backpropagation and mini-batch gradient descent, written by hand (Part 5)
- Training, validation and test splits, and detecting overfitting (Part 6)
- Running experiments the way ML engineers do: change one thing at a time, and record everything
Prerequisites: lesson 02.1 (an optional lesson, but this project builds directly on it), Parts 3 to 6, and the NumPy demos in 5.5 and 5.6 as your starting code. No API key and no GPU.
Setup: uv add numpy scikit-learn matplotlib (scikit-learn is used only to load the dataset, and matplotlib only for charts)
Steps:
- Load and inspect the data. Load the data with
sklearn.datasets.load_digits(): 1,797 images of 8×8 pixels, with values from 0 to 16. Scale the pixels to the range 0 to 1. Plot a few images with their labels. - Split the data. Shuffle with a fixed seed and split 60/20/20 into training, validation and test sets. Don't look at the test set until the very end.
- Implement the network. Use an input of 64 numbers, a hidden layer of 32 ReLU neurons, and a 10-way softmax output. Initialize the weights with small random values (He initialization is a good choice). Write the forward pass, cross-entropy loss and backpropagation yourself.
- Train the network. Use mini-batches of 32 for at least 50 epochs. Log the training loss, validation loss and validation accuracy after every epoch, and plot all three.
- Check your gradients. Compare your backpropagation gradients with numerical gradients,
(loss(w + ε) - loss(w - ε)) / 2ε, on a handful of weights. They should agree to about 1e-6. This single check catches most bugs. - Run experiments. Change one thing at a time, and record each result in a table:
- hidden size: 8, 32 and 128
- learning rate: 0.001, 0.01, 0.1 and 1.0
- training on only 100 examples (watch the gap between training and validation accuracy grow: that's overfitting)
- adding L2 weight decay, or early stopping on validation loss
- Report a final score. Pick your best configuration using the validation set only, retrain, and report its accuracy on the test set once.
Hints:
- With softmax and cross-entropy, the gradient at the output layer is simply
(probabilities - one_hot_labels) / batch_size, the same shape of result as the XOR code in 5.6. Then pass it back throughW2, multiply by the ReLU slope (1 where the pre-activation was positive, else 0), and so on. - He initialization for ReLU layers: normal random numbers with standard deviation
sqrt(2 / fan_in). - For the gradient check, perturb one weight at a time with a small epsilon such as 1e-5, in float64, and compare relative error, not absolute error.
- If the loss does not fall at all, test your forward pass and loss on a single batch first and see whether it can overfit 10 examples.
Done when:
- Your gradient check passes.
- Your best model reaches at least 95% test accuracy. A well-tuned network should exceed 97%.
- Your experiment table and loss curves show at least one clear case of overfitting, and one of a learning rate that is too high (loss that oscillates or diverges).
- A short write-up connects each result to the concept in lesson 02.1 that explains it.
Extensions: Show a confusion matrix and the 10 images the model gets most confidently wrong. Then re-implement the network in PyTorch and check that it reaches the same accuracy. Or add a second hidden layer, and measure whether depth helps on such a small dataset.
Stretch: Failure-mode test harness and a model-choice memo#
Goal: Turn three of lesson 02.10's demos into a small, repeatable test harness, run it on two local models, and use the results plus a cost model to write a one-page memo recommending a model for a realistic feature.
What you'll practise:
- Measuring long-context retrieval by position (lesson 02.10, 9.2; lesson 02.7, 5.4)
- Measuring position bias in multiple-choice answers (lesson 02.10, 7.2)
- Validating structured output with retries and a safe fallback (lesson 02.10, 21.3)
- Evaluating over several runs instead of one (lesson 02.10, 11.4)
- Costing a workload with prices as parameters, and choosing a model from evidence (lesson 02.9, 6.13, Part 10, 7.6)
Prerequisites: lesson 02.10 (at least Parts 1, 7, 9 and 21), lesson 02.7 and lesson 02.9, Part 6. The core project needs no API key.
Setup: uv add torch transformers pydantic. Start from the llm.py helper in lesson 02.10, 1.4. The two models are Qwen/Qwen2.5-0.5B-Instruct (about 1 GB) and Qwen/Qwen2.5-1.5B-Instruct (about 3 GB). Both run on a laptop, the larger one slowly on a CPU.
Steps:
- Make the model swappable. Change
llm.pyso the model ID comes from an environment variable or argument, and give every test the same interface: it takes achatfunction and returns a dictionary of results. - Needle test. Adapt 9.2 into
test_needle(chat): at least three prompt lengths and five target positions, with 10 random cases each. Record accuracy for every length and position. - Position-bias test. Adapt 7.2 into
test_position_bias(chat). Record accuracy with the correct answer at each letter, and how often the model picks each letter overall. - Format-compliance test. Write 20 realistic inputs for the support-ticket extraction in 21.3, including messy and ambiguous ones. Record the share that validates on the first try, after a retry, and the share that falls back to human review.
- Repeat the runs. Run every test three times with sampling turned on (different seeds), plus once greedy, and report the mean and spread rather than a single number.
- Run both models and save everything. One command (
python harness.py --model ...) runs all tests and writes a JSON results file. A second script turns the JSON files for both models into a Markdown comparison table. - Cost the workload. Define a feature (for example "classify 20,000 support tickets a day, 1,500 input tokens and 150 output tokens each"). Using the cost model from lesson 02.9, 6.13, compute the monthly cost for two or three hosted models you might use in production. Read the prices from a config file or command-line options that you fill in from the providers' pricing pages on the day you run it (6.12). Never hard-code them.
- Write the memo. In one page, following the decision framework in lesson 02.9, 10.1: the requirements, what your harness measured, what it can't tell you about the hosted candidates, the cost comparison, your recommendation, and the result that would change it.
Hints:
- Keep each test a pure function of
chat, a seed and a list of cases, so a test can be re-run on a different model without edits. Store the raw model outputs in the results file, not just the scores, so you can re-score later. - With 10 cases per cell, accuracy moves in 10% steps, so report counts (for example 7 of 10) and treat differences of one or two cases as noise.
- Do not send secrets or real customer data to any hosted model in the optional extension; use invented tickets.
- A 0.5B and a 1.5B model are far weaker than the hosted models you are choosing between. The memo must say what your harness cannot tell you about them.
Done when:
- One command runs the whole harness on either model and writes a results file.
- The comparison table shows every test for both models, with spreads from repeated runs.
- The memo's costs are computed from price parameters, not constants, and every claim in it points to a measured result or a lesson section.
- You can name at least one failure the larger model still shows, and the mitigation from lesson 02.10, Part 20 you'd use for it.
Extensions: Add a sycophancy test that pushes back on correct answers (lesson 02.10, Part 10). For a free look at thinking budgets, run the budget-forcing demo from lesson 02.8, 9.4 through your harness's format test. Optional, needs API keys and costs money: point the harness at a hosted model, then (a) send the same long prefix twice and record the cache-read usage fields and the latency difference (lesson 02.7, 7.3), and (b) run the position-bias test at two reasoning-effort levels and record accuracy, reasoning tokens and cost for each (lesson 02.8, Part 3, 5.1).