A CUDA out of memory error during LLM inference means an allocation could not fit the available GPU memory budget. The useful first question is when it failed: while loading weights, processing the prompt, generating tokens, or admitting concurrent requests. Each stage points to a different experiment.
Start with one short request and concurrency one. Record the failing stage, memory counters, model precision, and runtime version before changing settings. Clearing a cache cannot make an oversized live model fit.
Diagnose CUDA out of memory by the failing stage
Use this sequence as a troubleshooting decision tree. The stage is a clue, not proof of the cause.
| First failing stage | First hypothesis to test | Controlled next step |
|---|---|---|
| Weight loading, before any request | Resident weights or loading-time allocations exceed the budget | Check actual weight dtype and device placement; compare the weight estimate below |
| Startup profiling or CUDA graph capture | Warm-up workspace, graph pools, or backend reservations consume the remaining memory | Inspect startup logs; test the runtime's documented eager mode |
| Prefill, when a long prompt arrives | Prompt processing and cache demand exceed the tested envelope | Hold concurrency at one and shorten only the prompt |
| Decode, after generation starts | Growing cache or retained outputs consume headroom | Keep the prompt fixed and lower the output-token limit |
| Several requests work alone but fail together | Aggregate live token demand exceeds capacity | Keep lengths fixed and reduce admitted concurrency |
| Identical requests become less stable over time | Retained state or changing allocation patterns need investigation | Compare post-request allocated memory with the same warmed baseline |
NVIDIA's NIM memory troubleshooting guide similarly separates weight loading, cache allocation, and warm-up. Its environment variables belong to NIM; do not paste them into an unrelated server. An illegal-memory-access error alone does not establish CUDA out of memory.
Read allocated, reserved, and device memory separately
In PyTorch, allocated memory tracks tensor storage, while reserved memory tracks the caching allocator's managed pool. Reserved includes allocated memory: adding the two double-counts storage. The gap can include reusable cached blocks; it is not automatically a leak. These distinctions are documented in PyTorch CUDA memory management.
Device-level usage can also include other processes and allocations outside this allocator. The following diagnostic helper reports allocator counters alongside driver-reported free memory. Run it inside your existing CUDA inference process, after selecting the intended device; it does not load a model.
import torch
def memory_snapshot(label, device=0):
torch.cuda.synchronize(device)
free, total = torch.cuda.mem_get_info(device)
gib = 1024 ** 3
print({
"stage": label,
"allocated_GiB": torch.cuda.memory_allocated(device) / gib,
"reserved_GiB": torch.cuda.memory_reserved(device) / gib,
"peak_allocated_GiB": torch.cuda.max_memory_allocated(device) / gib,
"device_free_GiB": free / gib,
"device_total_GiB": total / gib,
})
Call it after loading, after warm-up, and after a fixed request. Reset peak counters with torch.cuda.reset_peak_memory_stats(device) before the measured request if you want that request's peak. Synchronization affects timing, so use this during diagnosis rather than as a latency benchmark. The driver-memory API returns free and total bytes.
For example, a hypothetical reading of 15 GiB allocated and 18 GiB reserved describes an 18 GiB allocator pool containing 15 GiB of tensor storage, not 33 GiB of usage. Compare like-for-like stages on the same GPU. In a multi-GPU deployment, record every worker's device separately.
Recalculate the budget: an 8B model at 8K and 32K
A useful planning identity is:
required VRAM ≈ weights + resident KV cache + runtime allocations
Runtime allocations include workspace and other deployment-specific state. Do not replace them with a universal percentage. Use the ModelFit VRAM calculator to explore a configuration, and the VRAM planning guide to review the assumptions before a load test.
Here is a fully specified illustrative estimate, not a measured GPU result or a claim about a particular checkpoint:
- Exactly 8,000,000,000 stored parameters.
- 32 full-attention layers, 8 KV heads per layer, head dimension 128.
- BF16 keys and values: 2 bytes per element.
- One GPU; no prefix sharing, sliding window, offloading, or speculative draft model.
- Each active sequence has the same resident token length, including prompt and generated tokens.
The weight payload is parameters × bits / 8. BF16 weights require 16,000,000,000 bytes: 16 GB, or 14.90 GiB. An ideal packed 4-bit payload is 4 GB, or 3.73 GiB, before scales, metadata, unquantized tensors, and runtime overhead.
For this conventional full-attention cache layout:
KV bytes = 2 × layers × KV heads × head dimension
× resident tokens per sequence × active sequences
× bytes per cache element
bytes per token per sequence
= 2 × 32 × 8 × 128 × 2
= 131,072 bytes = 128 KiB
Therefore 8,192 tokens use exactly 1 GiB of payload per sequence; 32,768 use 4 GiB. Use KV heads, not query heads. The KV cache calculator lets you change these inputs.
| Resident tokens per sequence | Active sequences | KV payload | BF16 weights + KV | Ideal 4-bit weights + BF16 KV |
|---|---|---|---|---|
| 8,192 | 1 | 1 GiB | 15.90 GiB | 4.73 GiB |
| 32,768 | 1 | 4 GiB | 18.90 GiB | 7.73 GiB |
| 8,192 | 4 | 4 GiB | 18.90 GiB | 7.73 GiB |
| 32,768 | 4 | 16 GiB | 30.90 GiB | 19.73 GiB |
These totals exclude runtime allocations and cache-management overhead. They are neither minimum GPU recommendations nor fit guarantees. On a device reporting exactly 24 GiB usable capacity, the last BF16 case already exceeds capacity before overhead; the 32K single-sequence case leaves about 5.10 GiB for everything else. A product advertised as “24 GB” should be checked using its actual reported byte capacity. 1 GB = 10^9 bytes; 1 GiB = 2^30 bytes.
Weight quantization leaves this example's BF16 cache unchanged. Separately quantizing or offloading a cache requires runtime and model support. Transformers cache strategies describes dynamic, static, quantized, and offloaded cache choices. A static cache can reserve its maximum size upfront; a dynamic cache grows with generation. The simple table does not model every cache implementation.
Apply the smallest change that tests your hypothesis
If loading fails
Compare the stored precision and weight footprint with actual free memory. A shorter prompt cannot repair a weight allocation that fails before requests start. Consider a supported quantized checkpoint, a smaller model, or a supported multi-GPU placement, then repeat the same load test. Account for quantization overhead rather than treating ideal 4-bit storage as the final footprint.
If startup or prefill fails in vLLM
The following is a configuration template for an installed vLLM version supporting these arguments. Replace the path with a compatible model you already have. It has not been run here on a CUDA GPU.
from vllm import LLM
llm = LLM(
model="/path/to/compatible-model",
max_model_len=8192,
max_num_seqs=1,
enforce_eager=True,
)
max_model_len limits sequence length, max_num_seqs limits concurrent sequences, and enforce_eager=True disables CUDA graph capture. This is a diagnostic starting configuration, not a performance recommendation. If it starts, restore one setting at a time and measure again. See vLLM conserving memory.
For a long-prompt failure, investigate chunked prefill and its token budget in your installed version. max_num_batched_tokens describes scheduled tokens per iteration; it is not a synonym for maximum context. Reducing context does not necessarily shrink a preallocated cache pool. Changing gpu_memory_utilization also changes backend budgeting: increasing it is not a universal CUDA out of memory fix on a shared device. Consult vLLM optimization and tuning and read the effective startup configuration.
If decode or repeated requests fail
In custom PyTorch inference, disable gradient recording where appropriate:
model.eval()
with torch.inference_mode():
output = model.generate(**inputs, max_new_tokens=128)
This fragment assumes an already-loaded compatible model and inputs on the correct device. The output cap is an example to test, not a safe limit for every model. inference_mode() does not call eval() for you; see the PyTorch inference-mode reference.
After consuming results, inspect references to GPU outputs, cached state, and tensors retained by request history. Record whether allocated memory returns to the same warmed baseline. A rising reserved counter by itself does not prove retained tensors. Keep output length fixed while testing concurrency so the comparison has one changing variable.
Why empty_cache() often does not fix CUDA out of memory
torch.cuda.empty_cache() releases unused cached allocator memory; it cannot release storage still held by live tensors. It may help some fragmentation cases, but it cannot remove model weights or an active KV cache. This boundary is explicit in the empty_cache API documentation.
If an object is no longer needed, remove the owning references first. Calling a cache-clearing function after every token is not a capacity plan. If CUDA out of memory persists with a repeatable workload, capture allocator diagnostics and investigate the failing allocation before trying allocator settings.
A repeatable acceptance check
Before increasing traffic again:
- Record GPU capacity, model revision, weight/cache dtype, runtime version, and effective settings.
- Verify a short request at concurrency one, including startup and warm-up.
- Increase resident context while keeping concurrency fixed.
- Increase concurrency while keeping prompt and output limits fixed.
- Compare peak memory and post-request baseline, and record latency alongside completion/failure counts.
A configuration passes only the workload you tested. Keep the longest admitted request and concurrency within that measured envelope, then revisit the budget when either changes. To work through a CUDA out of memory incident, start with the ModelFit calculator, separate weights from cache, and validate the remaining runtime headroom on your actual deployment.
