Before you start: words you need#
| Word | Plain meaning |
|---|---|
| OOM | Out of memory: a request for memory that cannot be satisfied. On the GPU it raises an error; on the host the kernel may kill the process. |
| KV pool | The block of GPU memory the engine sets aside at startup for the KV cache (17.h). |
| Profiling run | A dummy forward pass the engine does at startup with the largest batch it expects, to measure peak activation memory before sizing the KV pool. |
| Activation spike | A short burst of temporary memory for one unusually large piece of work. |
| Preemption | The engine pausing a running request and freeing its KV blocks so others can continue (17.c). |
| cgroup | The Linux feature that caps a container’s memory (3.j). Going over the cap gets the process killed. |
| Exit code 137 | What a process killed by signal 9 (SIGKILL) reports: 128 + 9. The usual sign of a host OOM kill. |
1. What is it?#
A classification of out-of-memory failures in an inference service, because each kind has a different cause and a different fix. The first job is always to decide which kind you have.
TYPE SYMPTOM USUAL CAUSE
1. GPU OOM at startup fails while loading weights + pool do not fit
2. GPU OOM on an outlier fails on one unusual request activation spike the profiling
request run did not cover
3. GPU OOM under load fails intermittently at peak KV accounting wrong, or memory
outside the engine's budget
4. GPU OOM after hours fails eventually leak or fragmentation build-up
5. HOST OOM no traceback; exit code 137 container memory limit
6. "OOM" that is not CUDA error reported as memory a different errorType 5 confuses people most, because there is no Python traceback: the process is simply gone.
flowchart TB
O["Process died or CUDA out of memory"] --> T{"Traceback?"}
T -->|"no, exit 137"| H["Host OOM<br/>cgroup limit, host-side buffers"]
T -->|"yes"| W{"When?"}
W -->|"at load"| L["Weights + pool do not fit<br/>quantize, bigger GPU, more TP"]
W -->|"on one request"| P["Activation spike<br/>cap inputs, bound the token budget"]
W -->|"under load"| K["KV or unbudgeted memory<br/>headroom, max concurrency"]
W -->|"after hours"| F["Leak or fragmentation<br/>plot allocated and reserved"]
class O warn
class T,W queue
class L,K,F memory
class P compute
class H io2. Why does it matter?#
Because an OOM is the most disruptive way an inference server can fail. It usually kills the engine process, which drops every in-flight request, not just the one that triggered it. Then the server reloads weights and recaptures graphs, which takes from tens of seconds to minutes (20.h). If the trigger is a request shape that keeps arriving, the server crash-loops.
A slow server serves people slowly. A crash-looping one serves nobody.
3. Simple analogy#
A hotel that sold every room. The hotel (GPU) keeps a few rooms back for emergencies (headroom). One night a wedding party of forty arrives unannounced (an outlier request). If the emergency rooms are fewer than forty, there is no graceful option: the booking system crashes and everyone, including guests already checked in, is turned out (all in-flight requests fail).
The fixes are the obvious hotel ones: keep more rooms back, require group bookings in advance (cap input sizes), or split large parties across nights (chunking).
4. Tiny example: the budget, and the request that breaks it#
One H100 (79.2 GiB usable), Llama-3.1-8B BF16, --gpu-memory-utilization 0.90
engine share 71.3 GiB
weights 15.0 GiB
activations 4.0 GiB ← measured by the profiling run
graphs 1.0 GiB
KV pool 51.3 GiB = 420,086 tokens = 103 sequences of 4k
headroom 7.9 GiB ← everything nobody planned for
A scoring endpoint returns the log-probability of every prompt token.
It materialises FP32 logits: tokens × 128,256 vocabulary × 4 bytes.
2,048-token prompt 1.0 GiB fits
8,192-token prompt 3.9 GiB fits
30,000-token prompt 14.3 GiB OOMNothing is wrong with the KV accounting. One feature allocates memory outside the budget the engine measured. Section 6 has the program.
5. Technical explanation#
Type 1: at startup#
Write down what should fit (12.f, 17.h): weights + activations + graphs + KV pool ≤ the engine’s share. Then check:
- Is the checkpoint the size you think, and the precision what you think? A “quantized” model loaded in BF16 is the classic mistake.
- Is
max_model_lenlarger than the KV pool can hold for even one sequence? vLLM refuses to start in that case and prints the largest length that would fit. - Is another process on the GPU?
nvidia-smi --query-compute-apps=pid,used_memory --format=csv. - With tensor parallelism, does each rank hold 1/N of the weights?
Type 2: an outlier request#
The engine’s profiling run measures peak activation memory for the largest step it expects,
which is set by the per-step token budget (--max-num-batched-tokens in vLLM) and the batch
limit. Chunked prefill (12.k) means even a very long prompt is processed in steps no larger than
that budget, so plain prompt length is bounded. Spikes come from work the profiling run did not
model:
full-vocabulary logits for many positions prompt log-probs, custom scoring endpoints
very large n / best_of many sequences sampled from one prompt
multimodal inputs an unusually large image or video
custom code paths a logits processor that copies tensors
a token budget raised after tuning a much larger step than the one profiledDiagnose by correlation: does every OOM coincide with a particular request shape? Bisect the size to find the cliff. Fix by capping the input at the gateway, computing the large thing in chunks, lowering the engine’s memory share to give more headroom, or (for features you cannot cap) running them on a separate deployment.
Type 3: under load#
A correct engine does not OOM when the KV pool fills: it stops admitting requests or preempts running ones (17.c). An OOM under load therefore usually means memory outside the engine’s accounting grew:
- a second process or library allocating on the same GPU,
- NCCL or communication buffers that grow with the number of peers,
- LoRA adapters loaded on demand (18.g),
- the engine’s memory share set so high (0.97) that ordinary variation has no room.
Check the preemption counter (vllm:num_preemptions): if it was rising before the crash, you
were over-admitting; lower --max-num-seqs.
Type 4: after hours#
Plot torch.cuda.memory_allocated() and memory_reserved() (or the engine’s equivalents) over
time:
allocated grows → a real leak: tensors kept alive
reserved − allocated grows → fragmentation (22.e)
both flat, still OOM → memory outside PyTorch: NCCL, cuBLAS workspaces, another libraryCommon leaks: a finished request object still referenced (holding its tensors), a cache without
eviction, exception paths that skip clean-up, graphs captured per request instead of once, and
running without torch.inference_mode() so autograd keeps intermediate results (1.b).
Type 5: host OOM#
dmesg -T | grep -i "killed process" # the kernel's OOM-killer message
cat /sys/fs/cgroup/memory.events # oom_kill counter for this cgroup (v2)
kubectl describe pod <pod> # Last State: Terminated, Reason: OOMKilledCauses: loading the whole checkpoint into host RAM before copying to the GPU (stream it shard by shard), page cache from memory-mapped weights counted against the limit, large pinned-memory pools (including CPU KV offload, 14.k), tokenizing very long prompts, or a leak in the API process. Fix the cause, then set the container limit with headroom for host-side buffers.
Type 6: not memory at all#
Some CUDA errors surface as memory errors: an illegal address after a bad kernel, a failed
allocation inside a library that reports a generic error, or a GPU that has fallen off the bus
(an Xid error in dmesg). If the numbers in the message do not add up, look for the first error
in the log, not the last.
The prevention checklist#
[ ] Memory budget written down before deploying (section 6)
[ ] Engine memory share with headroom (0.85–0.92, not 0.97)
[ ] max_model_len from traffic, not the model's maximum
[ ] max_num_seqs below what memory allows, so preemption is rare
[ ] Per-step token budget bounded; long prompts chunked
[ ] Input length, output length, n and image size capped at the gateway
[ ] Tested with the largest request you accept, at maximum concurrency
[ ] Container memory limit with headroom for host-side buffers
[ ] Monitored: KV usage, preemptions, allocated, reserved, host RSS
[ ] Runbook entry for exit code 1376. Under the hood: the budget as a program#
// budget.go: write the GPU memory budget down, then check an outlier
// request against the headroom that is left.
package main
import "fmt"
const GiB = 1 << 30
func main() {
// One H100 80GB serving Llama-3.1-8B in BF16.
total := 79.2 * GiB // what the driver reports as usable
util := 0.90 // engine's share (--gpu-memory-utilization)
weights := 15.0 * GiB
activations := 4.0 * GiB // peak measured by the engine's profiling run
graphs := 1.0 * GiB // CUDA graph pools
kvPerToken := 128.0 * 1024
engine := total * util
kv := engine - weights - activations - graphs
headroom := total - engine
fmt.Printf("engine share %6.1f GiB\n", engine/GiB)
fmt.Printf(" weights %6.1f GiB\n", weights/GiB)
fmt.Printf(" activations %6.1f GiB\n", activations/GiB)
fmt.Printf(" graphs %6.1f GiB\n", graphs/GiB)
fmt.Printf(" KV pool %6.1f GiB = %.0f tokens = %.0f sequences of 4k\n",
kv/GiB, kv/kvPerToken, kv/kvPerToken/4096)
fmt.Printf("headroom %6.1f GiB (CUDA context, NCCL, everything unplanned)\n\n", headroom/GiB)
// An outlier: full-vocabulary FP32 logits for every prompt position,
// e.g. a scoring endpoint that returns the log-probability of each prompt token.
vocab := 128256.0
for _, tokens := range []float64{2048, 8192, 30000} {
logits := tokens * vocab * 4
verdict := "fits"
if logits > headroom {
verdict = "OOM"
}
fmt.Printf("prompt logits for %5.0f tokens: %5.1f GiB -> %s\n", tokens, logits/GiB, verdict)
}
}Output:
engine share 71.3 GiB
weights 15.0 GiB
activations 4.0 GiB
graphs 1.0 GiB
KV pool 51.3 GiB = 420086 tokens = 103 sequences of 4k
headroom 7.9 GiB (CUDA context, NCCL, everything unplanned)
prompt logits for 2048 tokens: 1.0 GiB -> fits
prompt logits for 8192 tokens: 3.9 GiB -> fits
prompt logits for 30000 tokens: 14.3 GiB -> OOMThe activation and graph numbers are illustrative; vLLM prints the real ones in its startup log (16.b). The fix for this case is to compute log-probabilities in chunks and return them as they are produced, and to cap prompt length on the scoring endpoint until that is done.
A worked incident#
INCIDENT Server OOMs 3–4 times a day, always near peak. Restarts cleanly.
CLASSIFY Not at startup (type 1 out). Allocated and reserved flat between incidents (type 4 out).
Python traceback present (type 5 out). → type 2 or 3.
CORRELATE Every OOM within 2 s of a request to /v1/score with a prompt over 25,000 tokens.
Preemption counter flat. → type 2: outlier request.
CONFIRM Send a 30,000-token prompt to /v1/score on a test replica: OOM reproduced.
Peak extra memory: 14.3 GiB of FP32 logits; headroom was 7.9 GiB.
FIX 1. Cap /v1/score prompts at 8,192 tokens at the gateway, with a clear 400 error.
2. Rewrite scoring to compute log-probs chunk by chunk.
3. Add the capped shape to the release load test.
RESULT No OOMs in 30 days. Throughput unchanged.7. Performance implications#
- Headroom costs capacity. Each GiB of headroom is about 8,000 tokens of KV cache for this model: roughly two 4k sequences. Ten per cent of an 80 GB GPU is a reasonable insurance price.
- Preemption is the healthy version of running out. It costs recomputation and latency, but the server stays up. A high preemption rate is a performance problem; an OOM is an outage.
- Restarts are expensive. Model loading and graph capture take tens of seconds to minutes; meanwhile the replica’s share of traffic goes elsewhere and may overload its neighbours.
8. Production implications#
- Bound every input. Prompt length, output length,
n, image size, number of images. Each one is a memory control. - Test the extremes in CI. Longest prompt × maximum concurrency × longest output, for every endpoint, including scoring and embedding endpoints.
- Watch the precursors. KV usage near 1.0 with rising preemptions; reserved memory creeping up; host RSS near the container limit.
- Exit code 137 belongs in the runbook, with the
dmesgandmemory.eventscommands. - Prefer rejecting requests to crashing. A clear 400 or 503 for an oversized request beats a crash that drops everyone (20.e).
- When it happens: if it is crash-looping, block the triggering request shape at the gateway
and lower concurrency; capture
memory_summary(), the request shape and the KV usage at the time; then classify and fix properly, and add the test that would have caught it.
9. Common mistakes#
- Raising the memory share to squeeze out capacity. A small gain for a class of incidents.
- Not testing with the largest request you accept.
- Setting
max_num_seqsat the memory maximum. No room for variation. - Confusing host OOM with GPU OOM. Completely different fixes.
- Not reading
memory_summary()or the startup memory log. They usually name the cause. - No input caps. One request can take down the server.
- Treating OOM as random. It correlates with something. Find the correlation.
10. Hands-on exercise#
- Run
budget.go. Changeutilto 0.95. How much KV do you gain, and at what prompt length does the scoring request now OOM? - Change the model to a 70B in FP8 on one H200 (141 GB, about 70 GiB of weights). Is there a KV pool left at 0.90? How many 4k sequences?
- Induce three types. On a test system, cause a type 1 (too large
max_model_len), a type 2 (an oversized request) and a type 5 (a container limit below the checkpoint size). Record what each looks like. - Leak detection. Run a server under load for an hour, sampling allocated and reserved memory every ten seconds. Is either growing?
- Write the runbook entry for your service: symptoms, classification steps, immediate mitigations, diagnosis.
11. Interview questions#
- Name the kinds of OOM in an inference service and how you tell them apart.
- Why does chunked prefill bound activation memory, and what can still cause a spike?
- What does exit code 137 mean, and how do you confirm it?
- Why is preemption the healthy version of running out of KV memory?
- A process OOMs after six hours but not at startup. How do you find out why?
- What would you cap at the gateway, and why is each a memory control?
- Walk through your first ten minutes with an OOM crash loop in production.
12. Further reading#
Checked on 12 November 2026.
- PyTorch: understanding CUDA memory usage
- vLLM: conserving memory
- Linux cgroup v2: memory controller and
memory.events - Lessons 17.h (how vLLM sizes the KV pool), 22.e (fragmentation), 23.e (failure modes).