Module contents
Lesson 8 of 24Core 80 min

Testing numerical code with pytest and Hypothesis

Numerical code fails silently: it returns plausible but incorrect numbers. Build a specific testing strategy: dtype-justified tolerances, tests against slow but obvious reference implementations, metamorphic relations without an oracle, Hypothesis properties over generated arrays, and stochastic-code tests with a controlled false-positive rate, all organized with pytest.

After this lesson you can

  • Organize a pytest suite using fixtures, parametrization, conftest.py, and markers (slow, gpu).
  • Choose rtol and atol justified by dtype and calculation, and use np.testing.assert_allclose and torch.testing.assert_close.
  • Write reference-implementation and metamorphic-relation tests (permutation, scaling, symmetry, conservation).
  • Write property-based tests with Hypothesis, including arrays of varying shapes and dtypes, and interpret minimal counterexamples.
  • Test stochastic code with fixed seeds and statistical thresholds with a known false-failure rate.

Before you start

Motivation: the bug that raises no exceptions

A syntax error is visible. An out-of-range index raises an exception. But a typical numerical-code error does neither: it returns numbers of the correct shape and size that look perfectly reasonable. They are wrong, and nothing says so.

The most cited case is Geoffrey Chang, a crystallographer at the Scripps Research Institute. In 2006 he retracted five papers, three in Science, published between 2001 and 2005: an analysis program written in his laboratory swapped two data columns, inverting the electron-density map from which protein structures were derived (G. Miller, “A Scientist’s Nightmare: Software Problem Leads to Five Retractions,” Science 314, 2006). The program did not crash. It produced coherent structures that passed peer review and were used by other groups for years, until another laboratory published the structure of a homologous protein and it proved incompatible with his.

In machine learning the problem is even more treacherous because training compensates: a network with incorrectly normalized softmax, an attention mask shifted one position, or a loss that unintentionally broadcasts shapes still learns something and its loss curve falls. Consider this example:

[ ]A bug that passes naive testsBrowser
import numpy as np

def softmax_filas(X):
    """Softmax de cada fila de X (una fila = los logits de un ejemplo)."""
    E = np.exp(X - X.max(axis=1, keepdims=True))
    return E / E.sum(axis=0, keepdims=True)        # bug: debería ser axis=1

rng = np.random.default_rng(0)
X = rng.normal(size=(4, 4))
P = softmax_filas(X)

print("forma correcta:              ", P.shape == X.shape)
print("valores en [0, 1]:           ", bool(((P >= 0) & (P <= 1)).all()))
print("suma total = número de filas:", bool(np.isclose(P.sum(), X.shape[0])))

def softmax_referencia(fila):          # una fila con un bucle: lenta, pero obviamente correcta
    e = [np.exp(v) for v in fila]
    s = sum(e)
    return [v / s for v in e]

R = np.array([softmax_referencia(fila) for fila in X])
print("\nerror máximo frente a la referencia:", np.abs(P - R).max())
print("suma de cada fila:", P.sum(axis=1))

The first three checks are what one writes in a hurry, and all pass: the shape is right, all values are probabilities, and the total sum is expected (because the matrix is square and column normalization also distributes one unit of mass per column). Only comparison with an obvious row-by-row implementation reveals an error on the order of 0.2. This lesson builds a testing strategy for numerical code, which has three distinctive problems:

  1. There is no exact equality. Two correct implementations of the same formula differ in their last bits. Approximate equality needs justified tolerances, neither so strict that rounding fails nor so loose that bugs pass.
  2. There is often no oracle. If you knew the exact result you would not need the program. Construct partial oracles: reference implementations, cases with closed-form solutions, and relationships that must hold even without knowing the result.
  3. Failures live at extremes. Overflow, zeros, empty arrays, repeated values: these rarely appear with rng.normal. Generate inputs that deliberately seek them.

Serious pytest

pytest is Python’s standard testing tool. Its model is simple: a test is a function whose name starts with test_ and fails if it raises an exception, usually AssertionError.

  • Discovery. pytest traverses the given directories (or configured testpaths) and collects test_*.py or *_test.py files; within them, test_* functions and test_* methods of Test* classes without __init__.
  • Assertions. A normal assert suffices. pytest rewrites assertions when importing the test module and, when one fails, shows intermediate expression values. No self.assertEqual is needed.
  • Expected exceptions and warnings. with pytest.raises(ValueError, match="forma"): and with pytest.warns(RuntimeWarning): fail if the block does not raise the expected item.

The three pieces turning a collection of functions into a maintainable suite are fixtures, parametrization, and markers.

Both are decorators in the sense of lesson 3: parametrize executes nothing, only annotates the function so collection can generate cases. The best way to demystify them is to write them. Here is a minimal runner with fixtures injected by name, fixtures using yield, and stackable parametrization:

[ ]A mini pytest from scratchBrowser
import inspect

FIXTURES = {}

def fixture(fn):
    """Registra una fixture: se inyecta en los tests que tengan un argumento con su nombre."""
    FIXTURES[fn.__name__] = fn
    return fn

def parametrize(nombres, valores):
    """Como pytest.mark.parametrize: guarda los casos en un atributo de la función."""
    nombres = [n.strip() for n in nombres.split(",")]
    def decorador(fn):
        previos = getattr(fn, "_casos", [{}])
        nuevos = [dict(zip(nombres, v if len(nombres) > 1 else (v,))) for v in valores]
        fn._casos = [{**p, **n} for p in previos for n in nuevos]    # apilar = producto cartesiano
        return fn
    return decorador

def resolver(nombre, cache, pendientes):
    """Valor de una fixture, resolviendo antes las fixtures de las que depende."""
    if nombre not in cache:
        fn = FIXTURES[nombre]
        args = {p: resolver(p, cache, pendientes) for p in inspect.signature(fn).parameters}
        valor = fn(**args)
        if inspect.isgenerator(valor):          # fixture con yield: lo que sigue al yield es la limpieza
            pendientes.append(valor)
            valor = next(valor)
        cache[nombre] = valor
    return cache[nombre]

def ejecutar(espacio):
    resultados = []
    for nombre, fn in list(espacio.items()):
        if not (nombre.startswith("test_") and callable(fn)):
            continue
        for caso in getattr(fn, "_casos", [{}]):
            ident = nombre + (f"[{'-'.join(map(str, caso.values()))}]" if caso else "")
            cache, pendientes = {}, []             # alcance «function»: fixtures nuevas en cada caso
            try:
                args = {p: caso[p] if p in caso else resolver(p, cache, pendientes)
                        for p in inspect.signature(fn).parameters}
                fn(**args)
                resultados.append(("PASA", ident, ""))
            except AssertionError as e:
                resultados.append(("FALLA", ident, str(e)))
            except Exception as e:
                resultados.append(("ERROR", ident, f"{type(e).__name__}: {e}"))
            finally:
                for gen in reversed(pendientes):  # limpieza en orden inverso al montaje
                    next(gen, None)
    return resultados

With a few dozen lines we have the essentials. Try it with three tests: one parametrized with two stacked decorators, one that fails, and one raising an unexpected exception.

[ ]Mini pytest in actionBrowser
import numpy as np

@fixture
def rng():
    return np.random.default_rng(0)

@fixture
def datos(rng):
    print("  montaje: datos nuevos")
    yield rng.normal(size=(5, 3))
    print("  limpieza")

@parametrize("eje", [0, 1])
@parametrize("escala", [1.0, 1e6])
def test_media_traslada(datos, eje, escala):
    x = escala * datos
    assert np.allclose((x + 7).mean(axis=eje), x.mean(axis=eje) + 7), "la media no se traslada"

def test_igualdad_exacta():
    assert 0.1 + 0.2 == 0.3, f"0.1 + 0.2 = {0.1 + 0.2!r}"

def test_formas(datos):
    datos @ datos                               # (5, 3) @ (5, 3)

for estado, ident, msg in ejecutar(dict(globals())):
    print(f"{estado:5s} {ident}  {msg}")

# pytest importa cada fichero de tests como un módulo aparte; aquí todas las celdas comparten
# un mismo espacio de nombres, así que retiramos estos tests para que no se mezclen con otros
for nombre in [n for n in globals() if n.startswith("test_")]:
    del globals()[nombre]

Notice three details pytest handles the same way. Fixture datos is set up and cleaned up once per case: with function scope, each test receives fresh data and no test can contaminate another. datos itself requests rng, and the runner resolves the chain by name. There are two kinds of failure: an unmet assert (FALLA, fail) and an unexpected exception (ERROR); pytest distinguishes them in its report too.

