NVIDIA, vLLM and GPU Sizing
Agents send long prompts many times per task, which makes memory and caching the center of serving design.
Self-hosting a model means providing GPU memory for the weights plus a key-value cache that grows with every token of every active request. A serving engine such as vLLM batches requests and manages that cache; NVIDIA and others supply packaged and distributed serving tools. Estimate first, then load test with real agent traffic, because estimates ignore much of what production does.
What you will learn: when self-hosting makes sense, what a serving engine does, how vLLM and NVIDIA tools fit, how to size GPU memory, what quantization and prefix caching trade, and how to deploy and measure.
Prerequisites: Inference Optimization and Quantization and Choosing Models: Reasoning, Open-Weight and Hosted.
The example runs in November 2026 with Python 3.13 and only the standard library. The model dimensions are hypothetical. Software release facts were checked on November 28, 2026; command options differ between versions, so read the documentation for the version you install.
Should you serve models yourself?
| Reason to self-host | Question to test it |
|---|---|
| Data must stay inside your boundary | Does an in-region or private provider option already satisfy the rule? |
| No external connectivity | Who will supply updates and fixes offline? |
| High, steady volume | What utilization will you really achieve? |
| Custom or fine-tuned model | Can a provider host it for you? |
| Latency or location control | Is the model or the network the delay today? |
Serving adds capacity planning, drivers, security patches, failures at night and model upgrades. If none of the reasons above survives its question, an API is usually the cheaper route. Managed vs Custom Platforms and Total Cost shows how to compare costs.
What a serving engine does
The engine loads the weights, groups requests so the GPU works on many at once, manages the cache that remembers processed tokens and exposes an API. Prefill processes the prompt and is heavy on computation. Decode produces one token at a time per request and is often limited by memory bandwidth. Agents stress prefill, because each step resends instructions, tool definitions and a growing history.
Common engines and tools
| Tool | Typical role |
|---|---|
| vLLM | Widely used open-source engine for shared GPU serving |
| SGLang | Open-source engine with attention to structured and agent workloads |
| TensorRT-LLM | NVIDIA's library for optimized inference on its GPUs |
| NVIDIA NIM | Packaged model serving containers with standard APIs |
| NVIDIA Dynamo | Distributed serving layer that coordinates engines across GPUs |
| llama.cpp and Ollama | Local and small-scale use, including without large GPUs |
Serving with vLLM
vLLM offers an OpenAI-compatible server, so clients that speak that API shape can point to your own address. For agents, tool calling needs explicit setup. Its tool calling guide shows that automatic tool choice requires an enabling flag and a parser matched to the model, often with a chat template:
vllm serve meta-llama/Llama-3.1-8B-Instruct \
--enable-auto-tool-choice \
--tool-call-parser llama3_json \
--chat-template examples/tool_chat_template_llama3.1_json.jinja
This is the documentation's illustration, not a recommendation of a model. A wrong parser or template can turn tool requests into plain text, which looks like a model that refuses to use tools. Test tool calls with nested arguments, several calls in one reply and streaming before you blame the model.
Where GPU memory goes
| Consumer | Grows with |
|---|---|
| Weights | Parameter count and bytes per parameter |
| Key-value cache | Tokens held, across all active requests |
| Activations and buffers | Batch size and model shape |
| Runtime overhead | Engine, drivers and fragmentation |
| Extra components | Vision encoders, draft models, adapters |
Two formulas give a first estimate:
- Weights ≈ parameters × bytes per parameter.
- Cache per token ≈ 2 × layers × key-value heads × head dimension × bytes per cached value.
Read the layer and head figures from the model's configuration file. Models with grouped attention have fewer key-value heads than attention heads, and some architectures cache differently, so the formula is a starting point.
A first-pass sizing tool
The program uses an invented 14 billion parameter model. It holds back a tenth of GPU memory, subtracts the weights and divides the rest among requests of a given length.
"""How many concurrent requests fit on a GPU? A first-pass memory estimate."""
GIB = 1024 ** 3
# A hypothetical model, not a real one. Read real values from the model config.
PARAMS = 14e9
LAYERS = 40
KV_HEADS = 8
HEAD_DIM = 128
BYTES_PER_WEIGHT = {"16-bit": 2.0, "8-bit": 1.0, "4-bit": 0.5}
def weights_gib(precision):
return PARAMS * BYTES_PER_WEIGHT[precision] / GIB
def kv_bytes_per_token(cache_bytes=2):
# 2 = one key and one value for every layer, head and dimension
return 2 * LAYERS * KV_HEADS * HEAD_DIM * cache_bytes
def sequences(gpu_gib, precision, tokens, reserve=0.10):
free = gpu_gib * (1 - reserve) - weights_gib(precision)
if free <= 0:
return 0
return int(free * GIB // (kv_bytes_per_token() * tokens))
print(f"KV cache per token: {kv_bytes_per_token() / 1024:.0f} KiB")
print(f"KV cache for one 32,000-token request: "
f"{kv_bytes_per_token() * 32000 / GIB:.2f} GiB\n")
print(f"{'precision':<11}{'weights':>10}{'GPU':>8}"
f"{'8k':>6}{'32k':>6}{'128k':>6}")
for precision in BYTES_PER_WEIGHT:
for gpu in (24, 48):
counts = [sequences(gpu, precision, t) for t in (8000, 32000, 128000)]
print(f"{precision:<11}{weights_gib(precision):>7.1f}GiB{gpu:>5}GiB"
+ "".join(f"{c:>6}" for c in counts))
peak_runs, tokens_per_run = 40, 32000
need = weights_gib("8-bit") + peak_runs * tokens_per_run * kv_bytes_per_token() / GIB
print(f"\n{peak_runs} agent runs at {tokens_per_run:,} tokens, 8-bit: "
f"{need / 0.90:.1f} GiB of GPU memory before any headroom for peaks")
Output:
KV cache per token: 160 KiB
KV cache for one 32,000-token request: 4.88 GiB
precision weights GPU 8k 32k 128k
16-bit 26.1GiB 24GiB 0 0 0
16-bit 26.1GiB 48GiB 14 3 0
8-bit 13.0GiB 24GiB 7 1 0
8-bit 13.0GiB 48GiB 24 6 1
4-bit 6.5GiB 24GiB 12 3 0
4-bit 6.5GiB 48GiB 30 7 1
40 agent runs at 32,000 tokens, 8-bit: 231.5 GiB of GPU memory before any headroom for peaks
Context length dominates. A single 32,000-token request needs almost five gigabytes of cache, so on the 24 GiB card the 8-bit version holds one such request but seven at 8,000 tokens. Forty concurrent agent runs at the longer length would need several large GPUs. The calculation assumes every request reserves its full length and shares nothing. Engines that allocate cache in blocks and reuse shared prefixes can do much better, while activation memory, fragmentation and traffic peaks can do worse. Use the numbers to choose what to test, not what to buy.
Quantization
Quantization stores numbers with fewer bits. It frees memory for more or longer requests and can raise throughput on suitable hardware.
| Effect | What to verify |
|---|---|
| Smaller weights | That the engine supports the format on your GPU |
| Quality change | Tool arguments, long reasoning, languages and rare cases |
| Speed change | Measured throughput; fewer bits is not always faster |
| Cache quantization | Separate setting with its own quality effect |
| Provenance | Who produced the quantized files and how |
Compare quantized and original versions on your evaluation set. Average benchmark scores can look unchanged while strict structured output gets worse.
Prefix caching and agents
If many requests begin with the same text, the engine can reuse the computed cache for it. Agents are a good fit, since instructions and tool definitions repeat on every step. Keep stable content first and changing content last, avoid timestamps or random identifiers near the start, and keep tool definitions in a fixed order. In multi-tenant systems, reuse across customers can leak information through timing. NVIDIA's Dynamo 1.4 release notes, for example, describe routing that never lets requests with a tenant namespace reuse another tenant's cache. Check how your engine and router isolate tenants.
Scaling beyond one GPU
| Technique | Idea | Cost |
|---|---|---|
| Replicas | Several copies behind a router | Weights duplicated; simplest to run |
| Tensor parallelism | One model split across GPUs | Needs fast links between them |
| Pipeline parallelism | Layers on different devices | Scheduling complexity |
| Disaggregation | Separate workers for prefill and decode | Cache transfer and more parts to operate |
| Cache-aware routing | Send requests where their prefix is cached | Load imbalance to manage |
NVIDIA released Dynamo 1.0 in March 2026 as an open-source distributed inference platform supporting engines including vLLM, with disaggregated serving and cache-aware routing. Adopt this level only when measurements show one engine with replicas cannot meet your targets.
Measure what users feel
- Time to first token: dominated by queueing and prefill.
- Time between tokens: the pace of generation.
- Total task time: all model calls and tools in an agent run.
- Throughput: input and output tokens per second at acceptable latency.
- Queue depth and preemption: early signs that cache is exhausted.
- Cache usage and hit rate: whether prompts are shaped well.
- GPU memory, temperature and errors: hardware health.
Report percentiles, not averages. Agent tasks chain many calls, so a slow tail on one call appears in a large share of tasks.
Load test with realistic traffic
Replay anonymized traces with their real prompt lengths, shared prefixes, output lengths, tool pauses and arrival bursts. Synthetic tests with identical short prompts can overstate capacity severely. Increase load until latency targets break, then plan to operate well below that point, with room for one replica to fail. Repeat after changing model, engine version, quantization or configuration.
Deploy it like a production service
- Pin model files by digest, and engine, driver and container versions.
- Prefer safe weight formats such as safetensors and review any model repository code before running it.
- Set maximum context, output length and concurrency deliberately.
- Put authentication, rate limits and tenant identity in front of the engine.
- Keep administrative and metrics endpoints off public networks.
- Add readiness checks that run a real, small generation.
- Plan for slow start-up while weights load, and keep warm capacity.
- Roll out new versions beside the old and compare quality before switching.
Cluster scheduling and rollout patterns are covered in Docker and Kubernetes for Agents and CI/CD, Infrastructure as Code and Safe Releases.
Capacity and cost
Cost per token on your own hardware equals total cost divided by tokens actually served. A GPU that is busy a quarter of the time costs four times as much per token as the same card fully used, so utilization matters as much as price. Combine workloads with different peaks, queue batch work for quiet hours and keep an overflow route for bursts if data rules allow it. See Latency, Load Testing and Capacity Planning.
Set limits that protect everyone
A shared endpoint has finite cache. One agent stuck in a loop with a very long history can push other requests into a queue. Set limits at the gateway and the engine.
| Limit | Protects against |
|---|---|
| Maximum input tokens | A single request taking most of the cache |
| Maximum output tokens | Runaway generation |
| Concurrent requests per client | One application crowding out others |
| Request deadline | Work continuing after the caller has gone |
| Queue length | Unbounded waiting that ends in timeouts anyway |
| Steps per agent run | Loops that multiply load |
Return a clear error when a limit is reached, with advice on whether to retry. Clients should back off and add random delay, or a brief overload becomes a retry storm. Give interactive requests priority over batch work where your engine or router supports it, or run them on separate replicas.
Troubleshooting guide
| Symptom | Likely area | First check |
|---|---|---|
| Out of memory at start | Weights or reservation too large | Precision, memory fraction and context limit |
| Slow first token under load | Queueing or long prefill | Queue depth and prompt length |
| Uneven generation speed | Preemption or competing prefill | Cache usage and scheduler settings |
| Tool calls appear as text | Parser or template | Documented pairing for the model |
| Low cache reuse | Changing prompt prefixes | Order and stability of prompt content |
| Quality differs from a hosted version | Template, sampling or precision | Compare settings case by case |
Keep the exact request, settings and versions for each reproduced fault. Many serving problems disappear or appear with an upgrade, so check release notes and rerun the failing case before and after. Fix Latency, Cost, Deployment and Score Regressions covers the wider application symptoms.
Before buying hardware
Rent comparable GPUs for a short trial and replay your traces. Confirm that the chosen model, engine, precision and context length meet latency targets at peak load with one replica removed. Include power, cooling, rack space, network links, support contracts and delivery time. Ask what you will do with the hardware if your preferred model in a year needs a different shape.
Write the sizing down
Record the assumed peak requests, prompt and output lengths, precision, reserve and latency targets next to the measured results. When traffic or the model changes, compare the new figures with these assumptions. Capacity problems often begin when an agent gains more tools or a longer history, which raises tokens per step although the number of users stays the same.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Sizing from weights alone | Out of memory under concurrency | Budget cache per active token |
| Maximum context for every request | Few requests fit | Set limits per workload |
| Wrong tool parser | Agents stop calling tools | Match parser and template, then test |
| Testing with tiny identical prompts | Capacity badly overstated | Replay real traces |
| Open inference endpoint | Anyone on the network uses or probes it | Authenticate and segment |
| Quantizing without evaluation | Quiet quality loss | Compare on your tasks |
Checklist
- The reason for self-hosting has been tested.
- Memory estimates include weights, cache and reserve.
- Tool calling is verified with the chosen parser and template.
- Quantized models pass the evaluation set.
- Load tests use real lengths, prefixes and bursts.
- Latency percentiles and queue metrics are monitored.
- Versions and model digests are pinned.
- Endpoints are authenticated and tenants isolated.
Frequently asked questions
How much GPU memory do I need?
Add weights at your chosen precision to cache for peak active tokens, then keep a reserve. Confirm with a load test on the real engine.
Is vLLM better than other engines?
It is a common, well documented choice. Performance depends on model, hardware, versions and traffic, so test candidates under your load.
Can a CPU serve an agent model?
Small models can run for personal or low-volume use. Long prompts become slow, so check task time rather than only whether it runs.
Does a longer context window cost memory if unused?
That depends on how the engine allocates cache. Configured limits affect scheduling and reservation, so read the settings for your version.
References
- vLLM documentation
- vLLM: tool calling
- vLLM: OpenAI-compatible server
- NVIDIA Dynamo 1.0 release notes
- NVIDIA Dynamo 1.4 release notes
Where to go next
Open-Source Stack and Local LLM Agents
Choose open models and run them.
Private, Air-Gapped and Sovereign Deployment
Deploy inside strict boundaries.
Latency, Load Testing and Capacity Planning
Plan latency and capacity end to end.