GPUs are the most expensive thing most ML platforms run, and most of them sit idle. Capacity for inference comes from four levers: batching (more requests per pass through the model), quantization (smaller numbers, so the model fits on fewer or cheaper GPUs and moves less memory), scheduling (putting the right work on the right GPU, sharing small models, scaling to traffic), and choosing between online inference (a user waiting, latency SLO) and batch inference (a job, throughput and deadline). This lesson sizes one service from its traffic and latency SLO to a GPU count and a cost per million predictions, and shows the two failures: a fleet sized for peak and idle the rest of the day, and a batch size raised until latency broke the SLO.
Difficulty: Master · Know this first: Lesson 326, Lesson 309, Lesson 271
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up milliseconds of one request at peak, from arrival to answer, against a 250 ms p99 budget. It is a worked example, not a measurement. The batching and GPU hops spend most of the budget.
Pick the precision, the batching, and the scaling. The service has 400 requests a second at peak, about 150 on average, and a 250 ms p99 budget.
Three questions. No score is saved anywhere — this is just you against the material.
GPU inference capacity grows in four levels: reading utilisation and cost, sizing a service, tuning the levers, and running a GPU fleet as a shared platform.
At the basic level you can say how busy the GPUs are and what a prediction costs.
nvidia-smi and DCGM metrics: utilisation, memory used, power.Where it breaks: reading "GPU utilisation 100%" as full; it means a kernel was running, not that the GPU was efficiently used.
Try it: Basic
What is the cost per million predictions for 4 GPUs at $1 an hour serving 100 requests a second all day?
Now do it: Compute it for one service you run.
At the intermediate level you size a service from traffic and the latency budget.
Try it: Intermediate
Peak is 400/s and one GPU does 55/s within budget. With an 80% target, how many replicas at peak?
Now do it: Size one service from its own numbers.
At the advanced level you spend the latency budget where it buys the most throughput.
Try it: Advanced
Three small models each use 10% of a large GPU. What do you try?
Now do it: Check which of your models could share a GPU.
At the master level GPU capacity is a shared platform with quotas, chargeback, and a plan.
Trade-off: reserved capacity is cheaper per hour and wasted when idle; spot is cheapest and interrupted; the mix follows how predictable each workload is.
Try it: Master
Online traffic peaks at midday; batch scoring can run any time before 06:00. How do you use one fleet for both?
Now do it: Plot your online and batch GPU use over a day.
Dynamic batching in NVIDIA Triton Inference Server: requests are held for up to 10 ms and run together up to a batch of 16. Check the Triton documentation for your version's options.
# model_repository/ranker/config.pbtxt
name: "ranker"
backend: "onnxruntime"
max_batch_size: 16
dynamic_batching {
preferred_batch_size: [8, 16]
max_queue_delay_microseconds: 10000 # the batch wait: spent from every request's budget
}
instance_group [{ kind: KIND_GPU, count: 1 }]
The arithmetic for sizing, written out:
Scheduling GPUs on Kubernetes: the NVIDIA device plugin exposes nvidia.com/gpu; MIG profiles expose slices such as nvidia.com/mig-1g.10gb; time-slicing is configured in the device plugin; Kueue adds queues, quotas, and priorities for batch jobs. Scale online replicas with KEDA or KServe on concurrency, and pre-scale before known peaks because GPU nodes take minutes to join.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A cost saving that broke checkout.
Batching settings are derived from the latency budget and load-tested before release, cost changes must report the p99 alongside the saving, and the real savings came from autoscaling and moving nightly re-ranking to batch on spot GPUs.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: An NVIDIA GPU with drivers installed for the nvidia-smi steps. Without one, read along: the program below needs only Python 3.
Type each one, read what it prints, and compare it with the note above it.
Read what each GPU is doing: memory, utilisation, power.
nvidia-smi --query-gpu=index,name,memory.used,memory.total,utilization.gpu,power.draw --format=csv
Sample utilisation every second for a minute while a load test runs.
nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used --format=csv,noheader -l 1 | head -60 > gpu.csv
awk -F", " '{gsub(/ %/,"",$2); s+=$2; n++} END {print "average utilisation " s/n "%"}' gpu.csvSee which processes hold GPU memory.
nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv
If the GPU supports MIG, list the partition profiles it offers (read-only).
Changes a real system: Enabling MIG (nvidia-smi -mig 1) or creating instances resets and repartitions the GPU: do it only on a drained node.
nvidia-smi mig -lgip
gpu_sizing.pyThis program sizes one inference service: the memory a model needs at each precision, how batch size and batch wait trade throughput against p99 latency, how many GPUs the peak needs, and the cost per million predictions for a fixed fleet against an autoscaled one. Save it as gpu_sizing.py, then run it.
# gpu_sizing.py
import math
PARAMS = 1.3e9
for bits in (16, 8, 4):
print(f"weights at {bits:>2}-bit: {PARAMS * bits / 8 / 1e9:4.1f} GB")
print()
# measured on one GPU: forward-pass time grows with batch size (a fixed cost plus a per-item cost)
def forward_ms(batch):
return 120 + 2.6 * batch
BUDGET_MS, OVERHEAD_MS = 250, 12
print("max batch max wait p99 ms req/s per GPU within 250 ms?")
for batch, wait in ((1, 0), (8, 5), (16, 10), (32, 40), (64, 150)):
p99 = OVERHEAD_MS + wait + forward_ms(batch) * 1.12 # p99 forward is about 12% above the mean
throughput = batch / (forward_ms(batch) / 1000)
print(f"{batch:>9} {wait:>8} {p99:7.0f} {throughput:13.0f} {'yes' if p99 <= BUDGET_MS else 'NO'}")
print()
HOURLY = [60, 55, 50, 60, 80, 120, 180, 250, 320, 360, 380, 395, 400, 390, 370, 340, 300, 260, 220, 180, 150, 120, 90, 70]
# the load test, with real inputs and server overheads, measured 55 requests a second per GPU within budget
PER_GPU, TARGET, PRICE, MIN_REPLICAS = 55, 0.8, 0.80, 3
peak = max(HOURLY)
fixed = math.ceil(peak * 1.3 / PER_GPU)
auto = [max(MIN_REPLICAS, math.ceil(rps / (PER_GPU * TARGET))) for rps in HOURLY]
predictions_m = sum(HOURLY) * 3600 / 1e6
for name, gpu_hours in (("fixed for peak + 30%", fixed * 24), ("autoscaled", sum(auto))):
cost = gpu_hours * PRICE
used = sum(HOURLY) * 3600 / (gpu_hours * PER_GPU * 3600)
print(f"{name:<21} {gpu_hours:4d} GPU-hours {cost:6.2f} USD a day {cost / predictions_m:5.2f} USD per million utilisation {used:.0%}")
print(f"replicas by hour (autoscaled): {auto}")
Run it, and you should see this output:
$ python3 gpu_sizing.py
weights at 16-bit: 2.6 GB
weights at 8-bit: 1.3 GB
weights at 4-bit: 0.7 GB
max batch max wait p99 ms req/s per GPU within 250 ms?
1 0 149 8 yes
8 5 175 57 yes
16 10 203 99 yes
32 40 280 157 NO
64 150 483 223 NO
fixed for peak + 30% 240 GPU-hours 192.00 USD a day 10.26 USD per million utilisation 39%
autoscaled 136 GPU-hours 108.80 USD a day 5.81 USD per million utilisation 70%
replicas by hour (autoscaled): [3, 3, 3, 3, 3, 3, 5, 6, 8, 9, 9, 9, 10, 9, 9, 8, 7, 6, 5, 5, 4, 3, 3, 3]
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/gpu-inference-capacity-and-cost && cd ~/labs/gpu-inference-capacity-and-cost) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "GPU Inference Capacity and Cost: Batching, Quantization, and Scheduling", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Read what each GPU is doing: memory, utilisation, power.'
'Sample utilisation every second for a minute while a load test runs.'
'See which processes hold GPU memory.'
'If the GPU supports MIG, list the partition profiles it offers (read-only).'
)
step_1() {
nvidia-smi --query-gpu=index,name,memory.used,memory.total,utilization.gpu,power.draw --format=csv
}
step_2() {
nvidia-smi --query-gpu=timestamp,utilization.gpu,memory.used --format=csv,noheader -l 1 | head -60 > gpu.csv
awk -F", " '{gsub(/ %/,"",$2); s+=$2; n++} END {print "average utilisation " s/n "%"}' gpu.csv
}
step_3() {
nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv
}
step_4() {
nvidia-smi mig -lgip
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
awk, head, Pipes, Redirection.Your platform serves 12 models on 60 GPUs at 23% average utilisation, and finance wants the bill halved without breaking any SLO. Design the plan.
Which work is online and which can be batch? How do you measure capacity per GPU for each model? Which models can share GPUs, and how? What do batching and quantization buy each model within its budget? How do you scale, and what capacity do you buy? How do you report progress?
Say 12 models, 60 GPUs at $1.20 an hour, 23% average utilisation, peak-to-average traffic of 2.5, and latency budgets from 80 ms to 2 seconds.
Inventory each model's traffic, budget, and memory; move nightly and weekly scoring to a Kueue batch queue on spot capacity; load-test each online model for per-GPU capacity within budget; INT8 for models that pass the gate; MIG or multi-model serving for the five small models; dynamic batching with max wait set from each budget; autoscaling on concurrency with minimums and pre-scaling for known peaks; reserved capacity for the base, on-demand for peaks; a monthly report of cost per million predictions and p99 per model.
Autoscaling saves most and adds cold-start risk, so keep minimums and headroom; spot is cheapest and interrupts, so only for checkpointed batch work; quantization and sharing need a gate and load tests per model; reserved capacity commits you for a year or more.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Sized for peak, all day | Hop 8: Autoscaling | Breaks | 15 replicas all day (peak plus 30% margin, at 35/s each), no autoscaling. Latency is excellent; average GPU utilisation is 29%. The monthly bill is about six times the sized design for the same traffic and SLO. Nobody notices until the quarterly cost review. |
| Batch size chased | Hop 6: Batching | Breaks | To raise utilisation, max batch goes to 64 and max wait to 150 ms. |
| Batch size chased | Hop 7: GPU choice | Degrades | A batch of 64 takes 450 ms to run at p99. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.