Module contents
Lesson 16 of 24Core 90 min

The local GPU: asynchronous execution, memory and mixed precision on 8 GB

Get the most from an 8 GB RTX 4060: CUDA asynchronous execution and accurate timing, the memory budget of training (weights, gradients, optimizer state and activations), PyTorch’s caching allocator and memory-error diagnosis, and practical mixed precision using autocast, GradScaler, bfloat16 and TF32. Numerical format theory is in m09 and multi-GPU scaling in m21.

After this lesson you can

  • Explain asynchronous execution (kernel queues, streams and synchronization points) and measure time with CUDA events.
  • Estimate model training memory before running and compare it with torch.cuda.max_memory_allocated.
  • Interpret memory_allocated versus memory_reserved and diagnose memory errors using memory_summary and memory snapshots.
  • Train with float16 autocast and GradScaler or bfloat16, and enable TF32 for float32 matrix multiplication.
  • Choose batch size and precision to maximize performance within 8 GB.

Before you start

Motivation: two numbers that do not add up

This course’s lab is a laptop with an 8 GiB RTX 4060. Two five-minute experiments show that intuition carried over from CPUs does not work here.

The first is a benchmark. Multiply two 4096×40964096 \times 4096 matrices in float32 and time them with time.perf_counter() before and after. You get 0.07 ms. The product costs 2⋅40963≈1.4⋅10112 \cdot 4096^3 \approx 1.4 \cdot 10^{11} operations, so the card would have reached about 2000 TFLOP/s, an order of magnitude more than the most expensive GPU on the market. The number is false: the call did not wait for the GPU to do anything. Correct measurement gives around 22 ms, about 300 times more.

The second is an estimate. GPT-2 small has 124 million parameters, occupying half a GiB in float32. It should fit easily. Start training with context 1024 and batch size 8, and the process requests over 15 GiB. On Linux you would see OutOfMemoryError. On Windows, with default driver settings, not even that: training starts and runs inexplicably slowly because what does not fit spills into RAM over the PCIe bus.

Three mechanisms explain both, and this lesson takes them apart: CUDA’s asynchronous execution model (the CPU queues work and the GPU executes it later), memory accounting for a training step, and PyTorch’s caching allocator, which determines what nvidia-smi sees. These explain the most effective tool on a consumer GPU: mixed precision, which doubles the speed of a small transformer on this laptop. We build on device placement and the training loop. Floating-point format theory is in IEEE 754 formats; here we use them as engineers. Scaling to multiple GPUs is covered in m21.

The GPU as a work queue

When Python runs y = a @ b on GPU tensors, PyTorch checks shapes and dtypes, chooses a cuBLAS kernel and asks the driver to launch it. Launching means writing a command to a queue. The function returns once the command is written, long before the GPU starts multiplying. y is a perfectly valid tensor whose contents do not yet exist.

By default PyTorch uses one stream per device, so unless you create streams yourself, your whole program is one queue: GPU execution order follows your code, and synchronization is never needed for correctness. Asynchrony only changes when things happen, and therefore what a timer measures and where time is lost.

Launching a kernel is not free. On this Windows laptop it costs 10–40 µs of CPU time depending on power state, measured in the cell below. A GPU kernel on a small tensor takes much less, so the CPU cannot keep up. Common synchronization points include:

  • Reading a value: t.item(), t.tolist(), t.cpu(), t.numpy() on a GPU tensor, print(t) and f"{t:.3f}", float(t), if t > 0: (which calls bool).
  • Data-dependent output sizes: torch.nonzero(m), x[mascara] with a Boolean mask, torch.unique. The CPU must know the size to allocate the output.
  • Explicit: torch.cuda.synchronize() (waits for the entire device), evento.synchronize() (waits for an event), stream.synchronize().
  • Hidden: GPU-to-pageable-CPU-memory copies, torch.cuda.empty_cache() (calls cudaFree, which synchronizes), and in practice new allocations the allocator must request from the driver, which can block the CPU.

One consequence is worth remembering now: errors are asynchronous too. An out-of-range index inside a kernel (device-side assert triggered) is detected when the GPU executes it and reported at the next synchronizing call, potentially many lines later. For debugging, setting CUDA_LAUNCH_BLOCKING=1 in the environment makes every launch wait for its kernel so the error appears on the offending line. It is extremely slow: never leave it enabled.

A timeline

Model a loop of nn identical kernels. Each launch costs ℓ\ell of CPU time, execution costs gg of GPU time, and between launches the CPU does cc of its own work (data preparation, Python logic). Call rir_i the time kernel ii reaches the queue and eie_i the time it finishes on the GPU.

Proof

By induction on nn. For n=1n = 1, e1=r1+ge_1 = r_1 + g. If the formula holds for n−1n - 1, then en=max⁡(rn,en−1)+g=max⁡(rn+g, max⁡k≤n−1(rk+(n−k)g)+g)e_n = \max(r_n, e_{n-1}) + g = \max\big(r_n + g,\ \max_{k \le n-1}(r_k + (n - k)g) + g\big), the maximum over k≤nk \le n of rk+(n−k+1)gr_k + (n - k + 1)g. The expression is affine in kk with slope (ℓ+c)−g(\ell + c) - g, so the maximum is at an endpoint: k=1k = 1 (GPU bottleneck, busy continuously from the first kernel) or k=nk = n (CPU bottleneck, GPU finishing gg after the last launch). With .item(), the queue is empty when the CPU launches each kernel because the previous iteration waited for its own. The CPU launches (time ℓ\ell), waits for GPU execution (gg), pays σ\sigma and only then does its own work (cc), while the GPU has an empty queue. The GPU works gg of each ℓ+g+σ+c\ell + g + \sigma + c interval.

∎

The proposition says three things you will see in the figure. If g>ℓ+cg > \ell + c, the queue fills and total time is ≈ng\approx ng: the GPU runs at 100%. If g<ℓ+cg \lt \ell + c, the GPU waits for the CPU and is idle for fraction 1−g/(ℓ+c)1 - g/(\ell + c) of the time: this is the small-model regime, where the solution is to launch fewer kernels (fuse them with torch.compile and CUDA Graphs) rather than buy a larger GPU. And one .item() per step turns max⁡(ℓ+c,g)\max(\ell + c, g) in each iteration into the sum ℓ+g+σ+c\ell + g + \sigma + c: CPU and GPU time no longer overlap.

InteractiveThe misleading timer
CPUGPU0500 µs1.00 ms1.50 msk1k2k3k4k5k6k7k8k9k10measured: 102 µsqueue 0
t0 = time.perf_counter()
for _ in range(n):
    y = f(y)
t = time.perf_counter() - t0
  • launch a kernel (10 µs)
  • GPU kernel
  • CPU work
  • CPU waiting (synchronizing)
  • first call (initialization)
  • CUDA event
  • measured interval
Timer
t = 1.54 ms
10
150 µs
0 µs
Timer reading102 µs
Time until the GPU finishes1.51 ms
GPU busy time1.50 ms
GPU utilization99 %
Kernels queued at t0
Maximum queue length9
The timer measured queue submission: 102 µs. The GPU continues working until 1.51 ms, so the actual time is 15 times the reading.
Two timelines: the CPU launches kernels (thin blue bars) and the GPU executes them in order (orange); faint lines connect each launch to its kernel start and the row of boxes is the stream queue. The green bar above is the interval measured by the chosen timer and the dashed line is when the GPU actually finishes. Play the animation with unsynchronized perf_counter: what fraction of work did it measure? Switch to synchronize and events. Then enable .item() and watch GPU bubbles appear, increase CPU work until it exceeds kernel duration, and remove warmup (the first real call takes tens of milliseconds; here it is compressed).

Measuring GPU time

