Launch overhead and CUDA Graphs
Measure decode launch overhead, compile the step and capture CUDA Graphs using fixed shapes and preallocated cache, then compare throughput with a bandwidth reference.
After this lesson you can
- Measure CPU and GPU time per decode step with torch.profiler.
- Make decode-step shapes static with a preallocated cache.
- Capture and replay the step with CUDA Graphs and torch.compile reduce-overhead mode.
- Compare throughput against the roofline bandwidth bound.
Before you start
When the device waits
A GPU can finish a kernel before Python and the runtime prepare the next one. A batch-one decoding step has many small operations: projections, normalizations, masking, attention and MLP in each layer. Launch overhead appears in a trace as gaps between kernels, but a gap alone does not prove Python is the only cause. The profiler, synchronization, transfers and other tasks also affect scheduling.
In the measured SmolLM2-135M BF16 run, the profiled step region took 127.8 ms in eager and 12.1 ms with a graph; instrumentation adds cost. The union of kernel intervals between the first and last kernel occupied 3.4% in eager and 79.8% with the graph. This measures time with at least one kernel active, not utilization of all compute units or bandwidth. One trace on a shared GPU does not establish a stable distribution.
The CPU band shows CUDA runtime calls, not all Python work. The GPU band shows observed kernel intervals grouped into 160 segments. Intensity uses a nonlinear scale to reveal small fractions; a partially colored segment summarizes its occupied fraction, and multiple kernels can overlap inside it. Regions begin at the start of each run’s annotation, and the axis is time, not alignment between equivalent operations. The compiled trace comes from another run: it took 89.7 ms under the profiler and showed 543 kernels; the backend had skipped CUDA Graphs due to input mutation. A profile suggests hypotheses; unprofiled measurement checks effective cost.
With 24 layers, 15 kernels per layer and 8 microseconds per launch, the simplified calculation is microseconds, or 2.88 ms. This value should not always be added to GPU time: CPU and GPU can overlap. Launches also need not have equal cost. Measure CPU, GPU intervals and end-to-end latency under the same load.
Fixed shape with variable content
CUDA Graph decoding captures a sequence of operations and replays it as a unit. Input and output tensors retain their addresses and shapes; their contents are updated before each replay. The example uses a preallocated 32-position cache per layer, a fixed mask and a position held in a CUDA tensor. The position value changes, but the tensor and shapes do not.
Position is not incidental. RoPE must use the token’s absolute position and attention must read only valid positions. Indexing the entire capacity without a mask can let still-empty positions contaminate output. Passing position as a Python integer can cause a compiler to specialize the graph for each value; a tensor changes data without creating a new shape. Even so, operations converting that tensor to a Python scalar can introduce synchronization or break capture.
In the lab cache, each layer stores K and V with batch by KV heads by capacity by dimension shape. For one token, write at the tensor-indicated position and use a mask excluding all later positions. The cache is initialized to zeros so even unwritten values are finite. The mask, not those zeros, prevents softmax from treating them as context. Before each new request, clear or replace state and restore the initial position.
The example writes K and V with index_copy_ and builds a fixed-length mask from the position tensor. Attention still processes all capacity: this helps capture but can do unnecessary work. An engine can capture several capacities or batches and choose a compatible graph. Changing batch shape, precision or captured buffer address requires another graph or a compatible buffer strategy; copying a new same-shaped batch into a buffer does not change structure.
Capture, verify and measure
Before capture, warm operations on a side stream and synchronize with the main stream. Then restore initial cache state, capture the step and restore it again before comparison with eager. The graph uses its own buffer set; both paths receive the same IDs and positions. Graph output is overwritten at the next replay, so copy it if it must be retained.
During capture PyTorch may allocate temporary tensors from a graph-associated pool; the rule is not that no operation may create a tensor. The sequence must be capture-compatible and necessary addresses and resources must remain valid for replay. Operations with CPU synchronization, data-dependent branches or incompatible allocations and libraries need attention. The PyTorch CUDA guide explains restrictions and stream use.
Warmup also has state: a step can write cache and leave a position occupied. Restoring state before capture and comparison avoids attributing a difference caused by different inputs to the graph. With multiple concurrent requests, every replay needs a clear buffer ownership policy. Reusing the same graph and tensors while another request still uses them can mix results even when each individual launch is correct.
The lab replays four steps on the pinned p10-l02 checkpoint and checks all logits bitwise between eager and graph. Four inputs do not establish universal equivalence; extend testing to other positions, lengths, batches and edge cases. Comparing only argmax is insufficient because different logits can choose the same token. The test does not compare precision variants or validate arbitrary cache implementations.
Full-step torch.compile with reduce-overhead was also tested: the first call took 106.7 s and a later series averaged 54.0 ms per step in that run. The compiler warned it skipped CUDA Graphs because cache inputs were mutated. Maximum logit difference from eager was 0.3125 in BF16 and the greedy token matched; tolerance atol=0.5, rtol=0.05 was used. That broad tolerance and one input limit the conclusion: compilation worked in the test but does not itself validate application precision.
An explicit capture of the compiled step retained logits and cache bitwise over four steps versus the same compiled step without capture. With grouped Q/K/V and gate/up projections, another run observed 6.76 ms per step, 147.95 steps/s and a 99.34 GB/s copy reference: 40.1% of the weight bound. Grouped versus separate projections differed by up to 0.546875 logits over six BF16 steps, although the greedy token matched; the same broad tolerance was used. The variant has not been shown to preserve outputs universally or meet the 50% target.
Without the profiler, one run observed medians of 74.39 ms for eager and 8.98 ms for graph, repeating the same token and position. This is 111.3 steps per second for the captured case, not full-service throughput. In that run a large copy read and wrote at an effective 107.05 GB/s, counting both directions; dividing by 269030016 BF16 weight bytes gives an ideal reference of 397.9 steps/s if weights are read once per step. The observed result was 28.0% of that reference and did not reach the 50% target. The copy is not a universal ceiling and measurements vary with load; they also exclude all cache bytes and do not guarantee exactly one weight read.
The difference between profiled GPU interval and wall-time median illustrates why the timer must be named. A copy counting reads and writes can differ from sustainable weight-read bandwidth. The roofline model is a bound conditional on traffic and hardware; comparing ratios without stating the measurement implies false precision. Evaluating the target needs controlled repeats and the same bandwidth, model and precision definitions.
The block permits P10_L03_SDPA=1 to replace explicit attention with SDPA. In another run, six prefill steps gave the same greedy token but logit differences up to 0.5 versus explicit attention, with tolerance atol=0.5, rtol=0.05; that variant’s graph matched its own eager version bitwise. The observed rate was 25.3% of its copy reference. This short test, broad tolerance and shared load do not establish improvement or general equivalence.
Compilation and fusion
torch.compile(mode="reduce-overhead") attempts to reduce execution cost and may use CUDA Graphs when conditions hold. Compilation and warmup are measured separately; a slow first step must not be mixed with steady state. Fusion can reduce kernels but also change operation order and rounding. Check logits with explicit tolerance and tokens, and record specializations and recaptures. torch.compile documentation describes the mode and options.
Passing a different Python integer position at every token can cause a new specialization each step. A position tensor avoids that particular cause, though other shape, dtype, device or state guards remain. If recompilation occurs, inspect guard logs and test one variable at a time. Capture and compilation do not necessarily speed up a step dominated by weight reads or a large operation.
A reasonable comparison retains compilation and steady-state time. For a short request, initial cost can exceed all savings; in a persistent server it can be amortized across many calls if the same specialization is reused. Changing cache capacity or batch size may require another compiled and captured variant, which also uses memory. Count variants and reuse rate before extrapolating best-case results to variable shapes.
Local lab
The block loads the same SmolLM2-135M revision as p10-l02 using PyTorch, Transformers and CUDA. It needs the cached checkpoint; a first download can use local_files_only=False and a connection. It builds explicit BF16 attention and fixed-capacity cache, compares four steps and records Chrome traces. Set P10_L03_TRACE_DIR to select the output directory; otherwise it creates a temporary one and shows its path. Measurement repeats the same token and position to isolate the step, rather than generating a growing sequence.
import json, math, os, statistics, tempfile, time, torch
import torch.nn.functional as F
from transformers import AutoModelForCausalLM,AutoTokenizer
torch.set_num_threads(1);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
assert torch.cuda.is_available();device='cuda';MODEL='HuggingFaceTB/SmolLM2-135M';REV='93efa2f097d58c2a74874c7e644dbc9b0cee75a2'
tok=AutoTokenizer.from_pretrained(MODEL,revision=REV,local_files_only=True)
ref=AutoModelForCausalLM.from_pretrained(MODEL,revision=REV,local_files_only=True,dtype=torch.bfloat16,attn_implementation='eager').eval().cuda();cfg=ref.config
W=dict(ref.state_dict());W.setdefault('lm_head.weight',W['model.embed_tokens.weight']);L=cfg.num_hidden_layers;HQ=cfg.num_attention_heads;HKV=cfg.num_key_value_heads;D=cfg.hidden_size//HQ;C=32
PACKED=os.environ.get('P10_L03_PACKED')=='1'
if PACKED:
qkv_weights=[torch.cat([W[f'model.layers.{l}.self_attn.{name}_proj.weight'] for name in ('q','k','v')],0) for l in range(L)]
gateup_weights=[torch.cat([W[f'model.layers.{l}.mlp.{name}_proj.weight'] for name in ('gate','up')],0) for l in range(L)]
theta=getattr(cfg,'rope_parameters',None) or {};base=theta.get('rope_theta',10000.0);freq=1/base**(torch.arange(0,D,2,device=device,dtype=torch.float32)/D)
positions=torch.arange(C,device=device);angles=torch.outer(positions.float(),freq);angles=torch.cat([angles,angles],-1);cos_table=angles.cos().to(torch.bfloat16);sin_table=angles.sin().to(torch.bfloat16)
def new_cache():
return [(torch.zeros(1,HKV,C,D,device=device,dtype=torch.bfloat16),torch.zeros(1,HKV,C,D,device=device,dtype=torch.bfloat16)) for _ in range(L)]
def copy_cache(source,target):
for (a,b),(c,d) in zip(source,target):c.copy_(a);d.copy_(b)
def norm(x,w):
xf=x.float();return (xf*torch.rsqrt(xf.square().mean(-1,keepdim=True)+cfg.rms_norm_eps)).to(x.dtype)*w
def rotate(x):
a,b=x.chunk(2,-1);return torch.cat((-b,a),-1)
def step(token,pos,cache):
x=F.embedding(token,W['model.embed_tokens.weight']);cos=cos_table.index_select(0,pos)[None,None];sin=sin_table.index_select(0,pos)[None,None]
blocked=positions[None,None,None,:]>pos.reshape(1,1,1,1)
for l in range(L):
p=f'model.layers.{l}.';h=norm(x,W[p+'input_layernorm.weight'])
if PACKED:
q,k,v=F.linear(h,qkv_weights[l]).split([HQ*D,HKV*D,HKV*D],dim=-1)
else:
q=F.linear(h,W[p+'self_attn.q_proj.weight']);k=F.linear(h,W[p+'self_attn.k_proj.weight']);v=F.linear(h,W[p+'self_attn.v_proj.weight'])
q=q.view(1,1,HQ,D).transpose(1,2);k=k.view(1,1,HKV,D).transpose(1,2);v=v.view(1,1,HKV,D).transpose(1,2)
q=q*cos+rotate(q)*sin;k=k*cos+rotate(k)*sin
cache[l][0].index_copy_(2,pos,k);cache[l][1].index_copy_(2,pos,v)
keys=cache[l][0].repeat_interleave(HQ//HKV,1);values=cache[l][1].repeat_interleave(HQ//HKV,1)
if os.environ.get('P10_L03_SDPA')=='1':
context=F.scaled_dot_product_attention(q,keys,values,attn_mask=~blocked)
else:
scores=([email protected](-1,-2))/math.sqrt(D);scores=scores.masked_fill(blocked,torch.finfo(scores.dtype).min)
attn=F.softmax(scores,dim=-1,dtype=torch.float32).to(q.dtype);context=attn@values
x=x+F.linear(context.transpose(1,2).reshape(1,1,HQ*D),W[p+'self_attn.o_proj.weight'])
h=norm(x,W[p+'post_attention_layernorm.weight'])
if PACKED:gate,up=F.linear(h,gateup_weights[l]).chunk(2,dim=-1)
else:gate=F.linear(h,W[p+'mlp.gate_proj.weight']);up=F.linear(h,W[p+'mlp.up_proj.weight'])
x=x+F.linear(F.silu(gate)*up,W[p+'mlp.down_proj.weight'])
return F.linear(norm(x,W['model.norm.weight']),W['lm_head.weight']).float()
class GraphedDecoder:
def __init__(self,initial):
self.cache=new_cache();copy_cache(initial,self.cache);self.token=torch.zeros((1,1),device=device,dtype=torch.long);self.pos=torch.zeros((1,),device=device,dtype=torch.long)
side=torch.cuda.Stream();side.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(side):
for _ in range(2):step(self.token,self.pos,self.cache)
torch.cuda.current_stream().wait_stream(side);torch.cuda.synchronize();copy_cache(initial,self.cache)
self.graph=torch.cuda.CUDAGraph()
with torch.cuda.graph(self.graph):self.output=step(self.token,self.pos,self.cache)
copy_cache(initial,self.cache);torch.cuda.synchronize()
def __call__(self,token,pos):
self.token.copy_(token);self.pos.copy_(pos);self.graph.replay();return self.output
def profile(fn,path):
from torch.profiler import profile,ProfilerActivity,record_function
torch.cuda.synchronize()
with profile(activities=[ProfilerActivity.CPU,ProfilerActivity.CUDA]) as p:
with record_function('decode_step'):fn();torch.cuda.synchronize()
p.export_chrome_trace(path)
data=json.load(open(path,encoding='utf8'));events=data['traceEvents'];kernels=[e for e in events if e.get('cat')=='kernel' and e.get('ph')=='X']
if not kernels:return {'kernels':0}
begin=min(e['ts'] for e in kernels);end=max(e['ts']+e['dur'] for e in kernels);intervals=sorted((e['ts'],e['ts']+e['dur']) for e in kernels);union=0.;a,b=intervals[0]
for x,y in intervals[1:]:
if x>b:union+=b-a;a,b=x,y
else:b=max(b,y)
union+=b-a
return {'kernels':len(kernels),'span_us':end-begin,'active_union_us':union,'fraction':union/(end-begin) if end>begin else 0}
@torch.inference_mode()
def main():
print('GPU',torch.cuda.get_device_name(),'modelo',MODEL,'revisión',REV,'BF16 capacidad',C,flush=True)
ids=tok('A small static cache example.',return_tensors='pt').input_ids.to(device)[:,:8];initial=new_cache()
if os.environ.get('P10_L03_SDPA')=='1':
manual=new_cache();fused=new_cache()
for i in range(ids.shape[1]):
pos=torch.tensor([i],device=device);os.environ['P10_L03_SDPA']='0';a=step(ids[:,i:i+1],pos,manual)
os.environ['P10_L03_SDPA']='1';b=step(ids[:,i:i+1],pos,fused);torch.cuda.synchronize()
err=(a-b).abs().max().item();print('SDPA vs atención explícita paso',i,'error',err,'mismo token',int(a.argmax())==int(b.argmax()),flush=True)
assert torch.allclose(a,b,atol=.5,rtol=.05)
for i in range(ids.shape[1]):step(ids[:,i:i+1],torch.tensor([i],device=device),initial)
graph=GraphedDecoder(initial);eager_cache=new_cache();copy_cache(initial,eager_cache);p0=ids.shape[1]
for i in range(4):
token=torch.tensor([[42+i]],device=device);pos=torch.tensor([p0+i],device=device)
a=step(token,pos,eager_cache);b=graph(token,pos).clone();torch.cuda.synchronize();err=(a-b).abs().max().item()
print('paso',i,'error máximo',err,'mismo token',int(a.argmax())==int(b.argmax()),flush=True)
assert torch.equal(a,b)
# Mismo contexto y token en cada repetición, sin muestreo ni selección.
token=torch.tensor([[42]],device=device);pos=torch.tensor([p0],device=device);eager_cache=new_cache();copy_cache(initial,eager_cache)
for _ in range(3):step(token,pos,eager_cache);graph(token,pos)
def bench(fn,reps=12):
values=[]
for _ in range(reps):
torch.cuda.synchronize();t=time.perf_counter();fn();torch.cuda.synchronize();values.append((time.perf_counter()-t)*1000)
return statistics.median(values)
e=bench(lambda:step(token,pos,eager_cache));g=bench(lambda:graph(token,pos));print('mediana ms eager',e,'grafo',g,'tokens/s',1000/g,flush=True)
# Banda de copia: lectura y escritura de 128 MiB, eventos CUDA, no es un techo formal.
x=torch.empty(32*1024*1024,device=device,dtype=torch.float32);y=torch.empty_like(x)
for _ in range(3):y.copy_(x)
torch.cuda.synchronize();start=torch.cuda.Event(enable_timing=True);stop=torch.cuda.Event(enable_timing=True);start.record()
for _ in range(20):y.copy_(x)
stop.record();torch.cuda.synchronize();bw=2*x.numel()*x.element_size()*20/(start.elapsed_time(stop)/1000)
weights=sum(p.numel()*p.element_size() for p in ref.parameters());bound=bw/weights
print('copia efectiva GB/s',bw/1e9,'pesos bytes',weights,'cota pesos tokens/s',bound,'fracción',1000/g/bound,flush=True)
out=os.environ.get('P10_L03_TRACE_DIR') or tempfile.mkdtemp(prefix='p10-l03-');os.makedirs(out,exist_ok=True);print('directorio de trazas',out,flush=True)
try:
before=profile(lambda:step(token,pos,eager_cache),os.path.join(out,'p10-l03-eager.trace.json'))
after=profile(lambda:graph(token,pos),os.path.join(out,'p10-l03-graph.trace.json'))
print('perfil eager',before,'perfil grafo',after,flush=True)
except Exception as error:print('profiler no disponible:',type(error).__name__,str(error)[:500],flush=True)
if __name__=='__main__':main()
npm run lab and open the connection link.The next optional block uses the previous definitions to compile the same full function, compare logits and save a trace. Its first call may take several minutes. The mutated-cache warning must be checked in each environment; the requested mode does not guarantee backend graph capture.
import functools, os, time, torch
torch.set_num_threads(1)
with torch.inference_mode():
ids=tok('A small static cache example.',return_tensors='pt').input_ids.to(device)[:,:8]
initial=new_cache()
for i in range(ids.shape[1]):step(ids[:,i:i+1],torch.tensor([i],device=device),initial)
eager_cache=new_cache();copy_cache(initial,eager_cache);compiled_cache=new_cache();copy_cache(initial,compiled_cache)
token=torch.tensor([[42]],device=device);pos=torch.tensor([ids.shape[1]],device=device)
eager=step(token,pos,eager_cache);torch.cuda.synchronize()
start=time.perf_counter();compiled=torch.compile(functools.partial(step,cache=compiled_cache),mode='reduce-overhead',fullgraph=True)
result=compiled(token,pos);torch.cuda.synchronize();compile_seconds=time.perf_counter()-start
error=(eager-result).abs().max().item();print('compile reduce-overhead segundos primera llamada',round(compile_seconds,2),'error máximo',error,'mismo token',int(eager.argmax())==int(result.argmax()),flush=True)
assert torch.allclose(eager,result,atol=.5,rtol=.05)
for _ in range(2):compiled(token,pos)
torch.cuda.synchronize();start=time.perf_counter()
for _ in range(8):compiled(token,pos)
torch.cuda.synchronize();print('compile milisegundos medios',round((time.perf_counter()-start)*1000/8,3),flush=True)
out=os.environ.get('P10_L03_TRACE_DIR') or tempfile.mkdtemp(prefix='p10-l03-compile-');os.makedirs(out,exist_ok=True)
print('perfil compile',profile(lambda:compiled(token,pos),os.path.join(out,'p10-l03-compiled.trace.json')),flush=True)
The next optional test groups projections, compiles the step and explicitly captures the compiled function. It creates additional grouped-weight copies on GPU and may take several minutes; it checks four steps of logits and cache against the compiled version without graph. Comparison with separate projections uses BF16 tolerance and is not bitwise equality.
PACKED=True
qkv_weights=[torch.cat([W[f'model.layers.{l}.self_attn.{name}_proj.weight'] for name in ('q','k','v')],0) for l in range(L)]
gateup_weights=[torch.cat([W[f'model.layers.{l}.mlp.{name}_proj.weight'] for name in ('gate','up')],0) for l in range(L)]
import functools, os, statistics, time, torch
torch.set_num_threads(1)
with torch.inference_mode():
ids=tok('A small static cache example.',return_tensors='pt').input_ids.to(device)[:,:8];initial=new_cache()
if PACKED:
manual=new_cache();packed=new_cache()
for i in range(ids.shape[1]):
position=torch.tensor([i],device=device);PACKED=False;a=step(ids[:,i:i+1],position,manual)
PACKED=True;b=step(ids[:,i:i+1],position,packed);torch.cuda.synchronize();err=(a-b).abs().max().item()
print('proyecciones agrupadas vs separadas',i,'error',err,'mismo token',int(a.argmax())==int(b.argmax()),flush=True)
assert torch.allclose(a,b,atol=.5,rtol=.05)
for i in range(ids.shape[1]):step(ids[:,i:i+1],torch.tensor([i],device=device),initial)
cache=new_cache();copy_cache(initial,cache);token=torch.tensor([[42]],device=device);pos=torch.tensor([ids.shape[1]],device=device)
compiled=torch.compile(functools.partial(step,cache=cache),mode='reduce-overhead',fullgraph=True)
baseline=compiled(token,pos).clone();torch.cuda.synchronize();copy_cache(initial,cache)
side=torch.cuda.Stream();side.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(side):
for _ in range(2):compiled(token,pos)
torch.cuda.current_stream().wait_stream(side);torch.cuda.synchronize();copy_cache(initial,cache)
graph=torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):output=compiled(token,pos)
copy_cache(initial,cache);graph.replay();torch.cuda.synchronize();error=(baseline-output).abs().max().item()
print('compilado vs compilado+grafo error máximo',error,'iguales',torch.equal(baseline,output),flush=True);assert torch.equal(baseline,output)
prior=new_cache();after=new_cache();copy_cache(initial,cache)
for i in range(4):
token.fill_(42+i);pos.fill_(ids.shape[1]+i);copy_cache(cache,prior)
expected=compiled(token,pos).clone();copy_cache(cache,after);copy_cache(prior,cache);graph.replay();torch.cuda.synchronize()
assert torch.equal(expected,output) and all(torch.equal(k,a) and torch.equal(v,b) for (k,v),(a,b) in zip(cache,after))
print('cuatro pasos compilado vs grafo, logits y caché bit a bit iguales',flush=True)
def bench(fn):
samples=[]
for _ in range(12):
torch.cuda.synchronize();start=time.perf_counter();fn();torch.cuda.synchronize();samples.append((time.perf_counter()-start)*1000)
return statistics.median(samples)
in_token=token.clone();in_pos=pos.clone()
def replay():token.copy_(in_token);pos.copy_(in_pos);graph.replay()
t=bench(replay);x=torch.empty(32*1024*1024,device=device);y=torch.empty_like(x)
for _ in range(3):y.copy_(x)
start=torch.cuda.Event(enable_timing=True);stop=torch.cuda.Event(enable_timing=True);start.record()
for _ in range(20):y.copy_(x)
stop.record();torch.cuda.synchronize();bw=2*x.numel()*x.element_size()*20/(start.elapsed_time(stop)/1000);weights=sum(p.numel()*p.element_size() for p in ref.parameters());roof=bw/weights
print('compilado+grafo mediana ms',t,'tokens/s',1000/t,'copia GB/s',bw/1e9,'cota',roof,'fracción',1000/t/roof,flush=True)
out=os.environ.get('P10_L03_TRACE_DIR') or tempfile.mkdtemp(prefix='p10-l03-packed-');os.makedirs(out,exist_ok=True)
print('perfil compilado+grafo',profile(replay,os.path.join(out,'p10-l03-compiled-graph.trace.json')),flush=True)
Exercises
import torch
class GraphedDecoder:
def __init__(self,fn,example_token,example_pos):
...
def replay(self,token,pos):
...