Module contents
Lesson 17 of 24Core 90 min

Profiling: measure before you optimize

A methodology for finding where time and memory go in numerical and training code: benchmarks with warm-up and repetition, deterministic and sampling Python profilers, memory profiling and torch.profiler CPU and GPU traces viewed in Perfetto. Classify a program as overhead-, memory-, compute- or data-bound and apply the matching remedy.

After this lesson you can

  • Design reliable benchmarks with warm-up, repetitions, median and interquartile range using timeit and torch.utils.benchmark.
  • Locate Python bottlenecks with cProfile, line_profiler and py-spy and explain their overhead and bias differences.
  • Measure peak memory of NumPy code with tracemalloc and PyTorch code with CUDA memory statistics.
  • Obtain and interpret a torch.profiler trace: GPU gaps, dominant kernels, launch overhead and synchronizations.
  • Classify a training step by its bottleneck and justify its remedy with a measurement.

Before you start

Motivation: optimizing the wrong function

You have a script that prepares a dataset with NumPy and then clusters the points with k-means written in Python loops. It takes too long. Intuition points to the obvious culprit: the Python loop, which calls a tiny function tens of thousands of times. You spend an afternoon vectorizing it, make it a hundred times faster, and the entire script gains 17%. The loop accounted for only 15% of the time; the remaining 85% was spent in NumPy generating and standardizing data, and you did not touch that.

The same story repeats in training. A step takes about 5 ms on a GPU capable of billions of operations per millisecond, and it is natural to suspect the architecture, precision or loss. In the complete case at the end of this lesson, the trace will tell a different story: the GPU is busy less than 5% of the time, running kernels of a few microseconds, and spends the rest of the step waiting for Python to submit the next one. No improvement in computation can gain more than 5% there. Changing how work is launched gains an order of magnitude.

Both situations illustrate the same law.

Proof

Normalize the original time to 1. The part that is not accelerated still costs 1−p1 - p and the accelerated part goes from pp to p/sp/s, so the new time is (1−p)+p/s(1 - p) + p/s and the speedup is its reciprocal. The expression increases with ss and its limit is 1/(1−p)1/(1 - p).

∎

With p=0.15p = 0.15 and s=100s = 100, S=1/(0.85+0.0015)≈1.17S = 1/(0.85 + 0.0015) \approx 1.17; even s=∞s = \infty would not exceed 1/0.85≈1.181/0.85 \approx 1.18. Amdahl’s law is often cited for parallelization, but its content is more basic: the fraction pp determines the possible gain, and pp is measured, not guessed. This lesson provides the method for measuring it well and acting accordingly:

  1. Measure total time with a reliable benchmark, because without a baseline and its variability you will not know whether an improvement is real.
  2. Locate where time (and memory) goes with a profiler, knowing what each one distorts.
  3. Classify the bottleneck: interpreter or launch overhead, memory bandwidth, computation or data.
  4. Remedy it with the appropriate approach for that class, and measure again, because removing one bottleneck exposes the next.

Measuring time: the benchmark

Where noise comes from

In the Jupyter lesson you saw how %timeit works internally and why it disables the garbage collector (IPython magics). Here we need a more complete model of what spoils a measurement, because the goal is no longer a single number but comparing two versions and deciding whether one is faster. If τ\tau is the intrinsic cost of the code, the iith measurement looks like

Ti=τ (1+ηi) d(ti)+wi+εi,T_i = \tau \,(1 + \eta_i)\, d(t_i) + w_i + \varepsilon_i,

with four ingredients of very different kinds:

  • Warm-up wiw_i, large in the first measurements and zero thereafter. Cold data and instruction caches, memory pages supplied by the operating system on first access, lazy imports, tables computed the first time (FFT factors for a new size), cuDNN algorithm selection, JIT compilation. The first call to np.fft.rfft in the cell below takes ten times longer than subsequent calls.
  • Outliers εi≥0\varepsilon_i \ge 0, rare but huge: an interrupt, another process taking the core, a garbage collection pass, a page fault. They only add, never subtract.
  • Drift d(t)d(t), slow and systematic: CPU frequency rises in turbo and falls as the chip heats up (on a laptop, 10% in a few minutes is common), the battery switches mode, another job starts halfway through the session.
  • Symmetric noise ηi\eta_i, small and of both signs: memory alignment, cache collisions, clock resolution, system scheduling.

Each ingredient calls for a different remedy. Warm-up is discarded. Outliers call for a statistic that they cannot drag around. Drift cannot be cured by repetition, because it is bias: if you measure all repetitions of A and then all of B, B bears the hotter machine, so you must interleave versions. Symmetric noise is only reduced by more repetitions.

Mean, minimum and median

Which statistic best summarizes T1,…,TnT_1, \dots, T_n? It depends on the noise, and understanding why is useful.

The mean is the best choice if there is only symmetric noise of finite variance, but its breakdown point is zero: a single outlier of size MM shifts it by M/nM/n, and with heavy-tailed outliers its variance can be enormous. The median withstands almost half the measurements being contaminated, and its precision is known.

Proof

Fix xx and let tn=m+x/nt_n = m + x/\sqrt{n}. The median falls below tnt_n if and only if at least half the measurements do: with Kn=#{i:Ti≤tn}∼Bin⁡(n,F(tn))K_n = \#\{i : T_i \le t_n\} \sim \Bin(n, F(t_n)), P(m^n≤tn)=P(Kn≥n/2)\Pr(\hat{m}_n \le t_n) = \Pr(K_n \ge n/2) (apart from a rounding term that does not affect the limit). By Taylor expansion, F(tn)=12+f(m) x/n+o(1/n)F(t_n) = \tfrac12 + f(m)\,x/\sqrt{n} + o(1/\sqrt{n}). Standardizing the binomial,

P(Kn≥n/2)=P ⁣(Kn−nF(tn)nF(tn)(1−F(tn))≥n/2−nF(tn)nF(tn)(1−F(tn))),\Pr(K_n \ge n/2) = \Pr\!\left(\frac{K_n - nF(t_n)}{\sqrt{nF(t_n)(1 - F(t_n))}} \ge \frac{n/2 - nF(t_n)}{\sqrt{nF(t_n)(1 - F(t_n))}}\right),

and the right side of the inequality tends to −f(m)x/(1/2)=−2f(m)x-f(m)x/(1/2) = -2f(m)x. By the central limit theorem (its version for triangular arrays of Bernoulli variables, which applies because F(tn)F(t_n) converges to 1/21/2), the probability tends to 1−Φ(−2f(m)x)=Φ(2f(m)x)1 - \Phi(-2f(m)x) = \Phi(2f(m)x), which is the distribution function of a N(0,1/(4f(m)2))\Normal(0, 1/(4f(m)^2)) evaluated at xx.

∎

With pure Gaussian noise the median loses something to the mean (it needs π/2≈1.57\pi/2 \approx 1.57 times as many measurements for the same precision), but with just one outlier per session the mean already loses by far. That is the price of cheap insurance.

The minimum deserves separate analysis, because timeit documentation recommends it: if all noise is additive and positive, Ti=τ+εiT_i = \tau + \varepsilon_i with εi≥0\varepsilon_i \ge 0, the minimum is the most stable bound on τ\tau. Indeed, P(min⁡iTi>τ+t)=(1−G(t))n\Pr(\min_i T_i > \tau + t) = (1 - G(t))^n, where GG is the distribution of ε\varepsilon; if G(t)≈g0tG(t) \approx g_0 t near 0, then n(min⁡iTi−τ)n(\min_i T_i - \tau) converges to an exponential with parameter g0g_0 and error decreases as 1/n1/n, faster than the median’s 1/n1/\sqrt{n}. But that advantage depends on there being no symmetric noise. If there is, the minimum of nn Gaussians moves away from the center as σ2ln⁡n\sigma\sqrt{2\ln n} to leading order and fluctuates on a scale decreasing only as σ/2ln⁡n\sigma/\sqrt{2\ln n}. The minimum then estimates the “best case”, which is not the same as τ\tau, and converges very slowly. With the frequency variability of a modern CPU or GPU, noise of both signs is always present.

How many repetitions are needed?

Compare two versions with estimators SAS_A and SBS_B of their times and estimate the relative improvement δ^=1−SB/SA\hat{\delta} = 1 - S_B/S_A. If each estimator is calculated from nn independent measurements with coefficient of variation cc (the relative standard deviation of noise), the delta method gives

