AI & LLM Exercises
Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Solutions are hidden below each exercise — try for a few minutes before you peek.
| # | Exercise | Topics |
|---|---|---|
| 1 | Character tokenizer | tokens, encode/decode |
| 2 | Most frequent pair | BPE |
| 3 | Nearest neighbour | embeddings, cosine similarity |
| 4 | Softmax with temperature | sampling |
| 5 | Top-k filter | sampling |
| 6 | Safe prompt template | prompt templates |
| 7 | Validate a JSON reply | structured output |
| 8 | Keyword retriever | RAG |
| 9 | Accuracy of a classifier | evaluation |
1. Character tokenizer
Build a vocabulary of the sorted unique characters of text, then write encode(s) (string → list of IDs) and decode(ids) (IDs → string).
Expected: vocab size: 5, encode('banana'): [2, 1, 4, 1, 4, 1], decode back: banana.
text = "a banana bandana"
vocab = [] # TODO: sorted unique characters of text
def encode(s):
return [] # TODO
def decode(ids):
return "" # TODO
print("vocab size:", len(vocab))
print("encode('banana'):", encode("banana"))
print("decode back:", decode(encode("banana")))vocab size: 0
encode('banana'): []
decode back:
Show solution
text = "a banana bandana"
vocab = sorted(set(text))
stoi = {ch: i for i, ch in enumerate(vocab)}
def encode(s):
return [stoi[ch] for ch in s]
def decode(ids):
return "".join(vocab[i] for i in ids)The vocabulary is [' ', 'a', 'b', 'd', 'n']: the space sorts first, so b gets ID 2 and n gets ID 4.
2. Most frequent pair
Count all adjacent symbol pairs in words (each word is a list of characters) and print the most frequent pair and its count. Break ties by choosing the alphabetically smallest pair.
Expected: most frequent pair: ('a', 'n') x 5.
from collections import Counter
words = [list("banana"), list("bandana"), list("ban")]
pairs = Counter()
# TODO: count adjacent pairs in every word
best = ("?", "?") # TODO: pick the most frequent pair (ties: smallest)
print("most frequent pair:", best, "x", pairs[best])most frequent pair: ('?', '?') x 0
Show solution
for w in words:
for a, b in zip(w, w[1:]):
pairs[(a, b)] += 1
best = min(pairs, key=lambda p: (-pairs[p], p))('a', 'n') appears twice in banana, twice in bandana and once in ban. This pair would be BPE's first merge.
3. Nearest neighbour
Write cosine(a, b) and print the word whose vector is most similar to query (excluding exact zero vectors), with its similarity rounded to 3 decimals.
Expected: nearest: lemon 0.997.
import numpy as np
vectors = {
"lemon": np.array([0.9, 0.1, 0.8]),
"banana": np.array([0.8, 0.2, 0.1]),
"car": np.array([0.0, 0.9, 0.1]),
}
query = np.array([1.0, 0.0, 0.9]) # "sour yellow fruit"
def cosine(a, b):
return 0.0 # TODO
best = max(vectors, key=lambda w: cosine(vectors[w], query))
print("nearest:", best, round(cosine(vectors[best], query), 3))nearest: lemon 0.0
Show solution
def cosine(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))4. Softmax with temperature
Implement softmax(logits, temperature) (divide by the temperature, subtract the maximum for numerical stability, exponentiate, normalise). Print the rounded probabilities for T = 0.5, 1 and 2.
Expected: T=1: [0.665 0.245 0.09 ].
import numpy as np
logits = np.array([2.0, 1.0, 0.0])
def softmax(logits, temperature=1.0):
return np.ones_like(logits) / len(logits) # TODO
for T in [0.5, 1, 2]:
print(f"T={T}:", np.round(softmax(logits, T), 3))T=0.5: [0.333 0.333 0.333]
T=1: [0.333 0.333 0.333]
T=2: [0.333 0.333 0.333]
Show solution
def softmax(logits, temperature=1.0):
z = logits / temperature
e = np.exp(z - z.max())
return e / e.sum()Lower temperature sharpens the distribution (T=0.5 gives the first token about 0.87), higher temperature flattens it.
5. Top-k filter
Write top_k(probs, k) that keeps the k largest probabilities, sets the rest to 0 and renormalises.
Expected: [0.625 0.375 0. 0. ].
import numpy as np
probs = np.array([0.5, 0.3, 0.15, 0.05])
def top_k(probs, k):
return probs # TODO
print(np.round(top_k(probs, 2), 3))[0.5 0.3 0.15 0.05]
Show solution
def top_k(probs, k):
keep = np.argsort(-probs)[:k]
out = np.zeros_like(probs)
out[keep] = probs[keep]
return out / out.sum()6. Safe prompt template
Use string.Template to fill the template. If a variable is missing, catch the error and print missing: <name>.
Expected:
Translate into French: Good night
missing: 'text'from string import Template
TEMPLATE = Template("Translate into $language: $text")
def render(**values):
return "TODO" # TODO: substitute, catch KeyError
print(render(language="French", text="Good night"))
print(render(language="French"))TODO
TODO
Show solution
def render(**values):
try:
return TEMPLATE.substitute(values)
except KeyError as e:
return f"missing: {e}"7. Validate a JSON reply
check(reply) should return "ok" when the reply parses as JSON and has a string city and an integer population; otherwise return a short error message.
Expected:
ok
error: invalid JSON
error: population must be an integerimport json
def check(reply):
return "ok" # TODO
print(check('{"city": "Lyon", "population": 520000}'))
print(check("{city: Lyon}"))
print(check('{"city": "Lyon", "population": "about 500k"}'))ok
ok
ok
Show solution
def check(reply):
try:
data = json.loads(reply)
except json.JSONDecodeError:
return "error: invalid JSON"
if not isinstance(data.get("city"), str):
return "error: city must be a string"
if not isinstance(data.get("population"), int) or isinstance(data.get("population"), bool):
return "error: population must be an integer"
return "ok"8. Keyword retriever
Score each document by how many distinct query words (lower-cased, punctuation stripped) it contains, and print the best document's id.
Expected: best: d2 (score 3).
docs = {
"d1": "Our cafe opens at 8am on weekdays.",
"d2": "Dogs are welcome on the terrace of the cafe.",
"d3": "We roast our coffee beans every Monday.",
}
query = "Can I bring my dog to the cafe terrace?"
def words(text):
return {w.strip(".,?!").lower() for w in text.split()}
def score(doc_text):
return 0 # TODO
best = max(docs, key=lambda d: score(docs[d]))
print(f"best: {best} (score {score(docs[best])})")best: d1 (score 0)
Show solution
def score(doc_text):
return len(words(query) & words(doc_text))d2 shares the, cafe and terrace with the query. Note that dog ≠ dogs — real retrievers use stemming or embeddings to match such variants.
9. Accuracy of a classifier
Compute the accuracy of predictions against labels and list the indices of the mistakes.
Expected: accuracy: 0.75, mistakes: [2, 5].
labels = ["spam", "ham", "spam", "ham", "ham", "spam", "ham", "spam"]
predictions = ["spam", "ham", "ham", "ham", "ham", "ham", "ham", "spam"]
accuracy = 0.0 # TODO
mistakes = [] # TODO
print(f"accuracy: {accuracy}, mistakes: {mistakes}")accuracy: 0.0, mistakes: []
Show solution
mistakes = [i for i, (l, p) in enumerate(zip(labels, predictions)) if l != p]
accuracy = 1 - len(mistakes) / len(labels)Test yourself
In exercise 4, what happens to the top token's probability when you lower the temperature from 1 to 0.5?
- It decreases
- It stays the same
- It increases
- It becomes exactly 1
Why did the keyword retriever in exercise 8 not match 'dog' with 'Dogs'?
- Python can't compare strings
- Exact word matching treats different word forms as different words
- The document was too long
- The query had a question mark
Why check isinstance(x, bool) separately when validating an integer field in Python?
- Booleans are strings in JSON
boolis a subclass ofint, soTruewould otherwise pass as an integer- Integers can't be validated
- JSON has no integers