Phase 04/Measure and tune/Performance modeling, capacity and cost per token
PHASE 04 · Measure and tune

Performance modeling, capacity and cost per token

0%
10 h6 subtopics3 lessons · 2 required
In plain English

Before buying a thousand ovens, a restaurant chain works out on paper how many meals each oven can cook per hour, how long a customer will wait at the busiest time, and what each meal will cost. Inference teams do the same for GPUs. A simple physics-style model (the roofline) says how fast a chip could possibly run a model given how quickly it can read memory and do arithmetic. Comparing that ceiling with what the fleet actually achieves shows how much money is being left on the table and where. The same model, fed with a GPU's hourly price and a target for how long users may wait, turns into a price per million words and a count of GPUs needed. The final skill is writing the result down in one page that a busy decision-maker can act on.

Why it matters

Anthropic's Inference System Dynamics role, OpenAI's inference performance roles and Baseten's performance team all ask for the same chain of reasoning. Build a roofline model, size the gap to measured throughput, translate it into cost per token and GPUs, and write it up so other teams change their priorities. Every optimization in this phase is justified in those terms.

Hiring signal

Anthropic asks performance engineers to "build a FLOPs funnel that breaks down where compute actually goes across the fleet, exposing the gap between achieved throughput and kernel rooflines", to model the latency-cost impact of batch-sizing and utilization targets, and to communicate quantitative results in writing to influence teams they do not manage; Baseten wants engineers who improve tokens per GPU-hour and give customers clear latency/throughput/cost trade-offs.

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Cursor, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Build a roofline model of prefill and decode time for a model and GPU, including weight, KV and compute terms and an efficiency factor.
  • Quantify the gap between measured throughput and roofline as achieved memory-bandwidth and FLOP utilization and attribute it to named causes.
  • Compute cost per million tokens and GPUs required for H100, A100 and L4 at a given SLO, workload and price, and show how the answer moves with batch size, quantization and context length.
  • Model the latency-cost trade-off of utilization targets under bursty demand and pick an autoscaling target with a stated error budget.
  • Write a one-page findings memo with a FLOPs funnel, a quantified recommendation and explicit assumptions.

Key concepts

Roofline
time = max(bytes / bandwidth, FLOPs / peak_FLOPs); decode usually sits on the bandwidth roof, prefill on the compute roof.
Model bandwidth utilization (MBU) and MFU
Achieved bytes per second (or FLOPs per second) divided by the hardware peak; the honest utilization numbers, unlike nvidia-smi GPU-Util.
FLOPs funnel
A staged breakdown from theoretical peak through roofline-achievable, kernel-achieved and fleet-achieved throughput, so each loss has an owner.
Tokens per GPU-hour
Throughput integrated over an hour at the operating point; the quantity that divides the hourly GPU price to give cost per token.
Cost per million tokens
GPU hourly price divided by (tokens per second times 3600) times one million; usually quoted separately for input and output tokens.
SLO-constrained operating point
The largest batch size (or concurrency) whose predicted or measured p99 TTFT and ITL still meet the SLO; it sets achievable throughput per GPU.
Utilization target and headroom
The average load fraction an autoscaler aims for; lower targets cost more GPUs but absorb bursts without SLO violations.
Sensitivity analysis
Recomputing the cost model while varying one input (price, SLO, context length, quantization) to see which assumptions the conclusion depends on.
Goodput
Throughput counting only requests that met their SLO; the right numerator for capacity decisions.

Subtopics

  1. 1. Roofline for a serving step

    Weight bytes, KV bytes per token times batch times context, activation traffic, and FLOPs per token; bandwidth and compute roofs per GPU; the crossover batch.

  2. 2. Roofline versus measured

    Compute MBU and MFU from a benchmark run; typical gaps from launch overhead, scheduling, padding, attention efficiency, sampling and idle time; the FLOPs funnel.

  3. 3. From throughput to dollars

    Hourly GPU prices, tokens per GPU-hour, input versus output token cost, amortizing prefill, and how quantization and context length move the number.

  4. 4. Capacity under an SLO

    Finding the SLO-constrained batch size, GPUs needed for a demand curve with peak-to-mean ratio, and the cost of tail-latency headroom.

  5. 5. Utilization targets and autoscaling signals

    Simulating bursty arrivals against a fixed fleet, violation rate versus utilization target, scale-up lag, and turning the model into an autoscaler threshold.

  6. 6. Writing the findings memo

    One page; question, method, funnel table, recommendation with a dollar figure, assumptions and sensitivity, what you need from other teams; writing for readers who will not run your code.

Resources

paper
article
documentation

Hands-on lessons

L1

Build a capacity and cost-per-token calculator

CPU · your Macnotebook150 minrequired