The timeline yields the rules for an honest GPU benchmark.

  1. Synchronize before reading the clock. torch.cuda.synchronize() before starting (to exclude previously queued work) and after finishing (to wait for yours). Better still, use events.
  2. Use CUDA events. torch.cuda.Event(enable_timing=True) creates an event; evento.record() queues it in the stream like another operation, and the GPU records the time when it reaches it. ini.elapsed_time(fin) returns GPU milliseconds between two timestamps, with approximately half-microsecond resolution according to CUDA documentation. Since the GPU records timestamps itself, they exclude synchronization overhead and CPU scheduler interruptions. Before reading elapsed_time, wait for fin with fin.synchronize().
  3. Warm up. Each operation’s first call pays lazy initialization costs: creating the cuBLAS handle, loading the kernel module (CUDA loads kernels on demand), choosing an algorithm. With torch.backends.cudnn.benchmark = True, the first convolutions of each shape additionally try several algorithms. Discard a few iterations.
  4. Repeat and summarize with the median. Laptop GPU frequency rises and falls with temperature and power limit. Measure many iterations within one event pair and repeat the experiment.

The library version is torch.utils.benchmark.Timer, which synchronizes, warms up and chooses the repetition count for you; systematic measurement is covered in benchmarking methodology. Here we do it manually to see each piece.

[ ]Three timers for the same multiplicationLocal GPU
import time
import torch

assert torch.cuda.is_available(), "esta lección necesita una GPU NVIDIA"
dev = torch.device("cuda")
print(torch.cuda.get_device_name(), "| PyTorch", torch.__version__, "| CUDA", torch.version.cuda)

a = torch.randn(4096, 4096, device=dev)
b = torch.randn(4096, 4096, device=dev)

def ingenuo(f):
    t0 = time.perf_counter(); f(); return (time.perf_counter() - t0) * 1e3

def sincronizado(f):
    torch.cuda.synchronize()                      # que no quede trabajo previo en la cola
    t0 = time.perf_counter(); f(); torch.cuda.synchronize()
    return (time.perf_counter() - t0) * 1e3

def eventos(f, rep=10):
    ini, fin = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    ini.record()                                  # se encola en el stream, como un kernel más
    for _ in range(rep):
        f()
    fin.record()
    fin.synchronize()                             # espera solo a ese evento
    return ini.elapsed_time(fin) / rep            # milisegundos de GPU entre los dos sellos

mm = lambda: a @ b
print(f"\nprimera llamada, sincronizada:  {sincronizado(mm):8.3f} ms   (incluye inicializar cuBLAS)")
for _ in range(3):
    mm()                                          # calentamiento
print(f"perf_counter sin sincronizar:    {ingenuo(mm):8.3f} ms   <- solo el encolado")
torch.cuda.synchronize()
print(f"perf_counter con synchronize:    {sincronizado(mm):8.3f} ms")
print(f"eventos CUDA (media de 10):      {eventos(mm):8.3f} ms")

# lanzar kernels diminutos: el coste lo pone la CPU
z = torch.zeros(1, device=dev)
for _ in range(100):
    z.add_(1)
torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(5000):
    z.add_(1)
t_encolar = time.perf_counter() - t0
torch.cuda.synchronize()
t_total = time.perf_counter() - t0
print(f"\n5000 sumas de un elemento: {t_encolar / 5000 * 1e6:.1f} µs por lanzamiento (encolar), "
      f"{t_total / 5000 * 1e6:.1f} µs por suma en total")

# un .item() por paso: burbujas en la GPU
def bucle(leer, pasos=200):
    torch.cuda.synchronize(); t0 = time.perf_counter()
    acum = torch.zeros((), device=dev)
    for _ in range(pasos):
        y = torch.tanh(a[:1024] @ b)              # unos 6 ms de GPU
        p = y.mean()
        if leer:
            acum += p.item()                      # la CPU espera a la GPU en cada paso
        else:
            acum += p                             # se queda en la GPU, sin esperar
        _ = sum(i * i for i in range(20_000))     # trabajo de CPU entre pasos, ~1-2 ms
    float(acum)                                   # una sola sincronización al final
    return (time.perf_counter() - t0) / pasos * 1e3
bucle(False, 5)
print(f"\ncon .item() en cada paso: {bucle(True):.2f} ms/paso;  acumulando en la GPU: {bucle(False):.2f} ms/paso")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the lab laptop the first call takes 100–300 ms, the naive timer reports 0.07 ms and the other two agree at about 22 ms. For tiny additions, enqueueing and completion cost the same: each kernel takes less than its launch, the queue never fills and per-operation cost is CPU cost. In the final experiment, .item() per step increases time from about 6.2 ms to 7.5–9.5 ms depending on machine load: the proposition’s sum versus maximum (about 6 ms GPU plus 1 or 2 ms CPU that no longer overlap).

To find hidden synchronizations in a real loop, torch.cuda.set_sync_debug_mode("warn") emits a warning whenever an operation synchronizes (and "error" raises an exception). The torch.profiler traces lesson will show them on a real timeline like the figure.

The memory budget of a training step

Move from time to space. Five kinds of object coexist on the GPU during a training step, and almost all out-of-memory errors arise from forgetting one.

State: bytes per parameter

With parameters in float32, each contributes 4 bytes for weight and 4 for gradient. Optimizer state depends on the optimizer (as seen in the optimizer API): SGD stores nothing, SGD with momentum stores a velocity buffer, and Adam stores two moments, mm and vv, each parameter-sized.

OptimizerWeightsGradientsStateTotal per parameter
SGD4408 bytes
SGD with momentum44412 bytes
Adam, AdamW44816 bytes

Adam’s 16 bytes per parameter is the number to remember: the ZeRO paper (Rajbhandari et al., 2020) starts with the same accounting. A 124-million-parameter model needs 1.99 GB of state alone before seeing one example, and a 1 300-million-parameter model cannot fit in 8 GiB even with batch size zero.

The table hides two subtleties. First, opt.step() also needs transient memory: Adam’s default CUDA implementation (foreach=True) processes all parameters at once and creates temporaries the size of a parameter copy, 4 extra bytes per parameter during the step; with fused=True calculations run inside one kernel without temporaries. Second, as the mixed-precision section explains, autocast does not change this table: parameters stay in float32.

Activations: what autograd saves

Each operation’s backward pass needs some forward tensors: a linear layer y=Wx\vb{y} = \mat{W}\vb{x} needs x\vb{x} to compute ∂L/∂W\partial \Loss / \partial \mat{W}; ReLU needs to know which inputs were positive (it saves its output); softmax saves its output. These tensors live from forward until backward reaches their operation, and dominate by far as batch size or context grows.

For a pre-LN transformer block with batch bb, context ss, dimension hh and aa heads, counting what each operation saves gives, in float32 with hand-written attention:

  • the input of each layer_norm and each linear layer of dimension hh: five tensors of bshbsh elements (the two normalizations and inputs to the QKVQKV projections, output projection, and first MLP layer; the second MLP layer’s input is the GELU output, counted below);
  • Q\mat{Q}, K\mat{K} and V\mat{V}, three bshbsh tensors saved as contiguous copies by the batched product;
  • the MLP GELU input and output, two 4bsh4bsh tensors;
  • attention softmax output, a⋅b⋅s2a \cdot b \cdot s^2 elements.

In total, (5+3+8) bsh+abs2=16 bsh+abs2(5 + 3 + 8)\,bsh + a b s^2 = 16\,bsh + a b s^2 elements per layer, or 64 bsh+4 abs264\,bsh + 4\,a b s^2 bytes. The language head with vocabulary VV saves log-softmax output, 4 bsV4\,bsV bytes, and during backward the logits gradient occupies about 8 bsV8\,bsV more workspace. These coefficients do not come from a book: the cell below measures them with torch.autograd.graph.saved_tensors_hooks, intercepting every tensor autograd decides to save.