What our runner does not do is what makes pytest useful in a real project:

  • conftest.py. A file with that name in any test directory defines fixtures and hooks visible to every test in that directory and its subdirectories, without importing it. Shared random generators, test data, and marker configuration live there.
  • Markers. @pytest.mark.slow or @pytest.mark.gpu label tests, and -m "not slow" selects by labels with Boolean expressions. -k "softmax and not grande" selects by name substrings. Custom markers are declared (in pyproject.toml or pytest_configure) and --strict-markers turns a misspelled marker into an error.
  • Built-in markers. skip, skipif(condición, reason=...), and xfail (expected failure; with strict=True, unexpected success is also an error).
  • Built-in fixtures. tmp_path (a unique temporary directory per test), monkeypatch (replace attributes or environment variables during a test), capsys (capture output), and request (information about the test requesting the fixture).

Real pytest is available in the browser. The next cell writes conftest.py and a test file in a temporary directory and runs pytest three times, as you would in a terminal:

[ ]Real pytest: conftest, parametrize, markers, and selectionBrowser
import os, io, textwrap, tempfile, contextlib
import numpy as np
import pytest

carpeta = tempfile.mkdtemp()
def escribe(nombre, codigo):
    with open(os.path.join(carpeta, nombre), "w", encoding="utf-8") as f:
        f.write(textwrap.dedent(codigo))

escribe("conftest.py", '''
    import numpy as np
    import pytest

    def pytest_configure(config):
        config.addinivalue_line("markers", "slow: test lento")

    @pytest.fixture(scope="session")
    def datos():
        return np.random.default_rng(0).normal(size=(200, 3))
''')

escribe("test_estandarizar.py", '''
    import numpy as np
    import pytest

    def estandarizar(X):
        s = X.std(axis=0)
        if np.any(s == 0):
            raise ValueError("columna constante: no se puede estandarizar")
        return (X - X.mean(axis=0)) / s

    @pytest.mark.parametrize("escala", [1e-3, 1.0, 1e3])
    @pytest.mark.parametrize("desplazamiento", [0.0, 50.0])
    def test_invariante_afin(datos, escala, desplazamiento):
        Z = estandarizar(escala * datos + desplazamiento)
        np.testing.assert_allclose(Z, estandarizar(datos), rtol=1e-9, atol=1e-12)

    def test_media_cero_y_varianza_uno(datos):
        Z = estandarizar(datos)
        assert Z.mean(axis=0) == pytest.approx(0, abs=1e-12)
        assert Z.std(axis=0) == pytest.approx(1)

    def test_columna_constante_falla():
        with pytest.raises(ValueError, match="constante"):
            estandarizar(np.ones((4, 2)))

    @pytest.mark.slow
    def test_muchos_datos():
        X = np.random.default_rng(1).normal(size=(10**6, 3))
        assert abs(estandarizar(X).mean()) < 1e-12
''')

def pytest_(*args):
    salida = io.StringIO()
    with contextlib.redirect_stdout(salida):
        codigo = pytest.main(["-p", "no:cacheprovider", *args])
    print(f"$ pytest {' '.join(args)}    (código de salida {int(codigo)})")
    print(salida.getvalue().strip(), "\n")

anterior = os.getcwd()
os.chdir(carpeta)
try:
    pytest_("--collect-only", "-q")
    pytest_("-q", "-m", "not slow", "--tb=line")
    pytest_("-q", "-k", "media or constante")
finally:
    os.chdir(anterior)

Collection shows nine tests from four functions: the two stacked parametrize decorators generate 2×3=62 \times 3 = 6 cases, with identifiers like [50.0-0.001] that can be passed to -k. The second run deselects the slow test and, above all, finds a real failure: test_invariante_afin[50.0-0.001]. Standardization is invariant to affine transforms in exact arithmetic, but with offset 50 and scale 10−310^{-3}, subtracting the mean cancels almost all digits: each datum carries absolute rounding of about u⋅50u \cdot 50, which divided by standard deviation 10−310^{-3} becomes a Z\mat{Z} error on the order of 5⋅104 u≈10−115\cdot 10^{4}\,u \approx 10^{-11}. For Z\mat{Z} elements of size 1 that error fits rtol=10−9\texttt{rtol} = 10^{-9}, but near 0 only the requested absolute tolerance 10−1210^{-12} remains, which is stricter: failing elements are precisely the small-valued ones. The code has no bug; the test tolerance is wrong. The next sections explain how to choose it.

Approximate equality

The assert_allclose condition

If aa is the obtained value and dd the desired one, absolute error is ∣a−d∣\abs{a - d} and relative error is ∣a−d∣/∣d∣\abs{a - d}/\abs{d} (defined if d≠0d \neq 0). Relative error is natural for floating-point numbers, whose rounding is relative: by the standard model, each operation satisfies fl⁡(x∘y)=(x∘y)(1+δ)\operatorname{fl}(x \circ y) = (x \circ y)(1 + \delta) with ∣δ∣≤u\abs{\delta} \le u, where uu is unit roundoff: u=2−24≈6.0⋅10−8u = 2^{-24} \approx 6.0\cdot 10^{-8} in float32 and u=2−53≈1.1⋅10−16u = 2^{-53} \approx 1.1\cdot 10^{-16} in float64 (machine epsilon returned by np.finfo(dtype).eps is 2u2u). But relative error explodes as dd approaches zero, and a result that should be exactly 0 rarely is.

Geometrically, in the (desired, obtained) plane the accepted region surrounds diagonal a=da = d: a cone of slope rtol\texttt{rtol} closing at d=0d = 0, widened by a band of half-width atol\texttt{atol}. For ∣d∣≪atol/rtol\abs{d} \ll \texttt{atol}/\texttt{rtol} the band dominates; for ∣d∣≫atol/rtol\abs{d} \gg \texttt{atol}/\texttt{rtol} the cone does. On a logarithmic scale the boundary is a hockey stick: horizontal at atol\texttt{atol} and then a line of slope 1.

InteractiveThe assert_allclose acceptance zone
10⁻²⁵10⁻²⁰10⁻¹⁵10⁻¹⁰10⁻⁵10⁰10⁻¹²10⁻⁹10⁻⁶10⁻³10⁰10³0↑ error |a − d|expected value |d| →0np.sum of 10⁴ uniform samples on [0, 1)sumdot product of two normal samples, n = 1000dotstable logsumexp of 100 valueslsestable softmax: smallest probability (≈ 9·10⁻⁸)min psin(π), which should equal 0sin πmean of 1000 already centered values (should equal 0)mean 0variance with ddof=1 of 1000 valuesvarexp(log(10⁻¹⁰))exp∘logbug: variance with ddof=0 instead of ddof=1 (n = 1000)ddofbug: N(0, 1) density at x = 6 without factor 1/√(2π)densitybug: softmax of a 4×4 matrix normalized with axis=0axisbug: mean that skips first element (n = 1000)skips firstbug: sum of 10⁴ uniform values without the last termskips last
  • correct calculation (rounding)
  • calculation with a bug
  • accepted region: ∣a−d∣≤atol+rtol ∣d∣\abs{a - d} \le \texttt{atol} + \texttt{rtol}\,\abs{d}
  • ring: test is wrong
Tolerances
1·10⁻⁷
0
Rounding accepted4 of 8
Bugs rejected5 of 5
With atol=0\texttt{atol} = 0, a result that should equal 0 passes only if exactly 0: there rtol⋅∣d∣=0\texttt{rtol}\cdot\abs{d} = 0. Rounding of sin⁡π\sin\pi cannot be accommodated without absolute tolerance.
sin(π), which should equal 0
Expected dd0
∣a−d∣\abs{a - d}8.74·10⁻⁸
Relative errorundefined
atol+rtol⋅∣d∣\texttt{atol} + \texttt{rtol}\cdot\abs{d}0
Verdictfails
Thirteen real results computed with NumPy in float32 and float64 against their exact values. Circles are correct calculations with only rounding error; diamonds contain a bug. Horizontally is expected value, vertically error; values that should be exactly 0 have their own column at left, where only atol counts, and results with no error have their own row below. The shaded region is accepted by ∣a−d∣≤atol+rtol ∣d∣\abs{a - d} \le \texttt{atol} + \texttt{rtol}\,\abs{d}, and dashed rings mark wrong decisions. Start with assert_allclose defaults and try other configurations. Find a float64 pair accepting all rounding and rejecting all five bugs; then try the same in float32. In ‘Geometry’ view, drag a test result and see how band and cone share the work.

