Platform Engineering · Lesson 327

GPU Inference Capacity and Cost: Batching, Quantization, and Scheduling

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: size the fleet and see the bill

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.

182 msp99
3–10GPUs
$7.41per million

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

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.

Basic — Read utilisation and cost

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.
  • The server's batch size, queue wait, and latency percentiles.
  • GPU-hours, price, and predictions: the cost per million.

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.

Intermediate — Size a service

At the intermediate level you size a service from traffic and the latency budget.

  • A load test at real input sizes: requests a second per GPU within the p99 budget.
  • Replicas = peak ÷ (per-GPU capacity × target utilisation), with a minimum for the trough.
  • Separate online and batch work; batch on cheaper or spot capacity.

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.

Advanced — Tune the levers

At the advanced level you spend the latency budget where it buys the most throughput.

  • Dynamic or continuous batching, with max wait chosen from the budget.
  • INT8, FP8, or 4-bit quantization, through the gate.
  • MIG or multi-model serving for small models; compiled runtimes (TensorRT, ONNX Runtime).

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.

Master — Run a GPU fleet

At the master level GPU capacity is a shared platform with quotas, chargeback, and a plan.

  • Quotas and priorities per team (Kueue or the scheduler's queues); batch work fills idle capacity.
  • Cost per prediction reported per model with its SLOs; chargeback or showback to owners.
  • A capacity plan: reserved for the base, on-demand for peaks, spot for batch; GPU generations retired on schedule.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A cost saving that broke checkout.

Timeline

  • 10:00A cost review shows the ranking service's GPUs at 45% utilisation. To raise it, max batch size goes from 16 to 64 and max wait from 10 ms to 150 ms.
  • 12:30Traffic reaches its midday peak. Requests queue for up to 150 ms, then run in batches of 64 that take about 450 ms. p99 reaches 610 ms.
  • 12:40Checkout's 300 ms timeout fires on a third of ranking calls; it falls back to a default ordering. Conversion dips.
  • 13:05The batching change is reverted. p99 returns to 182 ms within minutes.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. 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

    Options: --query-gpu picks the fields; --format=csv makes it easy to log or parse.

    Expect: One line per GPU. High memory with low utilisation usually means a model loaded and waiting for work.

  2. 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.csv

    Options: -l 1 repeats every second; head -60 stops after a minute.

    Expect: An average over the minute: the number to compare with the fleet's cost.

    Clean up: rm gpu.csv.

  3. See which processes hold GPU memory.

    nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv

    Expect: Each inference server and its memory; several small models can share one GPU this way.

  4. 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

    Options: -lgip lists GPU instance profiles; creating them needs root and an idle GPU.

    Expect: Profiles such as 1g.10gb and their counts, or a message that MIG is not supported.

2. Python: gpu_sizing.py

This 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]

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

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.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Sized for peak, all dayHop 8: AutoscalingBreaks15 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 chasedHop 6: BatchingBreaksTo raise utilisation, max batch goes to 64 and max wait to 150 ms.
Batch size chasedHop 7: GPU choiceDegradesA batch of 64 takes 450 ms to run at p99.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Traffic → Latency SLO → Online or batch → Model memory → Quantization → Batching → GPU choice → Autoscaling → Cost. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 328
AIOps Event Correlation and Noise Reduction: From 2,400 Alerts to One Incident

When something important breaks, monitoring does not send one alert; it sends thousands, from every system that depends on the broken one. Event correlation turns that storm into one incident with a likely cause: events are…

Go to Lesson 328 →

Or browse the full course from the Lessons index.