sd⁡(δ^)≈2 κ cn,κ={1mean,π/2median (Gaussian noise).\operatorname{sd}(\hat{\delta}) \approx \sqrt{2}\,\kappa\,\frac{c}{\sqrt{n}}, \qquad \kappa = \begin{cases} 1 & \text{mean}, \\ \sqrt{\pi/2} & \text{median (Gaussian noise)}. \end{cases}

For the error of δ^\hat{\delta} to be less than ϵ\epsilon with probability 0.95, we need 1.96sd⁡(δ^)≤ϵ1.96\operatorname{sd}(\hat{\delta}) \le \epsilon, that is,

n ≥ 2(1.96 κ cϵ)2.n \ \ge\ 2\left(\frac{1.96\,\kappa\,c}{\epsilon}\right)^2 .

With 2% noise and tolerance of 2.5 points (enough to distinguish a 5% improvement from none), this gives 5 repetitions with the mean and 8 with the median. With 5% noise, 31 and 49. The dependence on c2/ϵ2c^2/\epsilon^2 is the lesson: halving noise quarters the number of measurements needed, and no other adjustment pays as much. That is why one closes the browser and other processes, fixes frequency where possible and measures in long blocks.

But this formula assumes the noise is symmetric and independent. The following simulator adds the other three ingredients.

InteractiveThe noisy benchmark
One session: each point is a measurement in chronological order (▲: off scale)
10152025msmeasurement order (0 to 9)
Estimated improvement 1−S(B)/S(A)1 - S(B)/S(A) over 400 sessions, with SS = mean
−20 %−10 %0+10 %+20 %real 0.0 %← 238 →
  • version A
  • version B
  • mean of each version
  • error < 2.5 points
0.0 %
5
2.0 %
Statistic
Measurement order
This session: mean of A and B15.83 and 19.82 ms
This session: estimated improvement−25.2 %
400 sessions: typical improvement (median)−4.3 %
400 sessions: central 90%−22.4 % to +12.7 %
Sessions with apparent difference > 2%93 %
nn needed to measure 5% within 2.5 points (95%)more than 500
The two versions are identical, yet 93 % of sessions “see” a difference over 2%, and the typical difference is −4.3 %: bias rather than noise.
Each session measures two versions A and B of a 10 ms function nn times, with τB=τA(1−δ)\tau_B = \tau_A(1 - \delta). Above, one session in measurement order; dashed lines show each version's statistic. Below, estimated improvement δ^=1−S(B)/S(A)\hat\delta = 1 - S(B)/S(A) in 400 independent sessions: its width is noise and its displacement from the δ\delta line is bias. You start with δ=0\delta = 0 (two identical versions), the mean and batch measurements (all A then all B): how many sessions ‘find’ a difference? Try the median, interleave versions, discard warm-up and switch off noise sources one by one. Then set δ=5 %\delta = 5\,\% and find the combination needing fewest repetitions; with all three sources off, compare simulated nn with the Gaussian prediction.

What the figure shows, from worst to best:

  • With versions measured in batches (A…A B…B) and thermal drift, more repetitions do not help. The histogram narrows around a negative value rather than 0: B looks 4% slower because it was measured later, with the machine hotter. This is bias and does not decrease with nn. Interleaving eliminates it.
  • The mean is a slave to outliers. With 6% interruptions averaging 0.8τ0.8\tau and 50 repetitions per version, almost every session has one, and the mean jumps several points between sessions. The median barely moves.
  • Warm-up contaminates the first measurements of each version, and with few repetitions it drags even the median. Discarding it costs 55 measurements and is worthwhile.
  • The minimum, which seemed robust, needs a great many repetitions: it is immune to outliers, but symmetric noise in the simulator makes it converge very slowly, as predicted above.

With the three sources off and versions interleaved, simulated nn agrees with the formula except for discretization of the grid of nn values the figure tries, with one instructive exception: with the median and few repetitions (2% noise), simulation needs fewer measurements than the formula predicts, because the factor π/2\sqrt{\pi/2} is asymptotic and with five or six measurements the median loses much less to the mean (with six, its variance is only about 1.3 times the mean’s, not 1.57). In practice you are never in that ideal case, and the recipe that works is the one in the definition: warm up, interleave, median and IQR.

A benchmark from scratch

The following function implements the recipe and uses it for three things: observing warm-up, checking that a single measurement cannot compare versions (an A/A test, the same function measured twice) and comparing three ways to calculate a sum of squares. The cell runs in the browser, whose clock has coarse resolution, so it measures in blocks of NN calls.

[ ]An honest benchmark from scratchBrowser
import time, timeit
import numpy as np

def medir(f, calentamiento=3, repeticiones=21, objetivo=0.004):
    """Tiempos por llamada de f: calienta, calibra un bloque de N llamadas que dure al menos `objetivo` y repite."""
    for _ in range(calentamiento):
        f()
    n = 1
    while True:                                   # bloques de N llamadas: el reloj del navegador es grueso
        t0 = time.perf_counter()
        for _ in range(n):
            f()
        if time.perf_counter() - t0 >= objetivo:
            break
        n *= 2
    tiempos = []
    for _ in range(repeticiones):
        t0 = time.perf_counter()
        for _ in range(n):
            f()
        tiempos.append((time.perf_counter() - t0) / n)
    return np.array(tiempos)

def resumen(ts):
    q1, q2, q3 = np.quantile(ts, [0.25, 0.5, 0.75])
    return f"mediana {q2 * 1e6:7.1f} µs  IQR {(q3 - q1) * 1e6:5.1f}  media {ts.mean() * 1e6:7.1f}  mín {ts.min() * 1e6:7.1f}"

# 1) calentamiento: las primeras llamadas no se parecen a las demás
x = np.random.default_rng(0).random(3 * 2**14)
primeras = []
for _ in range(6):
    t0 = time.perf_counter()
    np.fft.rfft(x)
    primeras.append((time.perf_counter() - t0) * 1e3)
print("rfft, seis llamadas seguidas (ms):", " ".join(f"{t:.2f}" for t in primeras))

# 2) prueba A/A: la misma función medida dos veces
y = np.random.default_rng(1).random(50_000)
f = lambda: np.sort(y)
aa = []
for _ in range(8):
    t0 = time.perf_counter(); f(); a = time.perf_counter() - t0
    t0 = time.perf_counter(); f(); b = time.perf_counter() - t0
    aa.append(100 * (1 - b / a))
print("A/A con una llamada: «mejora» de B =", " ".join(f"{d:+.0f}%" for d in aa))
ta, tb = medir(f), medir(f)
print(f"A/A con medir():   «mejora» de B = {100 * (1 - np.median(tb) / np.median(ta)):+.1f}%")

# 3) tres formas de la suma de cuadrados
z = np.random.default_rng(2).random(100_000)
for nombre, g in [("np.sum(z**2)", lambda: np.sum(z**2)), ("z @ z", lambda: z @ z), ("einsum", lambda: np.einsum("i,i->", z, z))]:
    print(f"{nombre:13s}", resumen(medir(g)))

# lo mismo con la biblioteca estándar: repeat devuelve el tiempo de cada bloque de `number` llamadas
bloques = np.array(timeit.Timer(lambda: z @ z).repeat(repeat=7, number=200)) / 200
print(f"timeit: mediana {np.median(bloques) * 1e6:.1f} µs, mínimo {bloques.min() * 1e6:.1f} µs")

The first time you run the cell, the first FFT takes about ten times as long as subsequent ones (if you rerun it, no longer: the size factors are cached). The eight single-call A/A tests vary by several points, sometimes tens: with one measurement you can “prove” any improvement. With medir, the two medians of the same function are within a few points, the session’s residual noise; to resolve differences of 5% reliably would require interleaving and more repetitions, as the simulation just showed. And the order of the three sums of squares depends on the platform: in Pyodide, without an optimized BLAS, einsum beats z @ z, and np.sum(z**2) loses because it creates a temporary. On another machine the order may differ. This is why you measure in the environment where code will run, and do not generalize a benchmark to other hardware.

In PyTorch: asynchrony and torch.utils.benchmark

The GPU brings a new trap. As you saw in the local GPU lesson, CUDA operations are asynchronous: A @ B enqueues a kernel and returns control to Python before the GPU has started. A wall clock around it measures how long the CPU takes to enqueue, not how long the GPU takes to compute. Synchronize before and after, or use CUDA events, timestamps inserted into the GPU queue itself.

torch.utils.benchmark.Timer does all this for you: it warms up (important because much of PyTorch initializes lazily), synchronizes the GPU when necessary, fixes the number of CPU threads for fair comparisons, and chooses the block size. blocked_autorange(min_run_time) returns a Measurement object with median, mean, iqr and the times list, and benchmark.Compare arranges several measurements in a table.

[ ]torch.utils.benchmark and the asynchrony trapLocal GPU
import time
import torch
from torch.utils import benchmark

dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
sincronizar = torch.cuda.synchronize if dev.type == "cuda" else (lambda: None)
A = torch.randn(4096, 4096, device=dev)
B = torch.randn(4096, 4096, device=dev)

# 1) reloj de pared sin sincronizar: mide lo que tarda la CPU en ENCOLAR el kernel
ingenuo = []
for _ in range(3):
    t0 = time.perf_counter()
    C = A @ B
    ingenuo.append((time.perf_counter() - t0) * 1e3)
sincronizar()
print("sin sincronizar (ms):", " ".join(f"{t:.3f}" for t in ingenuo))

# 2) sincronizando antes y después
sincronizar(); t0 = time.perf_counter(); C = A @ B; sincronizar()
print(f"sincronizando:        {(time.perf_counter() - t0) * 1e3:.2f} ms")

# 3) eventos CUDA: marcas en la propia cola de la GPU
if dev.type == "cuda":
    ini, fin = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    ini.record(); C = A @ B; fin.record(); fin.synchronize()
    print(f"eventos CUDA:         {ini.elapsed_time(fin):.2f} ms")

# 4) torch.utils.benchmark: calienta, sincroniza, elige el tamaño de bloque y repite
m = benchmark.Timer(stmt="A @ B", globals={"A": A, "B": B}, label="matmul 4096", description="float32").blocked_autorange(min_run_time=0.5)
print(m)
print(f"-> {2 * 4096**3 / m.median / 1e12:.2f} TFLOP/s")

# 5) varias variantes en una tabla
resultados = []
for n in (1024, 4096):
    for dtype in (torch.float32, torch.float16):
        X = torch.randn(n, n, device=dev, dtype=dtype)
        resultados.append(benchmark.Timer(stmt="X @ X", globals={"X": X}, label="matmul", sub_label=f"n = {n}",
                                          description=str(dtype).replace("torch.", "")).blocked_autorange(min_run_time=0.3))
benchmark.Compare(resultados).print()

# 6) ojo: en CPU, Timer usa UN hilo salvo que se le pida otra cosa
Ac = torch.randn(1024, 1024)
uno = benchmark.Timer(stmt="Ac @ Ac", globals={"Ac": Ac}).blocked_autorange(min_run_time=0.3)
todos = benchmark.Timer(stmt="Ac @ Ac", globals={"Ac": Ac}, num_threads=torch.get_num_threads()).blocked_autorange(min_run_time=0.3)
print(f"CPU 1024: {uno.median * 1e3:.2f} ms con {uno.task_spec.num_threads} hilo, {todos.median * 1e3:.2f} ms con {todos.task_spec.num_threads}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the lab’s RTX 4060, the first unsynchronized call takes tens of milliseconds (including lazy cuBLAS initialization), and once initialization finishes, the following ones fall to fractions of a millisecond and then tens of microseconds: the cost of enqueueing. The actual figure, 20 to 24 ms, appears only with synchronization, and CUDA events confirm it. Also note the last line: Timer measures on CPU with one thread unless passed num_threads, a deliberate choice by its authors (single-thread performance is a good indicator of intrinsic efficiency and prevents accidentally comparing different configurations), but surprising when compared with production.

Where time goes: profilers

A benchmark tells you how much; a profiler tells you where. To speak precisely about “where”, let us define what is measured. Let S(t)\mathcal{S}(t) be the call stack at time t∈[0,T]t \in [0, T], the list of active functions from the root to the one executing.

Two immediate consequences. Self times sum to the total, ∑fTpropio(f)=T\sum_f T_{\text{propio}}(f) = T, because at each instant there is exactly one top; cumulative times do not, because a function and its caller share instants. And a recursive function counts its cumulative time only once even if it appears several times in the stack (which is why cProfile writes 3/1 in the calls column: three calls, one nonrecursive).

There are two ways to estimate these quantities, and the difference between them is the subject of this section.

A deterministic profiler from scratch

Python exposes the hook deterministic profilers use: sys.setprofile(gancho) makes the interpreter call gancho(marco, evento, arg) on each call and return of a Python function and each c_call and c_return of a C function (builtins and NumPy methods). A stack of open frames suffices to calculate both columns: on leaving a function, its total time is the elapsed time since entry, and its self time is that total less its children’s time. Saving the full stack path also gives the call tree, which a flame graph draws.

[ ]A toy deterministic profilerBrowser
import sys, time
from collections import defaultdict
import numpy as np
import matplotlib.pyplot as plt

class PerfiladorDeterminista:
    """Tiempo propio, acumulado y árbol de llamadas con sys.setprofile (lo que hace cProfile, en Python)."""
    def __init__(self, reloj=time.perf_counter):
        self.reloj = reloj
        self.pila = []                         # marcos abiertos: [nombre, t_entrada, t_de_los_hijos]
        self.llamadas = defaultdict(int)
        self.propio = defaultdict(float)       # tottime
        self.acumulado = defaultdict(float)    # cumtime (sin contar dos veces la recursión)
        self.arbol = defaultdict(float)        # ruta de la pila (tupla) -> tiempo propio en esa ruta

    @staticmethod
    def nombre(marco, evento, arg):
        if evento.startswith("c_"):            # funciones de C: builtins y métodos de NumPy
            return getattr(arg, "__qualname__", str(arg)) + " [C]"
        return marco.f_code.co_qualname

    def gancho(self, marco, evento, arg):
        t = self.reloj()
        if evento in ("call", "c_call"):
            self.pila.append([self.nombre(marco, evento, arg), t, 0.0])
        elif self.pila:                        # return, c_return, c_exception
            nombre, t0, hijos = self.pila.pop()
            total = t - t0
            self.llamadas[nombre] += 1
            self.propio[nombre] += total - hijos
            if all(m[0] != nombre for m in self.pila):
                self.acumulado[nombre] += total
            self.arbol[tuple(m[0] for m in self.pila) + (nombre,)] += total - hijos
            if self.pila:
                self.pila[-1][2] += total

    def __enter__(self):
        sys.setprofile(self.gancho)
        return self

    def __exit__(self, *exc):
        sys.setprofile(None)

# el programa que vamos a perfilar: preparar datos con NumPy y un k-medias escrito con bucles
def estandarizar(X):
    return (X - X.mean(axis=0)) / X.std(axis=0)

def preparar(n=200_000, d=8, semilla=0):
    X = np.random.default_rng(semilla).normal(size=(n, d)).cumsum(axis=0)
    return estandarizar(X)

def distancia2(p, q):
    return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2

def mas_cercano(p, centros):
    return min(range(len(centros)), key=lambda j: distancia2(p, centros[j]))

def kmeans_lento(puntos, k=4, iteraciones=3):
    centros = puntos[:k]
    for _ in range(iteraciones):
        etiquetas = [mas_cercano(p, centros) for p in puntos]
        centros = [tuple(np.mean([p for p, e in zip(puntos, etiquetas) if e == j], axis=0)) for j in range(k)]
    return etiquetas

def experimento():
    X = preparar()
    puntos = [tuple(fila) for fila in X[:1500, :2].tolist()]
    return np.bincount(kmeans_lento(puntos))

experimento()                                      # calentamiento: la primera ejecución no cuenta
with PerfiladorDeterminista() as perf:
    experimento()

print(f"{'función':30s} {'llamadas':>9s} {'propio (ms)':>12s} {'acumulado (ms)':>15s}")
for f in sorted(perf.propio, key=perf.propio.get, reverse=True)[:8]:
    print(f"{f[:30]:30s} {perf.llamadas[f]:9d} {perf.propio[f] * 1e3:12.1f} {perf.acumulado[f] * 1e3:15.1f}")

def dibujar_flame(arbol, ax, umbral=0.004):
    """Flame graph a partir de {ruta: tiempo propio}: anchura = tiempo acumulado del marco, raíz abajo."""
    acum = defaultdict(float)
    for ruta, t in arbol.items():
        for k in range(1, len(ruta) + 1):
            acum[ruta[:k]] += t                    # el tiempo propio de una ruta cuenta para todos sus prefijos
    total = sum(t for ruta, t in acum.items() if len(ruta) == 1)
    inicio, siguiente = {(): 0.0}, {}
    for ruta in sorted(acum, key=lambda r: (len(r), r)):   # por niveles y, dentro de cada uno, alfabético
        padre = ruta[:-1]
        x0 = siguiente.get(padre, inicio[padre])
        w = acum[ruta] / total
        inicio[ruta], siguiente[padre] = x0, x0 + w
        if w < umbral:
            continue
        ax.barh(len(ruta) - 1, w, left=x0, height=0.92, color=plt.cm.YlOrRd(0.2 + 0.1 * len(ruta)), edgecolor="white")
        if w > 0.05:
            ax.text(x0 + 0.004, len(ruta) - 1, ruta[-1][: int(w * 110)], va="center", fontsize=7)
    ax.set_xlim(0, 1); ax.set_yticks([])
    ax.set_xlabel("fracción del tiempo total (los hermanos van en orden alfabético, no temporal)")

fig, ax = plt.subplots(figsize=(9, 3.2))
dibujar_flame(perf.arbol, ax)
ax.set_title("experimento() bajo el perfilador de juguete")
plt.tight_layout(); plt.show()

The table and flame graph tell the same story you would see with %prun: at the top are the <lambda> that min calls with each center, min, mas_cercano and distancia2, the k-means functions, with tens of thousands of calls. K-means appears expensive. Is it?

Overhead distorts

Each event costs time: reading the clock, looking up the name, updating dictionaries. Let hh be the cost per call (several microseconds in the toy profiler, because it is written in Python; in cProfile, which is in C, on the order of a microsecond or less). That cost is measured as if it belonged to the function. If ff has cfc_f calls and actual self time TfT_f, the profile measures approximately Tf+cfhT_f + c_f h, and the fraction attributed to ff is

p~f=Tf+cfhT+Ch,C=∑gcg.\tilde{p}_f = \frac{T_f + c_f h}{T + C h}, \qquad C = \sum_g c_g .

The relative distortion of ff versus the rest is determined by its time per call, Tf/cfT_f/c_f: if comparable to hh, the profile inflates it; if much larger, it barely affects it. Small, frequently called functions, exactly those in Python loops, always look worse than they are, and long NumPy calls look better. The profile module (the pure Python version of cProfile) therefore includes a calibration method that estimates hh and subtracts it; cProfile does not. Let us measure the truth: each phase’s time without a profiler, using the median of five runs.

[ ]Overhead distorts the profileBrowser
import cProfile, pstats, statistics

def mediana_ms(f, repeticiones=5):
    ts = []
    for _ in range(repeticiones):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return statistics.median(ts) * 1e3

X = preparar()
puntos = [tuple(fila) for fila in X[:1500, :2].tolist()]
tp, tk = mediana_ms(preparar), mediana_ms(lambda: kmeans_lento(puntos))
print(f"verdad (sin perfilador): preparar {tp:.1f} ms, kmeans {tk:.1f} ms -> kmeans = {tk / (tp + tk):.0%}")

perfil = cProfile.Profile()
t0 = time.perf_counter(); perfil.runcall(experimento); t_cp = (time.perf_counter() - t0) * 1e3
st = {clave[2]: v for clave, v in pstats.Stats(perfil).stats.items()}   # (archivo, línea, función) -> estadísticas
cp, ck = st["preparar"][3] * 1e3, st["kmeans_lento"][3] * 1e3
print(f"cProfile:  una ejecución tarda {t_cp:.0f} ms; preparar {cp:.1f}, kmeans {ck:.1f} -> kmeans = {ck / (cp + ck):.0%}")

with PerfiladorDeterminista() as perf:
    t0 = time.perf_counter(); experimento(); t_j = (time.perf_counter() - t0) * 1e3
jp, jk = perf.acumulado["preparar"] * 1e3, perf.acumulado["kmeans_lento"] * 1e3
print(f"de juguete: una ejecución tarda {t_j:.0f} ms; preparar {jp:.1f}, kmeans {jk:.1f} -> kmeans = {jk / (jp + jk):.0%}")

def vacia():
    pass
def bucle(n=20_000):
    for _ in range(n):
        vacia()
libre = mediana_ms(bucle)
perfil = cProfile.Profile(); perfil.enable()
t0 = time.perf_counter(); bucle(); con = (time.perf_counter() - t0) * 1e3
perfil.disable()
print(f"20 000 llamadas vacías: {libre:.2f} ms libre, {con:.2f} ms con cProfile -> h ≈ {(con - libre) / 20_000 * 1e3:.2f} µs por llamada")

In Pyodide, k-means is around 15% of actual time (the exact figure depends on machine load). cProfile says about 40%, and the toy profiler nearly 75%. Neither miscounts: both faithfully measure a program that is not yours, but yours with half a microsecond (or several) added to each of its roughly 50 000 calls. With cProfile’s profile in hand, a reasonable person would optimize k-means and gain, as in the motivation, 17%.

line_profiler takes the idea to line level: with the decorator @profile and kernprof -l -v script.py (or %lprun in Jupyter), it measures the time between consecutive line events and accumulates it by line, with columns Hits, Time, Per Hit and % Time. It is essential when a long function is expensive and you do not know which line, and has the same disease multiplied: the hook fires on every line. Its minimal version fits in a cell (like line_profiler, it works on a source file, so we write the function in a module):

[ ]A minimal line profilerBrowser
import importlib, inspect, os, tempfile

def perfilar_lineas(f, *args):
    """Lo que hace line_profiler: tiempo entre eventos «line» consecutivos de f, acumulado por línea."""
    codigo = f.__code__
    tiempo, visitas = defaultdict(float), defaultdict(int)
    actual = [None, 0.0]                             # línea en curso y cuándo empezó
    def traza(marco, evento, arg):
        if marco.f_code is not codigo:
            return None                              # no se trazan las funciones a las que llama f
        if evento in ("line", "return"):
            t = time.perf_counter()
            if actual[0] is not None:
                tiempo[actual[0]] += t - actual[1]
            actual[0] = marco.f_lineno if evento == "line" else None
            if evento == "line":
                visitas[marco.f_lineno] += 1
            actual[1] = time.perf_counter()          # no se cobra a la línea el tiempo de este gancho
        return traza
    sys.settrace(traza)
    try:
        f(*args)
    finally:
        sys.settrace(None)
    lineas, primera = inspect.getsourcelines(f)
    total = sum(tiempo.values())
    print(f"{'línea':>5s} {'visitas':>8s} {'ms':>8s} {'%':>6s}  código")
    for i, texto in enumerate(lineas):
        if primera + i in visitas:
            n = primera + i
            print(f"{i:5d} {visitas[n]:8d} {tiempo[n] * 1e3:8.2f} {100 * tiempo[n] / total:6.1f}  {texto.rstrip()}")

fuente = """
import numpy as np

def normalizar_filas(X):
    salida = np.empty_like(X)
    for i in range(X.shape[0]):
        fila = X[i]
        norma = np.sqrt((fila * fila).sum())
        salida[i] = fila / norma
    medias = salida.mean(axis=0)
    return salida - medias
"""
carpeta = tempfile.mkdtemp()
with open(os.path.join(carpeta, "filas.py"), "w") as fichero:
    fichero.write(fuente)
sys.path.insert(0, carpeta)
filas = importlib.import_module("filas")
perfilar_lineas(filas.normalizar_filas, np.random.default_rng(0).random((2000, 64)))

The norm line takes half the time and division more than a quarter, but the correct diagnosis is not “the norm is expensive”: each of those lines performs a handful of NumPy operations on 64 numbers, and what costs time is the overhead of launching them 2000 times. The entire function can be rewritten in one line, X / np.linalg.norm(X, axis=1, keepdims=True), which is vectorization.

The sampling profiler

Sampling attacks the problem from the other side: instead of intercepting every call, it looks at the stack occasionally. If the observations have nothing to do with what the program is doing, the fraction of observations with ff on the stack estimates its cumulative time fraction, without per-call cost.

Proof

Each indicator is Bernoulli: it is 1 when UkU_k falls in the set of instants with ff on the stack, whose measure is Tacum(f)T_{\text{acum}}(f), so its probability is pfp_f. The mean of NN independent Bernoulli variables with parameter pfp_f has expectation pfp_f and variance pf(1−pf)/Np_f(1 - p_f)/N.

∎

The typical error is at most 1/(2N)1/(2\sqrt{N}): with 2500 samples, one percentage point. At the 100 Hz py-spy uses by default, that is 25 seconds of program time. This is why a sampling profile needs a long (and representative) run, and is unsuitable for a function lasting 50 ms. In practice samples are taken at regular intervals, not randomly; the estimator remains good as long as the program has no periodicity synchronized with sampling. To avoid that aliasing effect, py-spy randomizes intervals between samples (with an exponential distribution), so sampling instants are unrelated to the program, precisely the theorem’s assumption.

py-spy also has a design advantage: it is another process. It reads the target interpreter’s memory from outside, reconstructs the Python stack and does not need program cooperation or a single line of code changed, so its overhead on the program is practically zero and it can attach to training already running. Typical uses:

py-spy record -o perfil.svg -- python entrenar.py          # flame graph SVG de una ejecución
py-spy record --format speedscope -o perfil.json --pid 4242  # engancharse a un proceso vivo
py-spy top --pid 4242                                      # «top» de funciones, en directo
py-spy dump --pid 4242                                     # la pila de cada hilo, ahora (¿dónde se ha colgado?)

Options that matter in numerical code: --native adds C and C++ frames (without it, time inside NumPy or PyTorch appears on the Python line calling them), --subprocesses follows child processes (DataLoader workers), --idle includes sleeping threads, --gil samples only when the thread holds the GIL, --rate changes frequency and --nonblocking avoids pausing the process when reading each sample, at the cost of an occasional inconsistent stack.

We can write a sampling profiler in a cell, though within the process: a thread that sleeps one millisecond, copies the main thread’s stack with sys._current_frames() and sleeps again. It runs in local Python because the browser has no threads, so it repeats the k-means script.

[ ]A sampling profiler from scratchLocal GPU
import sys, threading, time, statistics, cProfile, pstats
from collections import Counter
import numpy as np

# el script de antes (esta celda corre en el Python local, que no comparte sesión con el navegador)
def estandarizar(X):
    return (X - X.mean(axis=0)) / X.std(axis=0)

def preparar(n=200_000, d=8, semilla=0):
    X = np.random.default_rng(semilla).normal(size=(n, d)).cumsum(axis=0)
    return estandarizar(X)

def distancia2(p, q):
    return (p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2

def mas_cercano(p, centros):
    return min(range(len(centros)), key=lambda j: distancia2(p, centros[j]))

def kmeans_lento(puntos, k=4, iteraciones=3):
    centros = puntos[:k]
    for _ in range(iteraciones):
        etiquetas = [mas_cercano(p, centros) for p in puntos]
        centros = [tuple(np.mean([p for p, e in zip(puntos, etiquetas) if e == j], axis=0)) for j in range(k)]
    return etiquetas

def experimento():
    X = preparar()
    puntos = [tuple(fila) for fila in X[:1500, :2].tolist()]
    return np.bincount(kmeans_lento(puntos))

class PerfiladorMuestreo:
    """Cada `intervalo` segundos, otro hilo copia la pila del hilo principal (la idea de py-spy, dentro del proceso)."""
    def __init__(self, intervalo=0.001):
        self.intervalo = intervalo
        self.muestras = Counter()                    # pila (de la raíz a la hoja) -> número de muestras
        self.pesos = Counter()                       # pila -> segundos de reloj que representa
        self.objetivo = threading.main_thread().ident
        self.parar = threading.Event()

    def _bucle(self):
        antes = time.perf_counter()
        while not self.parar.is_set():
            marco = sys._current_frames().get(self.objetivo)   # necesita el GIL: puede llegar tarde
            ahora = time.perf_counter()
            pila = []
            while marco is not None:
                pila.append(marco.f_code.co_qualname)
                marco = marco.f_back
            pila = tuple(reversed(pila))
            self.muestras[pila] += 1
            self.pesos[pila] += ahora - antes                 # cada muestra vale el tiempo desde la anterior
            antes = ahora
            time.sleep(self.intervalo)

    def __enter__(self):
        self.gil = sys.getswitchinterval()
        sys.setswitchinterval(self.intervalo / 4)    # el hilo principal cede el GIL a menudo
        self.hilo = threading.Thread(target=self._bucle, daemon=True)
        self.hilo.start()
        return self

    def __exit__(self, *exc):
        self.parar.set()
        self.hilo.join()
        sys.setswitchinterval(self.gil)

    def fraccion(self, funcion, ponderar=True):
        """Fracción del tiempo con `funcion` en la pila (su tiempo acumulado relativo)."""
        c = self.pesos if ponderar else self.muestras
        return sum(v for pila, v in c.items() if funcion in pila) / sum(c.values())

def mediana_ms(f, repeticiones=5):
    ts = []
    for _ in range(repeticiones):
        t0 = time.perf_counter(); f(); ts.append(time.perf_counter() - t0)
    return statistics.median(ts) * 1e3

X = preparar()
puntos = [tuple(fila) for fila in X[:1500, :2].tolist()]
experimento()                                           # calentamiento
tp, tk, te = mediana_ms(preparar), mediana_ms(lambda: kmeans_lento(puntos)), mediana_ms(experimento)
print(f"verdad (sin perfilador):  una ejecución tarda {te:.0f} ms; preparar {tp:.1f}, kmeans {tk:.1f} -> kmeans = {tk / (tp + tk):.1%}")

perfil = cProfile.Profile()
t0 = time.perf_counter(); perfil.runcall(experimento); t_cp = (time.perf_counter() - t0) * 1e3
st = {clave[2]: v for clave, v in pstats.Stats(perfil).stats.items()}
cp, ck = st["preparar"][3], st["kmeans_lento"][3]
print(f"cProfile:                 una ejecución tarda {t_cp:.0f} ms -> kmeans = {ck / (cp + ck):.1%}")

for intento in range(3):
    with PerfiladorMuestreo() as m:
        t0 = time.perf_counter()
        for _ in range(10):
            experimento()
        t_m = (time.perf_counter() - t0) * 1e2
    N = sum(m.muestras.values())
    q = m.fraccion("kmeans_lento", False) / (m.fraccion("kmeans_lento", False) + m.fraccion("preparar", False))
    p = m.fraccion("kmeans_lento") / (m.fraccion("kmeans_lento") + m.fraccion("preparar"))
    print(f"muestreo, intento {intento}: {N} muestras, {t_m:.0f} ms por ejecución -> "
          f"kmeans = {q:.1%} contando, {p:.1%} ponderando (± {(p * (1 - p) / N) ** 0.5:.1%})")

hojas = Counter()
for pila, w in m.pesos.items():
    hojas[pila[-1]] += w
total = sum(hojas.values())
print("tiempo propio por muestreo:", ", ".join(f"{f} {w / total:.0%}" for f, w in hojas.most_common(4)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The result has three readings. Execution under the sampler takes almost as long as without it: overhead is small and, above all, independent of call count. The weighted k-means fraction is within a point or two of the truth, within sampling error, compared with twice that from cProfile. And the fraction counting samples comes out a few points high, for an instructive reason: to read the stack, the sampling thread needs the GIL, and while the main thread is inside a long NumPy call that does not release it, the sampler waits. Samples of long C phases arrive late and are lost; those of a Python loop, which yields the GIL often, arrive on time. Weighting each sample by time elapsed since the previous one compensates for almost all the bias. py-spy has no such problem because it does not need the GIL: it reads memory from outside.

Reading a profile: flame graphs

A table sorted by tottime answers “which function is expensive?”, and sorted by cumtime, “which subsystem is expensive?”. Brendan Gregg’s flame graph answers both at once. Each rectangle is a stack frame; its row is depth; its width is cumulative time (the samples in which it appears). Children stack above their parent and the part of the parent they do not cover is its self time. The horizontal axis is not time: siblings are alphabetically ordered so identical stacks merge. Read it by looking for wide plateaus at the top, frames with lots of self time, and descending from them to see who calls them. The inverted variant, with the root at the top, is called an icicle graph; that is what snakeviz draws from a cProfile profile saved with python -m cProfile -o perfil.prof script.py.

InteractiveFlame graph explorer
experimento: self 0.2 %, cumulative 100.0 %experimento 100 %preparar: self 36.9 %, cumulative 59.6 %preparar 60 %ndarray.cumsum: self 6.0 %, cumulative 6.0 %ndar…estandarizar: self 5.2 %, cumulative 16.8 %estandarizar 17 %ndarray.mean: self 2.6 %, cumulative 2.6 %ndarray.std: self 0.7 %, cumulative 8.9 %ndarray…_var: self 8.2 %, cumulative 8.2 %_var 8 %kmeans_lento: self 0.4 %, cumulative 40.1 %kmeans_lento 40 %mas_cercano: self 3.7 %, cumulative 37.9 %mas_cercano 38 %len: self 2.9 %, cumulative 2.9 %min: self 4.3 %, cumulative 31.3 %min 31 %<lambda>: self 13.0 %, cumulative 27.0 %<lambda> 27 %distancia2: self 14.0 %, cumulative 14.0 %distancia2np.mean: self 1.8 %, cumulative 1.8 %
  • Python function
  • C function (NumPy, builtins)
  • self time inflated over ×1.8
Top by self time (tottime)
cProfile
ground truth
36.9 %
52.4 %
14.0 %
4.7 %
13.0 %
3.2 %
8.2 %
11.6 %
6.0 %
8.5 %
5.2 %
7.4 %
4.3 %
2.3 %
3.7 %
1.4 %
Profiler
Sort table by
0.80 µs
Selected framedistancia2
Calls per run18000
Self time according to cProfile14.0 %
Actual self time4.7 %
Self-time inflation×4.27
Duration of one run134 ms (×1.42)
With cProfile, kmeans_lento appears to take 40 % of the program; in reality it takes 15 %. Each of its 49 513 calls per run incurs overhead hh, and the program takes 134 ms instead of 94.5 ms.
The lesson's script (preparing data with NumPy and k-means with Python loops) as seen by each profiler. Times are calibrated with the ‘Overhead distorts the profile’ cell in the browser; the internal breakdown of each phase is a model. You start in cProfile with distancia2 selected and the self-time view: each frame's intense section is the part not covered by its children. Press ‘Truth’ and watch k-means shrink; return to cProfile and raise overhead hh. Switch to py-spy: the profile resembles the truth, but with noise; reduce duration to 1 s, press ‘Another run’ several times and watch how much each percentage moves. Enable --native to see C frames. Click a frame to zoom into its subtree, and its base to return.

Three things worth seeing in the figure:

  1. In cProfile, k-means functions turn red. Their self time is inflated by more than 80%, and distancia2, the most innocent function in the program, becomes one of the widest. The entire program also takes 40% longer than without a profiler.
  2. In py-spy, with 10 s at 100 Hz, percentages fluctuate around the point. With 1 s, several points. The error is that of the preceding theorem and appears in the selected frame’s column.
  3. Without --native, min, len and NumPy methods disappear and their time is added to the Python function that calls them. This is not an error: when deciding what to rewrite, it is often exactly what you want to know.
QuizReading cProfile output
A toy training run gives this pstats output sorted by tottime (times in seconds): decodificar with 51 200 calls, tottime 2.38 and cumtime 2.98; numpy.frombuffer with 51 200 calls, tottime 0.60; paso with 200 calls, tottime 0.01 and cumtime 1.05; ndarray.dot with 400 calls, tottime 1.02; cargar_lote with 200 calls, tottime 0.015 and cumtime 3.11; entrenar with 1 call and cumtime 4.21. Where do you start?

Memory: where the bytes are

Time is not the only resource that runs out. A numerical program that does not fit in memory is not slow: it does not finish. And memory and time are linked, because each temporary created must be requested, written, read and returned.

tracemalloc intercepts Python allocators and records each block with the stack that requested it; NumPy also reports its array data buffers (in its own domain, np.lib.tracemalloc_domain). get_traced_memory() returns current and peak memory, reset_peak() resets the peak and take_snapshot() lets you compare two instants by code line with compare_to. It cannot see memory that does not pass through those allocators, such as internal BLAS buffers or a memory-mapped file; tools that also intercept C malloc, such as memray, handle that.

How much peak memory does a * x**2 + b * x + c need with x of nn float64 elements? More than it looks like, and it can be calculated.

Proof

By induction on the tree. For a binary node, evaluation has three phases. While uu is evaluated, the maximum is r(u)r(u) by the induction hypothesis. While ww is evaluated, the result of uu is still alive and contributes t(u)t(u), and ww contributes at most r(w)r(w). When computing vv both operands and the new result coexist: t(u)+t(w)+1t(u) + t(w) + 1. Afterwards the operands are freed and only the result remains. The unary node is the case of ww a leaf with t(w)=0t(w) = 0, and a scalar or existing array does not count. The maximum over the three phases is r(v)r(v).

∎

The recurrence is a variant of the Sethi–Ullman number (1970), which counts the registers a compiler needs to evaluate an expression. There one also chooses the optimal operand order (evaluate the more demanding one first); here Python fixes left-to-right order.

For a * x**2 + b * x + c, the tree is ((a⋅x2)+(b⋅x))+c((a \cdot x^2) + (b \cdot x)) + c: x**2 leaves one temporary (r=1r = 1), a * ... needs two at once (r=2r = 2), b * x another while the first lives, and the addition has three live: the peak is three arrays. Horner form, (a * x + b) * x + c, never has more than two, and with in-place operations (y = x * a; y += b; y *= x; y += c) one suffices, the result. With np.multiply(x, a, out=y) on a preallocated y, none. And if you wanted a reduction, such as the expression’s mean, you can work in fixed-size chunks, chunked vectorization, and the peak no longer depends on nn.

[ ]Peak memory of NumPy expressionsBrowser
import tracemalloc, time
import numpy as np

n = 1_000_000
ARRAY = 8 * n                                  # bytes de un array de n float64
x = np.random.default_rng(0).random(n)
a, b, c = 2.0, -3.0, 0.5

def pico(f, *args):
    """Memoria pico y final que reserva f, en múltiplos de un array de n float64."""
    tracemalloc.start()
    tracemalloc.reset_peak()
    base = tracemalloc.get_traced_memory()[0]
    resultado = f(*args)
    actual, maximo = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return (maximo - base) / ARRAY, (actual - base) / ARRAY

def ingenua(x):
    return a * x**2 + b * x + c

def horner(x):
    return (a * x + b) * x + c

def en_el_sitio(x):
    y = x * a                                  # el único array nuevo: el resultado
    y += b
    y *= x
    y += c
    return y

def con_out(x, y):
    np.multiply(x, a, out=y); y += b; y *= x; y += c
    return y

def media_ingenua(x):
    return float(np.mean(a * x**2 + b * x + c))

def media_por_bloques(x, bloque=65_536):
    total, tmp = 0.0, np.empty(bloque)
    for i in range(0, len(x), bloque):
        xb = x[i:i + bloque]
        t = tmp[:len(xb)]
        np.multiply(xb, a, out=t); t += b; t *= xb; t += c
        total += t.sum()
    return total / len(x)

y = np.empty(n)
print(f"{'versión':18s} {'pico':>6s} {'queda':>6s} {'tiempo':>9s}   (en arrays de n float64)")
for nombre, f, args in [("ingenua", ingenua, (x,)), ("horner", horner, (x,)), ("en_el_sitio", en_el_sitio, (x,)),
                        ("con_out", con_out, (x, y)), ("media_ingenua", media_ingenua, (x,)),
                        ("media_por_bloques", media_por_bloques, (x,))]:
    p, queda = pico(f, *args)
    t0 = time.perf_counter()
    for _ in range(5):
        f(*args)
    print(f"{nombre:18s} {p:6.2f} {queda:6.2f} {(time.perf_counter() - t0) / 5 * 1e3:7.1f} ms")
print("mismo resultado:", np.allclose(ingenua(x), en_el_sitio(x)), abs(media_ingenua(x) - media_por_bloques(x)) < 1e-12)

Peaks are exactly those predicted by the theorem: 3, 2, 1 and 0 arrays, and 3 versus less than a tenth for the mean. Browser times barely separate the versions (the naive one is slowest, and the others are close), because WebAssembly memory is already reserved. On a real operating system, each new 8 MB temporary also requires requesting pages from the system and filling them on first access: with the lab’s local Python on Windows, the naive version takes about 14 ms and the out version about 1.4. Ten times, just by avoiding temporaries.

On the GPU, memory is scarcer and PyTorch’s allocator keeps a block cache, so one must distinguish allocated (live tensors) from reserved (what the cache has requested from CUDA and not returned), as you saw studying the caching allocator. Key functions are torch.cuda.memory_allocated, max_memory_allocated with reset_peak_memory_stats for a fragment’s peak, memory_reserved and memory_summary. To see who allocated what and when, torch.cuda.memory._record_memory_history() followed by torch.cuda.memory._dump_snapshot("instantanea.pickle") saves a snapshot that can be dragged to pytorch.org/memory_viz and shows each allocation with its stack. In training, the greatest consumption is usually activations autograd saves for backward.

[ ]Peak memory on the GPULocal GPU
import torch
dev = torch.device("cuda")
MiB = 2**20

def pico_gpu(f):
    """Memoria pico que reserva f en la GPU por encima de lo ya asignado, y la que queda al terminar, en MiB."""
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    base = torch.cuda.memory_allocated()
    r = f()
    torch.cuda.synchronize()
    return (torch.cuda.max_memory_allocated() - base) / MiB, (torch.cuda.memory_allocated() - base) / MiB, r

x = torch.rand(2**24, device=dev)                       # 64 MiB de float32
a, b, c = 2.0, -3.0, 0.5
def en_el_sitio():
    y = x * a; y += b; y *= x; y += c
    return y
for nombre, f in [("a*x**2 + b*x + c", lambda: a * x**2 + b * x + c), ("en el sitio", en_el_sitio)]:
    p, queda, _ = pico_gpu(f)
    print(f"{nombre:18s} pico {p:6.0f} MiB   queda {queda:5.0f} MiB")

# entrenamiento: autograd guarda tensores del forward hasta el backward
L, d = 8, 2048
modelo = torch.nn.Sequential(*[torch.nn.Sequential(torch.nn.Linear(d, d), torch.nn.GELU()) for _ in range(L)]).to(dev)
for lote in (256, 1024, 4096):
    entrada = torch.randn(lote, d, device=dev)
    with torch.no_grad():
        p_inf, _, _ = pico_gpu(lambda: modelo(entrada))
    p_ent, guardado, salida = pico_gpu(lambda: modelo(entrada))
    del salida                                          # libera el grafo y lo que guardaba
    teoria = 2 * L * lote * d * 4 / MiB                 # Linear guarda su entrada; GELU, la suya
    print(f"lote {lote:5d}: sin grafo pico {p_inf:5.0f} MiB | con grafo pico {p_ent:6.0f} MiB, "
          f"retenido {guardado:6.0f} MiB (2·L·B·d·4 bytes = {teoria:5.0f})")
print(f"asignado {torch.cuda.memory_allocated() / MiB:.0f} MiB, reservado por la caché {torch.cuda.memory_reserved() / MiB:.0f} MiB")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The naive expression has the same peak of three arrays on GPU as CPU (192 MiB for a tensor of 64), because PyTorch in eager mode evaluates in exactly the same way. And memory retained by the graph matches the count 2LBd⋅42LBd \cdot 4 bytes to the megabyte: each Linear stores its input and each GELU its own, 2L2L tensors of B×dB \times d. Without a graph (torch.no_grad), the peak is a few tensors of one layer. This count, linear in batch size, determines how large a batch fits in the local GPU’s 8 GB (you saw it as the memory budget), and is what activation recomputation and mixed precision target.

torch.profiler: the trace of a step

For PyTorch code, neither cProfile nor py-spy suffices: they see the CPU, and half the story happens on the GPU, at another time. torch.profiler records both at once: ATen operators and CUDA runtime calls on CPU, and kernels and copies on GPU, with arrows connecting each launch to its kernel. Results are summarized in tables or exported as a trace, a record of intervals with row, start and duration, opened in Perfetto (ui.perfetto.dev).

Labels with record_function("datos"): appear as named intervals in the trace and separate data loading from computation. prof.key_averages() aggregates by operator (with group_by_input_shape=True, by operator and shape) and .table(sort_by="self_device_time_total") gives the classic table (in older versions, self_cuda_time_total, a name now deprecated).

Let us profile a training loop written as one writes it the first time (the loop from the nn.Module and training loop lesson, with a Dataset that makes each example in __getitem__, like one that decodes and augments sample by sample), and read the trace with a program instead of by eye.

[ ]Profile the training loop with torch.profilerLocal GPU
import json, os, statistics, tempfile
import numpy as np
import torch, torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from torch.profiler import profile, schedule, record_function, ProfilerActivity

dev = torch.device("cuda")
D, CLASES = 256, 10

class Sinteticos(Dataset):
    """Cada ejemplo se fabrica en __getitem__ con NumPy, como un dataset que decodifica y aumenta muestra a muestra."""
    def __init__(self, n=8192, semilla=0):
        g = np.random.default_rng(semilla)
        self.X = g.normal(size=(n, D)).astype(np.float32)
        self.y = (self.X @ g.normal(size=(D, CLASES)).astype(np.float32)).argmax(1)
    def __len__(self):
        return len(self.X)
    def __getitem__(self, i):
        ruido = np.random.standard_normal(D).astype(np.float32)
        return torch.from_numpy(self.X[i] + np.float32(0.01) * ruido), int(self.y[i])

def nuevo_modelo():
    torch.manual_seed(0)
    m = nn.Sequential(nn.Linear(D, 512), nn.ReLU(), nn.LayerNorm(512),
                      nn.Linear(512, 512), nn.ReLU(), nn.LayerNorm(512), nn.Linear(512, CLASES)).to(dev)
    return m, torch.optim.AdamW(m.parameters(), lr=1e-3)

datos = Sinteticos()
perdida_fn = nn.CrossEntropyLoss()

def bucle_base(modelo, opt, pasos, lote=64, prof=None):
    """El bucle de entrenamiento tal y como se escribe la primera vez."""
    registro = []
    lotes = iter(DataLoader(datos, batch_size=lote, shuffle=True))
    for _ in range(pasos):
        with record_function("datos"):
            x, y = next(lotes)
        with record_function("computo"):
            x, y = x.to(dev), y.to(dev)
            perdida = perdida_fn(modelo(x), y)
            opt.zero_grad(set_to_none=True)
            perdida.backward()
            opt.step()
            registro.append(perdida.item())          # sincroniza en cada paso
        if prof is not None:
            prof.step()
    return registro

ruta = os.path.join(tempfile.gettempdir(), "atlas_traza_base.json")
modelo, opt = nuevo_modelo()
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
             schedule=schedule(wait=2, warmup=3, active=6),     # 2 pasos ignorados, 3 de calentamiento, 6 grabados
             on_trace_ready=lambda p: p.export_chrome_trace(ruta)) as prof:
    bucle_base(modelo, opt, 11, prof=prof)

ops = [e for e in prof.key_averages() if e.key.startswith("aten::")]
print(f"{'operador':26s} {'llamadas':>8s} {'CPU propio (ms)':>16s} {'GPU propio (ms)':>16s}")
for e in sorted(ops, key=lambda e: -e.self_cpu_time_total)[:6]:
    print(f"{e.key:26s} {e.count:8d} {e.self_cpu_time_total / 1e3:16.2f} {e.self_device_time_total / 1e3:16.3f}")
print("traza para Perfetto:", ruta, f"({os.path.getsize(ruta) / 1e6:.1f} MB)")

def resumen_traza(ruta):
    """Las cifras que buscarías a ojo en Perfetto, calculadas sobre los pasos grabados."""
    ev = [e for e in json.load(open(ruta))["traceEvents"] if e.get("ph") == "X"]
    pasos = [e for e in ev if e.get("cat") == "user_annotation" and e["name"].startswith("ProfilerStep")]
    t0, t1 = min(e["ts"] for e in pasos), max(e["ts"] + e["dur"] for e in pasos)
    gpu = sorted((e["ts"], e["ts"] + e["dur"]) for e in ev if e.get("cat") in ("kernel", "gpu_memcpy", "gpu_memset"))
    ocupado, fin = 0.0, t0                    # longitud de la unión de los intervalos de la GPU
    for a, b in gpu:
        a, b = max(a, fin), min(b, t1)
        if b > a:
            ocupado += b - a
            fin = b
    kernels = [e["dur"] for e in ev if e.get("cat") == "kernel"]
    suma = lambda nombre: sum(e["dur"] for e in ev if e["name"] == nombre) / len(pasos) / 1e3
    cuenta = lambda nombre: sum(e["name"] == nombre for e in ev) / len(pasos)
    return {"paso (ms)": (t1 - t0) / len(pasos) / 1e3, "GPU ocupada": ocupado / (t1 - t0),
            "kernels por paso": len(kernels) / len(pasos), "kernel mediano (µs)": statistics.median(kernels),
            "datos (ms por paso)": suma("datos"), "sincronizaciones por paso": cuenta("cudaStreamSynchronize")}

for k, v in resumen_traza(ruta).items():
    print(f"{k:28s} {v:8.3f}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

If you open the trace in Perfetto you will see a row per CPU thread and one per GPU stream. What to look for, and what the summary calculates:

  • GPU occupancy: the fraction of the step with any kernel or copy running. Here, between 3 and 5%. The GPU is idle almost all the time.
  • Tiny kernels: about 40 per step with median duration of a few microseconds. A kernel lasting less than its own launch is pure overhead.
  • Data loading: the datos interval lasts between 1 and 2 ms per step, a visible fraction but not the majority.
  • Synchronizations: three cudaStreamSynchronize per step. One is perdida.item(); the other two are x.to(dev) and y.to(dev) copies from pageable memory, which PyTorch waits to finish. In Perfetto they appear as a gap in the CPU row coinciding with the end of the GPU queue.
  • The operator table confirms the same picture from another angle: each operator’s CPU self time is tens of microseconds per call, GPU time a few. Requesting operations is expensive, not doing them.

Diagnosis: four regimes and their remedies

Horace He summarized GPU performance in three regimes according to which resource runs out first: overhead (time when the GPU does nothing because Python, the PyTorch dispatcher or kernel launches do not supply work fast enough), bandwidth (the GPU moves bytes between memory and cores at maximum speed and cores wait), and compute (cores perform operations at maximum speed). Training has a fourth, preceding the three: data, when the GPU waits for the next batch. Distinguishing them by measurement instead of a hunch requires a model of the step.

Why the maximum? Because the three can overlap. DataLoader workers prepare batches in parallel with the main thread (DataLoader workers), and the CPU queues kernels the GPU executes as they arrive.

Proof

Each stage of a pipeline with queues is a server processing steps in order. If stage jj takes TjT_j per step, it cannot finish kk steps before kTjkT_j, so steady-state throughput cannot exceed 1/max⁡jTj1/\max_j T_j. Conversely, with queues allowing work to run ahead, once queues are full the slowest stage never waits for the others and determines throughput: Tpaso=max⁡jTjT_{\text{paso}} = \max_j T_j. Synchronization at the end of a step prevents the CPU from enqueueing step k+1k + 1 before the GPU finishes kk; CPU and GPU stop being independent stages and become one, whose time is the CPU’s enqueue time plus what remains for the GPU when the CPU finishes.

∎

The same happens if loading occurs in the main thread (num_workers=0): data and CPU form one stage and their times add. This is the starting point of the interactive below.

The model has a useful practical consequence: each regime responds differently to the same experiment, so diagnosis is confirmed by changing one thing and measuring.

RegimeTrace symptomConfirming testRemedies
DataGPU gaps aligned with batch waitingiterating the DataLoader without a model gives the same rate as trainingmore workers, pin_memory, decode or augment on GPU, cache, faster formats
OverheadGPU lightly occupied, kernels of a few µs, CPU always busy launchingdoubling batch barely changes time per steplarger batch, fusion (torch.compile), fused optimizer, CUDA graphs, fewer .item() calls
MemoryGPU busy, elementwise operations, normalizations and copies dominateattained bandwidth approaches GPU maximumfuse, lower precision (bf16), avoid copies and transposes
ComputeGPU busy, matmul and convolutions dominateattained FLOP/s approaches maximumTF32 or mixed precision (tensor cores), fewer FLOPs, better algorithms

The last two rows are the roofline model: a kernel of intensity II cannot exceed min⁡(P, I⋅B)\min(P,\ I \cdot B) operations per second, and is memory-bound if I<P/BI < P/B and compute-bound if I>P/BI > P/B. Measuring PP, BB and the cost of a tiny operation on your machine turns the table into numbers.

[ ]Your GPU ceilings and four classified operationsLocal GPU
from torch.utils import benchmark

def medir_us(stmt, **variables):
    return benchmark.Timer(stmt=stmt, globals=variables).blocked_autorange(min_run_time=0.4).median * 1e6

# los tres techos de esta máquina
x = torch.randn(2**26, device=dev)                                # 256 MiB
B_pico = 2 * x.numel() * 4 / (medir_us("x * 2.0", x=x) * 1e-6)    # lee y escribe 4 bytes por elemento
M = torch.randn(4096, 4096, device=dev)
P_pico = 2 * 4096**3 / (medir_us("M @ M", M=M) * 1e-6)
uno = torch.ones(1, device=dev)
sobrecarga = medir_us("uno * 2.0", uno=uno)
print(f"ancho de banda {B_pico / 1e9:.0f} GB/s, cómputo FP32 {P_pico / 1e12:.2f} TFLOP/s, "
      f"op diminuta {sobrecarga:.1f} µs, punto de cresta {P_pico / B_pico:.0f} FLOP/byte")

def clasificar(nombre, stmt, flops, bytes_, **variables):
    t = medir_us(stmt, **variables) * 1e-6
    f_bw, f_comp = bytes_ / t / B_pico, flops / t / P_pico
    regimen = ("sobrecarga" if t * 1e6 < 3 * sobrecarga and max(f_bw, f_comp) < 0.3 else
               "memoria" if f_bw >= f_comp else "cómputo")
    print(f"{nombre:26s} {t * 1e6:9.1f} µs  intensidad {flops / bytes_:6.1f} FLOP/B  "
          f"{f_bw:5.0%} del ancho de banda  {f_comp:5.0%} del cómputo  -> {regimen}")

h = torch.randn(64, 512, device=dev); W = torch.randn(512, 512, device=dev)
clasificar("matmul del caso, lote 64", "h @ W", 2 * 64 * 512 * 512, 4 * (64 * 512 * 2 + 512 * 512), h=h, W=W)
h2 = torch.randn(8192, 512, device=dev)
clasificar("la misma, lote 8192", "h2 @ W", 2 * 8192 * 512 * 512, 4 * (8192 * 512 * 2 + 512 * 512), h2=h2, W=W)
clasificar("GELU de 64 M elementos", "torch.nn.functional.gelu(x)", 8 * x.numel(), 8 * x.numel(), x=x)
clasificar("matmul 4096", "M @ M", 2 * 4096**3, 3 * 4 * 4096**2, M=M)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the lab RTX 4060 we get 170 to 200 GB/s, about 6 TFLOP/s in FP32 and a ridge point of about 30 operations per byte. The tiny operation costs 20 to 30 µs: this is the floor for any PyTorch operation on this machine, the cost of Python, the dispatcher and launch. The case’s matmul, with batch 64, takes little more than that floor and uses a small fraction of either ceiling: it is overhead-bound. The same matmul with batch 8192 approaches the compute ceiling, GELU approaches the bandwidth ceiling (it does few operations per byte; 8 FLOPs per element is indicative), and the 4096 matmul is at the compute ceiling by definition, because we used it to measure PP.

The following interactive puts all the pieces together in a simulated trace, like Perfetto’s, with the theorem’s overlap model.

InteractiveReading a training trace
02 ms4 ms6 ms8 ms10 ms12 ms14 ms16 ms18 ms20 ms22 msstep 1step 2step 3step 4step 5step 6step 7step 8CPU (Python)GPU (stream 7).item(): cudaStreamSynchronize: 10.0 µsload batch 24 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 24): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 25 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 25): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 26 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 26): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 27 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 27): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 28 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 28): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 29 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 29): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 30 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 30): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µsload batch 31 on main thread: 1.44 msbatch H2D copy: 5.8 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsmatmul (GEMM): 23.2 µsmatmul (GEMM): 23.2 µselementwise: 9.4 µselementwise: 9.4 µselementwise: 9.4 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsoptimizer (foreach): 6.0 µsPython and 52 launches (step 31): 1.38 ms.item(): cudaStreamSynchronize: 16.0 µs
  • batch loading
  • batch wait
  • Python and launches
  • .item() (synchronizes)
  • GPU gap
  • H2D copy
  • matmul
  • elementwise
  • optimizer