Three lessons emerge. First: without atol there is no way to accept a rounded zero. sin⁡(π)\sin(\pi) gives 1.2⋅10−161.2\cdot 10^{-16} in float64 because π\pi is not representable, and with atol=0\texttt{atol} = 0 tolerance at d=0d = 0 is zero. Second: atol has units. With atol=10−8\texttt{atol} = 10^{-8}, the default of np.isclose, a normal density evaluated at x=6x = 6, worth 6.1⋅10−96.1\cdot 10^{-9}, passes even without factor 1/2π1/\sqrt{2\pi} and with 151% error. Third: rounding and bugs are often orders of magnitude apart. In float64 rounding errors are below 10−1510^{-15} relatively and bugs above 10−610^{-6}, so almost any intermediate rtol\texttt{rtol} works. In float32 the margin narrows to less than an order of magnitude, and no pair gets all thirteen cases right: rounded zeros need atol≥7.2⋅10−7\texttt{atol} \ge 7.2\cdot 10^{-7} and the density needs atol<9.2⋅10−9\texttt{atol} < 9.2\cdot 10^{-9}. The practical conclusion is each test must choose its own tolerance based on its problem’s scale; one global tolerance for the suite does not work.

How much error a correct calculation produces

Tolerances are derived from the calculation rather than chosen by trying values until the test passes. The model case is summation, appearing in almost everything (means, dot products, matrix products, normalizations).

The proof is a short induction on the standard model, done step by step in the guided exercise at the end. The theorem says three useful things for choosing rtol\texttt{rtol}:

  • The bound grows with nn, but is pessimistic. It assumes all rounding errors align in the worst direction. If rounding errors behave as independent centered variables, typical error grows as n u\sqrt{n}\,u; Higham and Mary (2019) turned this into a probabilistic theorem with bounds of form λn u\lambda\sqrt{n}\,u valid with high probability.
  • Order matters. Pairwise summation, which splits an array in half, recursively sums each half, and adds results, has bound γ⌈log⁡2n⌉\gamma_{\lceil\log_2 n\rceil}. np.sum uses a blocked version when reducing along a contiguous axis, making it much more accurate than a loop.
  • Cancellation dominates. When ∑ixi\sum_i x_i is small relative to ∑i∣xi∣\sum_i\abs{x_i}, relative error can be huge even when absolute error is tiny. This is where atol\texttt{atol} is needed, and the theorem indicates which: absolute error is on the order of u∑i∣xi∣u\sum_i\abs{x_i}, that is, uu times the data scale, not result scale.
[ ]Measuring float32 summation errorBrowser
import math
import numpy as np
import matplotlib.pyplot as plt

u32 = 2.0**-24                                    # unidad de redondeo de float32
rng = np.random.default_rng(1)
ns = np.unique(np.logspace(1, 6, 16).astype(int))
err_rec, err_pares = [], []
for n in ns:
    x = rng.uniform(0, 1, n).astype(np.float32)
    exacta = math.fsum(x.astype(np.float64))         # suma exacta de esos mismos float32
    recursiva = float(np.cumsum(x, dtype=np.float32)[-1])   # s = s + x[i], uno detrás de otro
    por_pares = float(np.sum(x, dtype=np.float32))          # np.sum: suma por pares
    err_rec.append(abs(recursiva - exacta) / exacta)
    err_pares.append(max(abs(por_pares - exacta) / exacta, 1e-10))   # 1e-10 = «exacta»

for n, a, b in zip(ns[::3], err_rec[::3], err_pares[::3]):
    print(f"n = {n:>7d}   recursiva {a:.1e}   np.sum {b:.1e}   √n·u = {math.sqrt(n) * u32:.1e}   (n-1)u = {(n - 1) * u32:.1e}")

plt.loglog(ns, err_rec, "o-", label="suma recursiva (bucle)")
plt.loglog(ns, err_pares, "s-", label="np.sum (por pares)")
plt.loglog(ns, (ns - 1) * u32, "k--", label="cota del peor caso (n − 1)u")
plt.loglog(ns, np.sqrt(ns) * u32, "k:", label="√n · u")
plt.xlabel("n"); plt.ylabel("error relativo en float32"); plt.legend(); plt.show()

A detail in the cell is itself a testing lesson: results are converted with float(...) before subtraction. If a np.float32 and a Python float are subtracted, NumPy 2 promotion rules treat float as a “weak” scalar and subtract in float32, so the exact value rounds to float32 before comparison and measured error is 0 precisely when it matters most. A test measuring error in the wrong dtype measures nothing.

Measurements confirm the theory: recursive summation stays far below the worst-case bound, even below n u\sqrt{n}\,u, and np.sum barely accumulates error. This gives a rule for choosing tolerances.

Oracles: what do you compare against?

An assertion needs a desired value. In testing terminology, the mechanism identifying the correct result for an input is an oracle, and the oracle problem is particularly hard in scientific software, as Kanewala and Bieman (2014) document in their systematic review: the program exists precisely because we do not know the answer. There are three classic sources of partial oracles.

Common variants are:

  • The definition in loops. Vectorization in lesson 5 rewrites loops as operations on whole arrays; the original loop is the natural reference. Slowness does not matter: the test runs it on small inputs.
  • Closed-form cases. Inputs with analytically known results: softmax of a constant vector is uniform, regression on noiseless data recovers coefficients, the gradient of 12∥x∥2\frac12\norm{\vb{x}}^2 is x\vb{x}, the standard deviation of (1,2,3)(1, 2, 3) is 1. They are cheap and expressive, but cover few points in input space.
  • An established library or higher precision. SciPy, math.fsum (exact sum rounded once), float64 versus float32, mpmath with 50 digits, or CPU versus GPU. This is called differential testing.

The reference also helps choose tolerances because it shows how far two correct implementations differ. Sometimes the surprise is that the “fast” implementation is less correct than expected:

[ ]A reference reveals cancellationBrowser
import numpy as np

def dists_vectorizada(X, Y):
    return (X**2).sum(1)[:, None] + (Y**2).sum(1)[None, :] - 2 * X @ Y.T

def dists_bucles(X, Y):                       # la referencia: la definición, en float64
    return np.array([[float(np.sum((x.astype(np.float64) - y.astype(np.float64))**2)) for y in Y] for x in X])

rng = np.random.default_rng(0)
for centro in [0.0, 100.0]:
    X = (centro + rng.normal(size=(3, 8))).astype(np.float32)
    Y = X + np.float32(1e-3) * rng.normal(size=(3, 8)).astype(np.float32)   # puntos muy cercanos
    V, R = dists_vectorizada(X, Y), dists_bucles(X, Y)
    escala = float((X.astype(np.float64)**2).sum(1).max())
    print(f"centro {centro:5.0f}: diagonal vectorizada  {np.diag(V)}")
    print(f"              diagonal de referencia  {np.diag(R).astype(np.float32)}")
    print(f"              error máximo {np.abs(V - R).max():.1e}   u·escala = {2**-24 * escala:.1e}\n")

The formula ∥x∥2+∥y∥2−2x⊤y\norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\vb{x}\T\vb{y} is the standard way to vectorize distances (used in lesson 5), but subtracts numbers of size ∥x∥2\norm{\vb{x}}^2 to obtain one of size ∥x−y∥2\norm{\vb{x} - \vb{y}}^2: catastrophic cancellation. With points centered at 100, distances of 10−510^{-5} come out 0 or even negative, and a subsequent np.sqrt would give NaN. Error is on the u∥x∥2u\norm{\vb{x}}^2 scale predicted by theory, so a well-written test uses atol proportional to ∥x∥2\norm{\vb{x}}^2; the implementation should clip at 0 (np.maximum(D, 0)) and document that small distances have no correct digits. torch.cdist uses this same trick for large sets and offers compute_mode="donot_use_mm_for_euclid_dist" for direct calculation when precision matters.

Metamorphic relations

What if there is no reference? A numerical solution to a differential equation, model training, a randomized algorithm: often no independent calculation exists for comparison. What often exists are relations between runs: even without knowing f(x)f(x), you know how it should change when transforming xx.

T. Y. Chen and coauthors formulated the idea in 1998 for the oracle problem, and Chen and coauthors’ review (2018) covers its use in compilers, bioinformatics, simulation, and machine learning. Relations most used in numerical code come from problem symmetries:

