Skip to content
BIASED

Debugging and profiling

Finding out why a program is wrong or slow without guessing — chained tracebacks, breakpoint() and pdb, logging instead of print, timing with perf_counter and timeit, profiling with cProfile, and memory with tracemalloc.

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.

Chained tracebacks

The topic Running Python gave the rule for reading a traceback. The last line says what went wrong, the frame above it says where, and the frames above that show how the program got there. Real programs add one more pattern. When an exception is raised while another one is being handled, Python prints both, the older one first, joined by one of two sentences.

Here a config parser turns a bad value into a clearer error on purpose, with raise ... from err:

def parse_lr(text):
    try:
        return float(text)
    except ValueError as err:
        raise RuntimeError(f"bad lr in config: {text!r}") from err
 
parse_lr("3e-4x")
Traceback (most recent call last):
  File ".../chain.py", line 3, in parse_lr
    return float(text)
ValueError: could not convert string to float: '3e-4x'
 
The above exception was the direct cause of the following exception:
 
Traceback (most recent call last):
  File ".../chain.py", line 7, in <module>
    parse_lr("3e-4x")
    ~~~~~~~~^^^^^^^^^
  File ".../chain.py", line 5, in parse_lr
    raise RuntimeError(f"bad lr in config: {text!r}") from err
RuntimeError: bad lr in config: '3e-4x'

The above exception was the direct cause of the following exception marks a deliberate translation. The second report is the meaningful one; the first gives the detail.

The other sentence is During handling of the above exception, another exception occurred. It means the second error happened by accident, inside the except block. Then the first report is the original problem, the second is a bug in the error handling, and both need fixing.

In either case the last line of the whole output names the exception that ended the program. It is not always the first thing that went wrong.

breakpoint() and pdb

A debugger pauses a running program at a chosen line and lets you inspect every active function call, each with its own local variables. The built-in breakpoint() (since Python 3.7) sets a breakpoint: the program stops at that line and opens pdb, the debugger of the standard library. The commands you need first:

Command Does
p expr, pp expr print (pretty-print) an expression in the current frame
l, ll list the source around the current line; the whole function
n next: run the current line, stepping over calls
s step: run the current line, stepping into a call
c continue to the next breakpoint or the end
w where: print the stack, oldest frame first
u, d move to the caller's frame (up) or back (down)
q quit and stop the program

Any other line runs as Python in the current frame, so len(sizes) works directly. A variable named like a command, such as n, needs p n.

Put breakpoint() before the return of epoch_loss (the version without strict) and run the script. This is a real session; the commands are shown after each (Pdb) prompt:

$ python grades.py
> .../grades.py(5)epoch_loss()
-> breakpoint()
(Pdb) p losses, sizes
([1.0, 0.5, 0.25], [32, 32])
(Pdb) w
  .../grades.py(11)<module>()
-> print(summarize({"losses": [1.0, 0.5, 0.25], "sizes": [32, 32]}))
  .../grades.py(9)summarize()
-> return epoch_loss(batch["losses"], batch["sizes"])
> .../grades.py(5)epoch_loss()
-> breakpoint()
(Pdb) up
> .../grades.py(9)summarize()
-> return epoch_loss(batch["losses"], batch["sizes"])
(Pdb) p batch["sizes"]
[32, 32]
(Pdb) c
0.75

p shows the bug at once: three losses, two sizes. w prints the stack in traceback order and marks the current frame with >. up moves to the caller, summarize, whose local batch shows that the data was already inconsistent when it arrived. c lets the program finish.

Why this works: every call of a Python function gets a frame, a record of the call's local variables, its current position and a link to the caller's frame. Frames form the chain that w and a traceback print. pdb itself is ordinary Python code. The interpreter calls a hook that pdb registers (sys.settrace) on every new line and every call, and the hook stops and reads the frame.

Debugging after the crash

Often you learn about a bug from a traceback, after the fact. python -m pdb -c continue script.py runs the script under pdb. When an uncaught exception ends it, pdb stops in the frame that raised, with all its variables intact. This is post-mortem debugging. On the strict=True version:

$ python -m pdb -c continue strict.py
Traceback (most recent call last):
  ...
ValueError: zip() argument 2 is shorter than argument 1
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> .../strict.py(3)epoch_loss()
-> for loss, n in zip(losses, sizes, strict=True):
(Pdb) up
> .../strict.py(8)summarize()
-> return epoch_loss(batch["losses"], batch["sizes"])
(Pdb) p batch["sizes"]
[32, 32]

In a REPL or a notebook, import pdb; pdb.pm() does the same for the last exception, and Jupyter's %debug is the same idea. New in Python 3.14: python -m pdb -p PID attaches pdb to a Python process that is already running. The debuggers of VS Code and PyCharm offer the same operations with a mouse, on the same interpreter hooks.

The common mistake is to commit a breakpoint(). A program that stops to wait for input during a test run or on a server simply hangs. breakpoint() calls sys.breakpointhook(), and the environment variable PYTHONBREAKPOINT changes that hook. PYTHONBREAKPOINT=0 turns every breakpoint() into a no-op, a cheap safety net for continuous integration.

