Inference Optimization and Quantization

Why model serving is slow or costly, and the techniques that fix it without silently harming your agent.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Serving a model is limited by memory and by how busy you keep the hardware. Quantization stores weights in fewer bits. Continuous batching and careful cache management let many requests share a processor. Prefix caching skips repeated work, which suits agents well. Speculative decoding can shorten response time. Every one of these must be measured on your own tasks, including tool calls.

What you will learn: the two phases of generation, how to estimate memory needs, what quantization trades away, why batching changes throughput so much, how caching and speculative decoding work, and how to test an optimized model.
Prerequisites: How LLMs Power Agents: Transformers, Tokens and Sampling. Basic Python helps with the examples. No graphics processor is needed to run them.

Beginner What happens when a model answers

Two phases: reading and writing

A language model works in tokens, which are words or pieces of words. Generating an answer has two phases. In prefill, the model processes the whole prompt, much of it in parallel. In decode, it produces the answer one token at a time, each new token depending on those before it.

Requestprompt tokens
Prefillprocess the prompt, fill the cache
Decodeone new token per step
Answerstreamed to the caller
↺ Decode repeats until the model stops or reaches its limit
Long prompts stress prefill; long answers stress decode.

Four numbers to watch

MeasureMeaningMatters most for
Time to first tokenDelay before output beginsChat and voice, where silence feels broken
Time per output tokenSpeed of writing after the first tokenLong answers and code generation
ThroughputTokens or requests completed per second by the whole serverCost per request
Tail latency (p95, p99)Delay experienced by the slowest 5% or 1%User trust and timeouts

An agent makes many model calls in sequence, so a small delay per call adds up. Ten calls of three seconds each is half a minute before counting any tool. Reducing the number of calls is often the first optimization, ahead of anything inside the server.

Using a hosted API?

If a provider runs the model, you do not choose quantization or batching. Your levers are model choice, shorter prompts, prompt caching, batch interfaces for work that can wait, output limits and streaming. The section Reducing Tokens, Tool Calls and Spend covers them. The rest of this page explains what happens underneath and what you control when you host a model yourself.

Memory comes first

Two things fill a graphics processor's memory. The weights are the model itself. The key-value cache (KV cache) holds intermediate results for every token already seen, for every request in progress, so they need not be recalculated.

"""Estimate memory for model weights and for the key-value cache."""

def weights_gb(parameters, bits):
    return parameters * bits / 8 / 1e9

def kv_cache_gb(layers, kv_heads, head_dim, tokens, bytes_per_value=2):
    """One key and one value per layer, per head, per token held."""
    return 2 * layers * kv_heads * head_dim * bytes_per_value * tokens / 1e9

if __name__ == "__main__":
    parameters = 8e9                      # an illustrative 8-billion model
    for bits in (16, 8, 4):
        print(f"weights at {bits:>2} bits: {weights_gb(parameters, bits):5.1f} GB")
    print()
    for requests, context in ((1, 8_000), (16, 8_000), (64, 8_000), (64, 32_000)):
        size = kv_cache_gb(layers=32, kv_heads=8, head_dim=128,
                           tokens=requests * context)
        print(f"{requests:>3} requests of {context:>6,} tokens: "
              f"cache {size:6.1f} GB")

Output:

weights at 16 bits:  16.0 GB
weights at  8 bits:   8.0 GB
weights at  4 bits:   4.0 GB

  1 requests of  8,000 tokens: cache    1.0 GB
 16 requests of  8,000 tokens: cache   16.8 GB
 64 requests of  8,000 tokens: cache   67.1 GB
 64 requests of 32,000 tokens: cache  268.4 GB

The layer and head counts are illustrative; read the real values from your model's configuration file. Note how the cache soon outgrows the weights: 64 requests with long conversations need many times the memory of the model itself. Context length is a serving cost, not only a quality choice. These figures also omit working memory used during calculation, so leave headroom.

Intermediate The main techniques

Quantization

Model weights are decimal numbers, commonly stored in 16 bits each. Quantization stores them in fewer bits, usually by saving small whole numbers together with a scale that converts them back. Moving from 16 to 4 bits cuts weight memory to about a quarter, and because decoding often waits on memory transfer, it can also be faster.

The cost is rounding error. This script shows why modern methods use many local scales instead of one:

"""What quantization does: store numbers as small integers plus a scale."""
import random

def quantize(values, bits):
    limit = 2 ** (bits - 1) - 1
    scale = max(abs(v) for v in values) / limit
    return [round(v / scale) for v in values], scale

def mean_error(values, bits, block):
    """Quantize in blocks; each block gets its own scale."""
    total = 0.0
    for start in range(0, len(values), block):
        part = values[start:start + block]
        integers, scale = quantize(part, bits)
        total += sum(abs(v - i * scale) for v, i in zip(part, integers))
    return total / len(values)

