Inference Optimisation: Making Models Faster and Cheaper

A deeper look at LLM inference: compute-bound vs memory-bandwidth-bound workloads, TTFT, TPOT, goodput, MFU and MBU, accelerators, model-level optimisations (quantisation, distillation, speculative decoding, inference with reference, parallel decoding, attention and KV-cache optimisation, kernels) and service-level optimisations (continuous batching, prefill/decode disaggregation, prompt caching, tensor and pipeline parallelism).

On this page

Simple definition#

Inference optimisation is making a model produce the same (or nearly the same) output faster, cheaper or for more users at once. It happens at three levels: the model (make it smaller or decode smarter), the hardware (use the accelerator well) and the service (schedule requests well).

You care about it most when you self-host models, but it also explains API pricing, latency and rate limits. Start with inference and serving for the basics.

Two kinds of bottleneck#

Every workload is limited by one of two things:

Bottleneck What limits speed LLM phase
Compute-bound How many arithmetic operations per second the chip can do Prefill — processing the whole prompt in parallel
Memory-bandwidth-bound How fast weights and the KV cache can be moved from memory to the compute units Decode — generating one token at a time
Prefill is compute-bound, decode is bandwidth-bound
flowchart LR
    P["Prompt tokens"] --> PF["PREFILL<br/>all prompt tokens at once<br/>compute-bound"]
    PF --> KV[("KV cache")]
    KV --> DC["DECODE<br/>one token per step<br/>reads all weights each step<br/>bandwidth-bound"]
    DC -->|"next token"| DC
    DC --> OUT["Output tokens"]

This is also why online (interactive) APIs and batch APIs are priced differently: batch jobs can be scheduled to keep hardware fully busy, so providers often discount them heavily.

Metrics that matter#

Metric Meaning Users feel it as
TTFT — time to first token Queueing + prefill “Is it responding?”
TPOT — time per output token Decode speed per stream Reading speed of the stream
Total latency TTFT + TPOT × output tokens Waiting for the whole answer
Throughput Tokens (or requests) per second across all users Cost per token
Goodput Requests per second that meet your latency targets Capacity you can actually sell
MFU — model FLOPs utilisation Achieved FLOP/s ÷ peak FLOP/s Compute efficiency (prefill, training)
MBU — model bandwidth utilisation Achieved bytes/s ÷ peak bandwidth Memory efficiency (decode)

Report latency as percentiles (p50, p90, p99), not averages; a few long prompts skew the mean.

Accelerators in brief#

When choosing hardware, three properties matter more than the brand:

Property Why
FLOP/s at your precision (FP16, FP8, INT8, INT4) Prefill speed and training
Memory size (HBM) Whether the model and KV cache fit on one device
Memory bandwidth Decode speed

Also count power and cooling — often the real constraint in an on-premise data centre. See on-premise and hybrid deployment.

Model-level optimisation#

Model compression#

Technique Idea Trade-off
Quantisation Store weights (and sometimes activations, KV cache) in fewer bits: FP16 → FP8/INT8 → INT4 Big memory and speed gains; small quality loss, larger at 4 bits and below
Distillation Train a smaller student to imitate a larger teacher Needs training data and effort; the student is cheaper to serve
Pruning Remove weights or structures that contribute little Less common in practice for LLMs; hardware support varies

Quantisation is the most widely used. See fine-tuning in depth: numerical formats.

Getting past one-token-at-a-time#

Decoding is sequential: token n+1 depends on token n. Several techniques generate more than one token per expensive step.

Technique How it works Best for
Speculative decoding A small, fast draft model proposes several tokens; the large model verifies them in one parallel pass and keeps the accepted prefix General chat and code; output distribution unchanged
Inference with reference Copy spans straight from the input (the “reference”) instead of generating them Code editing, document revision, RAG answers that quote sources
Parallel decoding Extra prediction heads (for example Medusa) or lookahead methods guess several future tokens at once, then verify Reducing latency without a separate draft model

Speculative decoding works because verifying k tokens costs about the same as generating one — decode is bandwidth-bound, so the extra compute is nearly free.

Attention and the KV cache#

The KV cache stores keys and values for every token in every layer so they are not recomputed. Its size is roughly:

KV cache bytes ≈ 2 × batch × sequence_length × layers × model_dim × bytes_per_value

For a 13B-class model (40 layers, dimension 5120) serving a batch of 32 with 2,048-token sequences in 16-bit, that is about 54 GB — more than the model weights. Long context and high concurrency make the KV cache the main memory consumer.

