Inference Efficiency: Quantization, Speculative Decoding, vLLM
After this lesson, you will be able to:
- Quantize an LLM from fp16 down to int4 with GPTQ or AWQ, and know when int4 is free, when it costs 1-3% quality, and when (int2 or below) it falls off the cliff
- Use speculative decoding to get a 2-3x latency speedup with no quality loss, and predict the speedup from the draft-acceptance rate
- Choose between vLLM, llama.cpp, and TGI for production serving based on whether you're throughput-bound, latency-bound, or running on consumer hardware
- Diagnose whether your inference workload is prefill-bound (compute) or decode-bound (memory bandwidth) and pick the right intervention for each
Before you start
Don't worry if "quantization" sounds like a separate field — it's mostly four ideas (per-tensor scaling, per-group scaling, calibration data, outlier handling), and the libraries do the heavy lifting once you understand the tradeoffs.
#The Inference Cost Problem
#Part 1: Quantization
The big LLM weight format ladder:
- fp32: 4 bytes per parameter, the original training format.
- fp16 / bf16: 2 bytes per parameter, the modern training default.
- int8: 1 byte per parameter, "essentially free" quality-wise on most models.
- int4: 0.5 bytes per parameter, costs 1-3% quality on most benchmarks.
- int2 / int1 (BitNet): research territory, 5-15% quality loss without specialized training.
#How Quantization Actually Works
Per-tensor scaling (one s for the whole layer) is naive and loses too much precision. Per-channel and per-group quantization preserve more of the dynamic range. Modern formats (GGUF, AWQ) use group sizes of 32-128 weights.
#The Scale, the Zero Point and the Error Bound
The formula above leaves open how to pick the scale s. The standard recipe spreads the range of the weights evenly over the available integers. Open the derivation for the scale, the zero point and the size of the rounding error.
Drag the outlier up with one scale for the whole tensor, then switch to one scale per group, and compare the error with the step squared over twelve line.
#GPTQ: Hessian-Aware Quantization
The update above is a small constrained minimisation. Open the derivation to see where it comes from.
GPTQ is the de-facto standard for serving (Hugging Face Transformers, vLLM, TGI all support GPTQ-quantized models out of the box). AutoGPTQ and gptqmodel are the standard Python libraries.
#AWQ: Activation-Aware Quantization
The result: AWQ-quantized models often match GPTQ quality but are 10-30% faster at inference because they don't require runtime dequantization for the salient channels (they're already at higher effective precision).
#Practical Quantization with bitsandbytes
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
import torch
# 4-bit NF4 quantization with double quantization (QLoRA-style)
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
"meta-llama/Llama-3-8B-Instruct",
quantization_config=bnb_config,
device_map="auto",
)
# Memory: ~5.5 GB instead of 16 GB for fp16
# Quality drop: usually under 2% on MMLU/HumanEvalYou serve a 70B model with very long input context (50k tokens) and short outputs (200 tokens). Where is the bottleneck?
Why is batch-1 decode limited by memory bandwidth and not by arithmetic? Open the derivation. It also gives the tokens-per-second ceiling that quantization raises.
Raise the batch size and watch the dot climb the slanted line to the ridge; then switch between fp16 and int4 to see the ridge batch move.
#When Quantization Hits the Cliff
#Part 2: Speculative Decoding
Autoregressive generation is sequential by definition: you can't predict token N+1 without knowing token N. This means decode latency is dominated by the per-token forward pass through the full model.
#The Math of Speculative Speedup
#Variants of Speculative Decoding
- Vanilla speculative (Leviathan 2023, Chen 2023): a separate small model is the draft.
- Medusa (Cai 2024): instead of a separate model, attach multiple parallel "medusa heads" to the main model that predict tokens k=1, k=2, k=3 ahead.
- EAGLE (Li 2024): an autoregressive prediction head trained on the verifier's hidden states; achieves higher acceptance rate than Medusa.
- Lookahead decoding (Fu 2024): no draft model needed; uses Jacobi-like fixed-point iteration on a sliding window of future tokens.
In production, vLLM and TGI both support vanilla speculative; EAGLE is the current research frontier with the highest acceptance rates (~0.85+ on common workloads).
#Part 3: Continuous Batching and PagedAttention
Where does the per-request formula come from, and how big is it for a real model? Open the derivation.
How much of this memory does paging save? The part of the saving that comes from block rounding has a short derivation.
This example needs a deep-learning library, so it does not run on this page. Copy the code below to Google Colab.
# Copy to Colab: needs torch, transformers and bitsandbytes, and a GPU, so it cannot run on this page.
# Quantize a 7B model with bitsandbytes and benchmark
# vs fp16. Run this in a Colab with a free T4 GPU.
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"
PROMPT = "Explain photosynthesis in one paragraph:"
def benchmark(model, tokenizer, prompt, n_tokens=128):
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
# Warmup
_ = model.generate(**inputs, max_new_tokens=8, do_sample=False)
# Benchmark
torch.cuda.synchronize()
start = time.perf_counter()
out = model.generate(**inputs, max_new_tokens=n_tokens, do_sample=False)
torch.cuda.synchronize()
elapsed = time.perf_counter() - start
n_generated = out.shape[1] - inputs["input_ids"].shape[1]
return elapsed, n_generated, torch.cuda.max_memory_allocated() / 1e9
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
# fp16 baseline
print("Loading fp16 model...")
torch.cuda.reset_peak_memory_stats()
model_fp16 = AutoModelForCausalLM.from_pretrained(
MODEL_ID, torch_dtype=torch.bfloat16, device_map="auto"
)
elapsed, n_tok, mem_gb = benchmark(model_fp16, tokenizer, PROMPT)
print(f"fp16: {elapsed:.2f}s for {n_tok} tokens ({n_tok/elapsed:.1f} tok/s), {mem_gb:.1f} GB")
del model_fp16
torch.cuda.empty_cache()
# 4-bit NF4 quantization
print("Loading int4 model...")
torch.cuda.reset_peak_memory_stats()
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
)
model_int4 = AutoModelForCausalLM.from_pretrained(
MODEL_ID, quantization_config=bnb_config, device_map="auto"
)
elapsed, n_tok, mem_gb = benchmark(model_int4, tokenizer, PROMPT)
print(f"int4: {elapsed:.2f}s for {n_tok} tokens ({n_tok/elapsed:.1f} tok/s), {mem_gb:.1f} GB")
# Expected: int4 uses ~4 GB vs ~14 GB for fp16,
# tokens-per-sec is similar (compute-bound, not memory-bound for short outputs),
# quality on MMLU drops by ~1-2%.
print("\nCHALLENGE: load with vLLM's GPTQ kernel and compare throughput.")
print("vLLM's quantization is much faster than bitsandbytes for serving.")
# vLLM-based version (much faster for serving):
# from vllm import LLM, SamplingParams
# llm = LLM(model="TheBloke/Mistral-7B-Instruct-v0.2-GPTQ", quantization="gptq")
# sampling = SamplingParams(temperature=0, max_tokens=128)
# # vLLM batches multiple requests together; on a single A100 you can serve
# # hundreds of concurrent users at int4. bitsandbytes is for development;
# # vLLM/TGI/llama.cpp is for production.#Inference economics: what does a token actually cost?
Throughput numbers like "80 tokens per second" feel abstract until you turn them into dollars. The conversion is mechanical: pick a model and quantization, look up the prefill and decode rates on a target GPU, divide GPU rental cost by tokens produced, and you have $/token. Let us run the arithmetic on a concrete workload — a customer-support chatbot answering one-thousand-token prompts with two-hundred-token replies — and compare self-hosted Llama against a metered API.
4.5 × 2.50 / 3600 = $0.0031 per request, or $3.10 per 1,000 requests. Stack a batch of 16 concurrent requests via continuous batching and the per-request cost can drop another 5–10×.1000 × 0.15/1e6 + 200 × 0.60/1e6 = $0.00015 + $0.00012 = $0.00027, or $0.27 per 1,000 requests. The API is ~10× cheaper here because (a) you only pay for what you use — no idle GPU, (b) the API runs a much smaller model than 70B, and (c) the provider amortizes one H100 across thousands of tenants.prefix caching, OpenAI's prompt cache, Anthropic's prompt caching) is the single biggest cost lever for repetitive workloads — the chatbot system prompt gets billed once instead of every turn. Second, latency is not the same as throughput-cost: an H100 doing batch-1 decode at 80 tok/s gives 12.5 ms per token (fast) but is wildly more expensive than the same H100 in batch-32 mode, which might give 35 ms per token but serve 32 users at once. SLO targets, not raw throughput, dictate which mode you run in.#Engine cheat-sheet
The right inference engine depends on what you are optimizing for. The table below is the short version of "which one do I install on Monday morning."
| Engine | Best at | Hardware | When to pick it |
|---|---|---|---|
| vLLM | High-throughput multi-tenant serving | Nvidia (A100/H100/L40S) | Default for production APIs. PagedAttention + continuous batching + GPTQ/AWQ. |
| SGLang | Structured outputs, constrained gen | Nvidia | Heavy JSON-mode/grammar workloads or RAG with shared prefixes — RadixAttention shines. |
| TGI | HF-ecosystem enterprise | Nvidia / AMD | You already live on Hugging Face Hub, need gRPC + tensor parallel + safetensors. |
| TensorRT-LLM | Lowest latency on Nvidia | Nvidia only | You are willing to compile per-model and lock in to Nvidia for max tok/s. |
| llama.cpp | Consumer / edge / Apple Silicon | CPU, Metal, CUDA, ROCm | Mac mini, single-user laptop, or air-gapped deployments. GGUF q4 / q5 / q6. |
The playground below turns the cost equation into a slider toy: dial in model size, GPU count, hourly cost, and throughput, and watch $/M tokens move.
#Key Takeaways
- int8 quantization is essentially free; int4 costs 1-3% quality. Modern formats (GPTQ, AWQ, NF4 with bitsandbytes) all deliver excellent int4 quality with proper per-group scaling. int2 and below remain research territory.
- GPTQ vs AWQ: GPTQ is more flexible, AWQ is faster. Both achieve similar quality. AWQ's activation-aware salient-channel handling makes it 10-30% faster at inference, and it's the modern default for new deployments. GPTQ has wider tooling support.
- Speculative decoding gives 2-3x latency speedup with zero quality loss. A small draft model generates k tokens, the big verifier accepts or rejects them in parallel. Net speedup depends on the draft acceptance rate (α): higher α = more accepted draft tokens per verify step.
- vLLM's PagedAttention is the production default for high-throughput serving. Continuous batching plus block-level KV cache management raises GPU utilization from 20-40% (naive) to 80-95%. Prefix caching is a free additional win for chatbot workloads with shared system prompts.
- Prefill and decode have different bottlenecks. Prefill is compute-bound (FLOPs); decode is memory-bandwidth-bound (reading model weights from VRAM). Modern serving systems are starting to disaggregate the two onto separate GPU pools optimized for each.
#Quick Check
You quantize a 70B model from fp16 to int4. What's the approximate memory reduction?