if __name__ == "__main__":
    random.seed(7)
    values = [random.gauss(0, 0.02) for _ in range(4096)]
    for index in range(0, len(values), 512):       # a few large outliers
        values[index] = 0.5
    print("bits  one scale  scale per 64   (mean absolute error)")
    for bits in (8, 4):
        print(f"{bits:>4}  {mean_error(values, bits, 4096):9.5f}  "
              f"{mean_error(values, bits, 64):12.5f}")

Output:

bits  one scale  scale per 64   (mean absolute error)
   8    0.00098       0.00021
   4    0.01476       0.00339

A few large values force a single scale to be coarse, so every other value is rounded badly. Giving each block of 64 values its own scale confines the damage. At either block size, 4 bits are far less precise than 8.

ApproachHow it worksNotes
16-bit floating pointReduced-precision format often used as the baselineLittle effort; the reference for comparisons
8-bitWeights, and sometimes activations, stored as 8-bit valuesUsually a small quality change; check it
4-bit, weight-only (for example GPTQ, AWQ)Calibration data guides how weights are rounded or scaledLarge memory saving; quality varies by model and method
Below 4 bitsMore aggressive schemesNeeds careful testing; often research territory

GPTQ compensates for the error introduced by rounding as it works through the model's layers. AWQ (activation-aware weight quantization) observes which weights matter most during real use and protects them; its authors report that protecting about 1% of salient weights greatly reduces error. Many open models are published in ready-quantized versions. Check who produced the file and test it, because it is a different model from the original in practice. See Supply Chain and Retrieval Poisoning.

Batching

A graphics processor can work on many requests at once at little extra cost per step. Static batching groups requests and waits until all of them finish, so short answers sit idle behind long ones. Continuous batching removes a finished request immediately and adds a waiting one in its place.

"""Static and continuous batching, counted in decoding steps."""

# Output length (tokens) of each waiting request, in arrival order.
LENGTHS = [20, 200, 30, 25, 180, 15, 40, 22, 160, 35, 28, 18]
SLOTS = 4

def static_batching(lengths, slots):
    """A batch finishes only when its longest member finishes."""
    clock, finished = 0, []
    for start in range(0, len(lengths), slots):
        batch = lengths[start:start + slots]
        finished += [clock + n for n in batch]
        clock += max(batch)
    return clock, finished

def continuous_batching(lengths, slots):
    """A free slot takes the next request immediately."""
    free_at, finished = [0] * slots, []
    for n in lengths:
        slot = free_at.index(min(free_at))
        free_at[slot] += n
        finished.append(free_at[slot])
    return max(free_at), finished

if __name__ == "__main__":
    for name, method in (("static", static_batching),
                         ("continuous", continuous_batching)):
        clock, finished = method(LENGTHS, SLOTS)
        busy = sum(LENGTHS) / (clock * SLOTS)
        print(f"{name:<11} total steps {clock:>4}  slots busy {busy:.0%}  "
              f"average finish {sum(finished) / len(finished):6.1f}")

Output:

static      total steps  540  slots busy 36%  average finish  257.8
continuous  total steps  222  slots busy 87%  average finish  104.8

The simulation counts decoding steps only and ignores prefill, but the pattern is real: when output lengths differ widely, filling free slots at once uses far more of the hardware and finishes the average request sooner.

Larger batches raise throughput up to a point. Beyond it, each request waits longer for each token, and the cache may fill. Serving software therefore has limits on concurrent requests that you should tune against your latency target.

Managing the cache

If a server reserves space for each request's longest possible answer, most of it goes unused. PagedAttention, introduced with the vLLM project, splits the cache into small blocks allocated as needed, much as an operating system pages memory. This allows more requests to fit and lets requests with a shared beginning share blocks.

Prefix caching

An agent's calls usually repeat a long beginning: system instructions, tool definitions and earlier turns. Prefix caching keeps the computed results for that beginning and reuses them when the next request starts with exactly the same tokens.

  • Put stable content first and changing content last.
  • Keep tool definitions in a fixed order.
  • Do not place the current time or a random identifier near the top.
  • Append to the conversation instead of rewriting earlier turns, unless you are deliberately compressing it.
  • Share caches only within a safe boundary. Separate tenants where policy requires it.

Context Assembly, Retrieval, Compression and Caching shows how to order a prompt with this in mind.

Speculative decoding

Decoding is slow partly because it produces one token per full pass of a large model. In speculative decoding, something cheaper, such as a small draft model, proposes several tokens. The large model checks them together in one pass, accepts the leading ones it agrees with and corrects the first one it does not. In its standard form this keeps the large model's output distribution while reducing the time taken.