Logging instead of print

A training run that lasts hours, or a server, has nobody to stop it in a debugger. The program has to record what it does, and the standard tool is the module logging. Its model has three parts.

  • A logger is a named channel, created once per module with logging.getLogger(__name__). Its methods debug, info, warning, error and critical are levels of importance: 10, 20, 30, 40 and 50.
  • A handler decides where records go (standard error, a file, a remote service), and a formatter decides how they look.
  • Configuration happens once, at the program's entry point. logging.basicConfig(level=..., format=...) attaches a handler that writes to standard error. A record below the configured level is dropped before it is formatted.
import logging
 
logger = logging.getLogger("train")
 
def train(losses):
    for epoch, loss in enumerate(losses):
        logger.debug("epoch %d: loss %.3f", epoch, loss)
        if loss > losses[0]:
            logger.warning("loss went up at epoch %d", epoch)
    logger.info("done, final loss %.3f", losses[-1])
 
logging.basicConfig(level=logging.INFO,
                    format="%(levelname)s %(name)s: %(message)s")
train([0.92, 0.71, 0.95, 0.40])
$ python train_log.py
WARNING train: loss went up at epoch 2
INFO train: done, final loss 0.400

The four DEBUG records are dropped at level INFO. With level=logging.DEBUG they appear, and the code that logs does not change. Every record carries its level and its logger's name, so a long log can be filtered. All of it goes to standard error: python train_log.py 2>/dev/null prints nothing, which keeps the log apart from the program's real output. Inside an except block, logger.exception(...) logs at ERROR level and appends the traceback, so the program records the error and keeps going.

Three rules follow from the model:

  • print for output, logging for diagnostics.
  • Pass arguments, not an f-string: with logger.debug("loss %.3f", loss) the message is built only if the record is emitted.
  • Libraries never configure logging. They create loggers and log; basicConfig belongs to the application. This is how PyTorch and Hugging Face Transformers report their warnings, and why your script can turn their verbosity down.

Measuring time

A correct but slow program raises a different question: where does the time go? First measure, in a way you can trust. The running example builds a vocabulary: the distinct words of a corpus in order of first appearance.

import random
 
def tokenize(text):
    return [w.strip(".,").lower() for w in text.split()]
 
def build_vocab(words):
    vocab = []
    for w in words:
        if w not in vocab:
            vocab.append(w)
    return vocab
 
rng = random.Random(1)
text = " ".join(f"w{rng.randrange(3_000)}" for _ in range(100_000))
print(len(build_vocab(tokenize(text))))

It prints 3000, after a noticeable pause. Before changing anything, time it.

Which clock. time.perf_counter() is a monotonic clock with the best available resolution; the difference of two readings is elapsed wall time. time.process_time() counts only the CPU time of the process. time.time() is the calendar clock. It can jump when the system adjusts its time, so it is the wrong tool for intervals. Around a function that sleeps for 0.2 s and then computes, one laptop showed wall 0.29 s, cpu 0.09 s.

Repeat, and report the minimum and the median.

import statistics, time
 
words = tokenize(text)
runs = []
for _ in range(5):
    t0 = time.perf_counter()
    build_vocab(words)
    runs.append(time.perf_counter() - t0)
print(" ".join(f"{t:.2f}" for t in runs))
print(f"min {min(runs):.2f} s, median {statistics.median(runs):.2f} s")
1.43 1.46 1.47 1.49 1.48
min 1.43 s, median 1.47 s

These numbers come from one laptop at one quiet moment; yours will differ. An earlier run of the same code, while other programs competed for the processor, gave 1.87, 2.29, 1.77, 1.64 and 1.63 s: on the same words, one run was 40 % slower than another. The minimum estimates the cost when nothing interferes; the median is what a user typically sees. A difference smaller than the spread between runs is not a difference. Discard the first run of a short benchmark too: imports, caches and the interpreter's own warm-up make it slower.

timeit for small pieces. An operation of nanoseconds cannot be timed with two clock readings. The module timeit runs a statement many times in a loop and divides:

$ python -m timeit -s "vocab = [f'w{i}' for i in range(3000)]" "'w2999' in vocab"
10000 loops, best of 5: 22.6 usec per loop
$ python -m timeit -s "vocab = {f'w{i}' for i in range(3000)}" "'w2999' in vocab"
20000000 loops, best of 5: 12.7 nsec per loop

-s is setup code and is not timed. The command chooses a number of loops so that one batch takes at least 0.2 s, repeats the batch five times and reports the best, with the garbage collector switched off while it times. In code, timeit.Timer(stmt, setup).repeat(repeat=5, number=n) returns the times of five batches of n runs each.

Profiling with cProfile

A timer says how long the whole program takes. A profiler says how that time divides between functions. The standard library's cProfile is a deterministic profiler: it records every function call and return and sums the time per function. Run the vocabulary script under it, sorted by the tottime column (the first rows):