Goal · A calculator that, for a model, GPU, SLO, workload and hourly price, returns the SLO-constrained batch size, output tokens per second, cost per million input and output tokens and GPUs needed for a demand level, for H100, A100 and L4.

  1. 1Enter a spec table for H100 SXM (80 GB, 3.35 TB/s, 989 dense FP16 TFLOPs), A100 80GB (2.0 TB/s, 312 TFLOPs) and L4 (24 GB, 300 GB/s, 121 TFLOPs) with an assumed on-demand price for each (write down your source and date).
  2. 2Enter model specs for Llama-3.1-8B and Llama-3.1-70B in FP16, FP8 and INT4 weight-only; compute weight bytes and KV bytes per token from config.json, and flag any combination that does not fit in one GPU's memory with 90 percent utilization.
  3. 3Implement decode_step_time(B, context) and prefill_time(prompt_len) from the roofline with an efficiency factor eff (start at 0.6) applied to both roofs; compute the KV-capacity bound on B for a given context.
  4. 4For a workload of 1024-token prompts and 256-token outputs and an SLO of p50 ITL under 50 ms and TTFT under 1 s, find the largest B meeting both the SLO and the KV bound, then output tokens per second and tokens per GPU-hour.
  5. 5Compute cost per million output tokens and per million input tokens (prefill time share) for every model x GPU x precision cell; produce a table and mark infeasible cells.
  6. 6Compute GPUs needed for a demand of 2,000 requests per minute at a peak-to-mean ratio of 2.5, with and without a 70 percent utilization target.
  7. 7Run a sensitivity sweep over eff in 0.4, 0.6, 0.8, SLO ITL 30 and 100 ms, and context 4k and 32k; plot cost per million output tokens for the 8B model on each GPU.
  8. 8Compare your T4 roofline prediction for Qwen2.5-0.5B at the concurrency you benchmarked in p3-benchmarking-engines-l1 with the throughput you measured; report achieved MBU as a percentage.
Deliverable
capacity_calc.ipynb with the spec tables, the cost table, the GPUs-needed figures, the sensitivity plot and the measured-versus-roofline MBU.
Check
Llama-3.1-70B FP16 is flagged as not fitting on any single GPU in the table; the 8B FP16 H100 cost lies between 0.03 and 0.60 USD per million output tokens at eff 0.6; your measured T4 MBU is reported and lies below 100 percent.
L2

Write a one-page findings memo with a FLOPs funnel

CPU · your Macdesign120 minrequired

Goal · A one-page memo, in the style of an Inference System Dynamics investigation, that explains where throughput is lost between peak hardware and your measured serving run and recommends one change with a quantified value.

  1. 1Take one measured run from p3-benchmarking-engines-l1 or p4-latency-throughput-l2 (model, GPU, concurrency, output tokens per second, TTFT and ITL percentiles).
  2. 2Build a four-stage funnel for that run; theoretical peak tokens per second (bandwidth roof at infinite batch), roofline at the measured batch and context, kernel-achieved (from an nsys or torch.profiler kernel-time share if you have one, else estimate from the GPU idle fraction in p4-nsight-profiling-l1), and measured end-to-end.
  3. 3For each stage drop, name the most likely cause and the team or component that owns it (scheduler, sampler, attention kernel, client, batching policy).
  4. 4Pick the single largest recoverable drop and estimate the value of closing half of it as tokens per GPU-hour and as dollars per month for a fleet of 100 GPUs at your assumed price.
  5. 5Write the memo in under 600 words with these sections; question, method and data, funnel table, finding, recommendation with dollar figure, assumptions and sensitivity, asks of other teams.
  6. 6Have a peer or an LLM read only the memo (not your notebook) and answer three questions; what is the recommendation, how much is it worth, and what would change the conclusion. Fix anything they could not answer.
Deliverable
findings_memo.md plus the funnel table as CSV.
Check
The memo is under 600 words, contains a funnel table with four stages where each stage is less than or equal to the previous one, and states one recommendation with a dollars-per-month figure and at least two explicit assumptions.
L3

Simulate utilization targets against bursty demand

CPU · your Macscript90 minoptional

Goal · A simulation showing how fleet cost and SLO-violation rate move as the autoscaling utilization target changes, and the target you would set with a stated error budget.

  1. 1Model one GPU with your calculator's SLO-constrained capacity in requests per second and a per-request latency that rises with load, for example an M/M/c queue or the throughput-latency curve from p4-latency-throughput-l2.
  2. 2Generate 24 hours of arrivals with a diurnal sine pattern (peak-to-mean 2.5) plus Poisson noise plus two 5-minute bursts of 4x load.
  3. 3Implement an autoscaler that targets utilization U with a 3-minute scale-up lag and 10-minute scale-down cooldown; run U in 0.5, 0.6, 0.7, 0.8, 0.9.
  4. 4For each U record GPU-hours consumed (cost) and the fraction of requests whose predicted latency exceeds the SLO (violations).
  5. 5Plot cost and violation rate against U and mark where violations cross a 1 percent error budget.
  6. 6Write a paragraph recommending a target and what signal (queue depth, KV utilization, predicted ITL) the autoscaler should act on.