FunctionTransformation TTRequired relation RR
Pairwise distances D(X,Y)\mat{D}(\mat{X}, \mat{Y})permute rows of X\mat{X} with P\mat{P}D(PX,Y)=PD(X,Y)\mat{D}(\mat{P}\mat{X}, \mat{Y}) = \mat{P}\mat{D}(\mat{X}, \mat{Y})
translate X\mat{X} and Y\mat{Y} by the same v\vb{v}D\mat{D} unchanged
scale X\mat{X} and Y\mat{Y} by ccD\mat{D} multiplied by c2c^2
swap X\mat{X} and Y\mat{Y}D\mat{D} transposed
softmaxadd a constant to all logitsunchanged
permute logitspermutes probabilities
Regression with interceptpermute examplessame coefficients
add cc to y\vb{y}same w\vb{w}; bb increases by cc
duplicate datasetsame coefficients (without regularization)
Numerical integration ∫abf\int_a^b fsplit interval at cc∫ac+∫cb=∫ab\int_a^c + \int_c^b = \int_a^b
Optimizerrescale loss by c>0c > 0same minimum (with adapted step if method is not invariant)
Physical simulationrotate systemresult rotates; energy is conserved

Conservation (mass, energy, total probability), idempotence (f(f(x))=f(x)f(f(x)) = f(x) for projections, normalizations, and sorts), and inverse relations (g(f(x))=xg(f(x)) = x, such as encode and decode) are also metamorphic in the broad sense. Their great advantage is turning each input into a test without knowing the answer. Their limitation is that they are necessary conditions: an implementation can satisfy every relation written and still be wrong (the zero function is invariant to almost everything).

The next example is a classic ridge-regression bug: add a column of ones for the intercept and regularize every coefficient, including it. The result is reasonable and training error small, but the model is no longer translation-equivariant: the intercept shrinks toward 0.

[ ]Metamorphic relations for ridge regressionBrowser
import numpy as np

def ridge(X, y, lam):
    """Ridge con término independiente (bug: también penaliza el término independiente)."""
    A = np.column_stack([X, np.ones(len(X))])
    w = np.linalg.solve(A.T @ A + lam * np.eye(A.shape[1]), A.T @ y)
    return w[:-1], w[-1]

def ridge_bien(X, y, lam):
    """Correcta: centrar X e y saca el término independiente del problema penalizado."""
    mx, my = X.mean(0), y.mean()
    Xc, yc = X - mx, y - my
    w = np.linalg.solve(Xc.T @ Xc + lam * np.eye(X.shape[1]), Xc.T @ yc)
    return w, my - mx @ w

rng = np.random.default_rng(0)
X = rng.normal(size=(50, 3))
y = X @ np.array([1.0, -2.0, 0.5]) + 3 + 0.1 * rng.normal(size=50)
p = rng.permutation(50)

for nombre, f in [("con bug", ridge), ("correcta", ridge_bien)]:
    w, b = f(X, y, 5.0)
    w2, b2 = f(X, y + 10, 5.0)
    relaciones = {
        "permutar filas": np.allclose(f(X[p], y[p], 5.0)[0], w),
        "y + 10 => b + 10": np.allclose(w2, w) and np.isclose(b2, b + 10),
        "X + 1.5 => mismo w": np.allclose(f(X + 1.5, y, 5.0)[0], w),
        "2y => 2w": np.allclose(f(X, 2 * y, 5.0)[0], 2 * w),
    }
    print(f"{nombre:9s}", "   ".join(f"{k}: {'sí' if v else 'NO'}" for k, v in relaciones.items()))

Observe which relations detect the bug and which do not. Permutation and scaling hold for both versions (the intercept penalty is invariant to both), so those tests see nothing. Both translations expose it. Choosing metamorphic relations means thinking which symmetry each plausible bug would break.

Property tests with Hypothesis

A test with fixed examples checks cases you thought of. Bugs live in cases you did not. Property-based tests reverse the approach: instead of cases, write a statement that must hold for every valid input, and a tool searches for counterexamples.

The idea began with QuickCheck, Claessen and Hughes’s Haskell library (2000). In Python the tool is Hypothesis (MacIver, Hatfield-Dodds, and collaborators, 2019). Useful numerical-code properties are of kinds already seen: invariants and bounds (probabilities sum to 1, distance is nonnegative, max⁡ixi≤LSE⁡(x)≤max⁡ixi+log⁡n\max_i x_i \le \operatorname{LSE}(\vb{x}) \le \max_i x_i + \log n), metamorphic relations, and comparison with a reference on generated inputs. The inputs are new.

Why generating is not the same as sampling

A Hypothesis strategy does not sample from a “natural” distribution: it searches corners. For floats it frequently generates zero, integer values, range extremes, exponents of all kinds, subnormals, and infinity and NaN unless excluded. For arrays, empty shapes, single elements, and size-1 axes. This choice matters enormously. Naive softmax, exk/∑lexle^{x_k}/\sum_l e^{x_l} without subtracting the maximum (seen in lesson 5; its numerical analysis is the log-sum-exp trick), overflows in float64 when any xkx_k exceeds log⁡(maˊximo float)≈709.78\log(\text{máximo float}) \approx 709.78 (the log of the maximum float). With rng.normal(size=5) * 10 this needs a 71-sigma deviation, which will never occur. By contrast, nearly half of representable positive floats exceed 709.78, and a strategy traversing exponents finds them quickly.

The method’s second half, shrinking, makes the result readable. The first failing array is often something like [4.37, -67.0, 2.1e-222, 4.19e+287, 7.37]. Knowing it fails is useful; knowing the minimal failing array is [710.0] is a diagnosis.

InteractiveHow Hypothesis finds the minimal counterexample
p = np.exp(x) / np.exp(x).sum() assert np.isfinite(p).all() and np.isclose(p.sum(), 1)
Generated examples 9 of 9Minimal counterexampleNo simplification still fails: this is the reported counterexample.x =710.p.sum() = nan → the property failsWhere it fails for a one-element array real line on a double logarithmic scale−10³⁰⁸−10¹⁵⁰−1−10⁻¹⁵⁰010⁻¹⁵⁰110¹⁵⁰10³⁰⁸best: 710.Recent attempts 16 accepted of 39✗x[0] → 695.x = [695.]now passes✗x[0] → 702.x = [702.]now passes✗x[0] → 706.x = [706.]now passes✗x[0] → 708.x = [708.]now passes✗x[0] → 709.x = [709.]now passes
report
Examples until first failure9
First failure[4.37, −67., 2.1e−222, 4.2e287, 7.37]
Shrink attempts16 accepted of 39
Minimal counterexample[710.]
What pytest would show: Falsifying example: x=array([710.]). e710e^{710} does not fit in float64 (the maximum is e709.78e^{709.78}): ∞/∞\infty/\infty = NaN.
Above is property code. Each circle is a generated example: green if the property holds, red if it fails. The first examples are small and simple, followed by extremes. At the first failure shrinking begins: delete elements, set values to 0, change sign, and lower magnitude by bisection, first in the exponent and then integers. Each attempt is accepted only if the test still fails. The lower line, on a double logarithmic scale, shows which single-element arrays fail the property (red); marks are tested values. Play the animation, change seed (the first failure changes, the minimum does not), and compare both functions.

The shrinker is greedy descent: it starts from the counterexample and tries transformations simplifying it in a fixed order (fewer elements, values closer to 0, positive before negative, integers before decimals); it accepts the first that still fails and repeats until none works. The result is a local minimum for that order: no one-step simplification still fails. It is not necessarily the only counterexample or the global minimum. In normalization, [0.0] is the simplest representative of a class of failures also including vectors whose norm overflows or underflows to zero, such as [1e200] or [1e-200]: each component’s square leaves float64 range even though the component does not.

Hypothesis shrinks not values directly but the sequence of random decisions that generated them (MacIver and Donaldson describe this “internal” shrinker in a 2020 paper). This lets it shrink any strategy, including ones you build by combining others, without writing a shrinker for each type. The homemade version in the next cell works on values, enough to understand the idea:

[ ]Generate and shrink from scratchBrowser
import numpy as np