Model: each worker takes 45 µs per example; each kernel costs the CPU 25 µs to dispatch and launch; the GPU executes the queue in order. Eight steady-state steps are shown.

DataLoader workers
Batch size
Time per step2.84 ms
Examples per second11.3 thousand
Speedup over starting point×1.00
GPU busy22 %
CPU: Python and launches per step1.38 ms
GPU: total kernel time per step610 µs
One batch every1.44 ms (on main thread)
.item() wait per step16.0 µs
Kernels per step (median)52 (9.4 µs)
Data-bound. The main thread loads each batch (1.44 ms) before launching the step (2.84 ms), leaving the GPU idle. Use parallel DataLoader workers or cheaper loading.
Eight training steps at steady state: above, DataLoader workers (if any); in the middle, the main Python thread, which loads batches if there are no workers, executes the loop and launches kernels; below, the GPU queue with kernels colored by type. Red bands are GPU gaps and dashed lines are .item() synchronizations. You start with the naive loop: data-bound. Apply one remedy at a time and follow the diagnosis: four workers (what dominates next?), remove .item() (how much do you gain, and why so little?), compile, and finally raise batch to 512. Click a block to see its duration.

The path proposed by the figure teaches this section’s most important rule: removing one bottleneck reveals the next, and one remedy does not work for another.

  • Baseline, data-bound, narrowly. The main thread loads each batch (1.44 ms) before launching the step (1.38 ms of Python and launches). The two stages run in series and loading is largest, although barely; the GPU spends more than three quarters of the time idle.
  • With four workers, overhead-bound. Batches arrive before needed, the step halves and the CPU row is full of launches: 52 kernels at 25 µs each are 1.3 ms, more than twice the 0.6 ms the GPU needs to execute them.
  • Without .item(), almost nothing. With the GPU idle most of the step, when the CPU reaches synchronization the queue is nearly empty: waiting costs nothing. The remedy is generally correct but here does not matter, exactly what measurement must tell you before celebrating it.
  • Compiling makes the GPU the bottleneck. Fewer kernels, larger and cheaper to launch: the CPU stops being the limit and the GPU fills up. Now restoring .item() costs 25%, because it serializes a CPU and GPU that were already balanced.
  • With batch 512, data again. Each step needs sixteen times more examples, and four workers cannot keep up. Throughput in examples per second is eight times the original, and the next remedy is once again in loading.

