Local AI

Conquering GPU Memory Fragmentation: A Guide to Stable Local LLM Inference

Running large language models locally is no longer a novelty; it is a practical engineering challenge. However, one of the most persistent issues developers face is the sudden, cryptic Out of Memory (OOM) error that appears after an hour of seemingly stable operation. Often, this is not due to a lack of total VRAM, but rather GPU memory fragmentation. Understanding this phenomenon is key to building robust, long-running inference pipelines.

What Is GPU Memory Fragmentation?

Modern GPUs manage memory similarly to systems RAM: via heap allocation. When you load a model, allocate KV caches, and process batches, the CUDA runtime requests memory blocks of varying sizes. Over time, as tensors are created and destroyed, free memory becomes scattered into small, non-contiguous blocks.

If your application requests a large contiguous block of memory (e.g., for a new batch or an expanded KV cache), the GPU might have enough total free memory but no contiguous space to satisfy the request. This triggers an OOM error, even though nvidia-smi shows available memory.

Diagnosing the Problem

Before applying fixes, confirm that fragmentation is the culprit. Monitor your GPU memory usage over time using tools like nvidia-smi dmon or Python libraries such as pynvml. Look for a pattern where memory usage spikes and dips, creating "holes" in the address space.

import pynvml

pynvml.nvmlInit()
handle = pynvml.nvmlDeviceGetHandleByIndex(0)
mem_info = pynvml.nvmlDeviceGetMemoryInfo(handle)

print(f"Total: {mem_info.total / 1024**3:.2f} GB")
print(f"Free: {mem_info.free / 1024**3:.2f} GB")
print(f"Used: {mem_info.used / 1024**3:.2f} GB")

If the "Free" memory is significant but allocations still fail, fragmentation is likely the issue.

Practical Solutions and Mitigation Strategies

1. Pre-allocate KV Cache

The most common cause of fragmentation in LLM inference is dynamic KV cache allocation. Instead of letting the inference engine allocate cache on-the-fly for each sequence, pre-allocate a fixed-size cache. This ensures memory is reserved upfront in a contiguous block.

# Example using Hugging Face Transformers conceptually
# Most engines (vLLM, TGI) have flags for this
# --max-num-batched-tokens
# --gpu-memory-utilization 0.9

2. Use Memory Pools (CUDA)

PyTorch and other frameworks utilize caching allocators. However, you can explicitly manage memory pools to reduce fragmentation. For custom CUDA code, use cudaMallocAsync or stream-ordered memory allocators, which are designed to handle variable-sized allocations more efficiently by reusing freed blocks.

3. Batch Size Stability

Fluctuating batch sizes are fragmentation accelerants. If possible, standardize your batch sizes. If dynamic batching is required, ensure that your scheduler groups similar sequence lengths together to minimize the variance in required memory footprints.

4. Regular Memory Resets

In long-running services, implement a periodic "warm-up" or memory compaction routine. While you cannot directly compact CUDA memory, you can force a garbage collection cycle in Python (gc.collect()) and call torch.cuda.empty_cache() to return unused blocks to the CUDA allocator, allowing it to reorganize.

import torch
import gc

def force_memory_cleanup():
    gc.collect()
    torch.cuda.empty_cache()
    # Optionally, sync to ensure all operations are complete
    torch.cuda.synchronize()

5. Leverage Modern Inference Engines

Engines like vLLM use PagedAttention, which breaks the KV cache into fixed-size blocks. This approach mimics OS virtual memory, allowing non-contiguous blocks to be managed via a table, effectively eliminating fragmentation for the KV cache.

# vLLM handles this internally, but configuration is key
# from vllm import LLM
# llm = LLM(model="meta-llama/Llama-2-7b", gpu_memory_utilization=0.9)

Conclusion

GPU memory fragmentation is a subtle but critical bottleneck for local LLM deployment. By pre-allocating resources, stabilizing batch sizes, and leveraging advanced inference engines like vLLM, you can achieve stable, long-running sessions without unexpected OOM crashes. Always monitor memory patterns and treat OOM errors not just as a capacity issue, but as a layout and management challenge.

Share: