1. See What Is Using the GPU
nvidia-smi # memory per GPU, and the processes using it ps -elf | grep python # leftover Python processes still holding memory
The Processes table lists each program's PID and GPU memory. A crashed notebook, an old training run or a second inference server is often the culprit: stop it (kill PID) and try again. Remember that PyTorch's cache shows as used in nvidia-smi even when no tensor occupies it.
2. Fix It in PyTorch
- Halve the batch size until it fits; use gradient accumulation to keep the effective batch.
- Do not keep the graph alive: add up losses as numbers,
total_loss += float(loss), nottotal_loss += loss, which keeps every step's history in memory. - Drop tensors you no longer need with
del x. - Run inference without gradients: wrap it in
with torch.no_grad():. - Do not recover inside
except: the exception keeps the failed step's tensors alive. Set a flag in the handler and retry after it.
To reduce fragmentation and see where memory goes:
export PYTORCH_ALLOC_CONF=expandable_segments:True # older PyTorch: PYTORCH_CUDA_ALLOC_CONF python - <<'EOF' import torch print(torch.cuda.memory_allocated() / 2**30, "GiB in tensors") print(torch.cuda.memory_reserved() / 2**30, "GiB reserved by the cache") print(torch.cuda.memory_summary()) EOF
Details in PyTorch's CUDA memory notes and FAQ.
3. Fix It in vLLM
| Option | What it does |
|---|---|
| --max-model-len 8192 | Caps the context length; the default comes from the model and can be huge |
| --max-num-seqs | Fewer sequences processed at once, so a smaller conversation cache |
| --gpu-memory-utilization 0.85 | Leaves room for other programs sharing the GPU |
| --enforce-eager | Turns off CUDA graphs, which take extra GPU memory |
| --tensor-parallel-size 2 | Splits the model across two GPUs |
| A quantized model | AWQ, GPTQ, FP8 and other formats take less memory at some cost in precision |
From vLLM's conserving memory guide. Start with --max-model-len: it is the most common cause when the weights alone fit.
4. Fix It in Ollama and llama.cpp
- Ollama: a large
OLLAMA_CONTEXT_LENGTHor a highOLLAMA_NUM_PARALLELgrows the conversation cache, and by default Ollama keeps up to three models loaded per GPU. SetOLLAMA_MAX_LOADED_MODELS=1and a smaller context withsudo systemctl edit ollama.service, or pick a smaller quantization of the model. - llama.cpp: lower
-nglto keep some layers in system memory, use a smaller-ccontext or fewer--parallelslots, and for mixture-of-experts models move experts to the processor with--n-cpu-moe, as in the gpt-oss guide.
When the Model Simply Does Not Fit
Work out what the model needs with how much VRAM an LLM needs: at 4-bit, about 0.7 GB per billion parameters with context. If that is more than your card has, the fixes above only trade speed for memory. A GPU with more memory, or several, is the lasting fix: see the best GPU for running LLMs for what fits on each of ours.