For the data regime there is a test needing no trace: iterate the DataLoader alone, without a model, and compare its rate to training. If they coincide, loading sets the pace; this is the input bottleneck measurement seen with the input pipeline.

QuizThe GPU at 35%
In a training trace, the GPU is busy 35% of the time and its gaps coincide with the interval when the loop waits for the next batch (next(iter(loader))). What remedy do you apply and what measurement would confirm it?

Complete case: profile the loop and gain a measurable factor

Return to the loop profiled with torch.profiler. The trace said: GPU busy less than 5% of the step, about 40 kernels of a few microseconds per step, data loading in a fraction of the step and three synchronizations. The diagnosis is overhead, with a smaller contribution from data. Apply remedies one by one and measure each version with torch.utils.benchmark, in examples per second, with median and IQR of steps.

There are three remedies, in the order the trace suggests. For data, since the entire dataset fits on the GPU, move it there once and perform “augmentation” in batches on the GPU itself (if it did not fit, more workers and pin_memory would be the remedy). Then remove .item() from each step, accumulating loss on the GPU. And for overhead, the most direct tool: record the entire step (forward, backward and optimizer) as a CUDA graph, so each step is a single call launching all its kernels at once, without going through Python or the dispatcher. CUDA graphs require fixed shapes and memory addresses and no synchronizations inside, so inputs are copied to static tensors and the optimizer is created with capturable=True; you will see them in depth with compilation modes and CUDA graphs, because this is what torch.compile(mode="reduce-overhead") does for you.

