Python Quiz

Bugs to spot in Python, NumPy and PyTorch code, with solutions.

Short snippets of Python, NumPy and PyTorch, each with at least one bug. Most of them run without an error, or fail only on some inputs. For each, say what goes wrong, give an input that shows it, and give the fix. Imports (math, random, time, json, asyncio, numpy as np, torch, torch.nn as nn, torch.nn.functional as F) are left out.

Python traps

1. Mutable default: What happens when this is called twice without vocab?

def add_token(token, vocab=[]):
    vocab.append(token)
    return vocab
Solution

The default list is created once, when the function is defined, so every call shares it. add_token("a") then add_token("b") returns ["a", "b"]. Use None as the default:

def add_token(token, vocab=None):
    if vocab is None:
        vocab = []
    vocab.append(token)
    return vocab

The same applies to any default computed at definition: ts=time.time() stamps every call with the time the def statement ran.

2. Class attribute: Two runs are created and only the first records a loss. What does the second one see?

class Run:
    metrics = {}

    def record(self, name, value):
        self.metrics[name] = value
Solution

metrics belongs to the class, so every instance shares one dict, and the second run sees the first run's loss. Create per-instance state in __init__: self.metrics = {}.

3. Closures in a loop: What does the last line return?

scalers = [lambda x: x * s for s in (1, 2, 3)]
[f(10) for f in scalers]
Solution

[30, 30, 30]. Each lambda looks up s when it is called, not when it is created, and by then the loop has finished with s = 3. Bind the current value as a default argument: lambda x, s=s: x * s.

4. Removing while iterating: What does drop_negatives([-1, -2, 3]) return?

def drop_negatives(xs):
    for x in xs:
        if x < 0:
            xs.remove(x)
    return xs
Solution

[-2, 3]. Removing -1 shifts every later element left, so the loop's next index skips -2. The function also changes the caller's list. Build a new one instead: return [x for x in xs if x >= 0].

5. Grid of zeros: After setting one cell, what does grid hold?

grid = [[0] * 3] * 2
grid[0][0] = 1
Solution

[[1, 0, 0], [1, 0, 0]]. The outer * 2 repeats a reference to the same inner list, so both rows are one object. Use [[0] * 3 for _ in range(2)].

6. Copying a config: Does changing cfg leave base alone?

base = {"optim": {"lr": 1e-3}, "seed": 0}
cfg = dict(base)
cfg["optim"]["lr"] = 3e-4
Solution

No: dict(base) is a shallow copy, so cfg["optim"] is the same dict as base["optim"] and both now have lr = 3e-4. Use copy.deepcopy(base) for nested data.

7. Generator used twice: What happens on mean_length(["ab", "c"])?

def mean_length(docs):
    lengths = (len(d) for d in docs)
    return sum(lengths) / sum(1 for _ in lengths)
Solution

ZeroDivisionError. A generator can be consumed only once, so the first sum uses it up and the count is 0. Build a list, lengths = [len(d) for d in docs], and divide by len(lengths).

8. Identity check: This passes every unit test with small buffers. What breaks in production?

def is_full(buffer, capacity):
    return len(buffer) is capacity
Solution

is compares object identity, not value. CPython reuses one object for each integer from −5 to 256, so small tests pass, but with capacity = 1000 it returns False when the buffer is full. Use ==.

9. Defaults with or: A caller passes warmup_steps=0 to turn warmup off. What do they get?

def train(lr=None, warmup_steps=None):
    lr = lr or 1e-3
    warmup_steps = warmup_steps or 500
Solution

500 warmup steps. 0 is falsy, so or replaces it with the default. The same happens to 0.0, "" and empty lists. Test for the missing value explicitly: if warmup_steps is None: warmup_steps = 500.

10. Top k: What does this return?

def top_k(scores, k):
    ranked = scores.sort(reverse=True)
    return ranked[:k]
Solution

It raises TypeError: list.sort() sorts in place and returns None. It also reorders the caller's list. Use sorted(scores, reverse=True)[:k], or heapq.nlargest(k, scores), which takes O(nlog⁡k)O(n \log k) time.

11. Loading a file: A file with one malformed line returns []. Why is that a problem?

def load_scores(path):
    try:
        with open(path) as f:
            return [float(line) for line in f]
    except:
        return []
Solution

The bare except turns every failure into "no scores": a missing file, a bad line, even Ctrl-C (KeyboardInterrupt). Callers can't tell an empty file from a broken one. Catch only what you can handle, such as FileNotFoundError, and let a ValueError from a bad line propagate, ideally with the line number.

12. Unique and sorted: What happens when this runs, and what else is wrong?

def unique_sorted(items):
    sorted = []
    for x in items:
        if x not in sorted:
            sorted.append(x)
    return sorted(sorted)
Solution

TypeError: 'list' object is not callable. The local name sorted hides the built-in. The membership test on a list is also O(n)O(n), so the loop is O(n2)O(n^2). Use return sorted(set(items)).

13. Float loop: When does this loop stop?

t = 0.0
while t != 1.0:
    t += 0.1
Solution

Never. 0.10.1 has no exact binary form, so ten additions give 0.9999999999999999, the next one jumps past 1, and t is never exactly 1.0. Compare floats with a tolerance (math.isclose), or count with an integer and compute t = i / 10.

Classes

14. Early stopping: Training should stop after patience epochs in a row without improvement. What does this do instead?

class EarlyStopping:
    def __init__(self, patience=3):
        self.patience = patience
        self.best = float("inf")
        self.bad_epochs = 0

    def step(self, val_loss):
        if val_loss < self.best:
            self.best = val_loss
            self.bad_epoch = 0
        else:
            self.bad_epochs += 1
        return self.bad_epochs >= self.patience
Solution

It stops after patience bad epochs in total, not in a row. The typo self.bad_epoch = 0 creates a new attribute instead of resetting the counter, and Python raises no error for it. With patience=2, the losses 1.0, 2.0, 0.5, 0.9 stop training at the fourth epoch even though the third improved. Linters flag attributes defined outside __init__, and __slots__ turns the typo into an AttributeError.

15. Deduplicating examples: What happens on the last line?

class Example:
    def __init__(self, text, label):
        self.text, self.label = text, label

    def __eq__(self, other):
        return (self.text, self.label) == (other.text, other.label)

unique = set(examples)
Solution

TypeError: unhashable type: 'Example'. Defining __eq__ without __hash__ sets __hash__ to None, because objects that compare equal must hash equal. Define __hash__ from the same fields, or use @dataclass(frozen=True), which generates both.

16. Batch iterator: What does the second for loop over the same Batches object yield?

class Batches:
    def __init__(self, data, bs):
        self.data, self.bs, self.i = data, bs, 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.i >= len(self.data):
            raise StopIteration
        batch = self.data[self.i:self.i + self.bs]
        self.i += self.bs
        return batch
Solution

Nothing. __iter__ returns the object itself, so its position self.i carries over and the second epoch starts at the end. Make __iter__ a generator, so each loop gets a fresh iterator:

def __iter__(self):
    for i in range(0, len(self.data), self.bs):
        yield self.data[i:i + self.bs]

The same bug appears outside classes when batches = iter(...) is created once, before the epoch loop.

17. Adding to an index: embed raises an error on one document in the middle of a call. What state is the index left in?

class VectorIndex:
    def add_documents(self, docs):
        for doc_id, text in docs:
            self.ids.append(doc_id)
            self.vectors.append(self.embed(text))
Solution

ids has one more entry than vectors, so every later search returns the wrong ID for each vector. The ID is appended before the step that can fail. Compute everything that can fail first, then update the state together:

def add_documents(self, docs):
    docs = list(docs)
    new_ids = [doc_id for doc_id, _ in docs]
    new_vecs = [self.embed(text) for _, text in docs]
    self.ids.extend(new_ids)
    self.vectors.extend(new_vecs)

18. Log writer: What can go wrong with this class?

class JsonlWriter:
    def __init__(self, path):
        self.f = open(path, "a")

    def write(self, record):
        self.f.write(json.dumps(record) + "\n")
Solution

The file is never closed or flushed. Writes sit in a buffer, so a reader sees missing lines, and if the process is killed they are lost. Each instance also holds a file handle open. Add a close method and make the class a context manager, so callers write with JsonlWriter(path) as w::

def close(self):
    self.f.close()

def __enter__(self):
    return self

def __exit__(self, *exc):
    self.close()

Logic and arithmetic

19. Batching: What happens to 5 items with bs=2?

def batches(data, bs):
    return [data[i * bs:(i + 1) * bs] for i in range(len(data) // bs)]
Solution

The last item is dropped: the result is [[0, 1], [2, 3]]. len(data) // bs counts only full batches. Step through the data instead, [data[i:i + bs] for i in range(0, len(data), bs)], and drop the last partial batch only when you mean to. The same off-by-one drops the last window or chunk in sliding-window code: nn items have n−k+1n - k + 1 windows of size kk.

20. Mean latency: What is the mean of [1, 2]?

def mean_ms(latencies_ms):
    return sum(latencies_ms) // len(latencies_ms)
Solution

1, not 1.5. // is floor division. Use /, and decide what an empty list should return instead of letting it raise ZeroDivisionError.

21. Lowest loss: What does min_loss([0.5, 0.3]) return?

def min_loss(losses):
    best = 0
    for l in losses:
        if l < best:
            best = l
    return best
Solution

0. The starting value is already below every positive loss. Start from float("inf") or the first element, or just use min(losses).

22. Any NaN: What does has_nan([[1.0], [float("nan")]]) return?

def has_nan(rows):
    for r in rows:
        if any(math.isnan(x) for x in r):
            return True
        else:
            return False
Solution

False: the else returns after the first row. For an empty input it returns None. Move return False after the loop.

23. Transpose: This passes on square matrices. What happens on a 2×32 \times 3 one?

def transpose(m):
    return [[m[i][j] for i in range(len(m))] for j in range(len(m))]
Solution

It returns only 2 of the 3 columns, and on a tall matrix such as 3×13 \times 1 it raises IndexError. The outer loop runs over columns, so it needs range(len(m[0])). Square test cases hide bugs that confuse rows with columns.

24. Scoring with failures: Results are [True, None, None, False], where None means the request failed. What is the accuracy?

def accuracy(results):
    scored = [r for r in results if r is not None]
    return sum(scored) / len(scored)
Solution

It reports 0.5, but only 1 of the 4 examples was answered correctly (0.25). Failed requests drop out of the denominator, so a model that times out on the hard examples scores higher. Count failures as wrong (sum(r is True for r in results) / len(results)) and report the failure rate alongside.

25. Epoch loss: The loss function averages over a batch. What is wrong with the epoch average?

total = 0.0
for x, y in loader:
    total += loss_fn(model(x), y).item()
avg = total / len(loader)
Solution

It is a mean of batch means, so a small last batch counts as much as a full one. Weight each batch by its size, adding loss_fn(model(x), y).item() * len(y), and divide by the number of examples.

State and caching

26. Response cache: What can this return that it shouldn't?

_cache = {}

def generate(prompt, model, temperature=0.0):
    if prompt not in _cache:
        _cache[prompt] = model.generate(prompt, temperature=temperature)
    return _cache[prompt]
Solution

The key leaves out everything except the prompt, so it returns a cached answer from a different model, model version or temperature. Key on every input that changes the output: (prompt, model.name, model.version, temperature). Think twice about caching sampled outputs at all, since the caller may expect a fresh sample. The dict also grows without limit.

27. Cached list: Why does a second caller see <pad> twice after this runs twice?

@functools.lru_cache(maxsize=None)
def load_vocab(path):
    with open(path) as f:
        return [line.strip() for line in f]

vocab = load_vocab("vocab.txt")
vocab.append("<pad>")
Solution

lru_cache returns the same list object every time, so each caller's change lands in the cache. Return something immutable (a tuple) or have callers copy it before changing it.

28. Validation metric: The accuracy printed rises smoothly and seems too stable. Why?

metric = Accuracy()      # keeps running totals of correct and total
for epoch in range(n_epochs):
    train_one_epoch()
    for preds, labels in val_batches:
        metric.update(preds, labels)
    print(epoch, metric.compute())
Solution

The totals are never reset, so each epoch's number averages over all epochs so far. Call metric.reset() at the start of each evaluation, or create a new metric each time.

29. Seeded shuffle: This is called once per epoch. What are the two problems?

def shuffle(xs, seed=0):
    random.seed(seed)
    random.shuffle(xs)
    return xs
Solution

Every epoch gets the same order, and every call resets the global random state for all other code that uses random. It also shuffles the caller's list in place. Pass the epoch in and use a private generator: rng = random.Random(seed + epoch), then return rng.sample(xs, len(xs)).

Async code

30. Moderation check: classify is an async method. What does is_safe return?

async def is_safe(text):
    verdict = moderation_client.classify(text)
    return verdict != "unsafe"
Solution

Always True, and the classifier never runs. Without await, verdict is a coroutine object, which never equals "unsafe". Python only prints a RuntimeWarning: coroutine ... was never awaited. Write verdict = await moderation_client.classify(text).

31. Retry with backoff: What does this do to the rest of the program, and what does it return when every attempt fails?

async def fetch_with_retry(url, tries=3):
    for attempt in range(tries):
        try:
            return await http.get(url)
        except TimeoutError:
            time.sleep(2 ** attempt)
Solution

time.sleep blocks the event loop, so every other coroutine stops while it waits. Use await asyncio.sleep(2 ** attempt). After the last failure the loop ends and the function returns None, which the caller will treat as a response. Raise the last error instead.

32. Scoring many prompts: prompts has 100,000 items. What goes wrong?

async def score_all(prompts):
    return await asyncio.gather(*(score(p) for p in prompts))
Solution

Two things. All 100,000 requests start at once, which hits rate limits and uses memory for every pending request. And if one call raises, gather raises that exception and you lose every other result, while the other tasks keep running. Bound the concurrency and keep the failures:

async def score_all(prompts, limit=32):
    sem = asyncio.Semaphore(limit)

    async def bounded(p):
        async with sem:
            return await score(p)

    return await asyncio.gather(*(bounded(p) for p in prompts),
                                return_exceptions=True)

Then count the exceptions as failures rather than dropping them (see question 24).

33. Background logging: What can go wrong with the logging task?

async def handle(request):
    asyncio.create_task(log_usage(request))
    return await respond(request)
Solution

The event loop holds only a weak reference to tasks, so a task nobody keeps a reference to can be garbage-collected before it finishes. Any exception it raises is also never seen. Keep the tasks in a set and remove each one when it finishes:

background = set()
task = asyncio.create_task(log_usage(request))
background.add(task)
task.add_done_callback(background.discard)

34. Embedding cache: Five requests for the same text arrive at once. How many times is embed called?

async def get_embedding(text):
    if text not in cache:
        cache[text] = await embed(text)
    return cache[text]
Solution

Five. Each request checks the cache, finds nothing and waits on embed before any of them has stored a result. Store the pending task instead, so later requests await the same one:

async def get_embedding(text):
    if text not in cache:
        cache[text] = asyncio.create_task(embed(text))
    return await cache[text]

NumPy and PyTorch

35. Softmax: logits has shape (batch, classes). What is wrong?

def softmax(logits):
    e = np.exp(logits)
    return e / e.sum()
Solution

It normalizes over the whole array, so the rows together sum to 1 instead of each row summing to 1. A row with large logits takes almost all the mass: [[10, 0], [0, 0]] gives row sums 0.99991 and 0.00009. It also overflows: np.exp is inf above about 709 in float64, or 88 in float32, and inf / inf is nan. Subtract the row maximum and sum over the last axis:

def softmax(logits):
    z = logits - logits.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)

36. Negative log-likelihood: softmax is the stable version from the previous question. What does this return for logits = np.array([[0.0, -800.0]]) and y = np.array([1])?

def nll(logits, y):
    p = softmax(logits)
    return -np.log(p[np.arange(len(y)), y]).mean()
Solution

inf. The probability e−800e^{-800} underflows to exactly 0 and log⁡0=−∞\log 0 = -\infty, though the true loss is 800. Compute log-probabilities directly with log-sum-exp, which never takes the log of a rounded-off probability:

def nll(logits, y):
    z = logits - logits.max(axis=-1, keepdims=True)
    logp = z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
    return -logp[np.arange(len(y)), y].mean()

37. Row normalization: x has shape (n, d). What happens?

def row_normalize(x):
    return x / x.sum(axis=1)
Solution

x.sum(axis=1) has shape (n,), which broadcasts along the last axis. If n≠dn \ne d it raises an error. If n=dn = d it silently divides each column by a row sum. Use x.sum(axis=1, keepdims=True), which has shape (n, 1).

38. Regression loss: The model returns shape (n, 1) and y has shape (n,). What is mse?

preds = model(X)
mse = ((preds - y) ** 2).mean()
Solution

The mean of an n×nn \times n matrix. (n, 1) - (n,) broadcasts to (n, n) and compares every prediction with every target, so the loss trains but towards the wrong thing. Use preds.squeeze(-1), and assert shapes where data enters a function. PyTorch's nn.MSELoss warns about this, but a hand-written loss does not.

39. Splitting heads: q has shape (B, T, d_model) and d_model = n_heads * head_dim. What is wrong?

q = q.view(B, n_heads, T, head_dim)
Solution

The shape is right but the data is scrambled. In memory each token's features are contiguous, so this view mixes features from different positions within each head, with no error. Split the last axis and then move the head axis: q.view(B, T, n_heads, head_dim).transpose(1, 2).

40. Standardizing features: What are the three problems?

def standardize(x):
    x -= x.mean(axis=0)
    x /= x.std(axis=0)
    return x
Solution

It changes the caller's array in place, it raises a casting error on an integer array, and a constant column has standard deviation 0, which gives nan. Return a new array and guard the denominator: (x - mu) / np.maximum(sd, eps).

41. Hand-written LayerNorm: Weights trained with nn.LayerNorm are loaded into this function. Why do the outputs differ?

def layer_norm(x, w, b, eps=1e-5):
    mu = x.mean(-1, keepdim=True)
    var = x.var(-1, keepdim=True)
    return (x - mu) / (torch.sqrt(var) + eps) * w + b
Solution

x.var divides by N−1N - 1 by default, while LayerNorm divides by NN, and ϵ\epsilon belongs inside the square root. With 8 features the first alone shrinks every output by 7/8\sqrt{7/8}. Use x.var(-1, keepdim=True, unbiased=False) and torch.sqrt(var + eps).

42. Causal mask: scores has shape (T, T). Why is the first row nan?

mask = torch.triu(torch.ones(T, T, dtype=torch.bool))
scores = scores.masked_fill(mask, float("-inf")).softmax(-1)
Solution

triu keeps the diagonal by default, so each token is blocked from attending to itself. Row 0 then has every entry set to −∞-\infty, and the softmax of an all-−∞-\infty row is nan. Mask strictly above the diagonal: torch.triu(..., diagonal=1).

43. Padding mask: Do padded positions still get attention?

scores = scores.masked_fill(pad_mask, 0.0).softmax(-1)
Solution

Yes. A score of 0 still gets weight e0=1e^0 = 1 before normalization, the same as any other token scoring 0. Fill with −∞-\infty (or the most negative value of the dtype) so the weight is exactly 0.

44. Attention scale: q and k have shape (B, h, T, head_dim). What is wrong?

scores = q @ k.transpose(-2, -1) / math.sqrt(d_model)
Solution

It should divide by dh\sqrt{d_h}, where dhd_h is head_dim, the length of the vectors in each dot product. With dmodel\sqrt{d_\text{model}} the scores are h\sqrt{h} times too small, so attention is too flat.

45. Language model loss: tokens has shape (B, T) and the model is causal. Why does the loss go to almost zero?

logits = model(tokens)                      # (B, T, V)
loss = F.cross_entropy(logits.reshape(-1, V), tokens.reshape(-1))
Solution

Position tt is trained to predict token tt, which it can already see, so the model learns to copy its input. Shift by one so position tt predicts token t+1t + 1:

loss = F.cross_entropy(logits[:, :-1].reshape(-1, V),
                       tokens[:, 1:].reshape(-1))

Use reshape, not view: for batch size above 1 the slice is not contiguous and view raises an error, though a test with batch size 1 passes.

46. Padded loss: mask is 1 on real tokens and 0 on padding. What is wrong with the average?

per_token = F.cross_entropy(logits.transpose(1, 2), targets, reduction="none")  # (B, T)
loss = (per_token * mask).mean()
Solution

.mean() divides by B⋅TB \cdot T, padding included, so the loss shrinks as the share of padding grows. Divide by the number of real tokens: (per_token * mask).sum() / mask.sum(). Alternatively, set padded targets to −100-100 and use the default ignore_index.

47. Nearest documents: docs has shape (n, d) and query has shape (d,). What does this return?

def top_k(query, docs, k):
    sims = docs @ query
    return np.argsort(sims)[:k]
Solution

The kk least similar documents. argsort sorts in ascending order. Use np.argsort(-sims)[:k], or np.argpartition when nn is large: it finds the top kk in linear time, then sort just those kk.

48. Cosine similarity: a has shape (n, d) and b has shape (m, d). What is wrong?

def cosine(a, b):
    return a @ b.T / (np.linalg.norm(a) * np.linalg.norm(b))
Solution

Without axis, np.linalg.norm returns one number for the whole matrix. The result is the raw dot product divided by a constant, so long vectors rank higher. The scores also shrink as a and b get more rows: 10 copies of the same unit vector score 0.1 against each other instead of 1, so a threshold such as 0.8 means nothing. Normalize each row:

def cosine(a, b):
    a = a / np.linalg.norm(a, axis=1, keepdims=True)
    b = b / np.linalg.norm(b, axis=1, keepdims=True)
    return a @ b.T

Training and evaluation

49. Training loop: What is missing?

for x, y in loader:
    loss = loss_fn(model(x), y)
    loss.backward()
    optimizer.step()
Solution

optimizer.zero_grad(). PyTorch adds each new gradient to .grad, so every step uses the sum of all gradients so far. Call it at the start of each step.

50. Evaluation: What are the problems?

def evaluate(model, loader):
    losses = []
    for x, y in loader:
        losses.append(loss_fn(model(x), y))
    return sum(losses) / len(losses)
Solution

Three:

  • No model.eval(), so dropout stays on and batch norm updates its running statistics from evaluation data.
  • No torch.no_grad(), so every forward pass builds a graph.
  • Each stored loss tensor keeps its graph alive, so memory grows with the dataset. Store loss.item().

Put the model back in model.train() mode afterwards, or the next training steps run in eval mode.

51. Gradient accumulation: Gradients are accumulated over accum batches. What is wrong?

for i, (x, y) in enumerate(loader):
    loss = loss_fn(model(x), y)
    loss.backward()
    if (i + 1) % accum == 0:
        optimizer.step()
        optimizer.zero_grad()
Solution

The gradient is the sum of accum batch means, so the update is accum times too large, as if the learning rate were scaled up. With Adam a uniform scale mostly cancels, but gradient clipping still sees the larger norm. Backpropagate loss / accum. Also, when the number of batches isn't a multiple of accum, the final batches are backpropagated but never stepped.

52. Shuffling data: What is wrong?

np.random.shuffle(X)
np.random.shuffle(y)
Solution

The two arrays are shuffled independently, so features no longer line up with labels. Accuracy drops towards chance and nothing raises. Apply one permutation to both: perm = np.random.permutation(len(X)), then X, y = X[perm], y[perm].

53. Normalizing before the split: What is wrong?

X = (X - X.mean(axis=0)) / X.std(axis=0)
X_train, X_test = X[:n_train], X[n_train:]
Solution

The statistics include the test set, so information about it leaks into training. Compute the mean and standard deviation on X_train only, and apply those to both sets. If the rows are ordered (by time or by class), a split by position is also biased: shuffle first, or split by time on purpose.

54. Pre-norm block: The docstring says pre-norm. Does the code match?

class Block(nn.Module):
    """Pre-norm transformer block."""

    def forward(self, x):
        x = self.norm1(x + self.attn(x))
        x = self.norm2(x + self.mlp(x))
        return x
Solution

No, this is post-norm: it normalizes after the residual add. Pre-norm normalizes each sublayer's input and leaves the residual path untouched, which is why it trains more stably in deep models:

x = x + self.attn(self.norm1(x))
x = x + self.mlp(self.norm2(x))

A pre-norm stack also needs a final norm after the last block.