Ways to shrink or manage it:

Approach Example
Share keys and values across heads Multi-query attention (MQA), grouped-query attention (GQA)
Limit what is attended to Sliding-window or local attention, layer sharing
Manage memory like an OS PagedAttention (vLLM): allocate KV cache in pages, avoid fragmentation
Quantise the cache Store KV in 8 or 4 bits
Faster attention kernels FlashAttention: compute attention in on-chip SRAM, avoiding slow memory round trips

Kernels and compilers#

Much of the remaining speed comes from software that maps the model efficiently to the chip: operator fusion (merge several operations into one kernel), vectorisation, parallelisation and loop tiling. Compilers such as torch.compile, TensorRT and XLA do this automatically; serving engines such as vLLM, SGLang and TensorRT-LLM bundle the best kernels. In practice, choosing a good serving engine is the largest single optimisation most teams make.

Service-level optimisation#

Batching#

Strategy Behaviour Drawback
Static batching Wait for a full batch, process together Early requests wait; short answers wait for long ones
Dynamic batching Process when the batch is full or a time window expires Better latency; still waits for the longest sequence
Continuous (in-flight) batching Requests join and leave the batch at each decode step Best utilisation; standard in modern servers

Decoupling prefill and decode#

Prefill (compute-bound) and decode (bandwidth-bound) compete when they share a GPU: a long prompt arriving stalls everyone’s token stream. Disaggregated serving runs them on separate instances and transfers the KV cache between them, so each pool can be sized and tuned independently.

Prompt caching#

Reuse the computed KV cache for repeated prefixes — a long system prompt, tool definitions, a shared document. It cuts TTFT and cost for every request that shares the prefix. Design prompts with the stable part first and the variable part last. See prompt caching.

Parallelism#

When a model does not fit on one device, or one device is too slow:

Type What is split Use
Replica (data) parallelism Nothing — run full copies Scale throughput when the model fits on one node
Tensor parallelism Each layer’s matrices across devices Fit large models and cut latency; needs fast interconnect
Pipeline parallelism Consecutive layers across devices Fit very large models; adds pipeline bubbles, better for throughput than latency
Context / sequence parallelism The input sequence across devices Very long contexts
Expert parallelism MoE experts across devices Serving mixture-of-experts models

A practical order of work#

  1. Measure TTFT, TPOT, goodput and cost per request against SLOs, by percentile.
  2. Use a modern serving engine with continuous batching, paged KV cache and fast attention kernels.
  3. Enable prompt caching and restructure prompts so stable content comes first.
  4. Quantise (FP8 or INT8 first; INT4 after evaluation).
  5. Try speculative decoding for latency-sensitive workloads.
  6. Right-size the model — distil or route easy requests to a smaller model (routing).
  7. Scale out with the parallelism strategy that matches your bottleneck.

Re-run your evaluation suite after every step: optimisations that change numerics can change answers.

Common mistakes#

Review questions#

Why is decode memory-bandwidth-bound? Each generated token needs every weight (and the KV cache) read from memory, but performs relatively little computation on it, so the speed of moving bytes — not arithmetic — sets the pace.

How does speculative decoding speed things up without changing quality? A small draft model proposes several tokens; the large model verifies them in one parallel pass, accepting the longest correct prefix. Because verification is nearly as cheap as generating one token, accepted tokens come almost for free, and the acceptance rule preserves the large model’s output distribution.

What is continuous batching? A scheduler that adds new requests to, and removes finished requests from, the running batch at every decode step, keeping the accelerator busy and avoiding waits for the longest sequence.

What is goodput and why is it better than throughput? The rate of requests that meet latency SLOs. Throughput can be raised by starving latency; goodput measures the capacity you can actually offer users.

How would you serve a model that does not fit on one GPU? Quantise it if quality allows; otherwise use tensor parallelism within a node (fast interconnect) and pipeline parallelism across nodes, sizing for both weights and KV cache.

Summary#

  • Prefill is compute-bound; decode is bandwidth-bound — most optimisations target decode.
  • Measure TTFT, TPOT, goodput, MFU and MBU, by percentile, against SLOs.
  • Model-level: quantise, distil, speculative or parallel decoding, shrink the KV cache, use fast kernels.
  • Service-level: continuous batching, prefill/decode disaggregation, prompt caching, the right parallelism.
  • Re-evaluate quality after every optimisation.

References#