Baseline, metrics and roofline
Load an open Llama-architecture model into a custom implementation with logit parity, build a naive generation and metrics harness, and analyze prefill and decode through a roofline model.
After this lesson you can
- Load an open Llama model’s weights into the custom implementation with logit parity.
- Implement latency, throughput and memory metrics.
- Calculate prefill and decode arithmetic intensity and locate them on an RTX 4060 roofline.
- Measure the baseline and compare it with a bandwidth bound.
Before you start
- P06Modern Llama-style blockPretrained weight parity test
- 21Inference latency metrics and goodputThroughput-latency tradeoffCost per token model
- 18Prefill and decode phasesAutoregressive generation loop
- 09Roofline modelMemory hierarchyGPU memory hierarchy
- 00Benchmarking methodologyCUDA asynchronous execution
A baseline that can be inspected
A request arrives with a prompt and leaves with a token sequence. Between those endpoints are two distinct jobs. First process the complete prompt; then each new token depends on earlier ones. A naive engine can repeat the full pass over the growing prefix each time. It is simple to check but does redundant work. Before optimizing, we need reference output and a measurement that distinguishes launching operations from completing them.
The Llama block contains RMSNorm, rotary positions and grouped-query attention. Here we want both to reproduce its function and identify execution cost. Logit parity is the first gate: if an optimization changes the model, a speed table does not show the same task was accelerated. Later we separate prefill and decoding with a KV cache; this lesson’s reference generation recomputes the full prefix.
Imagine a large weight matrix used with one input. Every weight participates in a multiplication and addition, but must reach the processor. With many simultaneous inputs, the same matrix can be reused. The figure formalizes this intuition with an idealized product, not observed times. Change size, batch and precision: observe how activation traffic prevents intensity from increasing without limit.
What loading weights correctly means
Loading Llama weights into a custom implementation assigns each checkpoint tensor to its mathematical operation and verifies the resulting function. Matching names or shapes is insufficient. For batch-by-length-by-dimension input, RMSNorm divides each vector by the square root of its mean square plus epsilon and applies a learned scale. It does not subtract the mean. In each block, attention and MLP write to the residual stream after their respective normalizations.
RoPE rotates pairs of query and key coordinates by position. Coordinate order, frequencies, initial position and any scaling must match the reference implementation. In GQA there can be more query than key and value heads: each query group shares one KV head. K and V projections consequently have fewer rows than Q; copying them as if all three had equal shapes or repeating weights on the wrong axis changes the calculation. The causal mask lets the current position see only earlier positions or itself. The MLP uses the gate and activation specified by configuration, not an activation chosen for convenience.
Loading can use the reference implementation’s state_dict, checking keys and shapes rather than ignoring unknown keys. For a downloaded model, record identifier and revision. Tied weights need care: two names can refer to the same logical tensor and serialized state may not contain both copies. The lab fixes effective configuration and explicitly compares custom output with Transformers. No generated token is sufficient proof of parity: sampling can hide a logit difference.
Comparison has two levels. First, structure: for query heads, key and value heads and per-head dimension , Q produces components while K and V each produce . Ratio must be an integer. If K and V are expanded for reference attention, repeat each KV head for its corresponding query group; repeating the entire head sequence changes that association. An optimized implementation can avoid materializing repeats but must compute the same result.
Second, arithmetic: bf16 rounds each operation and different reduction orders can differ. A tolerance test does not make every deviation acceptable. The usual condition compares each component with atol + rtol * abs(referencia), so error near zero depends mainly on absolute tolerance. Also record maximum and mean absolute differences. If only one position fails, check its mask and position first; if the first block already fails, examine normalization and projections before blaming rounding. A systematic orientation error can produce plausible-scale logits while changing the model.
The tokenizer belongs to the input contract. Do not compare two visually identical strings if each model converts them to different IDs. The parity test receives exactly the same integer tensor and avoids padding, so it does not depend on how each implementation interprets positions and masks in padded batches. Extending the test to padding requires separately defining position treatment and checking those cases. In real generation, the conversation template, BOS and EOS can also alter the prefix even when weights and block are correct.
Measuring a service and measuring an operation
The inference metrics harness defines what each timer includes. If is local admission, when the first token is available on CPU and when the last is available, for :
The first interval includes prefill and selection of the first token. TPOT averages the subsequent intervals; it is undefined for one token. The throughput above counts output tokens from request start to finish. Aggregate throughput across requests needs a defined observation window and token count. It is not the inverse of individual latency under concurrency. API-perceived latency may include queueing, network, tokenization and socket writes; a local harness receiving prepared IDs does not measure those. Latency definitions and the latency-throughput tradeoff are comparable only when boundaries match.
CUDA work is asynchronous relative to the CPU. A timer around a call without waiting can measure mostly launch. PyTorch documentation recommends synchronization or correctly synchronized CUDA events. If the goal is token availability on CPU, synchronize before starting and before each timestamp after token selection. Include what is declared in scope: synchronizing each step adds overhead but makes token boundaries observable. CUDA events may be preferable for kernel-only measurement, which answers a different question.
Warm the model and repeat requests; record input and output lengths, batch, precision, device, versions, generation mode and EOS treatment. If one method stops at EOS and another generates a fixed length, denominators are not comparable. Use the same prompts for comparisons. Report the distribution, not only the mean: median and percentiles with enough repetitions show variation hidden by a minimum. Other processes sharing the GPU also affect results.
To understand the measurement window, follow one request. Before there may be prior work and pending allocations; synchronization separates them from the experiment. The first prompt pass begins, a token is selected and selection is awaited: timestamp is taken there. The naive loop concatenates that token to the prefix and reruns the model. Each subsequent step grows the input, so intervals need not be equal. If the program converts a token to text or sends it over the network after the timestamp, that time is excluded from TTFT; state this when presenting the table.
Median request time and a request’s mean time per token are different aggregations. Suppose two requests produce different token counts. Averaging their TPOT weights each request equally; summing all intervals and dividing by the total number of intervals weights longer ones more. Neither is automatically an inter-token latency percentile. Retain individual timestamps to investigate pauses or queues later, and do not present the maximum of a small sample as a service guarantee.
Comparison with another engine must fix the starting point, concurrent request count and warmup period as well as lengths. If one engine uses cache and another does not, that difference may be the subject of study; if precision and model also change, the result cannot be attributed only to cache. Greedy output helps compare sequences, although even a small logit difference near a tie can change the selected token and cause later prefixes to diverge. Therefore compare logits on identical inputs first, then sequences.
PyTorch distinguishes tensor-allocated memory from allocator-reserved memory. max_memory_allocated counts PyTorch allocations since the peak counter was reset, not all device memory or necessarily every library. Reset after warmup and state whether the peak includes resident weights. empty_cache releases unused reserved blocks but not live tensors. After an experiment remove references and free unused cache.
Derive roofline without confusing it with a benchmark
Decode roofline analysis compares arithmetic work with memory traffic. Let be floating-point operations, bytes crossing the chosen memory boundary and operational intensity. If sustainable bandwidth is and applicable compute ceiling is , performance satisfies the model
The crossover is . To the left the traffic ceiling limits rate; to the right the compute ceiling does. The original roofline paper defines intensity by traffic reaching memory after caches and uses sustainable bandwidth. Nominal bandwidth gives an ideal ceiling, not a promise that a program attains it. Compute ceiling must match the precision, operation and units actually used: the FP32 CUDA-core peak is not the bf16 Tensor Core peak.
Consider and , with . Count a multiplication and addition as two FLOPs per term. Approximate work is . Assume weights occupy bytes each and are read once, while input and output activations occupy two bytes per element and are transferred once each. The ideal model is
When weight traffic dominates, : for bf16, , so one row gives approximately one FLOP per byte and 512 rows approximately 512. These approximate one product, not exact transformer intensity. As grows, reading and writing activations is no longer negligible. Cache reuse, matrix fragmentation, other operations, quantization scales and KV traffic also matter. Attention can add a context-dependent term. Four-bit precision in the figure means ideal half-byte weight storage without scale or dequantization cost.
The figure assigns to one projection per step for a batch of cached sequences, and to the prefill projection of length . It does not describe the uncached baseline: there each step reprocesses every prefix token and cost grows with length. Nor does it prove every prefill is compute-bound: a short prompt, inefficient kernel or different ceiling can place it elsewhere. The figure asks which resource could limit a product under its assumptions, not actual whole-engine performance.
The dimension slider changes a representative square matrix, not an architecture’s total parameter count. Two models of the same dimension can have different layer counts and matrix shapes, and therefore different total memory. The graph crossover does not move when the matrix grows: the two chosen ceilings determine it. Changing dimension does change activation bytes relative to weights. This shows why becomes less accurate when is no longer small relative to .
The figure’s initial compute value is an illustrative FP32 CUDA-core assumption. NVIDIA lists 3072 cores and 2.46 GHz boost for the RTX 4060; two operations per core-cycle give approximately 15.1 TFLOP/s. Actual frequency may vary and this calculation does not describe the bf16 Tensor Core ceiling. Set the control to the ceiling relevant to the measured operation. Comparing bf16 intensity with the example FP32 ceiling explores the model but does not determine a real bf16 kernel’s bottleneck.
The vertical axis shows maximum performance allowed by the model, not achieved performance. A point below the line may offer room for improvement, but its distance does not identify the cause. Intensity may be misestimated because of cache or repeated reads; the operation may have too few blocks to occupy the GPU; or execution may spend much time launching small kernels. A profile measuring traffic and compute activity helps distinguish those hypotheses. The ceiling only rules out higher rates under chosen assumptions.
From bytes per step to tokens per second
For a model with active weights, bytes per weight, batch one and one complete weight read from memory per step, weight-traffic time is at least . If one token is produced per step and all other costs are ignored, the ideal bound is tokens per second. That read assumption is essential: if some weights stay cached, actual DRAM traffic may be lower; additional traffic or rereads may make it higher. It is therefore not universal across implementations and memory hierarchies.
The PNY RTX 4060 specification lists 17 Gb/s memory and a 128-bit bus: multiplying and dividing by eight gives 272 decimal GB/s nominal. Capacity is 8 GB; leave room for activations, temporaries and other processes, not only weights. The exercise below explicitly uses a different 256 GB/s assumption. For measured comparison, use actual weight size read, declare the traffic model and divide observed rate by its ideal ceiling. A small ratio alone does not identify the bottleneck: prefix recomputation, launches, achieved bandwidth or other operations may contribute.
Pope and colleagues distinguish input and generation regimes and explicitly study weight and KV-cache movement. Their results concern their models and hardware, not a measurement of this GPU. In particular, KV caching makes state bytes grow with context length and batch. Its effect is absent from the weights-only bound.
An imperfect bound still permits concrete questions. If observed time greatly exceeds one weight read, the ideal model does not explain all cost. One test changes prompt length while fixing other parameters. Without cache, recomputed positions grow every step; with cache, the state read changes size but earlier positions are not projected again. Another test changes batch with equal lengths. Both need repeated measurements and one change at a time to be interpretable.
The weights-only bound also depends on what counts as an active weight. An embedding table accesses only some input rows, while final vocabulary projection can read a complete matrix. If input and output matrices share storage, counting resident memory once does not prove only one read per pass. A full transformer requires accounting for each operation and actual post-cache traffic; the formula is a working approximation, not a profiler replacement.
The distinction between capacity and bandwidth is practical. Weights fitting in 8 GB does not imply room for arbitrary context or multiple requests. The system also retains activations, buffers and possibly key and value cache. Allocator reservation may look occupied although part is available for later operations in the same process. Record both metrics and other-process conditions before comparing peaks; do not turn one observed reservation into a universal minimum model requirement.
weights = 1.5e9
bytes_per_weight = 2
for bandwidth in (256e9, 272e9):
print("GB/s:", bandwidth / 1e9, "cota tokens/s:", bandwidth / (weights * bytes_per_weight))
for rows in (1, 512):
print("filas:", rows, "FLOP/byte, solo pesos:", 2 * rows / bytes_per_weight)Lab: parity and naive generation
The next lab uses an open Llama model and a custom implementation. Loading occurs outside the timer. We generate greedily with fixed output length and no cache so the same operations and tokens can be compared. Times measure this environment when run, not fixed RTX 4060 properties. The table also prints an ideal nominal-bandwidth reference under the assumption above; because the loop recomputes the complete prefix, comparison is guidance rather than an exact cost decomposition.
The example uses SmolLM2-135M at the revision in code. It needs PyTorch with CUDA and Transformers, plus checkpoint access or a cached copy. The implementation is limited to this configuration: no padding, no attention bias and no specially scaled RoPE. Tolerance is fixed before execution; agreement on these examples is a bounded check, not a general proof. The harness shows medians of three repetitions, enough to illustrate the procedure but not estimate reliable percentiles. The ratio uses nominal 272 GB/s and counts each unique parameter once; it does not claim every parameter crosses DRAM exactly once per step.
import gc
import traceback
import torch
def run_lab():
import math
import statistics
import time
import torch.nn.functional as F
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL = "HuggingFaceTB/SmolLM2-135M"
REV = "93efa2f097d58c2a74874c7e644dbc9b0cee75a2"
assert torch.cuda.is_available(), "Este experimento necesita CUDA."
device = torch.device("cuda")
torch.backends.cuda.matmul.allow_tf32 = False
tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REV)
ref = AutoModelForCausalLM.from_pretrained(
MODEL, revision=REV, torch_dtype=torch.bfloat16,
attn_implementation="eager",
).eval().to(device)
c = ref.config
rope = getattr(c, "rope_parameters", None) or getattr(c, "rope_scaling", None) or {}
assert c.model_type == "llama" and rope.get("rope_type", rope.get("type", "default")) == "default"
theta = rope.get("rope_theta", getattr(c, "rope_theta", 10000.0))
assert not c.attention_bias and c.hidden_size % c.num_attention_heads == 0
assert c.num_attention_heads % c.num_key_value_heads == 0
assert c.hidden_act == "silu"
weights = ref.state_dict() # Comparte tensores con la referencia.
def own_logits(ids):
b, t = ids.shape
h, nk = c.num_attention_heads, c.num_key_value_heads
d = c.hidden_size // h
assert d % 2 == 0 and t <= c.max_position_embeddings
def norm(x, weight):
xf = x.float()
return (xf * torch.rsqrt(xf.square().mean(-1, keepdim=True) + c.rms_norm_eps)).to(x.dtype) * weight
def linear(x, key):
return F.linear(x, weights[key])
def rotate_half(x):
a, z = x.chunk(2, dim=-1)
return torch.cat((-z, a), dim=-1)
x = F.embedding(ids, weights["model.embed_tokens.weight"])
inv = 1.0 / (theta ** (torch.arange(0, d, 2, device=device, dtype=torch.float32) / d))
phases = torch.outer(torch.arange(t, device=device, dtype=torch.float32), inv)
phases = torch.cat((phases, phases), dim=-1)
cosine = phases.cos().to(x.dtype)[None, None]
sine = phases.sin().to(x.dtype)[None, None]
mask = torch.ones(t, t, dtype=torch.bool, device=device).triu(1)
for i in range(c.num_hidden_layers):
p = f"model.layers.{i}."
y = norm(x, weights[p + "input_layernorm.weight"])
q = linear(y, p + "self_attn.q_proj.weight").view(b, t, h, d).transpose(1, 2)
k = linear(y, p + "self_attn.k_proj.weight").view(b, t, nk, d).transpose(1, 2)
v = linear(y, p + "self_attn.v_proj.weight").view(b, t, nk, d).transpose(1, 2)
q = q * cosine + rotate_half(q) * sine
k = k * cosine + rotate_half(k) * sine
k = k.repeat_interleave(h // nk, dim=1)
v = v.repeat_interleave(h // nk, dim=1)
score = (q @ k.transpose(-1, -2)) / math.sqrt(d)
score = score.masked_fill(mask, torch.finfo(score.dtype).min)
prob = F.softmax(score, dim=-1, dtype=torch.float32).to(q.dtype)
out = (prob @ v).transpose(1, 2).contiguous().view(b, t, h * d)
x = x + linear(out, p + "self_attn.o_proj.weight")
y = norm(x, weights[p + "post_attention_layernorm.weight"])
gate = F.silu(linear(y, p + "mlp.gate_proj.weight"))
up = linear(y, p + "mlp.up_proj.weight")
x = x + linear(gate * up, p + "mlp.down_proj.weight")
x = norm(x, weights["model.norm.weight"])
head = weights.get("lm_head.weight", weights["model.embed_tokens.weight"])
return F.linear(x, head).float()
ids = tokenizer("The capital of France is a city with a long history and many monuments.", return_tensors="pt").input_ids.to(device)
with torch.inference_mode():
for length, batch in [(5, 1), (12, 1), (12, 2)]:
sample = ids[:, :length].repeat(batch, 1)
expected = ref(sample, use_cache=False).logits.float()
actual = own_logits(sample)
err = (actual - expected).abs()
print("paridad longitud/lote:", length, batch, "máximo:", err.max().item(),
"media:", err.mean().item(), "argmax final igual:",
bool(torch.equal(actual[:, -1].argmax(-1), expected[:, -1].argmax(-1))))
assert torch.allclose(actual, expected, atol=0.15, rtol=0.02)
del sample, expected, actual, err
own_logits(ids)
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
n_new = 8
measurements = []
for repetition in range(3):
tokens = ids
marks = []
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(n_new):
logits = own_logits(tokens)
next_id = logits[:, -1].argmax(-1, keepdim=True)
tokens = torch.cat((tokens, next_id), dim=1)
token_cpu = next_id.cpu()
torch.cuda.synchronize()
marks.append(time.perf_counter())
del logits, next_id, token_cpu
measurements.append((marks[0] - start, (marks[-1] - marks[0]) / (n_new - 1), n_new / (marks[-1] - start)))
ttft, tpot, throughput = (statistics.median(m[i] for m in measurements) for i in range(3))
n_params = sum(p.numel() for p in ref.parameters())
weight_bytes = sum(p.numel() * p.element_size() for p in ref.parameters())
bandwidth = 272e9 # Ancho nominal en bytes/s, no una medición.
bound = bandwidth / weight_bytes
print("parámetros únicos:", n_params, "bytes de pesos:", weight_bytes)
print("cota ideal de solo pesos tokens/s:", bound)
print("fracción de la cota hipotética:", throughput / bound)
print("tokens de entrada / salida:", ids.shape[1], n_new)
print("TTFT ms:", 1000 * ttft)
print("TPOT medio ms:", 1000 * tpot)
print("medianas de 3 repeticiones; throughput de salida tokens/s:", throughput)
print("pico asignado PyTorch MiB:", torch.cuda.max_memory_allocated() / 2**20)
print("texto generado:", tokenizer.decode(tokens[0], skip_special_tokens=True))
del ids, tokens, weights, ref
gc.collect()
torch.cuda.empty_cache()
try:
run_lab()
except Exception as error:
traceback.clear_frames(error.__traceback__)
raise
finally:
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()npm run lab and open the connection link.Output shows each parity case before the metrics table. If the test fails, do not interpret speed: first investigate the first diverging operation. When changing Transformers version or checkpoint, recheck loader assumptions and shapes. Peak includes resident weights and PyTorch temporaries, and is not total GPU occupancy.
Read the run as an investigation
The program first performs a numeric comparison, then warms the path to be measured. It does not interleave reference and custom model within the timer, which would include checking work in latency. The three parity cases share the same prefix; the batch-of-two case repeats that input to check batch dimension, but does not replace a test with two different sequences. A broader suite should include distinct inputs, lengths near supported limits and layer-by-layer comparison. Padding also needs per-sequence masks and positions absent from this loader.
The custom implementation reads tensors from the reference dictionary to limit memory consumption. This checks the operations applying those weights and key correspondence, but not an independent checkpoint-file reader. A production loader should also verify serialization, downloaded revision, integrity and shared-weight cases. Matching names is insufficient: the operation consumes the matrix in the orientation expected by linear. Transposing on import and then calling a function that already interprets rows as outputs can hide a structural error in a square shape.
In each block logits result from a chain of rounding operations. The lab computes mean square and softmax in float32 and returns results to activation precision at the relevant points. This choice is part of the function being compared. A version change may select another kernel or reduction order and produce numeric differences without necessarily changing semantics. Tolerance detects large discrepancies under the fixed contract; maximum, mean and location of greatest error help diagnose what occurred.
Printed TPOT is the median across repeated requests of their mean intervals after the first token. It is not the median of all individual intervals. Throughput is the median full-request rate including the first token. Since each uncached pass sees a longer prefix, the rate can change with output-token count. Keep the same prompt and final length to compare runs. For scaling studies, change one dimension at a time and retain each measurement distribution.
Greedy choice avoids a random generator but does not turn text output into proof of truth. A small model may complete a sentence incorrectly or incompletely. The goal is to compare function and execution cost, not text quality. Decoding to text is outside the timer, as is initial tokenization; copying each token to CPU is included before the timestamp under the local availability definition.
The ceiling ratio is especially delicate here. The numerator includes prefill and prefix recomputation, while the denominator imagines reading all weights per token at nominal bandwidth. A low fraction is compatible with many costs and does not show a particular fraction of memory bandwidth was used. Shared embeddings are counted once in resident size but may be used in two operations. Measuring traffic requires counters or an appropriate microbenchmark and a stated memory boundary.
When transferring the experiment to a larger model, first calculate weight size and leave buffer and state headroom. A load that barely fits can fail during the first pass because activations and temporaries remain to be allocated. In this lab reference and custom calculation share weights to avoid another copy; comparing independent instances requires budgeting both. Final cleanup removes references and empties free allocator blocks. If another session uses the GPU, a memory failure calls for waiting and repeating the same experiment, not silently reducing its size and presenting it as equivalent.
What changes when adding a cache
The next optimization stores previously processed keys and values per layer. Prefill calculates them for the full prompt; subsequent steps project only the new position and attend to stored and new keys and values. This has a correctness consequence: the new query’s rotary position must match its absolute prefix index, not reset to zero on every call. A mask must also let that query see the past without letting a prefill query see the future.
Stored state is not free. Per layer and sequence, each position retains a key and value per KV head. If each component occupies bytes, memory for these structures over positions is bytes, excluding metadata and fragmentation. Multiply by layer count and batch for equal-length reservations. GQA reduces this term by using fewer KV than query heads but does not remove context growth. This describes reserved capacity under the stated layout, not actual DRAM traffic served by a kernel.
A cache test must compare logits step by step for identical input tokens. Comparing only the final sentence can pass by chance when maxima remain equal. Also check that restarting a request discards prior state and two requests do not write to the same region. For a preallocated buffer, maximum size and length handling are part of the contract; reading unwritten positions can make results depend on old data. These tests connect today’s baseline directly to the project’s first optimization.
Exercises
def measure_generation(engine, prompts):
passFirst verify the function, then measure with explicit boundaries and synchronization. Roofline relates operations to bytes under a traffic model; the measured baseline includes costs that simplified model does not predict. The next lesson’s KV cache will remove prefix recomputation, but must be shown to preserve logits.