[ ]Three remedies, each measuredLocal GPU
from torch.utils import benchmark

class LotesEnGPU:
    """Remedio para los datos: el dataset entero vive en la GPU y el «aumento» se hace allí, por lotes."""
    def __init__(self, ds):
        self.X = torch.from_numpy(ds.X).to(dev)
        self.y = torch.from_numpy(ds.y).to(dev)
    def __call__(self, lote):
        while True:
            orden = torch.randperm(len(self.X), device=dev)
            for i in range(0, len(orden) - lote + 1, lote):
                idx = orden[i:i + lote]
                yield self.X[idx] + 0.01 * torch.randn(lote, D, device=dev), self.y[idx]
lotes_gpu = LotesEnGPU(datos)

def bucle_mejorado(modelo, opt, pasos, lote=64, item=True):
    acumulada, registro = torch.zeros((), device=dev), []
    lotes = lotes_gpu(lote)
    for _ in range(pasos):
        x, y = next(lotes)
        perdida = perdida_fn(modelo(x), y)
        opt.zero_grad(set_to_none=True)
        perdida.backward()
        opt.step()
        if item:
            registro.append(perdida.item())
        else:
            acumulada += perdida.detach()            # se queda en la GPU; se lee una vez al final
    return registro if item else [acumulada.item() / pasos]

