New Tool Radar

Local AI

How to Fix llama.cpp CUDA Out-of-Memory Errors

Recover from a llama.cpp CUDA out-of-memory error by lowering GPU offload and context.

Schematic illustration with three step boxes: Read the error; Lower the offload; Trim the context.

A CUDA out-of-memory error in llama.cpp means the model, the KV cache and the working buffers together do not fit on the GPU. The usual fixes are to offload fewer layers to the GPU, shorten the context, and turn on flash attention and quantized KV cache. This guide applies them in order of impact.

Before you start

  • llama.cpp installed, with an NVIDIA GPU.
  • A GGUF model that fails to load or crashes, for example a 32B Q4_K_M file.
  • nvidia-smi to check the GPU memory.

Read the error and check the GPU

Run nvidia-smi and note the free memory, then read the error line: “failed to allocate buffer” means the allocation itself did not fit. Compare the model size with the free memory; a 32B Q4 model is about 19 GB, so it needs a card with more than that free after the system takes its share.

Lower the GPU offload

Offload fewer layers to the GPU so the rest runs on the CPU:

llama-server -m qwen3-32b-q4_k_m.gguf -ngl 20 --port 8080

Lower -ngl further if it still fails. Each layer moved to the CPU frees GPU memory and costs speed, so lower it in steps rather than to zero at once.

Trim the context and quantize the cache

Shorten the context with -c, for example -c 4096 instead of 8192, and turn on flash attention with -fa. If it still fails, quantize the KV cache with -ctk q8_0 -ctv q8_0. Note that setting -ngl or -c yourself disables llama.cpp’s automatic fitting, so the values you pick are the ones that are used.

Worked example

Worked example: a 32B Q4 model fails on a 16 GB card with “failed to allocate buffer”. With -ngl 20 and -c 4096, the model should load with part of it on the CPU, and a short prompt should be answered. If it still fails, drop -ngl to 10 and try again.

Expected result

UNTESTED in this guide: no server was run while writing it. The expected result is that the model loads with the lower offload and answers a short prompt without a CUDA error.

Limitations

Offloading to the CPU is much slower than the GPU, so a model that only fits with most layers on the CPU may be too large for the machine. A smaller quantization of the same model is often the better trade.

Sources

See all