Skip to content
BIASED

Debugging and profiling

Block 1 of 8~3 min

The test failed — why?

The topic Testing ended with a failing test. A failing test says that a result is wrong and where the check was made, but not why. The cause is often a few calls away from the symptom, or shows up on one batch in ten thousand. This topic is about finding causes without guessing. It also covers the other kind of problem: a correct program that is too slow or uses too much memory.

The tool everyone reaches for first is print: add print(total), rerun, read, move the print, rerun. On larger problems it fails in three ways. Every question costs an edit and a rerun. You see only what you chose to print before you knew what was wrong. And the prints stay behind and clutter the output. This topic replaces each use of print with a tool built for the job: the traceback for where did it fail, the debugger for what were the values, logging for what happened during a long run, and profilers for where did the time go.

Start with the worst kind of bug, the one that raises nothing. The mean loss of an epoch weights each batch's loss by its size. A bug in the loader lost the size of the last, smaller batch:

def epoch_loss(losses, sizes):
    total = 0.0
    for loss, n in zip(losses, sizes):
        total += loss * n
    return total / sum(sizes)
 
def summarize(batch):
    return epoch_loss(batch["losses"], batch["sizes"])
 
print(summarize({"losses": [1.0, 0.5, 0.25], "sizes": [32, 32]}))

The program prints a plausible number and no error. zip stops at its shorter argument, so the third batch is dropped without a word. A test that expects the right answer, 0.65, fails, and its report points at the assert, far from the cause.

Since Python 3.10, zip(..., strict=True) raises ValueError when its arguments have different lengths. With zip(losses, sizes, strict=True) on line 3, the program fails where the problem is:

Traceback (most recent call last):
  File ".../strict.py", line 10, in <module>
    print(summarize({"losses": [1.0, 0.5, 0.25], "sizes": [32, 32]}))
          ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../strict.py", line 8, in summarize
    return epoch_loss(batch["losses"], batch["sizes"])
  File ".../strict.py", line 3, in epoch_loss
    for loss, n in zip(losses, sizes, strict=True):
                   ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: zip() argument 2 is shorter than argument 1

The rule: make wrong states fail loudly and early. Check inputs at the boundary of a function, use strict=True, and prefer an exception to a default value that hides the problem. A traceback near the cause is worth more than any debugger session far from it.

Answers are saved on the server and tied to this browser until you sign in.