def generar(rng):
    """Array 1-D «a lo Hypothesis»: valores corrientes, enteros, el cero, extremos y diminutos."""
    def valor():
        r, s = rng.random(), rng.choice([-1.0, 1.0])
        if r < 0.30: return round(rng.uniform(-10, 10), 2)
        if r < 0.48: return s * float(rng.integers(0, 100))
        if r < 0.58: return 0.0
        if r < 0.80: return s * 10 ** rng.uniform(0, 6)
        if r < 0.92: return s * 10 ** rng.uniform(0, 308)
        return s * 10 ** -rng.uniform(0, 320)
    return [valor() for _ in range(rng.integers(1, 6))]

def falla(prop, x):
    try:
        with np.errstate(all="ignore"):
            prop(np.array(x))
        return False
    except AssertionError:
        return True

def reducir(prop, x):
    """Reducción voraz: acepta cualquier simplificación que siga fallando, hasta que ninguna lo haga."""
    intentos = 0
    def sigue(c):
        nonlocal intentos
        intentos += 1
        return falla(prop, c)
    cambio = True
    while cambio:
        cambio = False
        i = 0
        while i < len(x) and len(x) > 1:                        # 1. borrar elementos
            if sigue(x[:i] + x[i + 1:]):
                x, cambio = x[:i] + x[i + 1:], True
            else:
                i += 1
        for i, v in enumerate(x):                               # 2. simplificar valores
            poner = lambda w: x[:i] + [w] + x[i + 1:]
            if v != 0 and sigue(poner(0.0)):
                x, cambio = poner(0.0), True
                continue
            if v < 0 and sigue(poner(-v)):                      # preferimos positivos
                x, cambio, v = poner(-v), True, -v
            a, s = abs(v), np.sign(v)
            if a >= 2:                                          # bisección en el exponente...
                lo, hi = 0, int(np.floor(np.log2(a)))
                if sigue(poner(s * 2.0**hi)):
                    x, cambio = poner(s * 2.0**hi), True
                    while hi - lo > 1:
                        m = (lo + hi) // 2
                        if sigue(poner(s * 2.0**m)):
                            x, hi = poner(s * 2.0**m), m
                        else:
                            lo = m
                    lo, hi = 2**lo, 2**hi
                else:                                           # 2^hi ya pasa: el borde está entre 2^hi y a
                    lo, hi = 2**hi, a
                while hi - lo > 1:                              # ...y después en los enteros
                    m = (lo + hi) // 2
                    if sigue(poner(s * float(m))):
                        x, hi, cambio = poner(s * float(m)), m, True
                    else:
                        lo = m
    return x, intentos

def comprobar(prop, n_ejemplos=200, semilla=0):
    rng = np.random.default_rng(semilla)
    for k in range(1, n_ejemplos + 1):
        x = generar(rng)
        if falla(prop, x):
            minimo, intentos = reducir(prop, x)
            print(f"  falla en el ejemplo {k}: {np.array(x)}")
            print(f"  reducido en {intentos} intento{'s' if intentos != 1 else ''} a x = {np.array(minimo)}")
            return
    print(f"  {n_ejemplos} ejemplos sin fallos")

def softmax_ingenua(x):
    e = np.exp(x)
    return e / e.sum()

def prop_softmax(x):
    p = softmax_ingenua(x)
    assert np.isfinite(p).all() and np.isclose(p.sum(), 1)

def prop_normalizar(x):
    y = x / np.linalg.norm(x)
    assert np.isclose(np.linalg.norm(y), 1)

for nombre, prop in [("softmax ingenua", prop_softmax), ("normalizar", prop_normalizar)]:
    print(nombre)
    for semilla in range(3):
        comprobar(prop, semilla=semilla)

rng = np.random.default_rng(0)
fallos = sum(falla(prop_softmax, list(rng.normal(size=5) * 10)) for _ in range(10_000))
print("\nfallos de la softmax ingenua con 10 000 arrays normales (σ = 10):", fallos)

Three different starts reach the same counterexample, [710.], the smallest integer overflowing exe^x in float64. Ten thousand normal arrays find nothing: generation strategy is half the test.

Hypothesis in practice

With Hypothesis, the softmax property is written as follows (this code needs pip install hypothesis or uv add --dev hypothesis; you will run it in the final local lab):

import numpy as np
from hypothesis import given, settings, example, strategies as st
from hypothesis.extra import numpy as hnp

floats = st.floats(allow_nan=False, allow_infinity=False)

@given(hnp.arrays(np.float64, st.integers(1, 10), elements=floats))
def test_softmax_es_una_distribucion(x):
    p = softmax(x)
    assert np.isfinite(p).all()
    np.testing.assert_allclose(p.sum(), 1, rtol=1e-12)

With the naive version, pytest reports:

Falsifying example: test_softmax_es_una_distribucion(
    x=array([710.]),
)

The most-used pieces:

  • Basic strategies. st.integers(a, b), st.floats(a, b, allow_nan=..., allow_infinity=..., width=32), st.lists(...), st.tuples(...), st.sampled_from([...]), and combinators .map(f), .filter(pred), and st.builds(Clase, ...). width=32 generates float32-representable floats.
  • Arrays. hnp.arrays(dtype, shape, elements=...) generates arrays; shape may be fixed or a strategy such as hnp.array_shapes(min_dims=1, max_dims=3, max_side=8). hnp.floating_dtypes() generates dtypes, hnp.mutually_broadcastable_shapes(num_shapes=2) generates compatible shapes to test broadcasting, and hnp.basic_indices(shape) generates indices. Note: with floating dtype and no elements, arrays include NaN and infinities.
  • Dependencies between values. st.data() permits drawing values inside the test (for example, a k dependent on array length); @st.composite defines custom strategies.
  • Assumptions. assume(cond) discards an example failing a precondition. If too many are discarded, Hypothesis warns via a health check: it is better to construct the strategy to generate valid inputs directly.
  • Explicit examples. @example(np.array([0.0])) adds a case always tested: a way to turn a discovered counterexample into a regression test.
  • Configuration. @settings(max_examples=..., deadline=...); defaults are 100 examples and 200 ms per example, which should be disabled (deadline=None) for numerical functions with variable timing.

Bug hunt: no single test type is enough

You now have four test types: reference, metamorphic, property, and closed-form cases. Does one cover everything? The next interactive presents five functions with subtle bugs of the kind surviving months in a repository, and actually applies all four test types to correct and buggy versions. Implementations run in float32, as a GPU kernel would, and references in float64.

InteractiveHunting bugs with tests
Function and planted bug
Reference
4 of 5
Metamorphic
1 of 5
Property
2 of 5
Closed form
3 of 5
row-wise softmax
normalizes by column (axis=0)
linear layer x Wᵀ + b
missing transpose: x W + b
discounted returns
off by one: skips reward rₜ
mean squared error
ŷ of shape (n, 1) and y of shape (n,) broadcast to (n, n)
standard deviation, n = 2·10⁵, float32
divides by n instead of n − 1 (ddof=0)
standard deviation, n = 2·10⁵, float32 · Referencemisses
assert_allclose(std(x), np.std(x.astype(np.float64), ddof=1), rtol)
Measured: |std − reference en float64|
Correct version: 3.81·10⁻⁵ passes
With the bug: 4.31·10⁻⁵ passes
Tolerance: rtol = atol = 0.001
Test types in suite
Numerical comparisons
0.001
Bugs detected by suite4 of 5
False alarms0
Using only reference tests misses 1 of the 5 bugs. Try combining types.
Each row is a function with a planted bug and each column a test type; tests actually run on random data with correct and buggy versions. ‘Detects’ means the test passes the correct version and fails the buggy one; ‘false alarm’ means it fails even the correct version. Click a cell to see test code and errors. Start with a suite of reference tests only: which bug escapes and why? Lower rtol to try to catch it. Then combine types until all five are detected without false alarms.

What the table shows:

  • The reference is the strongest test, but not infallible. It detects four of five bugs. The fifth, dividing by nn instead of n−1n - 1 in a standard deviation with n=2⋅105n = 2\cdot 10^5, changes the result by factor n/(n−1)\sqrt{n/(n-1)}, a relative error of 1/(2n)=2.5⋅10−61/(2n) = 2.5\cdot 10^{-6}. But the correct version, with sequential float32 sums of 2⋅1052\cdot 10^5 terms, already has relative error about 2⋅10−52\cdot 10^{-5}: the bug is eight times smaller than rounding. For some data rounding and bug push in the same direction, leaving a narrow gap between correct and buggy errors (with several seeds, rtol ≈1.8⋅10−5\approx 1.8\cdot 10^{-5} detects the bug without false alarm), but the gap moves with data: no rtol detects the bug for every seed without false alarms for some. Tuning a tolerance until the test distinguishes versions on specific data is coincidence, not a test.
  • The closed-form case catches exactly that bug. The standard deviation of (1,2,3)(1, 2, 3) is 1 with n−1n - 1 and 2/3≈0.82\sqrt{2/3} \approx 0.82 with nn: with n=3n = 3 the bug has an 18% effect. Bugs dependent on nn show up better with small nn.
  • Metamorphic and property tests see little here, but remain essential. A linear layer with a forgotten transpose is still linear, so the linearity relation misses it; with W=I\mat{W} = \mat{I} the closed-form case misses it too, because I⊤=I\mat{I}\T = \mat{I}. Only the reference with nonsymmetric W\mat{W} detects it. Conversely, MSE broadcasting (n,1)(n, 1) with (n,)(n,) to (n,n)(n, n) is invariant under simultaneously permuting predictions and labels (the metamorphic test passes), but violates the most basic error property: MSE⁡(y,y)=0\operatorname{MSE}(\vb{y}, \vb{y}) = 0.
  • Each test type has different blind spots, so their combination covers far more than any alone. Designing a suite resembles a good experiment: varied inputs (square and nonsquare, symmetric and nonsymmetric, small and large nn) and varied checks.

Testing stochastic code

Samplers, dropout, initializations, data augmentation, randomized algorithms: their output is random and any test on it is fundamentally a hypothesis test. There are two strategies, and both are useful.

Fixed seed. With a seeded generator (np.random.default_rng(1234) or torch.Generator().manual_seed(1234)), stochastic code is deterministic and tested like any other: against a reference, with metamorphic relations, or by checking that the result does not change between versions (regression test). It is fast and never fails spuriously. Its limitation is checking only one realization: it does not say whether the distribution is correct. A sample of 1000 values from a sampler with shifted mean can pass a fixed-seed test if nobody checks the mean.

Statistical threshold. Check a distribution property with a statistic and threshold. If theoretical mean is μ\mu and variance σ2\sigma^2, the sample mean of nn independent values has, by the central limit theorem, an approximately normal distribution, and the test

falla si∣z∣=∣xˉn−μ∣σ/n>k\text{falla si}\quad \abs{z} = \frac{\abs{\bar x_n - \mu}}{\sigma/\sqrt{n}} > k

fails with probability α=P(∣Z∣>k)=2(1−Φ(k))\alpha = \Pr(\abs{Z} > k) = 2(1 - \Phi(k)) even when code is correct. The formula’s “falla si” means “fails if.” This is the test’s type-I error (type-I and type-II errors), which can be controlled but not eliminated.

Proof

(1) Each execution of each test is Bernoulli with parameter α\alpha; expectation of the sum is the sum of expectations, mRαmR\alpha, without requiring independence. (2) Chebyshev: P(∣xˉn−μ∣>kσ/n)≤Var⁡(xˉn)/(kσ/n)2=(σ2/n)/(k2σ2/n)=1/k2\Pr(\abs{\bar x_n - \mu} > k\sigma/\sqrt{n}) \le \Var(\bar x_n)/(k\sigma/\sqrt{n})^2 = (\sigma^2/n)/(k^2\sigma^2/n) = 1/k^2. (3) With the bug, z≈N(δn/σ,1)z \approx \Normal(\delta\sqrt{n}/\sigma, 1), and P(∣z∣>k)\Pr(\abs{z} > k) is the sum of both tails. Power exceeds 1−β1 - \beta if δn/σ−k≥z1−β\delta\sqrt{n}/\sigma - k \ge z_{1-\beta}, the condition on nn.

∎

In numbers: a threshold of 3 standard deviations has α=0.0027\alpha = 0.0027. That seems small, but a suite with 20 such tests run 50 times a day by a team produces 20⋅50⋅0.0027=2.720 \cdot 50 \cdot 0.0027 = 2.7 spurious failures daily. A test failing for no reason several times a week eventually gets ignored, worse than not having it. Chebyshev’s bound also shows why improvisation is unwise: without normality, “3 sigma” only guarantees α≤1/9≈0.11\alpha \le 1/9 \approx 0.11. This is the multiple comparisons problem applied to your own suite.

[ ]Simulated false alarms and powerBrowser
import numpy as np
from math import erf, sqrt

Phi = lambda z: 0.5 * (1 + erf(z / sqrt(2)))

R, n, sesgo = 4000, 1000, 0.06          # 4000 ejecuciones del test; un bug que desplaza la media 0.06σ
rng = np.random.default_rng(0)
z_bien = np.array([rng.normal(size=n).mean() * sqrt(n) for _ in range(R)])
z_bug = np.array([(rng.normal(size=n) + sesgo).mean() * sqrt(n) for _ in range(R)])
d = sesgo * sqrt(n)

for k in [2, 3, 4, 5]:
    alfa = 2 * (1 - Phi(k))
    potencia = 1 - Phi(k - d) + Phi(-k - d)
    print(f"k = {k}:  falsas alarmas {np.mean(np.abs(z_bien) > k):.4f} (teoría {alfa:.4f})   "
          f"detecta el bug {np.mean(np.abs(z_bug) > k):.3f} (teoría {potencia:.3f})")

beta_z = 1.2816                          # z_{0.9}: potencia del 90 %
for k in [3, 5]:
    print(f"muestras para detectar el sesgo con probabilidad 0.9 y k = {k}: {((k + beta_z) / sesgo) ** 2:,.0f}")

The simulation agrees with theory and shows the tradeoff: raising the threshold from 3 to 5 lowers false alarms from 2.7⋅10−32.7\cdot 10^{-3} to 5.7⋅10−75.7\cdot 10^{-7}, but with the same samples power against that bias falls from 13% to 0.1%. Detecting it with probability 0.9 needs about 5100 samples with k=3k = 3 and 11 000 with k=5k = 5: a little over twice as many, and generating 11 000 normals takes less than a millisecond. Rule of thumb:

Key idea

For stochastic code, combine a fast deterministic fixed-seed test in the suite for every change with statistical tests using a demanding threshold (k≥5k \ge 5, or α\alpha corrected for the number of tests) and sufficient samples for required power, marked slow and with their calculated false-alarm rate written in a comment.

Fix the seed of those statistical tests too and change it only deliberately: then failures are reproducible, and false-alarm rate refers to what happens when the seed changes, not each run. Lessons on seeding and generators and streams explain giving each test its own random stream independent of execution order; the rng fixture in the lab below derives the seed from the test identifier.

A fast suite

A suite taking ten minutes is not run before every change, and one not run detects nothing. The usual organization separates three levels:

  • Fast (seconds): unit, reference on small inputs, metamorphic, and property tests with few examples. Run on each change, including before each commit.
  • Slow (minutes): large inputs, statistical tests with many samples, Hypothesis with thousands of examples, a short end-to-end training run. Marked @pytest.mark.slow and run in continuous integration or before merging.
  • GPU: marked @pytest.mark.gpu and skipped automatically without CUDA.

Configuration lives in the project’s pyproject.toml (lesson 1):

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
markers = [
    "slow: tarda más de un segundo; excluir con -m 'not slow'",
    "gpu: necesita CUDA",
]
filterwarnings = ["error::RuntimeWarning"]

The last line deserves attention: it turns every RuntimeWarning into an error, and in NumPy these warn of overflow, division by zero, and invalid operations preceding NaN. A test causing overflow encountered in exp fails even if nobody checks the result. If a test should produce a warning, declare it with pytest.warns. (Warnings depend on the processor signaling floating-point exceptions; WebAssembly does not, so NumPy in browser cells does not emit them. Tests depending on them must run locally.)

To run fast tests before every commit, use a local pre-commit hook (covered in more detail in quality automation):

repos:
  - repo: local
    hooks:
      - id: tests-rapidos
        name: tests rápidos
        entry: pytest -m "not slow and not gpu" -x -q
        language: system
        pass_filenames: false
        types: [python]

Three more options help keep the suite fast: --durations=10 lists slowest tests, -x stops at the first failure, and pytest-xdist (-n auto) distributes tests across cores. Hypothesis configuration profiles permit few examples locally and many in continuous integration without changing tests.

The next lab combines everything on functions from earlier lessons: pairwise distances, softmax, top-k, and group aggregation. Write a small library, conftest.py with markers, an rng fixture per test and Hypothesis profiles, a reference and metamorphic test file (with one slow and one GPU test), and another of Hypothesis properties. If Hypothesis is not installed in your environment, that module is skipped with pytest.importorskip and appears in the report; install it with uv add --dev hypothesis.

