Why Memory Usage Explodes 10x When Running LLMs Locally for Agents

    A practical breakdown of why a local LLM agent's process memory can balloon to ten times the size of the model file. The article shows that the gap rarely comes from the weights themselves and instead comes from three dynamic overheads—KV Cache, compute buffers, and weight copies across processes. It includes the exact KV Cache formula, the mmap and loading-peak pitfalls that inflate RSS readings, and a copy-and-run Python function for estimating peak memory before you deploy.

    The Short Answer

    A model file is a static stream of bytes. Process memory is “alive”: it grows in real time with context length, concurrency, and batching strategy. When people see a local LLM’s process RSS climb to ten times the size of the model file, they often assume something is wrong with the weights. In reality, that tenfold gap almost never originates in the weights themselves. It comes from the large block of memory the runtime allocates on top of them—to hold computation intermediates and to preserve session state.

    To judge whether running an agent locally will exhaust memory, you cannot just look at the model file size. You have to break down everything beyond the weights, item by item, and account for each piece.

    1. Weights Are the Floor, Not the Ceiling

    Take a 7B model quantized to 4-bit as an example. The model file is roughly 4GB, and once loaded into memory the weights sit at around 4GB too. This portion is nearly a constant—it is the floor of memory usage, not the ceiling. What actually catches people off guard are the three dynamic overheads stacked on top of this floor. Each one can multiply with configuration.

    2. KV Cache: Often Larger Than the Weights

    During autoregressive generation, the model must cache the Key and Value of all past tokens to avoid recomputing them. This is the KV Cache. Its size can be derived from an exact formula:

    1. KV bytes per token = 2 (K and V) × layers × KV heads × head_dim × bytes per element

    Working through 32 layers, hidden size 4096, grouped-query attention (GQA) reducing KV heads to 8, head_dim of 128, and fp16 storage (2 bytes):

    1. 2 × 32 × 8 × 128 × 2 = 131072 bytes ≈ 128 KB / token

    Open the context to 32k (32768 tokens) and a single session is 128KB × 32768 ≈ 4GB; run 8 concurrent sessions and it becomes 4GB × 8 = 32GB. At this point the model file is still 4GB, but the process is no longer in the same order of magnitude. This is the intuitive source of “the KV Cache is often larger than the weights.”

    What makes it trickier is that many inference frameworks do not allocate “as much as is used.” Instead, they pre-allocate up to the context limit. Whether it is the context-length parameter of a lightweight local inference framework or the memory/GPU utilization ceiling of a high-performance inference engine, the names differ but the action is the same: the space is claimed at startup. So even if the current session is short, memory is already reserved for the maximum context.

    3. Compute Buffers: A Hidden Cost That Scales with Batch Size

    During the forward and backward pass, intermediate tensors need somewhere to land: the attention workspace, the temporary buffers for batch and ubatch, and the intermediate results of normalization and activation functions all occupy memory temporarily. Their magnitude roughly follows batch size × sequence length.

    Any single item looks small on its own, but it grows alongside the KV Cache as the batch scales. When you pack concurrency and high throughput into limited GPU memory, the buffers stack on top of the KV Cache, and total usage loses any sense of an upper bound.

    4. Weight Copies: Process Count Multiplies the Weights

    In a served deployment, if you spin up 4 worker processes to provide concurrency, the worst case is 4 independent copies of the weights: 4 × 4GB = 16GB. Some frameworks use fork with copy-on-write (CoW) so multiple processes share the same read-only weights, and it looks like there is only one copy; but as soon as a write operation triggers a page copy, the sharing partially breaks down. Other frameworks load weights independently in each process, so several copies really do mean several times the memory. Before deploying, be sure to confirm whether the weights are shared or independent—this directly determines the true multiplier on the weights.

    5. Two Easy-to-Misread Pitfalls

    The first is the mmap accounting. When you load a model through memory mapping, the pages backing the model file are counted in RSS, but a large share of them are reclaimable page cache—when system memory is under pressure, the kernel simply returns these clean pages, and reading them back costs almost nothing. So looking only at the peak RSS significantly overstates real usage. The column that actually matters is anonymous memory, because that is the hard overhead that cannot be reclaimed.

    The second is the loading peak in the Python ecosystem. Some mainstream deep learning frameworks first load the entire model into memory in fp16, then quantize it. The fp16 version of a 7B model is 14GB, and only after quantizing to 4-bit does it settle back to about 4GB. That 14GB in between is genuinely occupied—even if the model ultimately runs in just 4GB, insufficient machine memory will OOM right at the “load + quantize” step.

    6. An Estimation Method You Can Run Up Front

    Rather than discovering the crash after deployment through monitoring alerts, it is better to do the math before you start:

    1. Peak memory ≈ weights × copies + KV Cache + compute buffer margin
    2. where KV Cache = 2 × layers × KV heads × head_dim × precision bytes × token count × concurrency

    Of the three terms, only the weights are a constant; the KV Cache and the buffers are both “functions of configuration.” Plug in the concurrency and context length, and where the memory ceiling lands becomes obvious. Here is an estimation function you can apply directly:

    1. def estimate_memory_gb(
    2. weight_gb=4.0, # weight footprint (the floor)
    3. copies=1, # number of weight copies (~= worker process count)
    4. layers=32, # number of network layers
    5. kv_heads=8, # number of KV heads (usually far fewer than attention heads under GQA)
    6. head_dim=128, # dimension of each head
    7. kv_bytes=2, # KV precision in bytes: fp16=2, int8=1
    8. context=32768, # context length per session (tokens)
    9. concurrency=8, # number of concurrent sessions
    10. buffer_gb=1.0, # compute buffer margin
    11. ):
    12. per_token_bytes = 2 * layers * kv_heads * head_dim * kv_bytes
    13. kv_gb = per_token_bytes * context * concurrency / (1024 ** 3)
    14. return weight_gb * copies + kv_gb + buffer_gb
    15. # 32k context, 8-way concurrency: weights 4GB + KV 32GB + buffer 1GB ≈ 37GB
    16. print(estimate_memory_gb())

    A rule of thumb: if the estimated peak comes within less than 20% of available memory, it will almost certainly crash. Do not gamble on luck—always leave a safety margin for the operating system, the runtime, and traffic spikes.

    7. If You Can Only Change One Thing, Cut Context and Concurrency First

    There are many optimization paths—quantize the weights, share weight copies, lower the buffer batch—but the fastest to take effect is narrowing the context length and the concurrency. The reason is that the KV Cache is proportional to both, and every time either one doubles, the KV Cache doubles with it. By comparison, switching to a smaller quantized model only saves a limited slice off the floor line. Bringing down the two multipliers, context and concurrency, first is usually the step with the smallest investment and the largest payoff.