class PasoGrafo:
    """Remedio para la sobrecarga: el paso entero (forward, backward y optimizador) grabado como un CUDA graph."""
    def __init__(self, modelo, opt, lote):
        self.x = torch.zeros(lote, D, device=dev)             # entradas estáticas: el grafo lee siempre de aquí
        self.y = torch.zeros(lote, dtype=torch.long, device=dev)
        lateral = torch.cuda.Stream()
        lateral.wait_stream(torch.cuda.current_stream())
        with torch.cuda.stream(lateral):                      # calentamiento fuera del grafo, como pide la documentación
            for _ in range(3):
                opt.zero_grad(set_to_none=True)
                perdida_fn(modelo(self.x), self.y).backward()
                opt.step()
        torch.cuda.current_stream().wait_stream(lateral)
        opt.zero_grad(set_to_none=True)
        self.grafo = torch.cuda.CUDAGraph()
        with torch.cuda.graph(self.grafo):
            self.perdida = perdida_fn(modelo(self.x), self.y)
            self.perdida.backward()
            opt.step()
    def __call__(self, x, y):
        self.x.copy_(x)
        self.y.copy_(y)
        self.grafo.replay()                                   # una llamada lanza todos los kernels del paso
        return self.perdida

grafos = {}
def bucle_grafo(modelo, opt, pasos, lote=64):
    if id(opt) not in grafos:
        grafos[id(opt)] = PasoGrafo(modelo, opt, lote)
    paso, acumulada, lotes = grafos[id(opt)], torch.zeros((), device=dev), lotes_gpu(lote)
    for _ in range(pasos):
        acumulada += paso(*next(lotes)).detach()
    return [acumulada.item() / pasos]