[ ]The course library test suiteLocal GPU
import os, sys, io, textwrap, tempfile, contextlib
import numpy as np
import pytest

d = tempfile.mkdtemp(prefix="atlas_tests_")
def escribe(nombre, codigo):
    with open(os.path.join(d, nombre), "w", encoding="utf-8") as f:
        f.write(textwrap.dedent(codigo))

# 1. la librería que se va a testear (funciones de las lecciones 5 y 6)
escribe("atlas_lib.py", '''
    import numpy as np

    def pairwise_sq_dists(X, Y):
        """D[i, j] = ||X[i] - Y[j]||^2 sin bucles: ||x||^2 + ||y||^2 - 2 x.y"""
        D = (X**2).sum(1)[:, None] + (Y**2).sum(1)[None, :] - 2 * X @ Y.T
        return np.maximum(D, 0)          # la cancelación puede dejar valores como -1e-13

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

    def topk(x, k):
        idx = np.argpartition(-x, k - 1, axis=-1)[..., :k]
        vals = np.take_along_axis(x, idx, -1)
        orden = np.argsort(-vals, axis=-1, kind="stable")
        return np.take_along_axis(vals, orden, -1), np.take_along_axis(idx, orden, -1)

    def groupby_sum(claves, valores):
        grupos, cod = np.unique(claves, return_inverse=True)
        return grupos, np.bincount(cod, weights=valores, minlength=len(grupos))
''')

# 2. configuración compartida: marcas, una semilla por test y perfiles de Hypothesis
escribe("conftest.py", '''
    import zlib
    import numpy as np
    import pytest

    def pytest_configure(config):
        config.addinivalue_line("markers", "slow: tarda más de un segundo")
        config.addinivalue_line("markers", "gpu: necesita CUDA")

    def pytest_collection_modifyitems(config, items):
        try:
            import torch
            hay_cuda = torch.cuda.is_available()
        except ImportError:
            hay_cuda = False
        if not hay_cuda:
            saltar = pytest.mark.skip(reason="no hay CUDA")
            for item in items:
                if "gpu" in item.keywords:
                    item.add_marker(saltar)

    @pytest.fixture
    def rng(request):
        """Generador propio de cada test: distinto entre tests, idéntico entre ejecuciones."""
        return np.random.default_rng(zlib.crc32(request.node.nodeid.encode()))

    try:
        from hypothesis import settings
        settings.register_profile("rapido", max_examples=60, deadline=None)
        settings.register_profile("ci", max_examples=1000, deadline=None, derandomize=True)
        settings.load_profile("rapido")
    except ImportError:
        pass
''')

# 3. referencias lentas pero obvias y relaciones metamórficas
escribe("test_referencia.py", '''
    import numpy as np
    import pytest
    from atlas_lib import pairwise_sq_dists, softmax, topk, groupby_sum

    EPS = np.finfo(np.float64).eps

    def dists_bucles(X, Y):
        return np.array([[sum((a - b) ** 2 for a, b in zip(x, y)) for y in Y] for x in X])

    @pytest.mark.parametrize("n, m, d", [(1, 1, 1), (5, 3, 2), (7, 7, 16)])
    def test_dists_referencia(rng, n, m, d):
        X, Y = rng.normal(size=(n, d)), rng.normal(size=(m, d))
        # la cancelación de ||x||^2 + ||y||^2 - 2 x.y deja un error absoluto del orden de eps * escala
        escala = (X**2).sum(1).max() + (Y**2).sum(1).max()
        np.testing.assert_allclose(pairwise_sq_dists(X, Y), dists_bucles(X, Y), rtol=1e-12, atol=16 * EPS * escala)

    def test_dists_metamorficas(rng):
        X, Y = rng.normal(size=(6, 4)), rng.normal(size=(5, 4))
        D = pairwise_sq_dists(X, Y)
        p = rng.permutation(6)
        np.testing.assert_allclose(pairwise_sq_dists(X[p], Y), D[p])            # permutar filas
        np.testing.assert_allclose(pairwise_sq_dists(Y, X), D.T)                # intercambiar
        np.testing.assert_allclose(pairwise_sq_dists(3 * X, 3 * Y), 9 * D)      # escalar
        v = rng.normal(size=4)
        np.testing.assert_allclose(pairwise_sq_dists(X + v, Y + v), D, atol=1e-12)  # trasladar

    @pytest.mark.parametrize("forma", [(5,), (3, 4), (2, 3, 6)])
    def test_softmax_relaciones(rng, forma):
        x = rng.normal(size=forma) * 5
        p = softmax(x)
        np.testing.assert_allclose(p.sum(-1), 1, rtol=1e-13)
        np.testing.assert_allclose(softmax(x + 100.0), p, rtol=1e-12, atol=1e-15)   # invariancia
        np.testing.assert_allclose(softmax(x[..., ::-1]), p[..., ::-1])              # equivariancia

    def test_topk_frente_a_ordenar(rng):
        x = rng.normal(size=(4, 50))
        vals, idx = topk(x, 5)
        np.testing.assert_array_equal(vals, -np.sort(-x, axis=-1)[:, :5])
        np.testing.assert_array_equal(np.take_along_axis(x, idx, -1), vals)

    def test_groupby_frente_a_diccionario(rng):
        claves = rng.integers(0, 6, size=200)
        valores = rng.normal(size=200)
        ref = {}
        for c, v in zip(claves, valores):
            ref[c] = ref.get(c, 0.0) + v
        grupos, sumas = groupby_sum(claves, valores)
        np.testing.assert_allclose(sumas, [ref[g] for g in grupos], rtol=1e-12)

    @pytest.mark.slow
    def test_dists_grande_float32(rng):
        X = rng.normal(size=(2000, 64)).astype(np.float32)
        D = pairwise_sq_dists(X, X)
        X64 = X.astype(np.float64)
        D64 = pairwise_sq_dists(X64, X64)
        escala = 2 * (X64**2).sum(1).max()
        np.testing.assert_allclose(D, D64, rtol=1e-5, atol=32 * np.finfo(np.float32).eps * escala)

    @pytest.mark.gpu
    def test_dists_gpu_frente_a_numpy(rng):
        import torch
        X = rng.normal(size=(500, 32)).astype(np.float32)
        Dt = torch.cdist(torch.from_numpy(X).cuda(), torch.from_numpy(X).cuda()).pow(2).cpu()
        escala = 2 * float((X.astype(np.float64)**2).sum(1).max())
        torch.testing.assert_close(Dt, torch.from_numpy(pairwise_sq_dists(X, X)),
                                   rtol=1e-4, atol=64 * float(np.finfo(np.float32).eps) * escala)
''')

# 4. propiedades con Hypothesis sobre arrays generados
escribe("test_propiedades.py", '''
    import numpy as np
    import pytest
    hypothesis = pytest.importorskip("hypothesis")    # si no está instalado, el módulo se salta
    from hypothesis import given, strategies as st
    from hypothesis.extra import numpy as hnp
    from atlas_lib import pairwise_sq_dists, softmax, topk

    finitos = st.floats(-1e3, 1e3, allow_nan=False, allow_infinity=False)
    matrices = hnp.arrays(np.float64, hnp.array_shapes(min_dims=2, max_dims=2, max_side=8), elements=finitos)

    @given(matrices)
    def test_dists_no_negativas_y_simetricas(X):
        D = pairwise_sq_dists(X, X)
        escala = 4 * (X**2).sum(1).max()
        # residuo de la cancelación, más tiny: con subnormales el redondeo deja de ser relativo
        tol = 64 * np.finfo(float).eps * escala + np.finfo(float).tiny
        assert (D >= 0).all()
        np.testing.assert_allclose(D, D.T, atol=tol)  # X @ X.T no es exactamente simétrica
        assert np.abs(np.diag(D)).max() <= tol

    @given(hnp.arrays(np.float64, hnp.array_shapes(min_dims=1, max_dims=3, max_side=6),
                      elements=st.floats(-1e4, 1e4)))
    def test_softmax_es_una_distribucion(x):
        p = softmax(x)
        assert np.isfinite(p).all() and (p >= 0).all()
        np.testing.assert_allclose(p.sum(-1), 1, rtol=1e-12)

    @given(hnp.arrays(np.float64, st.integers(1, 30), elements=finitos), st.data())
    def test_topk_son_los_mayores(x, data):
        k = data.draw(st.integers(1, x.size), label="k")
        vals, idx = topk(x, k)
        assert (np.diff(vals) <= 0).all()                           # en orden descendente
        assert len(set(idx.tolist())) == k                          # sin índices repetidos
        assert vals[-1] >= np.delete(x, idx).max(initial=-np.inf)   # nadie fuera es mayor
''')

