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 matrices in float32 and time them with time.perf_counter() before and after. You get 0.07 ms. The product costs 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)andf"{t:.3f}",float(t),if t > 0:(which callsbool). - 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()(callscudaFree, 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 identical kernels. Each launch costs of CPU time, execution costs of GPU time, and between launches the CPU does of its own work (data preparation, Python logic). Call the time kernel reaches the queue and the time it finishes on the GPU.
Proof
By induction on . For , . If the formula holds for , then , the maximum over of . The expression is affine in with slope , so the maximum is at an endpoint: (GPU bottleneck, busy continuously from the first kernel) or (CPU bottleneck, GPU finishing 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 ), waits for GPU execution (), pays and only then does its own work (), while the GPU has an empty queue. The GPU works of each interval.
The proposition says three things you will see in the figure. If , the queue fills and total time is : the GPU runs at 100%. If , the GPU waits for the CPU and is idle for fraction 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 in each iteration into the sum : CPU and GPU time no longer overlap.
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.
- 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. - 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 readingelapsed_time, wait forfinwithfin.synchronize(). - 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. - 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.
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")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, and , each parameter-sized.
| Optimizer | Weights | Gradients | State | Total per parameter |
|---|---|---|---|---|
| SGD | 4 | 4 | 0 | 8 bytes |
| SGD with momentum | 4 | 4 | 4 | 12 bytes |
| Adam, AdamW | 4 | 4 | 8 | 16 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 needs to compute ; 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 , context , dimension and heads, counting what each operation saves gives, in float32 with hand-written attention:
- the input of each
layer_normand each linear layer of dimension : five tensors of elements (the two normalizations and inputs to the projections, output projection, and first MLP layer; the second MLP layer’s input is the GELU output, counted below); - , and , three tensors saved as contiguous copies by the batched product;
- the MLP GELU input and output, two tensors;
- attention softmax output, elements.
In total, elements per layer, or bytes. The language head with vocabulary saves log-softmax output, bytes, and during backward the logits gradient occupies about 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.
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, , context 256, vocabulary 8192). The model ties embedding and head weights like GPT-2 and uses fused=True in Adam to exclude optimizer temporaries.
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")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,
cudaMallocis called. IfcudaMallocfails, the allocator releases all entirely free segments and retries. If it fails again, it raisestorch.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.
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:
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.torch.cuda.memory_stats()returns the same counters as a dictionary, useful for logging during training.- Memory snapshots:
torch.cuda.memory._record_memory_history()starts recording each allocation and release with the Python trace that caused it, andtorch.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.
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, optnpm 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 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 : exponent bits determine range and mantissa bits relative precision.
| Format | Sign, exponent, mantissa | Largest finite | Smallest normal | Smallest subnormal | (distance from 1 to next) |
|---|---|---|---|---|---|
float32 | 1, 8, 23 | ||||
| TF32 (Tensor Cores only) | 1, 8, 10 | as float32 | as float32 | ||
float16 | 1, 5, 10 | ||||
bfloat16 | 1, 8, 7 |
float16 is more precise than bfloat16 (10 mantissa bits versus 7) but has vastly less range: below it enters subnormals, which lose precision bits, and below it rounds to zero. bfloat16 is literally the upper half of float32: same exponent, truncated mantissa. Its range is that of float32.
The 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 times the weight or less. In float16, rounds to because the next representable number after 1 is away; in bfloat16 even 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: bytes per layer versus . Autocast reduces the linear term 44% and increases explicit attention’s term 50%, which is why it delivers full savings only with SDPA.
float16 and bfloat16 and notice which operations change color. Below, activation gradient distribution in backward on a 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.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 = Nonenpm 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 , the smallest float16 subnormal. In float16, values below (half the smallest subnormal) round to zero, and those between and lose bits.
The solution is simple and elegant. Loss is a scalar and backward is linear in it: multiplying loss by constant multiplies all backward gradients by by the chain rule. With multiplication is exact (only the exponent changes) and the whole histogram shifts positions right on the scale, away from underflow. Before the optimizer step divide by in float32, where range is not a problem. If is too large, larger gradients overflow to inf: the step is discarded and reduced.
torch.amp.GradScaler automates all three. scaler.scale(loss) multiplies by (initially ). scaler.step(opt) calls unscale_ if you have not (dividing gradients by and checking for inf or NaN), and calls opt.step() only if neither is present. scaler.update() multiplies 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 . 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.
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 ( disappears in both formats) and illustrates range ( vanishes in float16 and 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 almost all are in the normal range and error falls to float16 rounding level, ; with , 1.5% overflow and GradScaler would discard the step. bfloat16 loses nothing to range, but its rounding relative error 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 . Scaler state (scaler.state_dict()) belongs in the training checkpoint, or on resumption the scale returns to . Evaluation may also run under autocast, inside torch.no_grad().
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()npm run lab and open the connection link.In the lab, a 4-layer GPT with , 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 floor set by the Markov chain itself). GradScaler’s scale remains 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.
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"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 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: versus 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:
- Set a ceiling. At script start,
libre, total = torch.cuda.mem_get_info()andtorch.cuda.set_per_process_memory_fraction(0.9 * libre / total), so excess becomesOutOfMemoryErrorrather than silently spilling to RAM. The fraction applies to total memory, so it must account for desktop usage. - Enable the free gains.
bfloat16with autocast,scaled_dot_product_attentionfor attention, TF32 for anything remaining infloat32, andfused=Truein Adam. - 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.
- Measure maximum batch size. Binary-search batch size while catching
torch.cuda.OutOfMemoryError(implemented in an exercise) and check peak withmax_memory_allocated(). Leave 10% headroom for fragmentation and variable-size peaks. - 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). - Do not retain memory unintentionally. Release references to large tensors with
del, usezero_grad(set_to_none=True)(the default), and accumulate losses usingperdida.detach(), never bareperdida: a tensor with history keeps the step’s entire graph alive, including activations.
Common mistakes
Exercises
float32, occupy for a model with 350 million parameters? Exclude activations.torch.autocast(dtype=torch.bfloat16), model parameters in float32 and Adam. How many bytes per parameter do weights, gradients and optimizer state occupy together?y = modelo(x) on the GPU. Which method measures it correctly?bfloat16 autocast but needed with float16?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.
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 0Summary
- 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. Unsynchronizedperf_countermeasures enqueueing. - Step memory: weights, gradients and optimizer (8, 12 or 16 bytes per parameter with SGD, momentum or Adam), saved activations ( 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_allocatedcounts tensors,memory_reserveddriver requests, and nvidia-smi also adds context and other processes. An OOM with much “reserved but unallocated” memory is fragmentation;empty_cachedoes not fix it. - Autocast lowers matmuls and convolutions to 16 bits, raises normalizations, softmax and losses to
float32, and leaves parameters infloat32. It reduces activations and time, not state.float16needsGradScalerdue to limited range;bfloat16does not. - TF32 accelerates
float32matmuls 60% on this card at 10-bit precision; enable it withset_float32_matmul_precision("high")orfp32_precision = "tf32"without mixing interfaces. - On Windows, set a ceiling using
set_per_process_memory_fractioncalculated from free memory, so excess memory becomes an error instead of silently spilling into RAM.