Squeezing the RTX 4060: throughput and memory
Optimize training step by step while measuring each change: bf16 autocast, TF32, fused attention, torch.compile, fused AdamW, padded vocabulary, and microbatching with gradient accumulation. Calculate MFU, profile with torch.profiler, and fit a 124M model with context 1024 and an effective batch of hundreds of thousands of tokens into 8 GB.
After this lesson you can
- Measure tokens per second after each optimization using sound benchmarking methodology.
- Calculate MFU from FLOPs per token and theoretical GPU peak.
- Profile a training step and identify its dominant bottleneck.
- Configure microbatching, accumulation, and recomputation for the target effective batch within 8 GB.
Before you start
- P06Training sanity protocolGPT model implementation
- 21Mixed-precision trainingPer-op precision policyTraining compute C ≈ 6NDModel FLOPs utilizationGradient accumulationActivation (gradient) checkpointing
- 18FlashAttentionI/O complexity of attention
- 00Graph capture with TorchDynamoOperator fusiontorch.profiler traces
Measure before optimizing
The GPT from p06-l03 already reproduces GPT-2’s outputs, and the p06-l04 loop can detect unhealthy training. Now it needs to be fast. On a laptop RTX 4060, the most direct training step, float32, mathematical attention, and unfused AdamW, processes around 3500 tokens per second: one billion tokens would take 3.3 days. With this lesson’s optimizations, the same model reaches around 11700 tokens per second and the same calculation falls to one day. That difference determines which p06-l06 experiments fit into a week.
“Faster” is meaningless without saying what is measured. Two runs advertising the same model may do different work: one includes compilation, another omits data copying, and another uses a different attention mask or batch size. This lesson follows a strict method: specify the step, token count, and timed interval; change one configuration at a time; measure with synchronization and the median; and whenever precision or implementation changes, verify that loss and gradients still match the reference.
The figure starts with the float32 baseline and adds one optimization per row. Notice three things. The largest individual gain comes from changing the attention implementation rather than lowering precision. Padding the vocabulary improves nothing in this configuration. And in MFU mode, even the best row leaves two thirds of the GPU’s peak unused. Each row is a complete executed configuration: the effect of an optimization depends on the others, so an unmeasured combination cannot be estimated by multiplying gains from other rows.
Throughput optimization increases training tokens processed per second under declared conditions, including model, microbatch, context, precision, attention, compilation, optimizer, and timed interval, while preserving the function being optimized. Both requirements matter: a faster variant computing a different loss is a different experiment.
Clocks, warmup, and the median
CUDA executes operations asynchronously: a Python call enqueues a kernel and returns immediately, long before the GPU finishes. Reading time.perf_counter() immediately after loss.backward() measures enqueue time rather than computation. Each interval therefore begins and ends with torch.cuda.synchronize(), which waits for the queue to empty. The PyTorch CUDA note describes this behavior.
Early steps are not representative. The first initializes cuBLAS and cuDNN, chooses algorithms, reserves allocator memory, and, if using torch.compile, compiles. Run warmup steps outside the timed interval, then repeat the step and take the median. If each interval processes tokens and its median duration is , throughput is . Unlike the mean, the median is not pulled by one interval where the operating system or GPU clock behaved unusually. On a laptop, frequency depends on temperature and power profile: retain ratios among configurations measured in the same session rather than promising absolute times elsewhere.
For memory, distinguish three numbers. torch.cuda.max_memory_allocated() is peak bytes held by live tensors; max_memory_reserved() also includes blocks cached by the PyTorch allocator for reuse and is usually larger; nvidia-smi reports those plus the CUDA context and other processes. This lesson uses the first, reset with reset_peak_memory_stats() before timing. torch.cuda.empty_cache() returns unused cached blocks to the system but does not release a tensor still referenced.
How many FLOPs a token costs
To tell whether 11700 tokens per second is a lot, we need a reference: how many operations each token requires and how many the GPU can perform.
The 6N count plus attention
A linear layer with performs multiplications and the same number of additions per token: FLOPs, or two per weight. Backpropagation needs two products of the same size: the input gradient and the token’s contribution to weight gradient . Each weight thus costs FLOPs per training token, and a model with dense-matrix parameters costs about .
Attention adds products without weights. In each layer for a sequence of length , all heads’ scores total FLOPs, since each head contributes and , and multiplication by costs another . Per token this is forward, triple with backpropagation, or per layer.
The formula is a model rather than an instruction counter. It slightly overestimates the weight term: includes the position table, biases, and normalizations, 907776 parameters not involved in matrix multiplication, so exceeds three times the p06-l03 dense count by 0.6% (). The embedding matrix does count because it is tied to the output head, a product. The formula excludes softmax, normalization, activations, and optimizer operations, which are order per layer rather than . Padding vocabulary to 50304 increases by parameters and gives .
GPU peak
MFU is not the fraction of time the GPU is busy: a memory-intensive kernel doing few operations can keep the GPU “busy” with tiny MFU. It measures how much arithmetic capacity becomes useful model work, enabling comparison across implementations, GPUs, and batch sizes with one number, as used for training planning in the scaling module.
The denominator must be the dense peak at the Tensor Core precision in use. Construct it rather than copying a commercial specification, which often advertises structured sparsity or FP8 figures. For Ada, NVIDIA’s whitepaper gives the RTX 4090, 128 SMs at 2520 MHz, 165.2 dense TFLOPS in BF16 with FP32 accumulation, or FLOPs per cycle and SM. On GeForce, FP32 accumulation runs at half the rate of FP16 accumulation and is what PyTorch uses with BF16. NVIDIA’s laptop table lists 3072 CUDA cores for the RTX 4060 Laptop, 24 SMs of 128, and a boost clock of 1470 to 2370 MHz depending on manufacturer. At the maximum,
This is consistent with the table’s 233 “AI TOPS,” which are FP8 with sparsity, eight times the preceding figure. Tensor Core TF32 runs at 256 FLOPs per cycle and SM, 14.56 TFLOPS, exactly the same as 3072 FP32 cores performing a multiply-add each cycle. On this GPU, TF32 has no higher peak than float32 and can win only through efficiency. We use as the denominator for every row, including float32, so MFU describes how far each configuration is from the hardware’s best. The lab also measures a large BF16 matrix multiplication to see how much of that peak is reached in practice. Your laptop’s actual clock can be below or above 2370 MHz and is declared with P06_GPU_BOOST_MHZ.
With these numbers, the float32 baseline achieves and the best configuration 34.6%. As a reference, nanoGPT’s estimate_mfu uses the same formula, with excluding the position table, and the A100 BF16 peak of 312 TFLOPS.
What each option changes
TF32 and BF16 with autocast
TF32 makes float32 matrix multiplications use Tensor Cores with a 10-bit product mantissa and float32 accumulation. Tensors remain float32 and other operations do not change. Enable it with torch.backends.cuda.matmul.allow_tf32 = True or torch.set_float32_matmul_precision('high'). BF16 with autocast goes further: inside torch.autocast('cuda', dtype=torch.bfloat16), each operation chooses its type according to a policy. Matrix multiplications and attention become BF16, while softmax, normalization, and cross-entropy remain float32. Master weights and gradients remain float32, and BF16 has the same exponent range as float32, so loss scaling required by FP16 in Micikevicius et al. (2018) is unnecessary.
In the waterfall, TF32 achieves 1.31 times baseline, and BF16 only 2.7% more than TF32 despite twice the peak. Mathematical attention explains this: the step is dominated by materializing and traversing score matrices, memory-bandwidth-limited operations barely accelerated by product dtype. BF16 does reduce memory by 555 MB because activations saved for backpropagation take half the space.
Changing precision changes the numerical trajectory. The lab compares BF16 loss and gradients with a float32 reference on a fixed batch with identical weights. Relative gradient discrepancy is on the order of , expected with an 8-bit mantissa. A higher rate does not prove correctness; this comparison provides evidence.
Fused attention
F.scaled_dot_product_attention selects among implementations. The mathematical implementation computes , applies mask and softmax, and multiplies by as separate operations, writing scores to memory: in BF16, MB per layer and sequence. Fused implementations such as FlashAttention and cuDNN traverse blocks of and , accumulating softmax online without writing the full matrix and recomputing it blockwise in backpropagation. FlashAttention-2 also distributes work better across thread blocks and skips blocks entirely masked by causality. In the waterfall, switching from mathematical attention to cuDNN is the largest individual jump, 1.59 times, and frees 676 MB, about 56 MB per layer, slightly more than two score matrices.
The lab also tries SDPBackend.FLASH_ATTENTION. Official PyTorch wheels for Windows do not include that kernel, so the attempt ends with No available kernel; the lab records an error rather than a rate. It works on Linux. Pin the backend with sdpa_kernel rather than relying on automatic selection, so you know which kernel you are measuring.
Fused AdamW
AdamW updates each of 148 parameter tensors with moving means of gradient and squared gradient, bias correction, and weight decay. With foreach=False and fused=False, it uses a Python loop launching eight tiny kernels per tensor, 1184 per step. fused=True performs the full update in a few kernels. In the waterfall it adds 18%, from 7484 to 8842 tokens per second, substantial for a change that does not touch the model: at microbatch 1, a step takes 116 ms and thousands of small kernel launches matter. The baseline deliberately uses the loop to expose this effect; PyTorch’s GPU default, foreach=True, groups tensors and falls between them.
torch.compile
torch.compile captures the forward and backward graph, and Inductor fuses elementary operations, including residual additions, GELU, normalizations, and masks, into Triton kernels that read and write each tensor once. In the waterfall it gives 1.33 times the preceding row and reduces peak memory by 474 MB because many intermediates disappear inside fused kernels. The cost is initial compilation time, excluded from the median, and the risk of recompilation.
Dynamo specializes the graph to observed tensor shapes. If sequence length changes from step to step, each new shape may trigger compilation taking several seconds. The lab demonstrates this with a small function: with dynamic=False, each new length recompiles; with the default, after the second distinct shape Dynamo generates a graph with symbolic dimensions and stops recompiling. For pretraining the solution is simpler: fixed-shape batches, like those produced by the p06-l02 loader.
Vocabulary padded to a multiple of 64 and pinned memory
Matrix multiplication kernels operate on tiles of power-of-two size. An odd dimension like 50257 leaves partially empty tiles and can prevent the fastest aligned accesses. Padding to 50304, the next multiple of 64 (), is a known nanoGPT trick. But if the 47 new rows participate in softmax, their exponentials enter the denominator and loss changes even if they are never labels. nanoGPT does not mask them and lets training push their logits down. Here they are replaced with before cross-entropy, preserving the objective exactly, as the lab checks. In our measurement padding gained nothing: 8800 versus 8842 tokens per second, a 0.5% difference below run-to-run noise and including masking cost. This shows why each change is measured: a popular optimization may not help on a different GPU, shape, or cuBLAS version. The row is also not weight-paired with the previous one: changing table size alters random generator consumption at initialization.
Pinned memory (pin_memory()) allows asynchronous CPU-to-GPU DMA copies without an intermediate buffer. It speeds a step only if copying was on the critical path. A microbatch of 8 sequences of 1025 int64 tokens occupies 65.6 kB, and its copy takes tens of microseconds versus hundreds of milliseconds for a step. The lab measures the two copies separately. The waterfall benchmarks declare that data is already on the GPU: they measure computation, not the loader.
Memory: where the 8 GB go
Fitting training into 8 GB allocates memory between the fixed training portion and the portion growing with microbatch, then chooses microbatch, recomputation, and accumulation so the target effective batch fits with headroom. There are two parts.
Fixed. With AdamW and float32 master weights, each parameter takes 4 bytes of weight, 4 of gradient, and 8 for the two moments: 16 bytes. For 124.4 million parameters that is 1.99 GB regardless of microbatch. BF16 autocast does not reduce this part; it converts weights to BF16 on the fly for each product.
Proportional to . Activations needed for backpropagation include inputs to each linear layer, normalization and GELU outputs, and logits. Logits are substantial: values per sequence are 103 MB in BF16 and 206 MB in float32, and cross-entropy saves versions in both types as well as their gradient. In the waterfall, BF16 with cuDNN and microbatch 1 peaks at 3.21 GB, 1.22 GB above the fixed portion. If that portion grew linearly, a 7.5 GB budget would fit about sequences. This estimate is optimistic: in that step without accumulation, gradients are created during backpropagation and do not all exist at peak, while during accumulation the 0.5 GB of gradients are present throughout the pass from the second microbatch onward. The lab searches for the actual maximum microbatch under accumulation.
Activation checkpointing saves only the input of each block, float32 values, 3.1 MB per block and sequence, and reruns the block during backpropagation to reconstruct the rest. It trades memory for compute: one extra forward pass through the twelve blocks, with 85054464 parameters and no output-head recomputation, costs extra FLOPs per token. If the step were limited solely by arithmetic, throughput would be multiplied by . MFU, which counts only , falls by the same proportion, while HFU does not. This pays off only if it permits a microbatch that otherwise would not fit and that larger microbatch gains more than recomputation costs. With torch.utils.checkpoint and use_reentrant=False, the function is unchanged, including with dropout: PyTorch saves random generator state by default and restores it during recomputation, repeating the same masks.
Gradient accumulation
The effective batch GPT-3 used for its 125M model, 0.5 million tokens in table 2.1, does not fit in a consumer GPU. Gradient accumulation reproduces it with consecutive microbatches before each optimizer step: with sequences of length per microbatch, the effective batch has tokens. For 524288 tokens with and , .
Proof
Backpropagating adds to .grad, since the gradient of a constant times a function is the constant times its gradient. After microbatches, .grad by linearity. Since all microbatches have targets, , the mean across all effective-batch tokens. If microbatch has targets, the same calculation shows that must be weighted by instead of .
In floating-point arithmetic, equality is approximate because summation order changes, and with dropout each microbatch uses another mask. After microbatches, clip the norm once and take one AdamW step. During accumulation memory is that of the microbatch; the effective batch is never entirely on the GPU.
Lab
Before using the GPU, check two invariants with small numbers computed in the browser: the average gradient of two microbatches equals that of the full batch, and adding a finite class to the softmax denominator changes loss even when the label does not change.
import math
def sigmoid(z):
return 1.0 / (1.0 + math.exp(-z))
def grad(w, points):
return sum((sigmoid(w*x) - y)*x for x, y in points) / len(points)
points = [(1.0, 1), (2.0, 0), (-1.0, 1), (3.0, 0)]
whole = grad(0.4, points)
accumulated = (grad(0.4, points[:2]) + grad(0.4, points[2:])) / 2
assert math.isclose(whole, accumulated, rel_tol=1e-12, abs_tol=1e-12)
original = math.log(math.exp(1.0) + math.exp(0.0)) - 1.0
padded = math.log(math.exp(1.0) + math.exp(0.0) + math.exp(0.0)) - 1.0
assert padded > original
print('Gradiente completo y acumulado:', round(whole, 8), round(accumulated, 8))
print('Pérdida sin y con clase añadida:', round(original, 8), round(padded, 8))
print('FLOPs por token, 6N + 12LTd:', 6*124439808 + 12*12*1024*768)
print('Microlotes por actualización:', 524288 // (8*1024))
print('Pico BF16 denso supuesto (TFLOPS):', 24 * 2.37e9 * 512 / 1e12)The local lab reads the current GPT class from the “GPT propio y controles” cell in p06-l03, so it works in a fresh kernel without running that lesson. It requires PyTorch with CUDA and, for compilation, Triton, using triton-windows on Windows. Run from the project root: P06_PROJECT_ROOT changes that root and P06_BENCH_DIR changes the results directory, p06_bench by default. Every measurement uses the 12-layer, 12-head, 768-dimensional model without dropout to compare backends, with synthetic IDs already on GPU. They measure forward, backward, and AdamW, excluding data loading.
Three more variables control execution. P06_BENCH_BUDGET_GB, 7.5 by default, limits memory PyTorch can reserve with set_per_process_memory_fraction, so the microbatch search respects the budget even if the card has somewhat more. P06_GPU_BOOST_MHZ (2370) sets the clock for theoretical peak, and P06_PEAK_TFLOPS replaces it entirely if your GPU is not an Ada GeForce. With P06_BENCH_QUICK=1, the lab is a smoke test: waterfall, profiling, microbatch search, and final update use context 256 rather than 1024, fewer repetitions, and the final update accumulates only 4 microbatches because after the second, peak memory no longer depends on how many are accumulated. This is how the lesson was verified with a 3 GB budget. The complete run you should do takes a few minutes plus compilation.
"""Benchmark del GPT vigente de p06-l03: datos sintéticos ya en GPU, mediciones sincronizadas."""
import contextlib
import gc
import hashlib
import json
import os
import statistics
import time
from pathlib import Path
def find_project_root():
configured = os.environ.get('P06_PROJECT_ROOT')
candidates = [Path(configured).resolve()] if configured else [Path.cwd(), *Path.cwd().parents]
for candidate in candidates:
if (candidate / 'src/content/lessons/p06/l03-modelo-gpt-y-paridad.mdx').is_file():
return candidate
raise FileNotFoundError('No se encontró la raíz del proyecto; fija P06_PROJECT_ROOT')
ROOT = find_project_root()
HERE = Path(os.environ.get('P06_BENCH_DIR', 'p06_bench')).resolve()
HERE.mkdir(parents=True, exist_ok=True)
QUICK = os.environ.get('P06_BENCH_QUICK') == '1'
BUDGET_GB = float(os.environ.get('P06_BENCH_BUDGET_GB', '7.5'))
BOOST_MHZ = float(os.environ.get('P06_GPU_BOOST_MHZ', '2370'))
CONTEXT = 256 if QUICK else 1024 # contexto de la cascada
WARMUPS, REPEATS = (1, 3) if QUICK else (2, 5)
EFFECTIVE_TOKENS = 524288
VOCAB, LAYERS, HEADS, D = 50257, 12, 12, 768
os.environ.setdefault('TORCHINDUCTOR_CACHE_DIR', str(HERE / 'inductor'))
os.environ.setdefault('TRITON_CACHE_DIR', str(HERE / 'triton'))
import torch
import torch.nn.functional as F
from torch.nn.attention import sdpa_kernel, SDPBackend
from torch.utils.checkpoint import checkpoint
def model_definition():
text = (ROOT / 'src/content/lessons/p06/l03-modelo-gpt-y-paridad.mdx').read_text(encoding='utf-8')
marker = '```python run runtime=local title="GPT propio y controles"\n'
cell = text.split(marker, 1)[1].split('\n```', 1)[0]
code = cell.split('\nattention_test()\nbehavior_test()', 1)[0]
env = {'__name__': 'modelo_p06_l03'}
exec(compile(code, 'p06-l03.mdx', 'exec'), env)
return env['GPT'], hashlib.sha256(cell.encode('utf-8')).hexdigest()
def n_params(vocab, context=1024):
"""Parámetros del GPT de p06-l03 (embeddings atados a la cabeza)."""
return vocab*D + context*D + LAYERS*(12*D*D + 13*D) + 2*D
def flops_per_token(vocab, context):
"""6N + 12LTd: convención densa del apéndice B de PaLM."""
return 6*n_params(vocab) + 12*LAYERS*context*D
def peak_bf16_flops(sms=None):
"""Pico denso BF16 con acumulación FP32: 512 FLOPs por ciclo y SM en Ada GeForce."""
if os.environ.get('P06_PEAK_TFLOPS'):
return float(os.environ['P06_PEAK_TFLOPS'])*1e12
if sms is None:
props = torch.cuda.get_device_properties(0)
if (props.major, props.minor) != (8, 9) or 'GeForce' not in props.name:
raise ValueError('512 FLOPs/ciclo/SM vale para Ada GeForce: fija P06_PEAK_TFLOPS')
sms = props.multi_processor_count
return sms*BOOST_MHZ*1e6*512
def estimate_mfu(tokens_per_second, flops_per_token, peak_flops_per_second):
if min(tokens_per_second, flops_per_token, peak_flops_per_second) <= 0:
raise ValueError('Las tres cantidades deben ser positivas')
return tokens_per_second*flops_per_token/peak_flops_per_second
def apply_budget():
total = torch.cuda.get_device_properties(0).total_memory
fraction = min(1.0, BUDGET_GB*1e9/total)
torch.cuda.set_per_process_memory_fraction(fraction)
print(f'Presupuesto: {BUDGET_GB} GB de {total/1e9:.2f} GB (fracción {fraction:.3f})', flush=True)
def accumulation_check():
GPT, _ = model_definition()
torch.manual_seed(64)
model = GPT(vocab=32, context=8, layers=2, heads=2, d=32, dropout=0).train()
x = torch.randint(0, 32, (2, 8)); y = torch.randint(0, 32, (2, 8))
F.cross_entropy(model(x).reshape(-1, 32), y.reshape(-1)).backward()
full = {n: p.grad.detach().clone() for n, p in model.named_parameters()}
model.zero_grad(set_to_none=True)
for i in range(2):
(F.cross_entropy(model(x[i:i+1]).reshape(-1, 32), y[i:i+1].reshape(-1))/2).backward()
error = max((p.grad - full[n]).abs().max().item() for n, p in model.named_parameters())
assert error < 1e-6, error
print('Gradientes lote completo frente a acumulación: error máximo', error, flush=True)
def training_step(model, opt, x, y, cfg, accum=1):
opt.zero_grad(set_to_none=True)
backend = (SDPBackend.CUDNN_ATTENTION if cfg.get('cudnn', False) else
SDPBackend.FLASH_ATTENTION if cfg['flash'] else SDPBackend.MATH)
autocast = torch.autocast('cuda', dtype=torch.bfloat16) if cfg['bf16'] else contextlib.nullcontext()
with sdpa_kernel(backend), autocast:
for _ in range(accum):
if cfg.get('checkpoint', False):
t = x.shape[1]
z = model.transformer.drop(model.transformer.wte(x) + model.transformer.wpe(torch.arange(t, device=x.device)))
for block in model.transformer.h:
z = checkpoint(block, z, use_reentrant=False)
logits = model.lm_head(model.transformer.ln_f(z))
else:
logits = model(x)
if cfg['vocab'] > VOCAB: # las filas de relleno no entran en la softmax
logits = torch.cat((logits[:, :, :VOCAB], torch.full_like(logits[:, :, VOCAB:], float('-inf'))), dim=-1)
loss = F.cross_entropy(logits.reshape(-1, cfg['vocab']), y.reshape(-1))/accum
loss.backward()
last = loss.detach()
del logits, loss # si no, los logits de este microlote siguen vivos durante el siguiente
opt.step()
return last
def run_case(name, cfg, warmups=None, repeats=None, accum=1, batch=1, context=None, warmup_accum=None):
warmups = WARMUPS if warmups is None else warmups
repeats = REPEATS if repeats is None else repeats
context = CONTEXT if context is None else context
gc.collect(); torch.cuda.empty_cache()
torch.manual_seed(61)
GPT, source_hash = model_definition()
model = GPT(vocab=cfg['vocab'], context=1024, layers=LAYERS, heads=HEADS, d=D, dropout=0).cuda().train()
assert sum(p.numel() for p in model.parameters()) == n_params(cfg['vocab'])
opt = torch.optim.AdamW(model.parameters(), lr=0.0003, fused=cfg['fused'], foreach=False)
if cfg.get('compile', False):
model = torch.compile(model)
torch.backends.cuda.matmul.allow_tf32 = cfg['tf32']
torch.backends.cudnn.allow_tf32 = cfg['tf32']
x = torch.randint(0, VOCAB, (batch, context), device='cuda')
y = torch.randint(0, VOCAB, (batch, context), device='cuda')
times = []
try:
for _ in range(warmups): # el calentamiento también crea los estados de AdamW
training_step(model, opt, x, y, cfg, warmup_accum or accum)
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
for _ in range(repeats):
torch.cuda.synchronize()
start = time.perf_counter()
loss = training_step(model, opt, x, y, cfg, accum)
torch.cuda.synchronize()
times.append(time.perf_counter() - start)
if not torch.isfinite(loss):
raise ValueError('pérdida no finita')
tokens = batch*context*accum
rate = tokens/statistics.median(times)
fpt = flops_per_token(cfg['vocab'], context)
record = {'name': name, 'tokens_per_second': rate,
'mfu': estimate_mfu(rate, fpt, peak_bf16_flops()),
'peak_memory_bytes': torch.cuda.max_memory_allocated(),
'config': dict(cfg, batch=batch, context=context, accumulation=accum,
effective_tokens=tokens, warmups=warmups, repeats=repeats,
flops_per_token=fpt, model_code_sha256=source_hash, drop_probability=0,
measured='forward, backward, adamw; synthetic data already on GPU')}
print(json.dumps(record, ensure_ascii=False), flush=True)
return record
finally:
del model, opt, x, y
gc.collect(); torch.cuda.empty_cache()
def show_table(runs, sms=None):
base = runs[0]['tokens_per_second']
print(f"{'configuración':46s} {'tokens/s':>9s} {'x base':>7s} {'MFU':>7s} {'pico GB':>8s}")
for r in runs:
c = r['config']
mfu = estimate_mfu(r['tokens_per_second'], flops_per_token(c['vocab'], c['context']), peak_bf16_flops(sms))
print(f"{r['name']:46s} {r['tokens_per_second']:9.0f} {r['tokens_per_second']/base:7.2f} "
f"{100*mfu:6.1f}% {r['peak_memory_bytes']/1e9:8.2f}", flush=True)
def suite():
assert torch.cuda.is_available()
base = {'vocab': VOCAB, 'bf16': False, 'tf32': False, 'flash': False, 'fused': False}
cases = [('FP32, atención matemática', {}),
('FP32 con TF32', {'tf32': True}),
('BF16, atención matemática', {'tf32': True, 'bf16': True}),
('BF16, atención cuDNN', {'tf32': True, 'bf16': True, 'cudnn': True}),
('BF16, cuDNN y AdamW fusionado', {'tf32': True, 'bf16': True, 'cudnn': True, 'fused': True}),
('BF16, cuDNN, AdamW y vocabulario rellenado', {'vocab': 50304, 'tf32': True, 'bf16': True, 'cudnn': True, 'fused': True}),
('BF16, atención flash', {'tf32': True, 'bf16': True, 'flash': True}),
('BF16, cuDNN, AdamW, vocabulario y compile', {'vocab': 50304, 'tf32': True, 'bf16': True, 'cudnn': True, 'fused': True, 'compile': True})]
result = {'runs': [], 'errors': [], 'gpu': torch.cuda.get_device_name(),
'torch_version': torch.__version__, 'cuda_version': torch.version.cuda, 'quick': QUICK,
'peak_flops': peak_bf16_flops(),
'peak_memory_definition': 'PyTorch peak allocated bytes, not total global VRAM'}
for name, delta in cases:
try:
extra = {'warmups': WARMUPS + 1} if delta.get('compile') else {}
result['runs'].append(run_case(name, base | delta, **extra))
except Exception as exc: # un backend ausente se registra, no se inventa
result['errors'].append({'name': name, 'error': repr(exc)})
print('ERROR', name, repr(exc), flush=True)
(HERE/'runs.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
show_table(result['runs'])
def correctness():
GPT, source_hash = model_definition()
torch.manual_seed(62)
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
model = GPT(vocab=VOCAB, context=1024, layers=LAYERS, heads=HEADS, d=D, dropout=0).cuda().train()
x = torch.randint(0, VOCAB, (1, 64), device='cuda')
y = torch.randint(0, VOCAB, (1, 64), device='cuda')
try:
with sdpa_kernel(SDPBackend.MATH):
logits = model(x)
loss = F.cross_entropy(logits.reshape(-1, VOCAB), y.reshape(-1))
loss.backward()
base_loss = float(loss.item())
reference = {n: p.grad.detach().cpu().clone() for n, p in model.named_parameters()}
raw_logits = logits.detach().float()
base_logits = raw_logits.clone().requires_grad_()
padded_logits = torch.cat((raw_logits, torch.zeros_like(raw_logits[:, :, :47])), dim=-1).requires_grad_()
mask = torch.arange(50304, device='cuda') >= VOCAB
masked = padded_logits.masked_fill(mask, float('-inf'))
baseline_loss = F.cross_entropy(base_logits.reshape(-1, VOCAB), y.reshape(-1))
padded_loss = F.cross_entropy(masked.reshape(-1, 50304), y.reshape(-1))
a, = torch.autograd.grad(baseline_loss, base_logits)
b, = torch.autograd.grad(padded_loss, padded_logits)
loss_err = abs(baseline_loss.item() - padded_loss.item())
grad_err = (a - b[:, :, :VOCAB]).abs().max().item()
pad_grad_err = b[:, :, VOCAB:].abs().max().item()
assert loss_err < 1e-6 and grad_err < 1e-6 and pad_grad_err == 0.0
del logits, loss, raw_logits, base_logits, padded_logits, masked, a, b
rows, errors = [], []
for label, backend in [('BF16 math', SDPBackend.MATH), ('BF16 cuDNN', SDPBackend.CUDNN_ATTENTION), ('BF16 flash', SDPBackend.FLASH_ATTENTION)]:
try:
model.zero_grad(set_to_none=True)
with sdpa_kernel(backend), torch.autocast('cuda', dtype=torch.bfloat16):
logits = model(x)
loss = F.cross_entropy(logits.reshape(-1, VOCAB), y.reshape(-1))
loss.backward()
numerator, denominator, maximum = 0.0, 0.0, 0.0
for name, param in model.named_parameters():
actual = param.grad.detach().cpu()
delta = actual - reference[name]
numerator += delta.double().square().sum().item()
denominator += reference[name].double().square().sum().item()
maximum = max(maximum, delta.abs().max().item())
rows.append({'name': label, 'loss': loss.item(), 'loss_absolute_difference': abs(loss.item() - base_loss),
'gradient_max_absolute_difference': maximum,
'gradient_relative_l2_difference': (numerator/denominator)**0.5})
del logits, loss
except (RuntimeError, NotImplementedError) as exc:
errors.append({'name': label, 'error': repr(exc)})
result = {'torch_version': torch.__version__, 'cuda_version': torch.version.cuda,
'gpu': torch.cuda.get_device_name(), 'model_code_sha256': source_hash,
'context': 64, 'batch': 1, 'vocab': VOCAB, 'dropout': 0,
'tf32': False, 'reference': 'float32 SDPA math', 'reference_loss': base_loss,
'padding_loss_difference': loss_err, 'padding_original_gradient_max_difference': grad_err,
'padding_extra_gradient_max': pad_grad_err, 'comparisons': rows, 'errors': errors}
print(json.dumps(result, ensure_ascii=False, indent=2), flush=True)
(HERE/'correctness.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
finally:
del model, x, y
gc.collect(); torch.cuda.empty_cache()
def matmul_probe(n=4096, inner=10, repeats=7):
a = torch.randn(n, n, device='cuda', dtype=torch.bfloat16)
b = torch.randn(n, n, device='cuda', dtype=torch.bfloat16)
try:
for _ in range(inner):
a @ b
samples = []
for _ in range(repeats):
torch.cuda.synchronize(); start = time.perf_counter()
for _ in range(inner):
a @ b
torch.cuda.synchronize(); samples.append(time.perf_counter() - start)
rate = inner*2*n**3/statistics.median(samples)
peak = peak_bf16_flops()
print(f'Pico BF16 denso supuesto: {peak/1e12:.2f} TFLOPS ({torch.cuda.get_device_properties(0).multi_processor_count} SM a {BOOST_MHZ:.0f} MHz)')
print(f'Producto BF16 {n}x{n} medido: {rate/1e12:.2f} TFLOPS, {100*rate/peak:.0f} % del pico supuesto', flush=True)
return rate
finally:
del a, b
torch.cuda.empty_cache()
def reference_table():
recorded = json.loads((ROOT/'src/widgets/p06/l05/measured-runs.json').read_text(encoding='utf-8'))
source = model_definition()[1]
same = all(r['config']['model_code_sha256'] == source for r in recorded['runs'])
print('Celda de p06-l03 idéntica a la medida:', same)
print(recorded['gpu'], 'PyTorch', recorded['torch_version'], '| pico supuesto',
f'{peak_bf16_flops(sms=24)/1e12:.2f} TFLOPS | microlote 1, contexto 1024')
show_table(recorded['runs'], sms=24)
print('Errores registrados:', [e['name'] for e in recorded['errors']])
def recompile_demo():
def f(x):
return F.gelu(x)*2 + 1
for dynamic in (False, None):
torch._dynamo.reset()
g = torch.compile(f, dynamic=dynamic)
times = []
for t in (256, 512, 256, 768, 1024):
x = torch.randn(8, t, D, device='cuda')
torch.cuda.synchronize(); start = time.perf_counter()
g(x); torch.cuda.synchronize()
times.append(f'T={t}: {time.perf_counter() - start:.3f} s')
print(f'dynamic={dynamic}:', ', '.join(times), flush=True)
torch._dynamo.reset()
def copy_benchmark():
host = torch.randint(0, VOCAB, (8, 1025), dtype=torch.int64)
pinned = host.pin_memory()
device = torch.empty_like(host, device='cuda')
results = {}
try:
for label, source in [('paginable', host), ('fijada', pinned)]:
for _ in range(10):
device.copy_(source, non_blocking=True)
torch.cuda.synchronize()
samples = []
for _ in range(30):
torch.cuda.synchronize()
start = time.perf_counter()
device.copy_(source, non_blocking=True)
torch.cuda.synchronize()
samples.append(time.perf_counter() - start)
results[label] = {'bytes': source.numel()*source.element_size(),
'median_microseconds': 1e6*statistics.median(samples)}
assert torch.equal(device.cpu(), host)
print(json.dumps(results, ensure_ascii=False), flush=True)
(HERE/'copy.json').write_text(json.dumps(results, indent=2), encoding='utf-8')
finally:
del device, pinned, host
torch.cuda.empty_cache()
def gpu_busy_fraction(prof, window='paso'):
"""Fracción del intervalo `window` en que hay al menos un kernel o copia en la GPU."""
events = prof.events()
span = next(e for e in events if e.name == window and e.device_type == torch.autograd.DeviceType.CPU).time_range
pieces = sorted((max(e.time_range.start, span.start), min(e.time_range.end, span.end)) for e in events
if e.device_type == torch.autograd.DeviceType.CUDA and e.name != window
and e.time_range.end > span.start and e.time_range.start < span.end)
busy, cur_start, cur_end = 0.0, None, None
for s, e in pieces: # unión de intervalos: los kernels solapados cuentan una vez
if cur_end is None or s > cur_end:
if cur_end is not None:
busy += cur_end - cur_start
cur_start, cur_end = s, e
else:
cur_end = max(cur_end, e)
if cur_end is not None:
busy += cur_end - cur_start
return busy/(span.end - span.start), len(pieces), (span.end - span.start)/1e3
def profile():
GPT, _ = model_definition()
model = GPT(vocab=VOCAB, context=1024, layers=LAYERS, heads=HEADS, d=D, dropout=0).cuda().train()
opt = torch.optim.AdamW(model.parameters(), lr=0.0003, fused=True)
x = torch.randint(0, VOCAB, (1, CONTEXT), device='cuda'); y = x.clone()
cfg = {'vocab': VOCAB, 'bf16': True, 'tf32': True, 'flash': False, 'cudnn': True, 'fused': True}
try:
for _ in range(2):
training_step(model, opt, x, y, cfg)
torch.cuda.synchronize()
with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA]) as prof:
with torch.profiler.record_function('paso'):
training_step(model, opt, x, y, cfg)
torch.cuda.synchronize()
table = prof.key_averages().table(sort_by='self_cuda_time_total', row_limit=10)
print(table, flush=True)
busy, count, ms = gpu_busy_fraction(prof)
print(f'Paso de {ms:.1f} ms con {count} kernels y copias: GPU ocupada el {100*busy:.0f} % del tiempo', flush=True)
(HERE/'profiler.txt').write_text(table, encoding='utf-8')
prof.export_chrome_trace(str(HERE/'trace.json'))
finally:
del model, opt, x, y
gc.collect(); torch.cuda.empty_cache()
def find_max_microbatch():
"""Duplica el microlote hasta que no cabe en el presupuesto, con y sin recomputación.
Cada prueba acumula dos microlotes: desde el segundo, los gradientes completos (0.5 GB)
ya existen durante toda la pasada, y ese es el pico del régimen de acumulación."""
rows = []
for use_checkpoint in (False, True):
cfg = {'vocab': 50304, 'bf16': True, 'tf32': True, 'flash': False, 'cudnn': True, 'fused': True,
'checkpoint': use_checkpoint}
batch = 1
while batch <= 64:
name = f'microlote {batch}' + (' con recomputación' if use_checkpoint else '')
try:
rows.append(run_case(name, cfg, warmups=1, repeats=2 if QUICK else 3, accum=2, batch=batch))
except torch.cuda.OutOfMemoryError:
print(f'{name}: no cabe en {BUDGET_GB} GB', flush=True)
break
batch *= 2
(HERE/'microbatch.json').write_text(json.dumps(rows, ensure_ascii=False, indent=2), encoding='utf-8')
for r in rows:
print(f"{r['name']:32s} {r['tokens_per_second']:8.0f} tokens/s MFU {100*r['mfu']:5.1f} % pico {r['peak_memory_bytes']/1e9:.2f} GB")
best = max(rows, key=lambda r: r['tokens_per_second']) if rows else None
print('Más rápido dentro del presupuesto:', best['name'] if best else 'ninguno', flush=True)
return best
def memory_fit(best):
if best is None:
raise RuntimeError(f'Ningún microlote de {CONTEXT} tokens cabe en {BUDGET_GB} GB')
keys = ('vocab', 'bf16', 'tf32', 'flash', 'cudnn', 'fused', 'checkpoint')
cfg = {k: best['config'][k] for k in keys}
batch = best['config']['batch']
accum = EFFECTIVE_TOKENS // (batch*CONTEXT)
assert batch*CONTEXT*accum == EFFECTIVE_TOKENS
if QUICK:
accum = min(accum, 4) # a partir de dos microlotes, el pico no depende de cuántos se acumulan
# un paso de calentamiento con un solo microlote: sin él, los momentos de AdamW (1 GB) aún
# no existen durante la primera retropropagación y el pico saldría por debajo del real
record = run_case(f'{batch} x {CONTEXT} tokens, {accum} microlotes', cfg, warmups=1, repeats=1,
accum=accum, batch=batch, warmup_accum=1)
assert record['peak_memory_bytes'] < BUDGET_GB*1e9
(HERE/'fit.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
print(f"Actualización de {batch*CONTEXT*accum} tokens en {batch*CONTEXT*accum/record['tokens_per_second']:.1f} s; "
f"pico {record['peak_memory_bytes']/1e9:.2f} GB < {BUDGET_GB} GB", flush=True)
accumulation_check()
if torch.cuda.is_available():
apply_budget()npm run lab and open the connection link.The first check uses a tiny GPT on CPU without dropout: the gradient of two microbatches, with each loss divided by two, matches the full-batch gradient up to rounding. This applies the previous theorem to real code.
correctness()npm run lab and open the connection link.This test uses the complete GPT, one fixed batch of 64 tokens, shared weights, and TF32 disabled. It compares loss and relative error of all gradients against a float32 mathematical-attention reference for each available backend. It also adds 47 masked logits and verifies that loss and gradients do not change and the added rows receive exactly zero gradient. This is evidence for that batch, not a universal bound.
matmul_probe()npm run lab and open the connection link.A matrix product is the most favorable case for Tensor Cores, with much arithmetic per byte read. The measurement is a practical ceiling for training on your GPU, and its ratio to assumed peak shows whether your laptop clock is below or above 2370 MHz.
suite()npm run lab and open the connection link.The suite warms up, measures the median of synchronized repetitions, and saves runs.json with throughput, MFU, peak memory, and full configuration for each row; failed attempts go to errors. The waterfall widget accepts this file: load it to see your own measurements.
reference_table()npm run lab and open the connection link.This cell prints the lesson’s complete reference run, shown in the figure, with MFU computed using the 29.12 TFLOPS peak. Quick-mode results are not comparable: at context 256 attention has less weight and each kernel performs less work. With a complete run, you should reproduce the order and approximate ratios: cuDNN as the largest jump, fused AdamW as the second gain without compilation, no appreciable effect from padding, and around threefold total improvement. The cell also reports whether the p06-l03 cell matches the one measured. The reference used an earlier revision of that cell; with the current one, compiled configuration peak memory is 2755824128 bytes versus the recorded 2755037696, a 0.03% difference, so the measured model performs the same work.
recompile_demo()npm run lab and open the connection link.With dynamic=False, each new length pays for full compilation and repeating is instantaneous. With the default, the second distinct shape triggers recompilation with symbolic dimensions and later shapes no longer compile. The waterfall model always uses the same shape and compiles once.
copy_benchmark()npm run lab and open the connection link.profile()npm run lab and open the connection link.The profiler table orders operations by self CUDA time. Do not add rows from operator hierarchies as though they were independent times, and discard annotations such as paso and Optimizer.step#AdamW.step, which span kernels already counted elsewhere and distort percentages. Two rows merit attention. The fused AdamW kernel reads and writes the weight, gradient, and two moments for each parameter, about 28 bytes or 3.48 GB per step. In the short verification run it took 15.8 ms, around 220 GB/s, so it runs at memory bandwidth and costs the same for 1024 tokens as for 500000. Accumulation amortizes that cost. The aten::copy_ row groups autocast weight conversions to BF16 and the contiguous transpose copy GPTLinear makes every pass, the cost of p06-l03’s exact parity: there were 486 copies in that run. Fusing or avoiding copies is part of what torch.compile can do. The last line calculates from trace events the fraction of the step during which the GPU has at least one kernel or copy in progress. Far below 100%, there are gaps when the GPU waits. Open trace.json in Perfetto to identify the cause: if the CPU lane launches kernels continuously and barely stays ahead of the GPU, launch is the bottleneck; if the CPU is blocked on synchronization or a copy, the cause differs. Remedies are those in the waterfall: fewer kernels through compilation and fused AdamW, and more work per kernel through larger microbatches.
best = find_max_microbatch()npm run lab and open the connection link.The search doubles microbatch until the allocator throws OutOfMemoryError within budget, first without recomputation and then with it, always accumulating two microbatches, and chooses the fastest configuration that fits. The short verification run, context 256 and 3 GB budget, so its rates are not comparable to reference, illustrates the trade-off: without recomputation only microbatch 1 fit, peaking at 2.65 GB; with recomputation, 2 fit at 2.44 GB and was fastest because doubling work per kernel more than compensated for recomputation. With 7.5 GB and context 1024, the memory-section estimate predicts around four sequences without recomputation and more with it. Your run will show how many fit and whether a larger microbatch still pays off.
memory_fit(best)npm run lab and open the connection link.The final update accumulates microbatches with the selected configuration, divides each loss by , and takes one AdamW step. It repeats the same synthetic batch because it measures capacity and time rather than learning. The allocator imposes the budget, so the final assertion that peak is below 7.5 GB holds by construction if the cell completes. At 11717 tokens per second, one 524288-token update takes about 45 s. This is the rate p06-l06 uses to plan long pretraining.
Exercises
def measure(step, tokens, warmup, repeats, sync, timer):
passSummary
An optimization is worthwhile if it preserves the objective function and improves a repeatable measurement: synchronized intervals, warmup outside timing, median, and one changed configuration at a time. MFU, , places each configuration relative to the GPU’s dense BF16 peak, 29.12 TFLOPS on the RTX 4060 Laptop. The waterfall rises from 10.3% to 34.6%, mainly through fused attention, fused AdamW, and compilation. Memory has a fixed portion of 16 bytes per parameter and another proportional to microbatch, dominated by activations and logits. Search for maximum microbatch by measuring; accumulation, dividing each loss by , reproduces the effective half-million-token batch without placing it entirely on the GPU.