Deliverable
autoscale_sim.py, the cost-versus-violations plot and the paragraph.
Check
Cost falls monotonically as U rises while violation rate rises; you identify the largest U that keeps violations under 1 percent and state its cost premium over U 0.9 as a percentage.

Build your own

Build your own capacity calculator

PythonCPU · your Mac~8 h

A CLI that turns a model config and a GPU spec into KV budget, SLO-constrained batch size, tokens per second and dollars per million tokens, with CSV output and a calibration against numbers you measured.

The real thing: github.com/cli99/llm-analysis ↗

How you know a stage passes

Write tests/test_capcalc.py first. Every stage asserts hand-computed values for Llama-3.1-8B, Llama-3.1-70B, Qwen2.5-0.5B and GPT-2 small (from their config.json files committed under tests/configs) on H100 SXM, A100 80GB, L4 and T4 specs, plus a CSV shape check. `capcalc <command>` is the CLI and every command accepts --csv. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01model spec from config.json
    Parameter count, weight bytes per dtype, GQA-aware KV bytes per token and FLOPs per token (2 per parameter plus attention) computed from a Hugging Face config.
    test · GPT-2 small reports exactly 124,439,808 parameters and 36,864 KV bytes per token in fp16; Llama-3.1-8B reports 131,072 KV bytes per token in fp16 and a parameter count within 1 percent of 8.03 billion.
  2. 02GPU specs and the roofline step time
    A spec table (memory, bandwidth, dense fp16 and fp8 TFLOPs, hourly price with source and date) and decode_step_time(B, context) and prefill_time(L) as the max of the memory and compute roofs divided by an efficiency factor.
    test · Llama-3.1-8B fp16 on H100 at batch 1, context 0, efficiency 1.0 gives a decode step within 2 percent of 4.8 ms; the batch where the compute roof overtakes the memory roof is between 280 and 310.
  3. 03the KV budget
    Free memory after weights and a configurable activation margin at a utilisation target, converted to max cached tokens and max concurrent sequences at a given context, with infeasible combinations flagged.
    test · Llama-3.1-8B fp16 on H100 at 90 percent utilisation and zero margin fits within 2 percent of 427,000 KV tokens; Llama-3.1-70B fp16 is flagged infeasible on every single GPU in the table while its INT4 variant fits on H100 and A100.
  4. 04SLO-constrained throughput
    Given p50 ITL and TTFT SLOs, a prompt and output length and a context, find the largest batch that satisfies the SLOs and the KV bound, and report tokens per second, tokens per GPU-hour and which bound was binding.
    test · Tokens per second is non-decreasing in batch up to the chosen batch; tightening the ITL SLO from 50 to 30 ms never increases the chosen batch; the binding bound is reported as one of slo, kv or compute and the test checks each case with a crafted input.
  5. 05dollars per million tokens
    Cost per million output tokens and per million input tokens (prefill share) for every model x GPU x precision cell, written to a CSV with infeasible cells marked.
    test · The CSV has one row per cell and no empty cost for a feasible cell; Llama-3.1-8B fp16 on H100 at efficiency 0.6 lands between 0.03 and 0.60 USD per million output tokens with the price you recorded.
  6. 06sensitivity and calibration against your own measurements
    `capcalc sweep --eff 0.4,0.6,0.8 --itl 30,100 --context 4096,32768` writes a CSV and plot, and `capcalc calibrate --measured results.csv` compares the T4 prediction for Qwen2.5-0.5B with the throughput you measured in p3-benchmarking-engines and prints achieved model-bandwidth utilisation.
    test · The sweep CSV has 12 rows per model-GPU pair and the plot file exists; the calibration prints an MBU strictly below 100 percent and the README quotes it next to the predicted and measured tokens per second.

Knowledge check

QWhy is nvidia-smi GPU-Util the wrong utilization number for a cost model, and what do you use instead?

It only reports the fraction of time any kernel was resident; model bandwidth utilization or MFU compare achieved bytes or FLOPs per second against hardware peak and reflect real work done.

QDecode on an H100 for an 8B FP16 model takes about 4.8 ms per step at batch 1. What roofline term gave that number?

Weight bytes divided by bandwidth, 16 GB / 3.35 TB/s; at batch 1 the compute term is far smaller so the bandwidth roof dominates.

QWhy does cost per output token usually fall with batch size, and what stops it?

Weights are read once per step for the whole batch so tokens per step rise faster than step time; the KV cache budget, the compute roof and the ITL SLO cap the batch.

QA memo recommends an optimization worth 12 percent more throughput. What must it also include to be actionable?

The assumptions and sensitivity (prices, SLO, workload mix), the dollar or GPU value at fleet scale, who owns the change and what evidence would change the conclusion.

QWhy does a lower utilization target cost more, and what does it buy?

More GPUs sit partly idle on average; it buys headroom so bursts and scale-up lag do not push tail latency past the SLO.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lesson l1 calculator and lesson l2 memo saved with both checks passing.
  • Can explain, without notes, how a GPU price, a roofline and an SLO combine into a cost per million tokens and a GPU count.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →