PagedAttention Memory Management
vLLM 0.6 treats the key-value cache as virtual memory. Instead of allocating a single contiguous block for each sequence, it splits the KV cache into fixed-size pages of 16 tokens by default. When a sequence grows, the engine requests additional pages from a shared page pool rather than reallocating the entire cache. This eliminates the need to reserve maximum context length upfront for every request.
Traditional Hugging Face transformers with use_cache=True allocates a [batch_size, num_heads, max_len, head_dim] tensor immediately. For a 70B model with 64 attention heads, head dimension 128, batch size 16 and max 8192 tokens, that single tensor consumes over 64 GB before any tokens are generated. PagedAttention removes this waste by allocating only what is currently used plus a small overhead for page tables.
In practice the vLLM team measured 60-70% lower peak memory usage on long-context workloads. The page size is controlled with the --kv-cache-page-size flag. Most production deployments keep the default of 16 because smaller pages (8 tokens) increase the frequency of block manager calls while larger pages (32 tokens) lead to internal fragmentation when sequences finish mid-page.
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3.1-70B-Instruct \
--kv-cache-page-size 16 \
--gpu-memory-utilization 0.85 \
--max-num-batched-tokens 16384
The block manager lives inside the CacheEngine class. Each logical block maps to a physical block in GPU memory. Block tables are Python lists of integers stored on CPU for fast manipulation. When the scheduler needs to copy a sequence during beam search or when a request is preempted, only the relevant page references are copied. This copy-on-write semantic mirrors the fork() behavior in Linux operating systems and costs only a few microseconds.
To inspect cache behavior in a running server, query the /stats endpoint. It returns JSON with cache_config and current utilization. Teams add a small sidecar that scrapes this endpoint every 10 seconds and pushes metrics to Prometheus. This visibility lets operators adjust --gpu-memory-utilization before OOM occurs.
Block Table Internals and Eviction
vLLM maintains two structures: a block table that maps logical blocks to physical blocks and a free block list implemented as a deque for O(1) pops. When memory pressure rises above the --gpu-memory-utilization threshold (default 0.9), the scheduler preempts the lowest-priority running request. Preemption mode is selectable with --preemption-mode set to either swap or recompute.
Swap mode copies blocks to host DRAM if --swap-space is enabled. Recompute mode discards the cache and recomputes prefix tokens on resumption. Swap is preferred for latency-sensitive applications because recompute can add 200-800 ms for 4k token prompts. Production teams running 70B models on A100 80 GB cards typically set --gpu-memory-utilization 0.82, --swap-space 24 and --preemption-mode swap to leave 15% headroom for bursts.
The swap space lives in host DRAM. Copying a 16-token page between GPU and CPU costs approximately 0.3 ms on PCIe 4.0 links and 0.15 ms on PCIe 5.0. Because preemption is designed to be rare, the amortized cost stays negligible. Monitoring the vllm:swapped_blocks metric helps operators detect when the system is thrashing.
Continuous Batching Scheduler
Traditional static batching waits for an entire batch to finish before processing the next set of requests. vLLM's scheduler operates at the iteration level. After each forward pass of the transformer, it immediately adds newly arrived requests, removes finished ones, and constructs the next batch without padding to the original batch size.
The core loop lives in LLMScheduler.schedule(). It returns three groups: running sequences that continue decoding, swapped sequences being restored from CPU, and waiting sequences that have not yet started prefilling. The engine then builds one combined batch containing tokens from all three groups. Because padding only occurs for the current step rather than the entire request lifetime, GPU utilization stays above 85% even with highly variable sequence lengths from 16 to 4096 tokens.
Concrete measurements on Llama-3.1-8B using an H100 SXM show throughput rising from 180 tokens per second with static batching (batch size fixed at 64) to 410 tokens per second with continuous batching at peak batch size 256. The improvement comes from eliminating idle GPU cycles that occur when some sequences in a static batch finish early.
The scheduler also implements prefix caching. When two requests share a common prompt prefix, vLLM reuses the cached KV pages for that prefix. Enable this with --enable-prefix-caching. In RAG applications where many users query the same document chunks, prefix caching improves throughput by an additional 25-40%.
Preemption and Priority Queues
The scheduler uses two priority queues. Running requests are ordered by arrival time to implement fair scheduling. Waiting requests are ordered by estimated completion time using a simple linear model based on prompt length and average decode speed. When a new high-priority request arrives, vLLM can preempt a lower-priority request mid-generation if the estimated impact on tail latency stays below the configured threshold.
Use the --max-num-swapped-seq flag to limit simultaneous swaps. Setting it too high increases CPU-GPU traffic; setting it to zero disables preemption entirely, which is useful for latency-sensitive customer-facing chat where consistent 95th-percentile latency matters more than average throughput. The priority field can be passed in the OpenAI API extension:
client.chat.completions.create(
model="Meta-Llama-3.1-8B-Instruct",
messages=messages,
extra_body={"priority": 0} # lower number = higher priority
)
Tensor Parallelism and Pipeline Parallelism Configuration
vLLM 0.6 ships with both tensor parallelism (TP) and pipeline parallelism (PP). For a 70B model on 8×H100 GPUs the recommended configuration is TP=8, PP=1 because tensor parallelism scales better on NVLink-connected GPUs. The launch command is:
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3.1-70B-Instruct \
--tensor-parallel-size 8 \
--pipeline-parallel-size 1 \
--port 8000 \
--enable-overlap-agg
TP=8 shards every weight matrix and attention computation across all 8 GPUs using NCCL all-reduce operations. Communication volume per forward pass is approximately 2×model_size bytes. For the 70B model this equals roughly 140 GB of NCCL traffic per step. The --enable-overlap-agg flag overlaps this communication with computation, hiding most of the latency.
Pipeline parallelism becomes valuable when model size exceeds single-node memory or when using lower-end interconnects. With PP=4 and TP=2 on 8 GPUs the engine places four transformer layers per GPU. The scheduler must insert pipeline bubbles; vLLM's 1F1B (one forward one backward) schedule minimizes these bubbles to roughly 15% of total step time for typical 2048-token workloads.
For a 405B model, the configuration TP=8, PP=4 across 32 H100 GPUs is common. Tuning NCCL parameters is required: export NCCL_IB_GID_INDEX=3, NCCL_NET_GDR_LEVEL=5 and NCCL_P2P_LEVEL=5 to maximize bandwidth. Incorrect NCCL settings can halve effective throughput.
LoRA Serving Without Base Model Duplication
One of vLLM's strongest production features is dynamic multi-LoRA serving. The base model weights stay loaded once in GPU memory. Each LoRA adapter consists of a set of rank-decomposed matrices (typically rank 8 or 16) that are applied on-the-fly during the forward pass using fused kernels.
Load adapters at runtime with a POST to the /v1/lora/adapter endpoint or preload them at server start using the --lora-modules argument. The server can serve dozens of adapters concurrently without reloading the base weights.
python -m vllm.entrypoints.openai.api_server \
--model meta-llama/Meta-Llama-3.1-8B-Instruct \
--enable-lora \
--lora-modules "sql-lora=./adapters/sql-lora-adapter" "code-lora=./adapters/python-lora" \
--max-lora-rank 16 \
--max-num-seqs 256 \
--lora-cache-size 32
At inference time, specify which adapter to use by adding "lora_name": "sql-lora" inside extra_body. The engine keeps a LRU cache of loaded adapters. When the cache overflows, least-recently-used adapters are evicted to CPU and reloaded on next use. Because adapter application is fused into the GEMM kernels via custom CUDA code, the overhead of switching adapters mid-batch stays under 5% when the number of distinct LoRAs per batch remains below 4.
Adapter Memory Math
A rank-16 LoRA adapter for Llama-3.1-8B consumes approximately 42 MB per adapter (two matrices per linear layer across 32 layers, stored in BF16). With 64 adapters loaded simultaneously the extra memory footprint is only 2.7 GB. This fits comfortably alongside the 16-bit base model on a single A100 40 GB card when using --gpu-memory-utilization 0.9. Rank-32 adapters double the memory but often deliver better task performance on complex domains such as SQL generation or legal text.
To create a LoRA adapter, teams use the PEFT library with the following pattern:
from peft import LoraConfig, get_peft_model
lora_config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=["q_proj", "v_proj", "k_proj", "o_proj"],
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM"
)
model = get_peft_model(base_model, lora_config)
# training loop omitted
model.save_pretrained("adapters/sql-lora")
The saved adapter directory is then mounted into the vLLM container and referenced at startup.
Quantization Support and Kernel Selection
vLLM 0.6 ships with native support for AWQ, GPTQ, SqueezeLLM and FP8. The recommended path for most teams is AWQ-INT4 because it retains greater than 98% of original model quality on MMLU and HumanEval while cutting memory footprint in half.
First quantize the model using the AutoAWQ library:
from awq import AutoAWQForCausalLM
model = AutoAWQForCausalLM.from_pretrained("meta-llama/Meta-Llama-3.1-8B-Instruct")
model.quantize(tokenizer, quant_config=awq_config)
model.save_quantized("Meta-Llama-3.1-8B-AWQ")
Then serve with:
vllm serve Meta-Llama-3.1-8B-AWQ \
--quantization awq \
--quantization-config '{"zero_point": true, "group_size": 128}' \
--dtype auto
The engine automatically selects the best kernel: Marlin for GPTQ-4bit on Ampere and newer GPUs, and custom Triton kernels for AWQ. On H100, Marlin kernels deliver 1.8× higher tokens-per-second than the baseline CUTLASS kernels at batch size 128. FP8 support is new in 0.6 and requires the --dtype float8_e4m3fn flag together with an FP8 checkpoint. Current trade-off: FP8 reduces memory by 50% versus BF16 but introduces a small accuracy drop of 1-2 points on reasoning-heavy tasks. Teams running RAG pipelines usually stay with AWQ-INT4 while teams running pure creative writing prefer BF16.
OpenAI-Compatible Endpoint and Client Patterns
vLLM exposes an endpoint compatible with OpenAI Python SDK v1.40+. This means existing code written for GPT-4 can be pointed at a local vLLM server with a single line change of the base_url.
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="http://localhost:8000/v1",
api_key="EMPTY",
timeout=60.0
)
async def generate(stream=True):
stream = await client.chat.completions.create(
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
messages=[{"role": "user", "content": "Explain PagedAttention"}],
temperature=0.7,
max_tokens=1024,
stream=stream
)
async for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="")
Streaming works through Server-Sent Events. The --max-logprobs 20 flag controls how many top logprobs are returned when logprobs=True is set. Production teams usually disable logprobs on high-traffic endpoints to reduce token overhead and bandwidth.
For structured output, combine with guided_decoding using regex or JSON schema. The server integrates with outlines under the hood:
extra_body={
"guided_json": {
"type": "object",
"properties": {"sql_query": {"type": "string"}},
"required": ["sql_query"]
}
}
This guarantees valid JSON without post-processing. Error handling should wrap calls in retries with exponential backoff because transient NCCL errors can occur during high load.
Observability and Metrics Exposure
The server exposes Prometheus metrics at /metrics. Key metrics include vllm:num_running_requests, vllm:num_waiting_requests, vllm:gpu_cache_usage_perc, vllm:avg_prompt_throughput_tokens_per_sec and vllm:avg_generation_throughput_tokens_per_sec.
Useful PromQL queries for Grafana:
- Rate of requests:
rate(vllm:request_success_total[5m]) - Cache pressure:
vllm:gpu_cache_usage_perc * 100 - Queue latency:
vllm:avg_waiting_time_ms
Combine these with Kubernetes pod metrics and NVIDIA DCGM exporter to build a complete dashboard. The --otlp-traces-endpoint http://jaeger:4317 flag enables OpenTelemetry tracing. Each request trace contains spans for scheduling delay, prefill time, decode time, and LoRA adapter load time if applicable. Sampling rate should be set to 0.1 in production to avoid overwhelming the trace backend.
Deployment Patterns in Production
Most teams run vLLM behind a Kubernetes Service with Horizontal Pod Autoscaler based on custom metrics (average waiting queue length > 8). A recommended Deployment sets resource requests to 80% of GPU memory and uses the official NVIDIA GPU operator with MIG or time-slicing when multiple smaller models share a GPU.
Docker image choice matters. The official vllm/vllm-openai:v0.6.1 image is built with CUDA 12.4, Python 3.11 and PyTorch 2.4. For air-gapped environments, build a custom image pinning exact commit v0.6.1.post1 to avoid unexpected kernel changes between patch releases. Always mount model weights as a read-only volume to enable fast pod restarts.
Helm chart example values snippet:
replicas: 3
model: meta-llama/Meta-Llama-3.1-8B-Instruct
tensorParallelSize: 2
gpuMemoryUtilization: 0.85
lora:
enabled: true
modules:
- name: sql-lora
path: /models/adapters/sql
Autoscaling rules trigger when vllm:num_waiting_requests exceeds 16 for more than 30 seconds. This keeps 95th-percentile latency under 120 ms during traffic spikes.
Cost and Scaling Trade-offs
Running a 70B model with TP=8 on 8×H100 GPUs costs roughly $12-15 per million output tokens at current cloud spot prices in us-west-2. The same workload on two 8×H100 nodes with pipeline parallelism increases latency by 18% but allows the cluster to survive single-node failures without dropping requests. Teams must decide between latency, cost and availability SLAs before choosing parallelism strategy.
Continuous batching delivers the largest win for variable traffic. During traffic spikes the scheduler automatically grows effective batch size up to --max-num-seqs (default 256). During quiet periods the batch size shrinks to 1, keeping tail latency under 80 ms for the first token on Llama-3.1-8B. Prefix caching further reduces cost for repetitive RAG workloads by reusing KV pages across users.
Common Pitfalls and Mitigation Strategies
- OOM during peak load: Lower
--gpu-memory-utilizationto 0.80, enable swap space of 32 GB, and monitorvllm:gpu_cache_usage_perc. Add a circuit breaker that rejects new requests when cache usage exceeds 92%. - High prefill latency for long contexts: Set
--max-num-batched-tokens 32768and consider speculative decoding with a smaller draft model (available experimentally in 0.6). Use--speculative-modelwith a 1B or 2B draft. - Adapter thrashing: Increase
--lora-cache-sizeto 64 or co-locate similar LoRAs on the same pod using node affinity labels. - NCCL timeout on multi-node jobs: Set environment variables
NCCL_IB_TIMEOUT=22,NCCL_DEBUG=INFOand ensure all nodes sit in the same availability zone with 400 Gbps interconnect. - JSON output not valid: Use the built-in guided decoding with JSON schema instead of temperature 0.0 alone. This eliminates the need for retry loops in client code.
- High tail latency on cold starts: Warm up the server with 50 dummy requests at deployment time using a Kubernetes init container or lifecycle hook.
Advanced Sampling and Logits Processors
vLLM accepts custom logits processors through the logits_processors argument in the completion API. A common pattern is length-constrained generation or domain-specific token masking. The processor receives the logits tensor at every decode step and can mask tokens that would break JSON syntax or business rules.
def json_mode_processor(logits, _):
# mask all tokens except those valid in current JSON state
logits[invalid_token_ids] = float("-inf")
return logits
sampling_params = SamplingParams(
temperature=0.0,
max_tokens=512,
logits_processors=[json_mode_processor]
)
# passed inside extra_body when calling the server
Because this runs on GPU inside the sampling kernel, overhead stays below 2% even for complex processors that consult a small state machine. The extra_body also supports guided_regex and guided_choice for simpler cases without writing custom Python code.
Prefix Caching for Repeated Prompts
Prefix caching stores computed KV caches for common prompt prefixes. In a customer support use case where every request begins with the same 800-token system prompt plus company documentation, prefix caching reuses those pages across all users. Enable with --enable-prefix-caching and increase --max-num-batched-tokens to accommodate the shared prefixes. Measured improvement is 30-45% higher throughput in production RAG logs. The cache is automatically evicted using LRU when GPU memory is needed for new blocks.
Benchmarking Your vLLM Deployment
Use the bundled benchmarks/benchmark_serving.py script with a dataset of real query lengths. Example invocation:
python benchmarks/benchmark_serving.py \
--backend vllm \
--model meta-llama/Meta-Llama-3.1-8B-Instruct \
--dataset-name sharegpt \
--dataset-path ShareGPT_V3_unfiltered_cleaned_split.json \
--request-rate 10 \
--num-prompts 1000
Track output tokens per second, time to first token (TTFT) and inter-token latency. Run the benchmark at increasing request rates until latency exceeds SLO. This process determines the maximum stable request rate for your hardware configuration. Compare results across AWQ, FP8 and BF16 to quantify quality versus speed trade-offs for your specific application.
When Not to Use vLLM
vLLM is not ideal for every workload. If your primary concern is sub-30 ms first-token latency for a 7B model on a single GPU, consider TensorRT-LLM 0.12 with static batching, in-flight batching and aggressive quantization. TensorRT-LLM's paged KV cache is similar but its CUDA graphs give lower variance.
If you need guaranteed per-tenant isolation and complex rate limiting, Hugging Face Text Generation Inference (TGI) 2.0 may be easier to configure despite lower peak throughput. TGI's continuous batching is less aggressive than vLLM's iteration-level scheduler but includes built-in token-level rate limiting per API key.
For pure offline batch inference on trillion-token datasets, vLLM is overkill; use Hugging Face with DeepSpeed or custom PyTorch DataLoader instead. vLLM shines when online serving throughput per dollar is the dominant metric and you can tolerate occasional preemption under heavy load. The engine continues to evolve quickly. Version 0.6 introduced FP8 kernels and improved LoRA fusing. Teams should pin exact versions in production and allocate time each quarter to test new minor releases on shadow traffic before upgrading.
By combining PagedAttention for memory efficiency, continuous batching for GPU utilization, dynamic LoRA serving, prefix caching, and structured output support, vLLM 0.6 delivers a production-grade inference platform that requires minimal custom CUDA knowledge while exposing the precise controls necessary for aggressive optimization on modern GPU clusters.