$ python -m cProfile -s tottime vocab.py
3000
         840357 function calls (840334 primitive calls) in 1.992 seconds
 
   Ordered by: internal time
 
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    1.795    1.795    1.796    1.796 vocab.py:6(build_vocab)
   100000    0.039    0.000    0.061    0.000 random.py:245(_randbelow_with_getrandbits)
   100000    0.033    0.000    0.102    0.000 random.py:294(randrange)
   100001    0.032    0.000    0.134    0.000 vocab.py:14(<genexpr>)
        1    0.025    0.025    0.046    0.046 vocab.py:3(tokenize)
       37    0.013    0.000    0.148    0.004 {method 'join' of 'str' objects}
   136605    0.013    0.000    0.013    0.000 {method 'getrandbits' of '_random.Random' objects}
   100000    0.010    0.000    0.010    0.000 {method 'lower' of 'str' objects}
   100000    0.009    0.000    0.009    0.000 {method 'strip' of 'str' objects}
        1    0.003    0.003    0.003    0.003 {method 'split' of 'str' objects}

The columns: ncalls is the number of calls. tottime is the time inside the function itself, excluding the functions it called; cumtime includes them. Each percall divides the column before it by ncalls. Sort by tottime to find the function that does the work, by cumtime to find the high-level step that contains it. The <genexpr> row is the generator expression that builds the corpus: a generator is a function too, and each resumption counts as a call.

build_vocab takes 1.80 s of 1.99 s, about 90 %. Nothing else is worth optimizing.

What cProfile cannot see. Its unit is the function call; lines and operators inside a function are invisible. Further down the table, {method 'append' of 'list' objects} has a row of its own: 3,010 calls, 0.000 s.

Overhead. Recording every call costs time per call, so code made of many small calls looks slower under the profiler than it is. Timed with perf_counter and no profiler, tokenize took about 0.008 s instead of 0.046 s, while build_vocab, which makes few calls, took about the same. The ranking survives; the shares shift. Sampling profilers avoid this. They interrupt the program many times a second, record the current stack and estimate each function's share from how often it appears. Their overhead is small, and they can see lines. py-spy, a third-party tool, samples a running process from the outside; Python 3.15 adds profiling.sampling to the standard library.

The fix comes from the topic Dictionaries and sets: w not in vocab scans a list of up to 3,000 strings, while a set answers with one hash lookup. Keeping a seen set next to the list took build_vocab from more than a second to about 4 ms on the same words. To profile one section from code, use cProfile.Profile() with .enable() and .disable(), then pstats.Stats(profiler).sort_stats("cumulative").print_stats(10).

Memory, and what comes next

When a program runs out of memory, or a long run keeps growing, the question is which lines allocate. The module tracemalloc hooks Python's memory allocator and records, for each block, the line that allocated it. It sees everything allocated through Python's allocator, NumPy's array buffers included; memory that other C libraries take directly is not counted.

import tracemalloc
 
def peak_kib(f, n):
    tracemalloc.reset_peak()
    base = tracemalloc.get_traced_memory()[0]
    f(n)
    return (tracemalloc.get_traced_memory()[1] - base) / 2**10
 
tracemalloc.start()
rows = [{"step": i, "loss": 1 / (i + 1)} for i in range(100_000)]
print(tracemalloc.take_snapshot().statistics("lineno")[0])
print(f"{peak_kib(lambda n: sum([i * i for i in range(n)]), 1_000_000):,.1f} KiB")
print(f"{peak_kib(lambda n: sum(i * i for i in range(n)), 1_000_000):,.1f} KiB")
.../mem.py:10: size=23.6 MiB, count=399718, average=62 B
39,500.1 KiB
0.4 KiB

The largest line is line 10: 100,000 small dicts of metrics, about four blocks and 247 bytes each, where the two numbers alone would take 16. The list version of the sum peaks at about 38.6 MiB, because it holds a million integers before adding them. The generator holds one at a time and peaks at 0.4 KiB for the same answer: the lazy pipeline from Iteration, comprehensions and generators, measured. A second snapshot taken later can be compared with the first: snapshot2.compare_to(snapshot1, "lineno") lists the lines whose allocations changed between them. Tracing slows allocation down noticeably, so turn it on for an investigation and off afterwards.

The toolkit, question by question:

Question Tool
Where did it fail? the traceback, read from the bottom; chained reports in order
What were the values? breakpoint() and pdb; post-mortem with -c continue
What happened in a long run? logging, to standard error
How long does it take? perf_counter, repeated; timeit for small statements
Which function is slow? cProfile and pstats
Which line allocates? tracemalloc

This closes the module Reliable code, and it leaves a question open. Even the fast set version spends about 40 ns per word, while the processor adds two numbers in under one. Every Python function call costs enough that cProfile's bookkeeping inflates tokenize several times. And what exactly is the frame that pdb walks? The answers are inside the interpreter. The next topic, How CPython runs code, follows a function from source to bytecode and through the evaluation loop with its frames, and shows where Python's own costs come from.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

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