InteractiveDoes it fit in 8 GB?
Memoria de un paso: 15.46 GiB + 1.0 GiB ocupados10.5 GiB3.1 GiB8 GiB246
  • other processes and context
  • weights (475 MiB)
  • gradients (475 MiB)
  • optimizer state (949 MiB)
  • saved activations (10.53 GiB)
  • backward workspace (logits) (3.07 GiB)
Exceeds the budget by 8.46 GiB. On Linux this can raise an OutOfMemoryError. On Windows, the default driver policy can spill into system RAM over PCIe, allowing training to continue with accesses to that memory around 20 times slower.
Options ranked by memory saved
Activation checkpointing (m21)
−7.97 GiB
Halve the context length
−7.93 GiB
Halve the batch and use gradient accumulation to keep the effective batch size
−6.80 GiB
Memory-efficient attention (SDPA)
−4.50 GiB
Momentum SGD instead of Adam
−475 MiB
Mixed precision with bf16 autocast
−262 MiB
Model
Transformer (tied weights)
12
768 (12 heads)
1024
8
Precision
Optimizer
1.0 GiB
Parameters PP124 M
State per parameter16 bytes
Activations and workspace13.60 GiB
Step total15.46 GiB
Available7.00 GiB
Largest batch that fits3
Training-step memory against the RTX 4060's 8 GiB, using coefficients measured in this lesson's lab. Start with GPT-2 small in float32, context 1024 and batch size 8: over 15 GiB. Switch to autocast bf16 and see which bars move and which do not: does the total fall? Enable efficient attention and repeat. Then use the lever list, reordered for each state: which frees the most in each case? Also try ‘Parameters only’ mode with Adam and 1.3 billion parameters.

The figure’s initial state is the second number from the motivation: 15.5 GiB, comprising 1.85 state, 10.5 saved activations and 3.1 workspace. The language head alone takes 4.6 (1.5 saved log-softmax and 3.1 logits gradient, over 50,257 tokens). Autocast alone barely changes it (15.2 GiB): the attention matrix grows and the rest shrinks. Autocast with efficient attention falls to 8.45 GiB, and batch size 4 fits comfortably. Note that none of those levers changes the 1.99 GB of state.

Prediction versus measurement

The cell writes the estimator from scratch, counts activations with a hook, and compares predicted peak against torch.cuda.max_memory_allocated() on a small GPT (6 layers, h=384h = 384, context 256, vocabulary 8192). The model ties embedding and head weights like GPT-2 and uses fused=True in Adam to exclude optimizer temporaries.

[ ]Memory budget: prediction versus measurementLocal GPU
import math
import torch.nn as nn
import torch.nn.functional as F

MiB = 2**20

# ---- 1. el estimador, desde cero --------------------------------------------------------
BYTES_ESTADO = {"sgd": 0, "momentum": 1, "adam": 2}          # copias del tamaño de los parámetros

def memoria_estado(P, opt="adam", pesos_bytes=4):
    """Pesos, gradientes y estado del optimizador (bytes). Con autocast los pesos siguen en fp32."""
    return {"pesos": pesos_bytes * P, "gradientes": pesos_bytes * P,
            "optimizador": BYTES_ESTADO[opt] * pesos_bytes * P}

# bytes guardados por capa: (coef. de b·s·h, coef. de a·b·s², coef. de b·s·V en la cabeza)
COEF = {"fp32": (64, 4, 4), "amp": (36, 6, 6)}

def activaciones_gpt(b, s, h, L, a, V, modo="fp32", sdpa=False):
    c_h, c_att, c_v = COEF[modo]
    por_capa = c_h * b * s * h + (0 if sdpa else c_att * a * b * s * s)
    return L * por_capa + c_v * b * s * V

def pico_gpt(P, P_mat, b, s, h, L, a, V, modo="fp32", sdpa=False, opt="adam"):
    """Pico de un paso: estado + activaciones + copias de 16 bits + gradiente de los logits en el backward."""
    copias = 2 * P_mat if modo == "amp" else 0
    trabajo = (8 if modo == "fp32" else 4) * b * s * V
    return sum(memoria_estado(P, opt).values()) + activaciones_gpt(b, s, h, L, a, V, modo, sdpa) + copias + trabajo

# ---- 2. lo que autograd guarda de verdad, contado con un hook --------------------------
def bytes_guardados(modelo, *entradas, autocast=None):
    """Suma los storages distintos que autograd guardaría para el backward (sin los parámetros).
    El hook retiene los storages (como haría el grafo) y devuelve None: no se podrá hacer backward,
    pero tampoco queda un ciclo de referencias que mantenga vivo el grafo al terminar."""
    params = {p.untyped_storage().data_ptr() for p in modelo.parameters()}
    vistos = {}
    def pack(t):
        st = t.untyped_storage()
        if st.data_ptr() not in params:
            vistos[st.data_ptr()] = st
    with torch.autograd.graph.saved_tensors_hooks(pack, lambda _: None):
        with torch.autocast("cuda", dtype=autocast or torch.float16, enabled=autocast is not None):
            modelo(*entradas)
    return sum(st.nbytes() for st in vistos.values())