# 5. ejecución: primero la batería rápida, después los lentos y los de GPU
anterior = os.getcwd()
os.chdir(d)
sys.path.insert(0, d)
try:
    for titulo, args in [("rápidos", ["-m", "not slow and not gpu"]),
                         ("lentos y GPU", ["-m", "slow or gpu", "--durations=2"])]:
        salida = io.StringIO()
        with contextlib.redirect_stdout(salida):
            codigo = pytest.main(["-q", "-p", "no:cacheprovider", "-rs", *args])
        print(f"--- {titulo}: código de salida {int(codigo)}")
        print(salida.getvalue().strip())
finally:
    os.chdir(anterior)
    sys.path.remove(d)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Some lab details are worth copying into your projects. Distance tolerances are absolute and proportional to the scale ∥x∥2\norm{\vb{x}}^2 because of the cancellation seen earlier. References share no code with the library: the distance reference is the definition with a loop, and aggregation uses a dictionary. The distance property needs atol even to check symmetry, because X @ X.T is not exactly symmetric and the cancellation residual is on the order of u∥x∥2u\norm{\vb{x}}^2; it also needs an absolute floor, np.finfo(float).tiny, because Hypothesis generates rows like [9.3e-162], whose square is subnormal and no longer has relative error bounded by uu. Both corrections came from real Hypothesis counterexamples while writing this suite. The top-k property test checks the three defining properties (order, no repeats, and nothing outside exceeds the last) instead of comparing to a sort, making it valid with ties. The rng fixture derives the seed from the test identifier: each test has its own random stream, and adding or reordering tests does not change other tests’ data.

Common mistakes

Exercises

NumericTolerance at 1000
With rtol = 1e-5 and atol = 1e-8, what is the maximum difference ∣a−d∣\abs{a - d} accepted by np.testing.assert_allclose(a, d, rtol=1e-5, atol=1e-8) when the desired value is d=1000d = 1000?
NumericA float32 summation bound
According to the recursive summation error theorem, what is the relative-error bound γn−1\gamma_{n-1} when adding n=104n = 10^4 positive numbers in float32 from left to right? Use u=2−24u = 2^{-24}.
QuizA metamorphic relation for distances
Let D(X,Y)\mat{D}(\mat{X}, \mat{Y}) be the squared Euclidean distance matrix between rows of X∈Rn×d\mat{X} \in \R^{n\times d} and Y∈Rm×d\mat{Y} \in \R^{m\times d}. Which metamorphic relation holds for all inputs?
QuizReading a counterexample
Hypothesis reports that test_normalizar fails with x=array([0.]). Which conclusion is correct?
NumericSpurious failures per day
A stochastic test fails when the sample mean differs from its theoretical value by more than 3 standard errors. It has no fixed seed and runs 200 times per day. Assuming a normal statistic, how many spurious failures per day are expected with correct code?
QuizHow do you fix it?
Continuing with the preceding test, producing about 0.5 spurious failures per day, which changes are good solutions?

More than one answer may be correct.

Codenp.isclose from scratch
Implement my_isclose(a, b, rtol=1e-5, atol=1e-8, equal_nan=False) with np.isclose semantics (except the pathological case where atol + rtol * abs(b) overflows to infinity): accept scalars or arrays (with broadcasting) and return a Boolean array with ∣a−b∣≤atol+rtol∣b∣\abs{a - b} \le \texttt{atol} + \texttt{rtol}\abs{b} elementwise. Infinities are close only to infinity of the same sign (even if the formula says otherwise), NaN is never close to anything unless equal_nan=True and both are NaN, and it must emit no warnings. Tests compare with np.isclose at edge cases.
import numpy as np

def my_isclose(a, b, rtol=1e-5, atol=1e-8, equal_nan=False):
  a = np.asarray(a, dtype=float)
  b = np.asarray(b, dtype=float)
  # tu código: casos finitos con la fórmula; infinitos; NaN
  return np.abs(a - b) <= atol + rtol * np.abs(b)
Shift+Enter to run
CodeProperties that reveal overflow
The functions lse_ingenua and lse_estable calculate LSE⁡(x)=log⁡∑iexi\operatorname{LSE}(\vb{x}) = \log\sum_i e^{x_i}. Write three parts of a property test, run by the tests in a loop of 300 Hypothesis-style examples: gen_x(rng), returning a 1-D float array of length 1 to 8 capable of reaching the overflow region (tests pass it a np.random.Generator); prop_acotada(lse, x), using assert to check that lse(x) is finite and lies between max⁡ixi\max_i x_i and max⁡ixi+log⁡n\max_i x_i + \log n with small relative tolerance; and prop_traslacion(lse, x, c), checking LSE⁡(x+c)=LSE⁡(x)+c\operatorname{LSE}(\vb{x} + c) = \operatorname{LSE}(\vb{x}) + c with tolerance proportional to the scale of x\vb{x} and cc. Your properties must fail with the naive version, always pass with the stable one (tests use ∣c∣≤104\abs{c} \le 10^4), and reject incorrect implementations.
import numpy as np

def lse_ingenua(x):
  return np.log(np.sum(np.exp(x)))

def lse_estable(x):
  m = np.max(x)
  return m + np.log(np.sum(np.exp(x - m)))

def gen_x(rng):
  # tu código: arrays 1-D de longitud 1 a 8 que lleguen a la zona de desbordamiento
  return rng.normal(size=rng.integers(1, 9))

def prop_acotada(lse, x):
  # tu código: finito y entre max(x) y max(x) + log(n), con tolerancia
  assert np.isfinite(lse(x))

def prop_traslacion(lse, x, c):
  # tu código: lse(x + c) = lse(x) + c, con tolerancia
  pass
Shift+Enter to run
ProofError of recursive summation
Prove: If s^\hat s is the floating-point left-to-right sum of x1,…,xnx_1, \dots, x_n and (n−1)u<1(n-1)u < 1, then ∣s^−∑ixi∣≤γn−1∑i∣xi∣\abs{\hat s - \sum_i x_i} \le \gamma_{n-1}\sum_i\abs{x_i}, with γk=ku/(1−ku)\gamma_k = ku/(1 - ku).
0
By the standard model, s^1=x1\hat s_1 = x_1 and s^k=(s^k−1+xk)(1+δk)\hat s_k = (\hat s_{k-1} + x_k)(1 + \delta_k) with ∣δk∣≤u\abs{\delta_k} \le u for k=2,…,nk = 2, \dots, n.

Step 1 of 3. What closed expression does s^=s^n\hat s = \hat s_n have?

Summary

Key idea
Numerical code fails silently, so a good test checks that the result agrees, with justified tolerance, with something known to be true: an obvious reference, a closed-form solution, a relation between runs, or a property required for every input.
  • pytest discovers test_* functions, rewrites assert to explain failures, and injects fixtures by argument name. parametrize multiplies cases, markers (slow, gpu) and -m / -k select what to run, and conftest.py shares fixtures and configuration by directory.
  • Approximate equality is ∣a−d∣≤atol+rtol∣d∣\abs{a - d} \le \texttt{atol} + \texttt{rtol}\abs{d}: a cone closing at 0 plus a band. rtol\texttt{rtol} comes from uu of the computation dtype times error growth (typical n\sqrt{n} to worst-case nn) and conditioning; atol\texttt{atol} from rtol\texttt{rtol} times data scale. Libraries’ defaults differ and none is neutral.
  • A reference must be obvious and independent; sharing the formula shares the bug. Closed-form cases catch what the reference cannot distinguish from rounding.
  • Metamorphic relations (permuting, translating, scaling, reflecting, conservation, idempotence) test without an oracle; each sees bugs breaking its symmetry.
  • Property tests generate inputs seeking extremes and shrink the first failure to a minimal counterexample. In Python use Hypothesis with hypothesis.extra.numpy; save each counterexample as @example.
  • A stochastic test is a hypothesis test: fixed seed for the fast suite and, for the distribution, thresholds with calculated false-alarm rate (mRαmR\alpha) and sufficient sample size for desired power.
  • No one test type suffices: combine types, use shapes with distinct axes, and check that every test can fail.