The benefit depends on how often proposals are accepted. Predictable text, such as editing code where much stays unchanged, accepts many. Surprising text accepts few, and the draft work is wasted. It uses extra memory and may reduce total throughput on a busy server, so judge it by your actual aim: faster single responses or more requests per machine.

Other techniques you will meet

TechniqueIdea
Efficient attention kernels (such as FlashAttention)Reduce slow memory movement inside the core calculation
Chunked prefillSplit a long prompt into pieces so it does not stall other requests
Multiple adaptersServe several small fine-tuned add-ons over one base model
Parallelism across devicesSpread a model that is too large for one processor
Smaller or distilled modelsDo less work for tasks that do not need a large model
RoutingSend each request to the cheapest model that handles it well; see Model Routing, Fallbacks and Gateways
Expert Running it responsibly

A serving setup

vLLM is a widely used open-source server. Its documentation lists PagedAttention, continuous batching, prefix caching, speculative decoding, chunked prefill, quantization support, multi-adapter serving and an OpenAI-compatible interface. A launch command has this shape; it was not run for this page because it needs a graphics processor and a model download:

vllm serve your-org/your-model-awq \
  --quantization awq \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --api-key "$VLLM_API_KEY"

Check each option against the documentation for your installed version, since serving software changes quickly.

Do not expose the server directly

The vLLM documentation warns that its API key option does not protect every endpoint. Put any model server on a private network behind a gateway that handles authentication, rate limits and logging. See Network, Tenant and Multi-Agent Isolation.

Test quality after every change

A smaller memory footprint is worthless if the agent starts calling the wrong tool. Aggregate scores can hide this, so compare the original and optimized models on the same cases and check each ability separately:

CheckHow to measure
Tool choice and argumentsExact comparison against expected calls
Valid structured outputShare of replies that pass the schema
Long-context recallQuestions whose answers sit at different depths
Instruction followingRules that code can verify, such as length or language
Safety behaviorYour refusal and injection test sets
Rare languages and domain termsA slice of cases for each, reported separately

Methods for these comparisons appear in Model Evaluation and Failure Modes.

Load testing

  1. Record real prompt and output lengths, including their spread.
  2. Replay a realistic arrival pattern, with bursts, not a steady trickle.
  3. Increase load until tail latency breaks your target.
  4. Note the throughput just before that point; this is your usable capacity.
  5. Repeat with each optimization switched on one at a time, so you know what helped.

Averages mislead here. A change can improve throughput while making the slowest users much worse off. Capacity planning is covered further in Latency, Load Testing and Capacity Planning and the hardware side in NVIDIA, vLLM and GPU Sizing.

A sensible order of work

1. Send less and call lessShorter prompts, fewer steps, output limits
2. Use the right size of modelRoute easy work to small models
3. Use a good serverContinuous batching and paged cache
4. Cache repeated prefixesOrder prompts for reuse
5. Quantize or speculateOnly with quality tests in place
Early steps are cheaper and carry less risk.
Illustrative example: an internal assistant

An invented team hosts a model for a help desk and sees slow answers at nine each morning. Measurement shows a long, unchanging instruction block with the date at the top. Moving the date to the end allows prefix reuse. They then cap output length for routine replies. Only afterward do they test a quantized version, keep it for classification, and keep the original for troubleshooting where tool accuracy dropped.

Count cost per successful task

A faster, cheaper model that fails more often may trigger retries and human clean-up. Divide the whole serving cost by the number of tasks completed correctly. That figure, not tokens per second, shows whether an optimization was worth it.

Common problems

SymptomLikely causeTry
Out-of-memory errors under loadCache exceeds available memoryLower context or concurrency limits
Long wait before outputQueueing, or very long promptsPrefix caching, chunked prefill, more replicas
Low processor useSmall batches or static batchingContinuous batching; check the client sends requests concurrently
Cache rarely reusedChanging content near the startReorder the prompt
Quality dropped after quantizingMethod or bit width too aggressiveUse more bits or another calibration; re-test

Optimization checklist

  • Latency and throughput targets are written down, including a tail target.
  • Memory estimate covers weights, cache and headroom.
  • Prompts are ordered with stable content first.
  • Each change is measured separately on realistic load.
  • Tool calls and structured output are re-tested after quantizing.
  • The server is private and sits behind authentication.
  • Cost per successful task is tracked.

Frequently asked questions

Does quantization always make a model faster?

No. It reduces memory and often memory transfer time, but speed depends on the hardware and on whether the server has efficient calculations for that format. Measure it.

How much quality does 4-bit quantization lose?

It varies by model, method and task, so no single figure is trustworthy. Compare against the original on your own cases.

Is self-hosting cheaper than an API?

It can be with high, steady volume and skilled operators. With uneven or low traffic, idle hardware often makes it dearer. Compare total cost, including staff time.

References and further reading

Next steps