Review: the arithmetic of training and serving a large model
This opening lesson revisits the roofline model, GPU memory hierarchy, and transformer parameter and FLOP counts from m09 and m18. It turns them into the tools used throughout this module: the C ≈ 6ND rule, MFU, the 16 bytes per parameter for mixed-precision AdamW, and activation memory. It concludes with a taxonomy of bottlenecks: each subsequent technique addresses one of them.
After this lesson you can
- Estimate training FLOPs, GPU-days and cost from N, D, the hardware and an assumed MFU.
- Calculate transformer weight, gradient, optimizer-state and activation memory for a given configuration.
- Measure the actual MFU of the course GPT on the RTX 4060 and explain the gap to peak performance.
- Classify a step's bottleneck from a profiler trace and propose a family of techniques to address it.
Before you start
Before training, do the arithmetic
If you double the number of accelerators, ideal time is halved only if efficiency stays the same. That condition is not free: communication, data loading, and operations other than matrix products take time too. A useful estimate states the work, the chosen peak, and the assumed efficiency explicitly. Moreover, fitting the work into a time budget does not imply that the training state fits in memory.
With parameters and tokens, this lesson’s rule gives FLOPs. With 1024 GPUs at 989 dense TFLOP/s and an assumed MFU of 40%, the ideal time is approximately 2.40 days. This is not a real execution forecast: it excludes failures, evaluation, checkpointing, and changes in efficiency. If each GPU costs per hour, compute costs would be times the number of GPU-days; storage, network, and other charges are excluded.
From matrix multiplication to 6ND
Count a multiplication and an addition as two FLOPs. For with and , the forward pass costs approximately . The backward pass computes and . Each product costs approximately as much as the forward pass, so all three add up to FLOPs per weight in that matrix. The exact count depends on additions, biases, weight use, and whether both gradients are calculated.
The 6ND rule extends this reasoning to dense weights active per token and processed tokens. It is an approximation, not an identity for every architecture. Embedding lookups do not require a multiplication per weight, an output embedding can be tied and still used in a projection, and the and products depend on context length. It also ignores normalization, softmax, the optimizer, and recomputation. In a sparse model, total parameters differ from those active per token.
For full dense attention with layers, heads, head dimension , and length , the two attention products contribute approximately FLOPs per token in the forward pass and in forward plus backward, under the same dense-product assumptions. Efficient causal attention can avoid part of the upper triangle; an implementation that computes the full matrix may not. The expression and scope used in PaLM appear in its appendix B.
GPT-3 table D.1 reports 174.6 billion parameters, 300 billion tokens, and FLOPs for its largest model. Applying gives : it matches the table after rounding because the published calculation itself uses that approximation without attention. It is not a profiler-measured count.
def budget(n, tokens, gpus, peak_flops, mfu):
work = 6*n*tokens
seconds = work/(gpus*peak_flops*mfu)
return work, seconds/86400
print('Ejemplo:', budget(7e9, 2e12, 1024, 989e12, 0.4))
print('GPT-3, 6ND:', 6*174.6e9*300e9)
print('Memoria AdamW, GB decimales:', 16*7e9/1e9)To understand what conceals, count a specific architecture: a decoder of width , blocks, an MLP of width , Q, K, V and output projections of size , affine LayerNorm before each sublayer, projection biases, learned token and position embeddings, and an output head tied to the embedding. Each block has matrix weights and biases and normalization parameters. The code adds embeddings and final normalization without counting the tied weight twice. The output head’s cost is counted: using a shared weight still requires the matmul.
For FLOPs we approximate full dense products, counting two FLOPs per multiply-add and both derivatives in backward. Causal attention can save the upper triangle with a kernel that skips it; here the counter computes the full matrix and omits elementwise operations, masking, input embeddings, and the optimizer. The activation formula follows the Korthikanti model below, which does not necessarily match every detail of this block.
import numpy as np
def decoder_budget(vocab, context, width, layers, batch=1, heads=4):
d, T, L = width, context, layers
if min(vocab,T,d,L,batch,heads) <= 0 or d % heads:
raise ValueError('dimensiones positivas y anchura divisible por cabezas')
parameters = vocab*d + T*d + L*(12*d*d+13*d) + 2*d
# Por token: matrices del bloque, dos productos de atención y cabeza atada.
forward = L*(24*d*d + 4*T*d) + 2*d*vocab
backward = 2*forward
states = {'peso_16': 2*parameters, 'grad_16': 2*parameters,
'maestro_32': 4*parameters, 'momentos_32': 8*parameters}
activations = T*batch*L*(34*d + 5*heads*T)
return parameters, forward, backward, states, activations
params, fw, bw, state, act = decoder_budget(100, 16, 32, 2)
print('parámetros:',params,'FLOPs forward/token:',fw,'backward/token:',bw)
print('estados, bytes:',state)
print('activaciones del modelo citado, bytes:',act)
print('aproximación 6N/token:',6*params,'frente a cuenta:',fw+bw)
assert sum(state.values()) == 16*params
shapes = [(100,32),(16,32)] + 2*[(32,96),(96,),(32,32),(32,),
(32,128),(128,),(128,32),(32,), (32,),(32,),(32,),(32,)] + [(32,),(32,)]
assert sum(np.prod(s) for s in shapes) == params
print('contraste contando formas: correcto')The result differs from : the tied input weight is counted once in , but the head uses it for every token; position embeddings are not matmuls, whereas the and products contain no learned weights. This comparison is meaningful only after stating what each numerator includes.
Peak, roofline, and utilization
A GPU contains multiprocessors that run many threads and specialized units for matrix products. The memory hierarchy separates registers and shared memory close to compute from external memory. GDDR and HBM are different memory technologies; capacity and bandwidth are different quantities. For example, the desktop RTX 4060 specifications list 8 GB GDDR6, while the H100 SXM lists 80 GB and 3.35 TB/s. These are different products and conditions, not timings for a particular program.
The roofline model bounds performance by , where is the applicable peak compute, is bandwidth, and is FLOPs per byte transferred. A large matmul can reuse data in nearby memory and reach high intensity; normalization or an elementwise operation performs little work per datum and often benefits from reducing traffic. The roof is an ideal bound, not a sufficient diagnosis: small sizes, launches, occupancy, and dependencies can reduce performance.
Model FLOPs utilization (MFU) divides useful model throughput, tokens per second multiplied by required FLOPs per token, by the sum of GPU peaks. MFU excludes additional FLOPs from recomputation. Hardware utilization (HFU) also attempts to count work actually executed, including recomputation; it can rise because extra work was done, even without improving tokens per second. Compare the same precision, model definition, and FLOP convention. Table 3 of PaLM reports 46.2% MFU including attention and 57.8% HFU for its 540B model, under its conventions.
The H100 SXM BF16 peak listed by NVIDIA is 1979 TFLOP/s with sparsity; the H100 architecture document gives 989.4 dense TFLOP/s, rounded to 989 in the example. Do not compare dense work with the sparse peak. FLOP/s measures speed; FLOPs measures the amount of work. A measured isolated matmul can also be a practical reference, but it is not necessarily the theoretical peak and cannot be compared without recording shape, dtype, and conditions.
Bytes that persist and bytes that grow with the batch
The anatomy of training memory depends on the recipe. In one mixed-precision implementation with 16-bit weights and gradients, a 32-bit master copy, and two 32-bit AdamW moments, each parameter takes bytes. For 7 billion parameters that is 112 decimal GB: 14 for weights, 14 for gradients, 28 for master weights, and 56 for moments. This excludes activations, buffers, and fragmentation; other implementations may store gradients in FP32, omit a master copy, or shard states.
Activation memory holds what backward needs and depends on sequence length, microbatch, architecture, and kernel. In the model of Korthikanti et al., for their transformer block without parallelism and with the precision and operations assumed by the authors, the per-layer estimate is
where is length, is microbatch size, is width, and is the number of heads. The quadratic term comes from storing attention intermediates. Table 2 of the paper gives for selective recomputation and for full recomputation per layer. These coefficients are not a universal law for every variant, FlashAttention, or PyTorch version: a fused kernel changes which intermediates are materialized, so measure its actual memory. The figure’s total multiplies by and excludes embeddings, loss, buffers, and parallelism.
def activation_memory(s, b, h, a, layers, selective=False, full=False):
if full:
return 2*s*b*h*layers
return s*b*h*layers*(34 if selective else 34+5*a*s/h)
print('Término de atención GPT-3:', 5*96*2048/12288)
print('Activaciones, GB, 96 capas:', activation_memory(2048,1,12288,96,96)/1e9)
print('Recomputación selectiva, GB:', activation_memory(2048,1,12288,96,96,selective=True)/1e9)Diagnose before choosing a technique
The bottleneck taxonomy distinguishes five limits. Compute: large products occupy most of the step and throughput approaches the applicable roof. Bandwidth: low-intensity operations read and write many bytes; fusion can reduce traffic. Capacity: an allocation fails or peak allocation exceeds memory; fragmentation and temporaries matter too. Communication: collectives or transfers lie on the critical path; inspect overlap and topology. Overhead: gaps between kernels and CPU or input work can leave the GPU idle.
A trace shows temporal correlation; it does not by itself explain the whole cause. Compare CPU and GPU events, synchronizations, copies, kernel names, and memory; use hardware counters if you need to distinguish bandwidth limits from low occupancy. Accumulation and recomputation address capacity with time tradeoffs; fused kernels address traffic and launches; parallelism distributes memory and compute in exchange for communication; serving and compression change the inference budget. The profiler gives the capture procedure.
The next three traces come from a real SGD training step of a synthetic linear layer, captured on an RTX 3060 with PyTorch 2.11.0+cu128 under shared load. In A the layer is 1024 by 1024; in B and C it is 128 by 128. B inserts 25 sine operations in the forward pass and C adds an artificial 25 ms wait before training. CPU markers correspond to explicit regions; the GPU track includes individual events and distinguishes names containing gemm. The figure preserves relative times and widens events too short to see to one pixel. These are teaching examples, not GPT profiles or evidence of hardware saturation.
The next cell reproduces the capture with the same three workloads and saves trace files in the current directory. Times, gaps, and kernel names vary with version, device, and load. Exporting a trace lets you study ordering and concurrency, but a step’s CPU annotation can end before the asynchronous kernels it launched; they are therefore shown separately.
import time, torch
from torch.profiler import profile, ProfilerActivity, record_function
assert torch.cuda.is_available(), 'se necesita CUDA'
torch.manual_seed(21)
for kind in ('matmul','kernels','entrada'):
n = 1024 if kind == 'matmul' else 128
model = torch.nn.Linear(n,n,device='cuda')
opt = torch.optim.SGD(model.parameters(),lr=1e-4)
x = torch.randn(n,n,device='cuda')
def step():
if kind == 'entrada':
with record_function('espera_de_datos_del_ejemplo'):
time.sleep(.025) # demora didáctica, no una medición de disco
opt.zero_grad(set_to_none=True)
with record_function('entrenamiento'):
y = model(x)
if kind == 'kernels':
for _ in range(25): y = torch.sin(y)
y.square().mean().backward()
opt.step()
step(); torch.cuda.synchronize()
with profile(activities=[ProfilerActivity.CPU,ProfilerActivity.CUDA]) as prof:
step(); torch.cuda.synchronize()
prof.export_chrome_trace(f'traza-{kind}.json')
events = [e for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA
and not e.is_user_annotation]
print(kind,'eventos GPU:',len(events),'suma de duraciones µs:',
round(sum(e.time_range.elapsed_us() for e in events),1))npm run lab and open the connection link.The figure uses five pairs of real events from a trace published by HolisticTraceAnalysis, not from the local GPU. The file declares NCCL backend, rank 0, and 64 ranks; each CPU nccl:all_reduce operation and GPU ncclKernel_AllReduce_TREE_LL_Sum_float kernel is paired by its external identifier. In the trace-event format, ts and dur are in microseconds; the CPU start is subtracted to draw relative intervals. Bars have a minimum visible width of 2 pixels, so the readouts give exact durations.
In the fifth pair, the CPU event lasts 94 µs; the kernel starts 2844 µs after the CPU start and lasts 12424 µs. Examining that window reveals no other overlapping Kernel event on device 0, but this alone does not prove the network is the bottleneck: the other ranks, dependencies, and counters are missing. In the fourth pair the kernel starts before the CPU event ends. These are distinct facts from one trace, not a rule about every collective.
This local control profiles two isolated patterns, not the GPT from the previous lesson: a matmul and a chain of elementwise operations. The output lists observed operations and their device time in that run. Nested events can attribute the same work to multiple names, so do not add that column as if its intervals were disjoint. It does not assume that the slowest operation is always the bottleneck of full training. Investigating communication requires a distributed run and a trace of its collectives.
import torch
from torch.profiler import profile, record_function, ProfilerActivity
assert torch.cuda.is_available(), 'se necesita CUDA'
print('GPU:', torch.cuda.get_device_name(), 'PyTorch:', torch.__version__)
torch.manual_seed(4)
x = torch.randn(512,1024,device='cuda',dtype=torch.float32)
w = torch.randn(1024,1024,device='cuda',dtype=torch.float32)
for _ in range(3):
warm = x @ w
torch.cuda.synchronize()
with profile(activities=[ProfilerActivity.CPU,ProfilerActivity.CUDA],record_shapes=True) as prof:
with record_function('matmul_grande'):
y = x @ w
with record_function('elementales_encadenadas'):
z = x
for _ in range(20):
z = torch.sin(z)
torch.cuda.synchronize()
for event in sorted(prof.key_averages(),key=lambda e:e.device_time_total,reverse=True)[:8]:
print(event.key, 'llamadas:', event.count, 'tiempo dispositivo total µs:', round(event.device_time_total,1))npm run lab and open the connection link.Now profile a step of the small PyTorch GPT created in lesson 12. Save its “GPT PyTorch y cargadores” cell as gpt_pytorch.py and generate gpt-pytorch-small.pt with the parity cell; you can also supply their paths through environment variables. The batch is a sequence of IDs constructed to measure shapes, not language learning. Here the count includes all parameters, including embeddings and positions, making it an especially imperfect approximation for this small model. FlopCounterMode counts operations for which it has formulas, not necessarily all kernel work or traffic: compare the two figures, but do not expect equality. The profile uses one GPU and contains no NCCL collectives.
import os, time
from pathlib import Path
import torch
from torch.profiler import profile, ProfilerActivity, record_function
from torch.utils.flop_counter import FlopCounterMode
assert torch.cuda.is_available(), 'se necesita CUDA'
scope = {}
torch.backends.cuda.matmul.allow_tf32 = False
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'), scope)
path = Path(os.environ.get('ORYON_GPT_TORCH','gpt-pytorch-small.pt'))
model, chars = scope['load_checkpoint'](path, map_location='cpu')
model = model.float().cuda().train()
opt = torch.optim.AdamW(model.parameters(),lr=1e-4)
batch, length = 4, min(32,model.config['context'])
gen = torch.Generator(device='cuda').manual_seed(13)
x = torch.randint(len(chars),(batch,length),generator=gen,device='cuda')
y = torch.randint(len(chars),(batch,length),generator=gen,device='cuda')
N = sum(p.numel() for p in model.parameters())
def step():
opt.zero_grad(set_to_none=True)
_,loss,_ = model(x,y)
loss.backward()
opt.step()
return loss
for _ in range(2): step()
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
for _ in range(5): step()
end.record(); end.synchronize()
elapsed = start.elapsed_time(end)/1000
rate = 5*batch*length/elapsed
print('GPU:',torch.cuda.get_device_name(),'PyTorch:',torch.__version__,
'TF32 permitido:',torch.backends.cuda.matmul.allow_tf32)
print('parámetros:',N,'tokens/s:',round(rate,1),'estimación 6N en TFLOP/s:',6*N*rate/1e12,
'pico asignado MiB:',round(torch.cuda.max_memory_allocated()/2**20,2))
opt.zero_grad(set_to_none=True)
with FlopCounterMode(display=False) as counter:
_,loss,_ = model(x,y)
loss.backward()
print('FLOPs registrados forward+backward:',counter.get_total_flops(),
'aproximación 6N por lote:',6*N*batch*length)
with profile(activities=[ProfilerActivity.CPU,ProfilerActivity.CUDA],record_shapes=True) as prof:
with record_function('paso_gpt'):
step()
torch.cuda.synchronize()
for event in sorted(prof.key_averages(),key=lambda e:e.device_time_total,reverse=True)[:12]:
print(event.key,'llamadas:',event.count,'tiempo dispositivo µs:',round(event.device_time_total,1))
gpu = [e for e in prof.events() if e.device_type == torch.autograd.DeviceType.CUDA
and not e.is_user_annotation]
total = sum(e.time_range.elapsed_us() for e in gpu)
matmul = sum(e.time_range.elapsed_us() for e in gpu if 'gemm' in e.name.lower())
print('suma de duraciones de eventos GPU µs:',round(total,1),
'fracción fuera de nombres GEMM:',round(1-matmul/total,3) if total else 'sin eventos')npm run lab and open the connection link.The printed fraction classifies kernel names containing “gemm”: it may omit other matrix implementations and includes copies among the remaining events. It sums GPU event durations, not wall time; if events overlap the sum counts both intervals. It guides inspection of this trace, rather than providing an exact breakdown of step time or proving a bottleneck.
To obtain MFU, divide estimated useful throughput by the relevant GPU peak for the operation type, expressed in the same units. Record whether TF32 is allowed or autocast is used, the load from other tasks, and the counting method. The next measurement adds an experimental reference: a square FP32 matmul with TF32 disabled. Its rate is observed performance for that shape, not the device’s theoretical peak; the ratio against it is a relative indicator, not formal MFU. The matmul and GPT step run sequentially, so changing shared load can affect them differently.
import time, torch
assert torch.cuda.is_available(), 'se necesita CUDA'
torch.backends.cuda.matmul.allow_tf32 = False
torch.manual_seed(13)
a = torch.randn(2048,2048,device='cuda',dtype=torch.float32)
b = torch.randn_like(a)
for _ in range(3): c = a @ b
torch.cuda.synchronize()
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
for _ in range(10): c = a @ b
end.record(); end.synchronize()
ms = start.elapsed_time(end)/10
reference = 2*2048**3/(ms/1000)/1e12
print('GPU:',torch.cuda.get_device_name(),'TF32 permitido:',torch.backends.cuda.matmul.allow_tf32)
print('matmul 2048 FP32, ms:',round(ms,3),'TFLOP/s observados:',round(reference,3))
print('Compara con el 6N TFLOP/s de la celda anterior, bajo las mismas condiciones.')npm run lab and open the connection link.One short interval on a shared GPU provides no basis to infer a stable value or compare hardware. The GPT rate above includes the optimizer and uses as an estimate; this isolated product measures only one shape. A stronger reference repeats both intervals under controlled load and uses the published dense peak for the step’s precision to calculate MFU.
In a run on an RTX 3060 with PyTorch 2.11.0+cu128 and TF32 disabled, an earlier version of the step, timed with a CPU clock and synchronization, produced approximately 0.0080 TFLOP/s estimated using , while the isolated matmul reached 4.48 TFLOP/s using CUDA events. Their ratio is approximately 0.18% under shared load and for these shapes; it is not MFU against nominal peak and does not characterize a large model. The counter recorded 85 688 320 FLOPs for forward and backward versus 81 297 408 by for that batch, helping quantify the approximation error in this example. The current cells use CUDA events for both intervals and will produce their own values.
The next control measures peak allocation during forward and backward of the same GPT with SDPA math and Flash forced separately. It uses BF16 autocast and disables dropout to compare gradients; it excludes the optimizer and does not measure traffic. If the binary or shape does not support Flash, it displays the exception and leaves that comparison pending. The result includes activations for the whole model and temporaries, so it is not equivalent to the isolated term in Korthikanti’s formula. The checkpoint and code file are the same as above.
import os
from pathlib import Path
import torch
from torch.nn.attention import SDPBackend, sdpa_kernel
assert torch.cuda.is_available(), 'se necesita CUDA'
scope = {}
exec(Path(os.environ.get('ORYON_GPT_TORCH_CODE','gpt_pytorch.py')).read_text(encoding='utf-8'), scope)
model, chars = scope['load_checkpoint'](Path(os.environ.get('ORYON_GPT_TORCH','gpt-pytorch-small.pt')))
model = model.float().cuda().eval() # dropout apagado; las derivadas siguen activas
torch.manual_seed(13)
x = torch.randint(len(chars),(4,min(32,model.config['context'])),device='cuda')
baseline = None
for backend in (SDPBackend.MATH,SDPBackend.FLASH_ATTENTION):
model.zero_grad(set_to_none=True)
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
before = torch.cuda.memory_allocated()
try:
with sdpa_kernel(backend), torch.autocast('cuda',dtype=torch.bfloat16):
logits,loss,_ = model(x,x)
loss.backward()
torch.cuda.synchronize()
peak = torch.cuda.max_memory_allocated()-before
grads = [p.grad.detach().float().cpu().clone() for p in model.parameters() if p.grad is not None]
out = logits.detach().float().cpu()
print(backend, 'pico adicional MiB:',round(peak/2**20,3),'pérdida:',float(loss))
if baseline is None:
baseline = (out,grads)
else:
err_out=float((out-baseline[0]).abs().max())
err_grad=max(float((a-b).abs().max()) for a,b in zip(grads,baseline[1]))
print('error máximo logits:',err_out,'gradientes:',err_grad)
assert err_out < .05 and err_grad < .05, 'diferencia superior a la tolerancia de este control BF16'
except RuntimeError as exc:
print(backend,'no disponible:',str(exc).splitlines()[0])npm run lab and open the connection link.In a WSL run with the small GPT and BF16, math recorded 1.252 MiB of additional peak allocation and Flash 1.174 MiB; maximum absolute error was 0.015625 for logits and 0.0078125 for gradients. The assertion uses 0.05 as the absolute tolerance for this specific control, not as a general guarantee. These figures are from an RTX 3060 and a small batch and do not extrapolate to large models; Flash was not compiled into the available Windows binary, and the control reported that absence.
Exercises
Step 1 of 3. What does the forward pass cost?
def activation_bytes(s, b, h, a, L, mode):
pass