def modelo_capturable():
    m, _ = nuevo_modelo()
    return m, torch.optim.AdamW(m.parameters(), lr=1e-3, capturable=True)

def rendimiento(nombre, bucle, lote=64, crear=nuevo_modelo, pasos=20, **kw):
    modelo, opt = crear()
    bucle(modelo, opt, 3, lote=lote, **kw)              # calentamiento (y captura del grafo)
    m = benchmark.Timer(stmt="bucle(modelo, opt, pasos, lote=lote, **kw)",
                        globals=dict(bucle=bucle, modelo=modelo, opt=opt, pasos=pasos, lote=lote, kw=kw)).blocked_autorange(min_run_time=1.0)
    q1, q3 = np.quantile(m.times, [0.25, 0.75])
    print(f"{nombre:28s} paso {m.median / pasos * 1e3:6.2f} ms (IQR {(q3 - q1) / pasos * 1e3:4.2f})  "
          f"{lote * pasos / m.median:9.0f} ejemplos/s")
    return lote * pasos / m.median

base = rendimiento("0. base", bucle_base)
r1 = rendimiento("1. datos en la GPU", bucle_mejorado)
r2 = rendimiento("2. + sin .item() por paso", bucle_mejorado, item=False)
r3 = rendimiento("3. + CUDA graph del paso", bucle_grafo, crear=modelo_capturable)
r4 = rendimiento("4. + lote 512", bucle_grafo, lote=512, crear=modelo_capturable)
print("aceleración en ejemplos/s: " + "  ".join(f"{r / base:.1f}x" for r in (r1, r2, r3, r4)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exact figures vary between runs (note the IQR, and that this laptop is not a benchmark machine), but the pattern is stable and was predicted by the diagnosis:

  1. Data on GPU gains around 20 to 70%: what serial loading cost, which was a fraction of the step.
  2. Removing .item() gains little or nothing, within noise, for the same reason as in the interactive: with the GPU idle, synchronization costs nothing.
  3. The CUDA graph divides time per step by a factor of seven to ten: it eliminates almost all Python and launch overhead, which made up most of the step.
  4. With the graph, a batch eight times larger costs less than twice as much per step, because the GPU still had room: in examples per second, several dozen times the baseline.

Each improvement is justified with before-and-after measurements, and an honest speedup report includes variability: “from about 13 000 to about 700 000 examples per second, median of blocks of 20 steps measured for 1 s per version, IQR between 5 and 20% of the median” can be reproduced and discussed; “50 times faster” cannot.

Common mistakes

Exercises

NumericSpeeding up 70%
A program spends 70% of its time in one function, and you speed it up 10 times without touching the rest. What is the overall program speedup?
NumericHow many repetitions?
Measurements of two versions have Gaussian noise with coefficient of variation 3%. You compare their medians and want the error in estimated improvement to be less than 2 percentage points with probability 0.95. Using the lesson's approximation, what is the smallest number of repetitions per version?
NumericHow long should you sample?
You profile at 100 samples per second with py-spy a function that occupies about 20% of the time. How many seconds of program should you sample for the typical error of its estimated fraction to be 1 percentage point?
NumericCounting temporaries
With x an array of nn float64 elements and no temporary reuse, how many arrays of nn float64 elements are alive at once at most (excluding x) when evaluating np.exp(-x**2) * np.sin(3 * x) + x?
QuizDoubling the batch
In GPU training, changing the batch from 64 to 128 changes time per step from 4.0 ms to 4.1 ms, and the profiler reports GPU occupancy of 8%. What regime is the step in?
CodeA benchmark decorator
Implement benchmark(calentamiento, tiempo_min, reps_min, reps_max, reloj), a decorator factory. When called with arguments, the decorated function runs the original calentamiento times without measuring and then measures it call by call with reloj (default time.perf_counter), repeating until both at least `reps_min` repetitions and at least `tiempo_min` total measured seconds are reached, never exceeding reps_max. Return a dictionary with mediana, iqr (0.75 quantile minus 0.25 quantile, with np.quantile linear interpolation), n and tiempos (the list of measured times). Use functools.wraps. Tests use a fake clock so they do not depend on the machine.
import functools, time
import numpy as np

def benchmark(calentamiento=2, tiempo_min=0.05, reps_min=5, reps_max=10_000, reloj=time.perf_counter):
  def decorador(f):
      def medir(*args, **kwargs):
          # tu código: calentamiento sin medir, repeticiones adaptativas, mediana e IQR
          t0 = reloj()
          f(*args, **kwargs)
          dt = reloj() - t0
          return {"mediana": dt, "iqr": 0.0, "n": 1, "tiempos": [dt]}
      return medir
  return decorador
Shift+Enter to run
CodeThree planted inefficiencies
confianza_media(X, W, b) computes, for each row of X (on the GPU), the maximum probability of softmax(X @ W + b) and returns their mean as a scalar tensor on X's device. The starter code is correct but has three typical inefficiencies: a Python loop over rows, a round-trip copy to CPU on each iteration, and a synchronization (.item()) on each iteration. Find them (you may profile it with torch.profiler or torch.cuda.set_sync_debug_mode('warn')) and eliminate them. Tests check the result, that the function never synchronizes with CPU, and that it is at least 20 times faster than the original.
import torch

def confianza_media(X, W, b):
  """Media sobre las filas de X de la probabilidad máxima de softmax(X W + b), como tensor escalar en X.device."""
  probs = []
  for i in range(X.shape[0]):
      x = torch.tensor(X[i].cpu().numpy())
      z = x.to(X.device) @ W + b
      probs.append(torch.softmax(z, dim=0).max().item())
  return torch.tensor(sum(probs) / len(probs), device=X.device)
Shift+Enter to run

Summary

Key idea
Measure before optimizing: possible gain is determined by the fraction of time targeted (Amdahl), that fraction is known only with a reliable profile, and the correct remedy depends on which resource runs out first (overhead, bandwidth, compute or data), confirmed by changing one variable and measuring again.
  • A reliable benchmark warms up and discards, measures in blocks if the clock is coarse, repeats as often as precision requires (n∝c2/ϵ2n \propto c^2/\epsilon^2), interleaves versions so drift does not become bias and summarizes with median and IQR. The minimum is a good estimator only for purely additive noise.
  • On GPU, an unsynchronized clock measures enqueueing. torch.utils.benchmark warms up, synchronizes and fixes threads (one by default on CPU).
  • Deterministic profilers (cProfile, line_profiler) see everything but add a per-call cost inflating small, frequently called functions; sampling profilers (py-spy) barely perturb and their error is binomial, p(1−p)/N\sqrt{p(1 - p)/N}, but require long runs. Self time identifies the expensive function; cumulative time the expensive subsystem.
  • Peak memory of a NumPy expression is determined by the number of simultaneously live temporaries, calculated with a recurrence on the expression tree; in-place operations, out= and chunking reduce it, and on a real operating system also reduce time. On GPU, max_memory_allocated measures the peak, and in training saved activations for backward dominate it.
  • torch.profiler with schedule and record_function produces a CPU and GPU trace opened in Perfetto. Look for GPU gaps, tiny kernels, synchronizations and data waiting.
  • With everything overlapped, a step takes max⁡(Tdatos,TCPU,TGPU)\max(T_{\text{datos}}, T_{\text{CPU}}, T_{\text{GPU}}); each synchronization turns the maximum into a sum. Removing one bottleneck exposes the next.