# ---- 3. un GPT pequeño (pre-LN, atención explícita o SDPA, cabeza atada) ----------------
class Bloque(nn.Module):
    def __init__(self, h, a, sdpa):
        super().__init__()
        self.a, self.sdpa = a, sdpa
        self.ln1, self.ln2 = nn.LayerNorm(h), nn.LayerNorm(h)
        self.qkv, self.proj = nn.Linear(h, 3 * h), nn.Linear(h, h)
        self.fc, self.fc2 = nn.Linear(h, 4 * h), nn.Linear(4 * h, h)
    def forward(self, x):
        B, T, H = x.shape
        q, k, v = (t.view(B, T, self.a, H // self.a).transpose(1, 2) for t in self.qkv(self.ln1(x)).split(H, 2))
        if self.sdpa:
            y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        else:
            att = (q @ k.transpose(-2, -1)) / math.sqrt(H // self.a)
            att = att.masked_fill(torch.ones(T, T, dtype=torch.bool, device=x.device).triu(1), float("-inf"))
            y = F.softmax(att, dim=-1) @ v
        x = x + self.proj(y.transpose(1, 2).reshape(B, T, H))
        return x + self.fc2(F.gelu(self.fc(self.ln2(x))))

class GPT(nn.Module):
    def __init__(self, V, s, h, L, a, sdpa=False):
        super().__init__()
        self.tok, self.pos = nn.Embedding(V, h), nn.Embedding(s, h)
        self.bloques = nn.ModuleList(Bloque(h, a, sdpa) for _ in range(L))
        self.ln, self.cabeza = nn.LayerNorm(h), nn.Linear(h, V, bias=False)
        self.cabeza.weight = self.tok.weight                   # pesos atados, como en GPT-2
    def forward(self, idx, objetivo):
        x = self.tok(idx) + self.pos(torch.arange(idx.shape[1], device=idx.device))
        for blq in self.bloques:
            x = blq(x)
        return F.cross_entropy(self.cabeza(self.ln(x)).flatten(0, 1), objetivo.flatten())

def pico_de_un_paso(modelo, *entradas, autocast=None, **kw_opt):
    opt = torch.optim.Adam(modelo.parameters(), lr=1e-4, **kw_opt)
    for _ in range(2):                                         # el 2.º paso ya tiene el estado de Adam
        torch.cuda.reset_peak_memory_stats()
        with torch.autocast("cuda", dtype=autocast or torch.float16, enabled=autocast is not None):
            perdida = modelo(*entradas)
        perdida.backward(); opt.step(); opt.zero_grad(set_to_none=True)
    return torch.cuda.max_memory_allocated() - sum(t.nbytes for t in entradas)

V, s, h, L, a, b = 8192, 256, 384, 6, 6, 16
idx = torch.randint(0, V, (b, s), device=dev); obj = torch.randint(0, V, (b, s), device=dev)
print(f"GPT: V={V}, s={s}, h={h}, L={L}, a={a}, lote b={b}")
print(f"{'':14s}{'activaciones: predichas':>25s}{'medidas':>9s}{'pico: predicho':>17s}{'medido':>9s}")
for modo, ac, sdpa in (("fp32", None, False), ("fp32", None, True), ("amp", torch.bfloat16, False), ("amp", torch.bfloat16, True)):
    torch.manual_seed(0)
    gpt = GPT(V, s, h, L, a, sdpa).to(dev)
    P = sum(p.numel() for p in gpt.parameters())
    pred = activaciones_gpt(b, s, h, L, a, V, modo, sdpa)
    medido = bytes_guardados(gpt, idx, obj, autocast=ac)
    P_mat = P - gpt.pos.weight.numel() - sum(p.numel() for n, p in gpt.named_parameters() if "ln" in n)
    if ac is not None:
        medido -= 2 * P_mat                                    # las copias de 16 bits de los pesos, aparte
    pico = pico_de_un_paso(gpt, idx, obj, autocast=ac, fused=True)
    pred_pico = pico_gpt(P, P_mat, b, s, h, L, a, V, modo, sdpa)
    etiqueta = f"{modo}{' + SDPA' if sdpa else ''}"
    print(f"{etiqueta:14s}{pred / MiB:21.0f} MiB{medido / MiB:5.0f} MiB{pred_pico / MiB:13.0f} MiB{pico / MiB:5.0f} MiB")
    del gpt
print(f"P = {P / 1e6:.2f} M parámetros: pesos + gradientes + Adam = 16P = {16 * P / MiB:.1f} MiB")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Predicted and measured activations agree within 2% (848 versus 861 MiB in float32; the difference is small tensors such as layer_norm statistics), and predicted peak is 1–5% above measured depending on the run, the safer direction. Two important readings. First: float32 peak (about 1290 MiB) is six times state (212 MiB); for a small model with long context, state is almost irrelevant. Second: autocast with explicit attention reduces activations only 14%, whereas SDPA reduces them 27%; the reason is the attention term, discussed under mixed precision.

The caching allocator

cudaMalloc and cudaFree are expensive: on this laptop a new allocation costs 0.3 ms (2 MiB) to 2 ms (1 GiB), versus about 20 µs from cache, and cudaFree also synchronizes the entire device. A training step creates and destroys thousands of tensors; requesting each from the driver would turn the loop into a series of waits. PyTorch steps in.

The rules for choosing and splitting blocks, according to allocator documentation and code:

  • Every allocation is rounded to a multiple of 512 bytes.
  • Allocations up to 1 MiB go to a small pool, which requests 2 MiB segments and divides them. Between 1 and 10 MiB it requests 20 MiB segments. Above that, the segment is the request rounded to a multiple of 2 MiB.
  • To serve a request, the smallest sufficient free cached block is chosen (best fit). If there is excess, it is split and the rest stays free. Adjacent free blocks in the same segment merge; blocks from different segments never do.
  • If no suitable block exists, cudaMalloc is called. If cudaMalloc fails, the allocator releases all entirely free segments and retries. If it fails again, it raises torch.cuda.OutOfMemoryError.

nvidia-smi knows nothing about blocks or tensors. It sees memory each process has requested from the driver: allocator reservations plus CUDA context (loaded kernels and driver structures, about 100 MiB on this laptop), plus other processes, including the desktop and browser on a Windows laptop (around 1 GiB here). That is why nvidia-smi always reports more than memory_allocated() and why allocator figures are what matter for debugging. Driver-reported free memory comes from torch.cuda.mem_get_info().

Block splitting has an inconvenient consequence: fragmentation. If a large block is split and only one piece is freed, that gap cannot satisfy a larger allocation, and its segment cannot return to the driver because it contains a live tensor. You can have gigabytes free in total and fail requesting less.

InteractiveThe caching allocator
GPU memory (8 GiB)others6 GiB limit
  • tensor block
  • free in allocator cache
  • segment (one cudaMalloc)
  • CUDA context and other processes
# freshly started process
The cache is empty: memory_allocated() and memory_reserved() are 0. The grey area on the right is occupied by the CUDA context and other processes.
Mode
step 0 of 10
memory_allocated()0.00 GiB
memory_reserved()0.00 GiB
nvidia-smi (this process + others)1.00 GiB
Free in cache0.00 GiB
Largest free cached block0.00 GiB
Free for cudaMalloc6.00 GiB
GPU memory as an 8 GiB strip: each black-bordered rectangle is a segment (one cudaMalloc); inside, colored blocks are live tensors and hatched blocks are free cached blocks. At right, memory used by other processes; the red line is the process limit set with set_per_process_memory_fraction. The guided tour reproduces the next cell's experiment: advance step by step and watch memory_allocated(), memory_reserved() and what nvidia-smi sees diverge, and why the 2 GiB allocation at step 7 fails with 2.5 GiB free. Enable expandable_segments and return to that step. In free mode, allocate and free your own tensors and try to cause another fragmentation OOM. Segment positions in the strip are illustrative: virtual memory prevents driver fragmentation; what matters is fragmentation inside segments.

An OutOfMemoryError message contains the entire diagnosis if you know how to read it: requested amount, driver free memory, memory occupied by tensors (allocated by PyTorch) and reserved but free memory (reserved by PyTorch but unallocated). If the last number is large relative to the request, fragmentation rather than insufficient memory is the problem. On Linux, PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True replaces fixed segments with one growing by mapping physical memory pages so gaps can be returned and reused; on Windows this option is unsupported and PyTorch ignores it with a warning. Another relevant option, max_split_size_mb, prevents splitting blocks above a threshold so large blocks do not fragment.

Three diagnostic tools, from least to most detail:

  1. torch.cuda.memory_summary() prints a table of allocated, reserved and non-releasable memory, current and peak use, and how many times the allocator freed cache and retried (cudaMalloc retries). Many retries mean you are near the limit and performance suffers.
  2. torch.cuda.memory_stats() returns the same counters as a dictionary, useful for logging during training.
  3. Memory snapshots: torch.cuda.memory._record_memory_history() starts recording each allocation and release with the Python trace that caused it, and torch.cuda.memory._dump_snapshot("snap.pickle") dumps the record. Drag the file to pytorch.org/memory_viz to see a memory timeline where each band is a tensor and hovering reveals its creation line. This is the fastest way to find a tensor that should not be there. The Understanding GPU Memory script (Shi and DeVito) walks through a complete case.
[ ]Inside the allocator: rounding, cache, fragmentation and snapshotLocal GPU
import gc, os, tempfile

def estado(txt):
    print(f"{txt:30s} allocated {torch.cuda.memory_allocated() / MiB:7.1f} MiB   reserved {torch.cuda.memory_reserved() / MiB:7.1f} MiB")

def segmento_de(t):
    """Tamaño del segmento (un cudaMalloc) que contiene el tensor t."""
    for sg in torch.cuda.memory._snapshot()["segments"]:
        if sg["address"] <= t.data_ptr() < sg["address"] + sg["total_size"]:
            return sg["total_size"]

gc.collect(); torch.cuda.empty_cache()
estado("al empezar")
for nbytes in (4000, 3 * MiB + 4, 25 * MiB):
    antes = torch.cuda.memory_allocated()
    t = torch.empty(nbytes, dtype=torch.uint8, device=dev)
    print(f"pido {nbytes:>10,d} B -> allocated +{torch.cuda.memory_allocated() - antes:>10,d} B, "
          f"en un segmento de {segmento_de(t) / MiB:4.0f} MiB")
    del t

# empty_cache no libera lo que sigue referenciado
w = torch.empty(512 * MiB // 4, device=dev)
vista = w[:10]                                  # una vista mantiene vivo el storage entero
del w; torch.cuda.empty_cache();                estado("del w, pero queda una vista")
del vista; torch.cuda.empty_cache();            estado("del vista; empty_cache()")

# fragmentación: un OOM con memoria libre de sobra, en total
GiB = 2**30
gc.collect(); torch.cuda.empty_cache()
total = torch.cuda.get_device_properties(0).total_memory
base = torch.cuda.memory_reserved()
torch.cuda.set_per_process_memory_fraction((base + 6 * GiB) / total)   # límite: lo que hay + 6 GiB
print(f"\nlímite del proceso: {(base + 6 * GiB) / GiB:.2f} GiB")
try:
    ty = torch.empty(2 * GiB // 4, device=dev)
    tx = torch.empty(3 * GiB // 4, device=dev); del tx          # su segmento de 3 GiB queda en caché
    ta = torch.empty(3 * GiB // 8, device=dev)                 # 1.5 GiB: parte el bloque de 3 GiB
    tb = torch.empty(3 * GiB // 8, device=dev)                 # otros 1.5 GiB del mismo segmento
    del ta                                                     # hueco de 1.5 GiB delante de tb
    estado("ty (2 GiB) y tb (1.5 GiB) vivos")
    libre = (base + 6 * GiB) - torch.cuda.memory_allocated()
    print(f"libre dentro del límite: {libre / GiB:.2f} GiB; pido 2 GiB...")
    tc = torch.empty(2 * GiB // 4, device=dev)
    print("¡cupo!")
except torch.cuda.OutOfMemoryError as e:
    print("OutOfMemoryError:", str(e).split(". If reserved")[0])
finally:
    ty = tb = tc = None
    gc.collect(); torch.cuda.empty_cache()
    torch.cuda.set_per_process_memory_fraction(1.0)

# una instantánea de memoria de dos pasos de entrenamiento
torch.cuda.memory._record_memory_history(max_entries=100_000)
gpt = GPT(V, s, h, L, a).to(dev)
opt = torch.optim.Adam(gpt.parameters(), fused=True)
for _ in range(2):
    gpt(idx, obj).backward(); opt.step(); opt.zero_grad(set_to_none=True)
ruta = os.path.join(tempfile.gettempdir(), "atlas_snapshot.pickle")
torch.cuda.memory._dump_snapshot(ruta)
torch.cuda.memory._record_memory_history(enabled=None)
print(f"\ninstantánea en {ruta} ({os.path.getsize(ruta) / MiB:.1f} MiB): ábrela en https://pytorch.org/memory_viz")
print(torch.cuda.memory_summary(abbreviated=True).split("\n")[3])
del gpt, opt
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The first three lines confirm the rules: 4000 bytes occupy 4096 in a 2 MiB segment; 3 MiB and 4 bytes occupy 3 145 728+5123\,145\,728 + 512 in a 20 MiB segment; 25 MiB get their own 26 MiB segment, and because the remaining 1 MiB is below the minimum for splitting a large block, the tensor gets the entire block and allocated rises by 26 MiB. The view shows empty_cache() cannot release memory of referenced storage. The fragmentation experiment ends with the same message as the figure: about 2.5 GiB free within the limit (1.5 in cache, as reserved by PyTorch but unallocated) and yet Tried to allocate 2.00 GiB.

Automatic mixed precision

An Ada GPU’s Tensor Cores multiply 16-bit matrices several times faster than the float32 path, and a 16-bit tensor takes half the space and half the read time. But training entirely in 16 bits fails in two ways: range (numbers too small or large for the format) and precision (lost additions). Mixed precision uses 16 bits where safe and 32 where not.

Four formats

Recall from IEEE 754 formats that a normal number is ±1.f×2e\pm 1.f \times 2^{e}: exponent bits determine range and mantissa bits relative precision.

FormatSign, exponent, mantissaLargest finiteSmallest normalSmallest subnormalε\eps (distance from 1 to next)
float321, 8, 233.4⋅10383.4 \cdot 10^{38}2−126≈1.2⋅10−382^{-126} \approx 1.2 \cdot 10^{-38}2−1492^{-149}2−23≈1.2⋅10−72^{-23} \approx 1.2 \cdot 10^{-7}
TF32 (Tensor Cores only)1, 8, 10as float32as float322−10≈9.8⋅10−42^{-10} \approx 9.8 \cdot 10^{-4}
float161, 5, 1065504655042−14≈6.1⋅10−52^{-14} \approx 6.1 \cdot 10^{-5}2−24≈6.0⋅10−82^{-24} \approx 6.0 \cdot 10^{-8}2−10≈9.8⋅10−42^{-10} \approx 9.8 \cdot 10^{-4}
bfloat161, 8, 73.4⋅10383.4 \cdot 10^{38}2−1262^{-126}2−1332^{-133}2−7≈7.8⋅10−32^{-7} \approx 7.8 \cdot 10^{-3}

float16 is more precise than bfloat16 (10 mantissa bits versus 7) but has vastly less range: below 2−142^{-14} it enters subnormals, which lose precision bits, and below 2−252^{-25} it rounds to zero. bfloat16 is literally the upper half of float32: same exponent, truncated mantissa. Its range is that of float32.

The ε\eps column yields the first principle: weights are updated in float32. Adam moves each weight on the order of the learning rate; with small or late-decayed rates, this is 10−410^{-4} times the weight or less. In float16, 1+10−41 + 10^{-4} rounds to 11 because the next representable number after 1 is 9.8⋅10−49.8 \cdot 10^{-4} away; in bfloat16 even 1+10−31 + 10^{-3} is lost. Training with 16-bit weights and small updates stalls silently. That is why Micikevicius et al.’s (2018) recipe keeps a master copy of weights in float32, and PyTorch goes further: model parameters are the master copy and never leave float32.

autocast

Autocast acts only on operations, never existing tensors: it converts neither model nor data. For each operation in the first list it converts inputs to 16 bits, and if an input is a parameter, caches the copy for the duration of the with block, so a layer used repeatedly is converted once. Backward runs outside the block: autograd follows the same operations in the dtypes used during forward. The gradient with respect to a 16-bit tensor is 16-bit; backward through a parameter’s float32-to-16-bit conversion converts back to float32, so W.grad is always float32.

Now redo the memory calculation. Weights, gradients and Adam state: exactly the same as without autocast, 16 bytes per parameter. The 16-bit weight copies: 2 extra bytes per multiplied parameter for the duration of the step. Activations of 16-bit operations: half. But not all are 16-bit. A transformer’s residual stream is float32 (adding an float32 tensor and a 16-bit tensor gives float32), so layer_norm inputs are saved in float32; attention softmax is computed in float32, saves its output in float32, and the next product also saves its 16-bit copy. Measured with the hook: 36 bsh+6 abs236\,bsh + 6\,abs^2 bytes per layer versus 64 bsh+4 abs264\,bsh + 4\,abs^2. Autocast reduces the linear term 44% and increases explicit attention’s term 50%, which is why it delivers full savings only with SDPA.

InteractivePrecision used by each operation under autocast
Forward (inside autocast)
Backward and optimizer step (outside autocast)
The batch arrives in float32. Autocast does not convert tensors on entry: it chooses the dtype for each operation.
Activation gradients in backward: log₂|g|2⁻²⁵: to zero2⁻¹⁴65504subnormals−40−30−20−1001020log₂ of absolute value
  • normal in float16
  • subnormal (loses bits)
  • lost: zero or inf
Precision
operation 1 of 11
16 (S = 65 536)
Current operation outputfloat32
Gradients becoming zero8.9 %
Subnormal gradients70.6 %
Gradients overflowing to inf0.00 %
8.9% of gradients become zero and 70.6% remain subnormal. Enable GradScaler.
A training step of a small block, operation by operation, with each output dtype as returned by PyTorch 2.11 (the cell below asks PyTorch). Explore it in float16 and bfloat16 and notice which operations change color. Below, activation gradient distribution in backward on a log⁡2\log_2 scale (synthetic, the same as the NumPy cell below), against the range of float16. Without GradScaler, what fraction becomes zero? Enable it and find the minimum scale leaving almost everything in the normal range. Raise the scale to 24: what happens? Finally switch to bfloat16.
[ ]Each operation’s dtype under autocast, queried from PyTorchLocal GPU
torch.manual_seed(0)
W1 = torch.randn(64, 32, device=dev, requires_grad=True)
W2 = torch.randn(10, 64, device=dev, requires_grad=True)
xb = torch.randn(8, 32, device=dev)                  # el lote, en float32
yb = torch.randint(0, 10, (8,), device=dev)
nombre = {torch.float32: "float32", torch.float16: "float16", torch.bfloat16: "bfloat16"}
for dt in (torch.float16, torch.bfloat16):
    with torch.autocast("cuda", dtype=dt):
        hb = F.linear(xb, W1); rb = F.relu(hb); nb = F.layer_norm(rb, (64,))
        zb = F.linear(nb, W2); Lb = F.cross_entropy(zb, yb)
    hb.retain_grad()
    Lb.backward()                                    # fuera del bloque autocast
    print(f"autocast {nombre[dt]}")
    for k, v in {"h = linear(x, W1)": hb, "relu(h)": rb, "layer_norm(r)": nb, "z = linear(n, W2)": zb,
                 "cross_entropy(z, y)": Lb, "dL/dh": hb.grad, "W1.grad": W1.grad}.items():
        print(f"   {k:20s} {nombre[v.dtype]}")
    W1.grad = W2.grad = None
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Why float16 needs GradScaler

Most activation gradients in a deep network are small numbers: products of many factors less than one. Micikevicius et al. show activation-gradient histograms of real networks where an appreciable fraction falls below 2−242^{-24}, the smallest float16 subnormal. In float16, values below 2−252^{-25} (half the smallest subnormal) round to zero, and those between 2−252^{-25} and 2−142^{-14} lose bits.

The solution is simple and elegant. Loss L\Loss is a scalar and backward is linear in it: multiplying loss by constant SS multiplies all backward gradients by SS by the chain rule. With S=2kS = 2^{k} multiplication is exact (only the exponent changes) and the whole histogram shifts kk positions right on the log⁡2\log_2 scale, away from underflow. Before the optimizer step divide by SS in float32, where range is not a problem. If SS is too large, larger gradients overflow to inf: the step is discarded and SS reduced.

torch.amp.GradScaler automates all three. scaler.scale(loss) multiplies by SS (initially 2162^{16}). scaler.step(opt) calls unscale_ if you have not (dividing gradients by SS and checking for inf or NaN), and calls opt.step() only if neither is present. scaler.update() multiplies SS by 0.5 on inf and by 2 after 2000 consecutive steps without them. The scale thus oscillates near the largest value that does not overflow. Skipping a few steps early in training while the scale adjusts is normal.

bfloat16 needs none of this: its exponent has 8 bits, like float32, and its smallest normal is 2−1262^{-126}. No realistic gradient vanishes. What it loses is precision (7 mantissa bits), which in practice has little effect on network activations and gradients. NVIDIA GPUs have supported it in hardware since Ampere; on RTX 4060 (Ada) both formats are equally fast, and bfloat16 is a reasonable default. float16 remains useful on pre-Ampere GPUs and when its extra mantissa matters.

The next cell, running in the browser, builds both formats from scratch with NumPy: float16 exists in NumPy, and bfloat16 is obtained by rounding float32 to its upper 16 bits using integer arithmetic on its representation.

[ ]float16, bfloat16 and underflow from scratchBrowser
import numpy as np

def a_bf16(x):
    """Redondea float32 a bfloat16 (al más cercano, empates al par) y lo devuelve como float32."""
    u = np.asarray(x, dtype=np.float32).view(np.uint32).astype(np.uint64)
    u = (u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000          # suma media unidad del bit 16 y trunca
    return u.astype(np.uint32).view(np.float32)

with np.errstate(over="ignore"):
    for nombre, f in (("float16", lambda v: np.float32(np.float16(v))), ("bfloat16", lambda v: a_bf16(np.float32(v)))):
        print(f"{nombre:9s} 1 + 1e-3 = {f(1 + 1e-3):.6f}   1 + 1e-4 = {f(1 + 1e-4):.6f}   "
              f"3e-8 -> {f(3e-8):.3e}   2e-8 -> {f(2e-8):.3e}   1e5 -> {f(1e5):.4g}")

# gradientes de activaciones sintéticos: log2|g| es una mezcla de dos normales (como en la figura)
rng = np.random.default_rng(0)
n = 200_000
log2g = np.where(rng.random(n) < 0.7, rng.normal(-21, 3.5, n), rng.normal(-13, 3, n))
g = (np.exp2(log2g) * rng.choice([-1.0, 1.0], n)).astype(np.float32)

def balance(S):
    with np.errstate(over="ignore", invalid="ignore"):
        g16 = (g * np.float32(S)).astype(np.float16)            # el backward en float16, con escala S
        vuelta = g16.astype(np.float32) / np.float32(S)          # unscale_ en float32
    ceros = np.mean((g16 == 0) & (g != 0))
    sub = np.mean((np.abs(g16) < 2.0**-14) & (g16 != 0))
    infs = np.mean(np.isinf(g16))
    ok = np.isfinite(vuelta)
    err = np.median(np.abs(vuelta[ok] - g[ok]) / np.abs(g[ok]))
    return ceros, sub, infs, err

print(f"\n{'escala S':>10s}{'a cero':>9s}{'subnormales':>13s}{'inf':>8s}{'error rel. mediano':>21s}")
for k in (0, 8, 16, 24):
    c, s_, i, e = balance(2.0**k)
    print(f"{'2^' + str(k):>10s}{c:9.1%}{s_:13.1%}{i:8.2%}{e:21.1e}")
eb = np.median(np.abs(a_bf16(g) - g) / np.abs(g))
print(f"{'bfloat16':>10s}{np.mean(a_bf16(g) == 0):9.1%}{'0.0%':>13s}{'0.00%':>8s}{eb:21.1e}   (sin escala)")

The first table argues for master copies (1+10−41 + 10^{-4} disappears in both formats) and illustrates range (2⋅10−82 \cdot 10^{-8} vanishes in float16 and 10510^{5} overflows). The second is GradScaler in miniature: without scaling, 8.8% of gradients become zero and 71% are subnormal, with median relative error 0.6%; with S=216S = 2^{16} almost all are in the normal range and error falls to float16 rounding level, 1.7⋅10−41.7 \cdot 10^{-4}; with S=224S = 2^{24}, 1.5% overflow and GradScaler would discard the step. bfloat16 loses nothing to range, but its rounding relative error 1.4⋅10−31.4 \cdot 10^{-3} is eight times that of float16: the three-bit mantissa difference.

The mixed-precision loop

Four lines are added to the canonical loop. With bfloat16 the autocast block suffices and GradScaler is unnecessary (you can create it with enabled=False so the same code works for both):

scaler = torch.amp.GradScaler("cuda", enabled=(dtype == torch.float16))
for x, y in loader:
    x, y = x.to(dev, non_blocking=True), y.to(dev, non_blocking=True)
    with torch.autocast("cuda", dtype=dtype):    # solo el forward y la pérdida
        loss = loss_fn(model(x), y)
    scaler.scale(loss).backward()                # el backward, fuera del bloque
    scaler.unscale_(opt)                         # antes de recortar: gradientes en su escala real
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    scaler.step(opt)                             # se salta el paso si hay inf o NaN
    scaler.update()
    opt.zero_grad(set_to_none=True)

Three easily forgotten details. Gradient clipping must follow unscale_, or you clip gradients multiplied by SS. Scaler state (scaler.state_dict()) belongs in the training checkpoint, or on resumption the scale returns to 2162^{16}. Evaluation may also run under autocast, inside torch.no_grad().

[ ]Training with mixed precision: fp32, TF32, fp16 and bf16Local GPU
import numpy as np
import matplotlib.pyplot as plt

# datos sintéticos aprendibles: una cadena de Markov en la que cada token tiene 4 sucesores probables
V2, s2, b2 = 512, 256, 32
g_datos = torch.Generator(device="cpu").manual_seed(0)
sucesores = torch.randint(0, V2, (V2, 4), generator=g_datos)
def lote(gen):
    x = torch.empty(b2, s2 + 1, dtype=torch.long)
    x[:, 0] = torch.randint(0, V2, (b2,), generator=gen)
    for t in range(s2):
        x[:, t + 1] = sucesores[x[:, t], torch.randint(0, 4, (b2,), generator=gen)]
    return x[:, :-1].to(dev, non_blocking=True), x[:, 1:].to(dev, non_blocking=True)

def entrenar(modo, pasos=150):
    torch.backends.cuda.matmul.fp32_precision = "tf32" if modo == "tf32" else "ieee"
    torch.manual_seed(0)
    base = torch.cuda.memory_allocated()                       # lo que ya ocupan las celdas anteriores
    modelo = GPT(V2, s2, h=256, L=4, a=4, sdpa=True).to(dev)
    opt = torch.optim.AdamW(modelo.parameters(), lr=1e-3, fused=True)
    dt = {"fp16": torch.float16, "bf16": torch.bfloat16}.get(modo)
    scaler = torch.amp.GradScaler("cuda", enabled=(modo == "fp16"))
    gen = torch.Generator().manual_seed(1)                     # los mismos lotes en los cuatro modos
    datos = [lote(gen) for _ in range(pasos)]
    perdidas, escalas = [], []
    torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
    ini, fin = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    for paso, (x, y) in enumerate(datos):
        if paso == 20:
            ini.record()                                       # 20 pasos de calentamiento fuera de la medida
        with torch.autocast("cuda", dtype=dt or torch.float16, enabled=dt is not None):
            perdida = modelo(x, y)
        scaler.scale(perdida).backward()                       # si enabled=False, scale() no hace nada
        scaler.unscale_(opt)
        torch.nn.utils.clip_grad_norm_(modelo.parameters(), 1.0)
        scaler.step(opt)
        scaler.update()
        opt.zero_grad(set_to_none=True)
        perdidas.append(perdida.detach())                      # sin .item(): nada de sincronizar
        escalas.append(scaler.get_scale() if modo == "fp16" else 1.0)
    fin.record(); fin.synchronize()
    torch.backends.cuda.matmul.fp32_precision = "ieee"
    return {"ms": ini.elapsed_time(fin) / (pasos - 20), "pico": (torch.cuda.max_memory_allocated() - base) / MiB,
            "perdidas": torch.stack(perdidas).float().cpu().numpy(), "escalas": escalas}

res = {m: entrenar(m) for m in ("fp32", "tf32", "fp16", "bf16")}
print(f"{'modo':6s}{'ms/paso':>9s}{'pico':>11s}{'pérdida final':>15s}")
for m, r in res.items():
    print(f"{m:6s}{r['ms']:9.1f}{r['pico']:7.0f} MiB{r['perdidas'][-10:].mean():15.3f}")
esc = res["fp16"]["escalas"]
print("escala del GradScaler: inicial", esc[0], " final", esc[-1],
      " pasos saltados:", sum(1 for e0, e1 in zip(esc, esc[1:]) if e1 < e0))
print(f"suelo teórico de la pérdida: ln 4 = {np.log(4):.3f}")

fig, ax = plt.subplots(figsize=(6.5, 3.2))
for m, r in res.items():
    ax.plot(r["perdidas"], label=m, lw=1.3)
ax.axhline(np.log(4), color="gray", ls="--", lw=1, label="ln 4")
ax.set_xlabel("paso"); ax.set_ylabel("pérdida"); ax.set_ylim(1, 7); ax.legend(ncols=5, fontsize=8); plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the lab, a 4-layer GPT with h=256h = 256, batch 32 and context 256 takes about 50 ms per step in float32, about 41 with TF32 and 21–25 with autocast, in float16 or bfloat16 (figures vary by a few milliseconds between runs): mixed precision doubles speed. Training peak memory, excluding what earlier cells already occupied, falls from 652 to 422 MiB. All four loss curves are nearly indistinguishable (all end around 1.9 after 150 steps, approaching the ln⁡4≈1.39\ln 4 \approx 1.39 floor set by the Markov chain itself). GradScaler’s scale remains 2162^{16} throughout: this model does not overflow and, since growth occurs every 2000 steps, it never changes. To see it move, create the scaler with init_scale=2**24 or growth_interval=10 and log scaler.get_scale().

TF32: multiplying float32 on Tensor Cores

Since Ampere, Tensor Cores accept a fourth format, TF32: the 8-bit exponent of float32 and 10-bit mantissa of float16. If enabled, float32 matrix multiplications and convolutions internally round inputs to TF32, multiply on Tensor Cores and accumulate in float32. Your code, tensors and dtypes stay the same: only internal product precision changes.

PyTorch does not enable it by default for matmul (it does for cuDNN convolutions), because it changes results of code written expecting exact float32. There are two interfaces: the classic torch.set_float32_matmul_precision("high") (or torch.backends.cuda.matmul.allow_tf32 = True), and the new one since PyTorch 2.9, torch.backends.cuda.matmul.fp32_precision = "tf32" (with "ieee" to disable it). Choose one and use it consistently: in PyTorch 2.11, querying state with one after setting it with the other raises RuntimeError asking you not to mix them.

[ ]Measuring the RTX 4060: TFLOP/s and error by formatLocal GPU
def tiempo_ms(f, rep=10, calentar=3):
    for _ in range(calentar):
        f()
    ini, fin = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)
    ini.record()
    for _ in range(rep):
        f()
    fin.record(); fin.synchronize()
    return ini.elapsed_time(fin) / rep

MODOS = {"fp32": (torch.float32, "ieee"), "tf32": (torch.float32, "tf32"),
         "fp16": (torch.float16, "ieee"), "bf16": (torch.bfloat16, "ieee")}
print("TFLOP/s alcanzados (2n³ / tiempo, eventos CUDA)")
print("    n " + "".join(f"{m:>8s}" for m in MODOS) + "   ingenuo fp32")
for n in (256, 1024, 2048, 4096):
    fila = []
    for nombre, (dt, prec) in MODOS.items():
        torch.backends.cuda.matmul.fp32_precision = prec
        x = torch.randn(n, n, device=dev, dtype=dt); y = torch.randn(n, n, device=dev, dtype=dt)
        fila.append(2 * n**3 / tiempo_ms(lambda: x @ y, rep=50 if n <= 1024 else 10) / 1e9)
    torch.backends.cuda.matmul.fp32_precision = "ieee"
    x = torch.randn(n, n, device=dev); y = torch.randn(n, n, device=dev)
    x @ y; torch.cuda.synchronize()
    t0 = time.perf_counter(); x @ y; t_ing = (time.perf_counter() - t0) * 1e3
    torch.cuda.synchronize()
    ingenuo = 2 * n**3 / t_ing / 1e9
    aviso = "  <- imposible" if ingenuo > 2 * max(fila) else ""
    print(f"{n:5d} " + "".join(f"{v:8.1f}" for v in fila) + f"   {ingenuo:10.0f}{aviso}")

# exactitud: error relativo frente a float64 en un producto 2048 x 2048
n = 2048
x64 = torch.randn(n, n, device=dev, dtype=torch.float64); y64 = torch.randn(n, n, device=dev, dtype=torch.float64)
ref = x64 @ y64
print("\nerror relativo ‖C - C64‖ / ‖C64‖ con n = 2048:")
for nombre, (dt, prec) in MODOS.items():
    torch.backends.cuda.matmul.fp32_precision = prec
    c = (x64.to(dt) @ y64.to(dt)).double()
    print(f"  {nombre}: {((c - ref).norm() / ref.norm()).item():.1e}")
torch.backends.cuda.matmul.fp32_precision = "ieee"
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, with matrices of 2048 or more, float32 gives about 5.7 TFLOP/s, TF32 about 9, and float16 and bfloat16 about 18: a 1.6× factor by enabling TF32 without changing code and 3× by moving to 16 bits. With n=256n = 256 no format exceeds 1.5–2 TFLOP/s: the product is so small launch cost and lack of parallelism dominate. The naive timer, by contrast, reaches impossible hundreds of TFLOP/s. TF32’s price is error: 3⋅10−43 \cdot 10^{-4} versus 8⋅10−78 \cdot 10^{-7} in float32, the same order as float16 (both have 10 mantissa bits) and ten times less than bfloat16. This is irrelevant for network training, but not for solving an ill-conditioned linear system or checking a gradient with finite differences.

A recipe for 8 GB

With all this, the procedure to get the most from the card before a long training run:

  1. Set a ceiling. At script start, libre, total = torch.cuda.mem_get_info() and torch.cuda.set_per_process_memory_fraction(0.9 * libre / total), so excess becomes OutOfMemoryError rather than silently spilling to RAM. The fraction applies to total memory, so it must account for desktop usage.
  2. Enable the free gains. bfloat16 with autocast, scaled_dot_product_attention for attention, TF32 for anything remaining in float32, and fused=True in Adam.
  3. Estimate. Use the lesson’s estimator (or figure) to calculate state and activations per example. If state alone does not fit, no batch-size lever will save you: another optimizer, lower-precision weights or m21 techniques are needed.
  4. Measure maximum batch size. Binary-search batch size while catching torch.cuda.OutOfMemoryError (implemented in an exercise) and check peak with max_memory_allocated(). Leave 10% headroom for fragmentation and variable-size peaks.
  5. If the batch that fits is smaller than desired, do not reduce effective batch size: accumulate gradients over several small batches before each opt.step() (gradient accumulation). If even the minimum batch does not fit, recompute activations during backward instead of saving them (activation checkpointing).
  6. Do not retain memory unintentionally. Release references to large tensors with del, use zero_grad(set_to_none=True) (the default), and accumulate losses using perdida.detach(), never bare perdida: a tensor with history keeps the step’s entire graph alive, including activations.

Common mistakes

Exercises

NumericState of a 350M model
How many GB (10910^9 bytes) do the weights, gradients and two Adam moments, all in float32, occupy for a model with 350 million parameters? Exclude activations.
NumericBytes per parameter with autocast
You train with torch.autocast(dtype=torch.bfloat16), model parameters in float32 and Adam. How many bytes per parameter do weights, gradients and optimizer state occupy together?
QuizFour timers
You want to measure the time of a forward pass y = modelo(x) on the GPU. Which method measures it correctly?
QuizWhy does bfloat16 not need GradScaler?
Why is GradScaler normally unnecessary with bfloat16 autocast but needed with float16?
QuizAn OOM with free memory
Training fails with Tried to allocate 2.00 GiB. At that time memory_allocated() reports 3.5 GiB, memory_reserved() 5.0 GiB and nvidia-smi 6.2 GiB, on an 8 GiB card with a 6 GiB process limit. Which statements are true? More than one may be correct.

More than one answer may be correct.

NumericWhen attention dominates
With autocast and hand-written attention, a transformer layer saves 36 bsh+6 abs236\,bsh + 6\,abs^2 activation bytes. With head dimension h/a=64h/a = 64, at what context length ss does attention's term equal the rest?
NumericCost of one more example
GPT-2 small (L=12L = 12, h=768h = 768, V=50 257V = 50\,257) trains with context s=1024s = 1024, autocast and SDPA. With the lesson's coefficients (36 bsh36\,bsh per layer; head saves 6 bsV6\,bsV and uses 4 bsV4\,bsV workspace in backward), how many GiB (2302^{30} bytes) does each additional batch sequence add?
CodeFind the maximum batch size
Implement find_max_batch_size(make_model, make_batch, train_step=None, max_bs=4096), returning the largest batch size bs in [1, max_bs] for which a training step does not raise torch.cuda.OutOfMemoryError, or 0 if even bs = 1 does not fit. Each attempt creates a fresh model with make_model(), a batch with make_batch(bs) and runs train_step(modelo, lote) (by default, modelo(lote).float().mean().backward()). Assume fitting is monotone in bs and use a two-phase search: double from 1 until failure or max_bs, then bisect. Requirements: catch only OutOfMemoryError (propagate other errors); between attempts release all references to the previous model and batch, call gc.collect() and torch.cuda.empty_cache() if CUDA is available, and do not retry inside the except block (the traceback keeps tensors from the failed attempt alive). Tests simulate a GPU with an artificial limit, so you do not need one.
import gc
import torch

def find_max_batch_size(make_model, make_batch, train_step=None, max_bs=4096):
  paso = train_step or (lambda modelo, lote: modelo(lote).float().mean().backward())
  # tu código: una función que pruebe un tamaño y diga si cabe (liberando todo al salir),
  # fase 1 duplicando desde 1 y fase 2 por bisección
  return 0
Shift+Enter to run

Summary

Key idea
GPU time and space follow rules invisible in code: the CPU enqueues and the GPU executes later, so CUDA events measure actual GPU time; step memory is state (16 bytes per parameter with Adam) plus batch-proportional activations, managed by an allocator caching freed memory; mixed precision lowers tolerant operations to 16 bits, keeps parameters and delicate operations in float32, and scales the loss in float16 to prevent gradient underflow.
  • GPU operations queue in a stream and execute in order; the CPU waits only at synchronization points (.item(), print, .cpu(), variable-size outputs, synchronize). Without synchronization, loop time is the maximum of CPU and GPU times; with .item() per step, their sum.
  • To measure: CUDA events with enable_timing=True, warmup and many repetitions. Unsynchronized perf_counter measures enqueueing.
  • Step memory: weights, gradients and optimizer (8, 12 or 16 bytes per parameter with SGD, momentum or Adam), saved activations (64 bsh+4 abs264\,bsh + 4\,abs^2 bytes per transformer layer in float32), and workspace. For a small model with long context, state matters least.
  • The caching allocator reserves segments and divides blocks; memory_allocated counts tensors, memory_reserved driver requests, and nvidia-smi also adds context and other processes. An OOM with much “reserved but unallocated” memory is fragmentation; empty_cache does not fix it.
  • Autocast lowers matmuls and convolutions to 16 bits, raises normalizations, softmax and losses to float32, and leaves parameters in float32. It reduces activations and time, not state. float16 needs GradScaler due to limited range; bfloat16 does not.
  • TF32 accelerates float32 matmuls 60% on this card at 10-bit precision; enable it with set_float32_matmul_precision("high") or fp32_precision = "tf32" without mixing interfaces.
  • On Windows, set a ceiling using set_per_process_memory_fraction calculated from free memory, so excess memory becomes an error instead of silently spilling into RAM.