Skip to content
CoRISE

Budgeting Local LLM VRAM: Beyond Model Weights

Budget weights, KV cache, context, concurrency and runtime memory with explicit llama.cpp/vLLM assumptions and a measurement plan.

T. AsanoPublished Updated 19 min read
  • Private AI
  • gpu
  • capacity-planning
Open table of contents

“8B at Q4 is 4GB” starts the estimate; it does not choose the GPU

If every parameter in an 8B model were stored in exactly four bits, the weights would occupy 8,000,000,000 × 4 ÷ 8 = 4,000,000,000 bytes. This is a useful first estimate. It does not establish that an 8GB GPU can serve the model.

Inference also needs a KV cache, intermediate tensors, workspaces, graph-related allocations and runtime or communication buffers. A short conversation for one person and long-document processing for several concurrent users have different requirements, even with identical weights.

This implementation companion to private AI boundary design separates three questions: can the model load, can it process the required context, and can it meet concurrency and latency requirements?

The planning bundle contains a Python estimator, hypothetical inputs, an empty measurement template, a proposed workload matrix and runtime profiles. Run the estimator with the supplied scenario to check the 14.8 GiB component demand and 16.8 GiB planning budget. Numbers below are analytical examples, not measurements of a particular model or GPU.

1. Agree on units and memory categories

Here, GB = 10^9 bytes and GiB = 2^30 bytes. B in 8B means one billion parameters. For token counts, 16K, 32K and 128K mean 16,384, 32,768 and 131,072. CLI suffix rules can differ, so the commands use explicit integers.

Ideal precision for all weights8B: GB / GiB70B: GB / GiB
FP3232 / 29.80280 / 260.77
FP16 / BF1616 / 14.90140 / 130.39
8-bit8 / 7.4570 / 65.19
4-bit4 / 3.7335 / 32.60

Use capacity reported by the driver in consistent units rather than relying on a product’s “24GB” label. A 24 GiB device and 24 decimal GB, approximately 22.35 GiB, are different quantities.

A conceptual budget is:

GPU planning budget
  = resident model weights
  + allocated KV cache
  + peak runtime memory outside weights and KV
  + additional resident models / state
  + design reserve

Runtime memory includes activations, compute workspaces, graph-related allocations, allocator overhead and communication buffers. Runtime logs do not necessarily use mutually exclusive categories: an activation buffer may already belong to a graph memory pool. Do not count the same allocation twice. A design reserve is intentionally unused headroom, not another allocation.

Scroll horizontally to view the complete diagram.

Separate weights, cache, runtime and reserve Budget resident weights, KV pool, runtime without double counting, additional models/state and unused reserve. The 4.8 + 8 + 2 + 2 = 16.8 GiB example is hypothetical, not measured.
Fig. 01 — Separate weights, cache, runtime and reserve
Read the diagram as text

Budget resident weights, KV pool, runtime without double counting, additional models/state and unused reserve. The 4.8 + 8 + 2 + 2 = 16.8 GiB example is hypothetical, not measured.

2. Inspect the actual quantized weights

parameters × bits ÷ 8 assumes all weights can be packed at the same width. Real formats also store scales, zero points, block information, alignment and tensors retained at higher precision. GGUF Q4 variants, GPTQ, AWQ, NF4 and FP4 do not imply identical footprints just because their names mention four bits.

Hugging Face’s bitsandbytes documentation describes modules outside quantized linear layers using other dtypes, and provides a model memory-footprint method. That footprint is still not the peak memory of a complete serving process. [1]

GGUF file size is a useful clue to weight storage. Metadata, tensors left on the CPU, repacking, conversion and padding can make GPU allocation differ. Include every shard of a split artifact.

For llama.cpp, inspect model, KV and compute allocations per device in startup logs. Exact labels depend on the build and backend. Keep artifact size, actual model buffer and inference peak as separate observations. A 22GB artifact does not by itself establish full GPU offload on a 24GB device. [3]

3. Estimate KV from the tokens it must retain

An autoregressive transformer reuses keys and values from previous tokens. For classic full attention with identical layer layouts and equal key/value head dimensions, the uncompressed payload can be estimated as follows. [2]

MKV≈LHKVdh(bK+bV)∑i=1STiM_{\mathrm{KV}} \approx L H_{\mathrm{KV}} d_h (b_K+b_V) \sum_{i=1}^{S} T_i

Here, LL is the number of layers, HKVH_{\mathrm{KV}} the KV head count, dhd_h the head dimension, bK,bVb_K,b_V the bytes per key/value element, and TiT_i the retained tokens for each sequence. Equal key and value types give the familiar 2 × layers × kv_heads × head_dim × tokens × bytes form.

With 32 layers, eight KV heads, head dimension 128 and FP16 keys and values, each token needs 32 × 8 × 128 × (2 + 2) = 131,072 bytes = 128 KiB.

Retained tokens per sequenceOne sequenceFour sequences
4,0960.5 GiB2 GiB
16,3842 GiB8 GiB
32,7684 GiB16 GiB
131,07216 GiB64 GiB

If the weights hypothetically occupy 4.8 GiB, one 32K sequence adds another 4 GiB. An 8 GiB device is already insufficient before runtime overhead. With 80 layers and the same other dimensions, the payload is 320 KiB per token: one 128K sequence consumes 40 GiB. Parameter count alone does not reveal this difference.

Scroll horizontally to view the complete diagram.

Context and resident sequences change KV demand For 32 layers, eight KV heads, dimension 128 and FP16 K/V, KV is 128 KiB per token. One 16K/32K/128K sequence needs 2/4/16 GiB; four 16K sequences need 8 GiB. Counts include prompt and output, without prefix sharing.
Fig. 02 — Context and resident sequences change KV demand
Read the diagram as text

For 32 layers, eight KV heads, dimension 128 and FP16 K/V, KV is 128 KiB per token. One 16K/32K/128K sequence needs 2/4/16 GiB; four 16K sequences need 8 GiB. Counts include prompt and output, without prefix sharing.

Grouped Query Attention shares fewer KV heads across query heads. For 64 query heads and eight KV heads, use eight in the usual KV formula. Other architectures require a different model:

ArchitectureAdditional information needed
Sliding-window / local attentionRetention window per layer and actual runtime allocation
MLALatent cache, RoPE components, dtype and backend implementation
Hybrid attention / state-space modelsKV groups plus recurrent state and other allocations
Different key/value dimensions or precisionSeparate calculations for keys and values

The referenced vLLM source also accounts for cache groups when a simple block count cannot describe hybrid-model token capacity. These internal fields explain the implementation; they are not a promised stable monitoring API. [5]

4. Context includes input and output; concurrency means resident sequences

A 16,384-token limit cannot all be assigned to input if generation still needs space. Include the system prompt, history, retrieved documents, chat template, special tokens and generated output. A concrete envelope is 12,288 input tokens plus at most 4,096 output tokens. Pin the tokenizer and template as well.

Count sequences retaining KV at the same time and their total tokens, rather than registered users or open browser tabs. Four independent 16K sequences require 64K tokens of KV. Multiple candidate generations can also make one request represent more than one sequence.

Queued requests do not necessarily have KV allocated yet. Separate a typical 4K request, a 12K P99 and a 16K hard limit. Arrival rate, generation duration, maximum output and queue limits all matter. Long outputs consume both more cache and a longer share of serving time.

Prefix caching can reuse shared prefixes and reduce computation. Its memory benefit depends on shareable tokens, retention policy and backend behavior. If the service must work with cold caches and unrelated long documents, do not assume prefix sharing in the worst-case budget.

5. Separate token demand from the allocated pool

The formula above describes KV payload demand. A runtime may allocate a fixed buffer up front or reserve a paged pool and assign blocks to sequences. Shorter requests therefore do not necessarily produce a proportional decrease in nvidia-smi memory usage. [2][4][5]

Scroll horizontally to view the complete diagram.

Demand, reservation and observation are distinct A workload consumes tokens assigned to runtime blocks or a fixed pool. Free blocks can remain allocated on the device. Driver, process and framework-reserved observations overlap and must not be added.
Fig. 03 — Demand, reservation and observation are distinct
Read the diagram as text

A workload consumes tokens assigned to runtime blocks or a fixed pool. Free blocks can remain allocated on the device. Driver, process and framework-reserved observations overlap and must not be added.

llama.cpp: make the slot limit and shared pool explicit

The referenced server README is pinned to commit 8172e6577ac2b35de1ec1e5d1c0aaad6c4a2129f. --parallel selects slots; --kv-unified selects a shared buffer. In this revision, --kv-unified-per-slot N, without --ctx-size, sizes the shared pool to parallel × N. [3]

llama-server \
  --model /path/to/approved-model.gguf \
  --host 127.0.0.1 \
  --gpu-layers all \
  --fit off \
  --parallel 4 \
  --kv-unified \
  --kv-unified-per-slot 16384 \
  --cache-type-k f16 \
  --cache-type-v f16 \
  --batch-size 512 \
  --ubatch-size 128

This profile intends four slots with a 16,384-token limit each and a 65,536-token shared pool. Do not read --ctx-size 16384 --parallel 4 alone as proof that every user gets 16K. Older revisions may not have the per-slot option. Inspect the actual binary’s help and logs for effective pool size, slot limits, padding and cache types.

--fit off prevents automatic adjustment of unspecified arguments in this comparison. Insufficient memory can deliberately cause startup failure; this is not a universal production setting. Enforce input plus output bounds rather than silently depending on context shifting or truncation.

vLLM: context limits and KV budgets are different controls

vllm serve /path/to/approved-compatible-checkpoint \
  --host 127.0.0.1 \
  --max-model-len 16384 \
  --max-num-seqs 4 \
  --max-num-batched-tokens 2048 \
  --gpu-memory-utilization 0.85

--max-model-len limits prompt plus output. --max-num-seqs bounds sequences processed in an iteration. --max-num-batched-tokens bounds tokens in a scheduling iteration, not the total tokens that can remain in KV. Review chunked-prefill behavior for long prompts in the chosen version. [4]

The explicit 0.85 is a starting assumption for an experiment. The referenced documentation and source use 0.92 as the default for gpu_memory_utilization; neither value is a safe ratio for every deployment. It is a per-instance budget, not isolation from other GPU processes. [4][5]

Setting --kv-cache-memory-bytes supplies a per-GPU cache size and overrides utilization-based KV sizing. Do not assume the ratio remains an additional guard on that explicit allocation. Rebudget weights and runtime memory too.

Lowering the context limit can constrain long-request demand and some runtime buffers. If remaining memory is still allocated to a KV pool, reserved memory may remain similar while usable capacity changes. Read startup token capacity and inspect preemption, recomputation and queueing under concurrent long requests. max-num-seqs=4 does not prove that four full 16K sequences meet the latency target.

6. Quantize weights and KV as separate decisions

Q4 weights can coexist with FP16 KV. Record weight, key, value and activation types independently. In the referenced llama.cpp revision, both KV types default to f16 and can be selected with --cache-type-k and --cache-type-v. [3]

Switching both cache types in the preceding profile to q8_0 is an option to investigate. Its block scales mean storage is not exactly half of FP16. Check supported key/value combinations, flash-attention requirements and backend restrictions against the implementation and effective startup settings.

vLLM’s FP8 KV is another way to reduce payload. It requires supported hardware, model and attention backend, plus a reviewed policy for scales, their calculation or calibration. The documentation covers calibration and behavior when suitable scales are not supplied. Smaller storage does not establish acceptable accuracy. [7]

Evaluate the actual languages, long-context retrieval, coding and structured-output tasks. Change one factor at a time: modifying both weight precision and KV precision makes quality regressions harder to attribute.

7. Measure prefill, batch and graph peaks

Prefill processes the prompt; decode generates tokens. Long prefills can create substantial intermediate tensors and workspace peaks. Long decodes retain KV and occupy capacity for longer. These are tendencies, not separate memory universes: prefill creates KV, and decode also needs compute buffers.

Distinguish llama.cpp’s logical batch from its physical microbatch. For vLLM, review batched tokens, sequences, chunked prefill and graph capture sizes. Flash-attention memory behavior also depends on supported kernels and shapes.

vLLM’s memory guide explicitly discusses additional CUDA graph memory and reducing capture sizes or using --enforce-eager. A successful eager-mode load does not validate a graph-enabled serving configuration. [6]

ControlPotential memory reductionMeasure alongside it
Prefill batch / microbatchIntermediate tensors and workspaceTTFT and prompt throughput
Graph capture sizesGraph-related allocationsDecode latency and throughput
Context / sequence limitsKV demand and some runner buffersQueue delay and rejection rate
KV dtypeCache payloadTask quality, including long inputs

Larger batches do not always improve performance, and smaller ones do not always reduce it. Bandwidth, utilization and queueing affect the result. Compare under the same workload.

8. For MoE and CPU offload, inspect placement and execution

For a “200B total / 20B active” MoE model, keeping every expert resident normally starts from the total parameter count. Ideal Q4 storage is 100 GB, approximately 93.13 GiB, not 10 GB. Active parameters describe the scale of selected computation per token; they are neither the full resident weights nor a direct latency prediction.

llama.cpp’s --cpu-moe, --n-cpu-moe and --gpu-layers change placement. Distinguish CPU execution of CPU-resident layers or experts from GPU execution that reads weights residing on the CPU. CPU compute and RAM bandwidth bottlenecks require different remedies from host–device transfer bottlenecks. [3]

In the referenced vLLM documentation, --cpu-offload-gb is measured in GiB per GPU, despite its name. Access to CPU weights during forward passes needs a fast interconnect. Describing a 24GB GPU plus ten offloaded units as a virtual 34GB GPU is a capacity intuition, not a contiguous VRAM region available to KV and workspaces, or a performance equivalence. [4]

Budget host-resident weights, pinned and staging buffers, runtime, OS and other applications. Avoid counting the same memory-mapped resident pages as file size, RSS and page cache. Loading or conversion may temporarily exceed steady-state usage. Unified-memory hardware needs a different physical budget from independently adding CPU RAM and discrete GPU VRAM.

9. Make the budget fit on every GPU

Two 24 GiB GPUs do not expose one interchangeable 48 GiB allocation. Weights, KV, computation and communication must be placed on individual devices.

Scroll horizontally to view the complete diagram.

Validate memory on each device, even with multiple GPUs Two 24 GiB GPUs are not one interchangeable 48 GiB region. Inspect each device’s weight shard, KV placement/replication, runtime and communication buffers. Interconnect and partitioning affect performance; CPU offload adds another memory tier and transfer/execution costs.
Fig. 04 — Validate memory on each device, even with multiple GPUs
Read the diagram as text

Two 24 GiB GPUs are not one interchangeable 48 GiB region. Inspect each device’s weight shard, KV placement/replication, runtime and communication buffers. Interconnect and partitioning affect performance; CPU offload adds another memory tier and transfer/execution costs.

Tensor parallelism partitions tensors. Layer or pipeline parallelism partitions stages such as layers. Data parallelism normally needs weights for each replica. MoE can combine this with expert parallelism. Weight and KV residency therefore cannot universally be calculated by dividing by GPU count. Head counts and tensor shapes can cause replication, imbalance or partitioning restrictions. [8]

vLLM supports options such as --tensor-parallel-size 2 for compatible models. The referenced llama.cpp revision offers layer, row and experimental tensor splitting, with --tensor-split for placement ratios. In row mode, the main GPU handles KV and intermediate results, so inspect placement rather than assuming symmetry. [3]

Record per-device peaks, KV capacity and communication workspaces, along with PCIe/NVLink connectivity, peer-to-peer support and NUMA placement. A model that fits can still miss TTFT or generation targets because of communication.

Speculative decoding with a draft model adds draft weights, cache and runtime buffers. Some methods, such as n-gram approaches, do not use a separate model. For multimodal inference, distinguish the vision encoder and image tokens, GPU encoder caches and CPU processor caches. vLLM’s mm_processor_cache_gb adjusts CPU RAM; reducing it does not imply an equal VRAM reduction. Input-modality limits also depend on model support. [3][6]

10. Build a worksheet with explicit assumptions

Return to one GPU, classic GQA and FP16 KV. The workload bound retains 12,288 input plus 4,096 output tokens across four sequences.

ComponentPlanning valueEvidence type
Ideal Q4 weights3.73 GiBTheoretical 8B × four bits
Selected model-buffer estimate4.8 GiBAssumption replacing the ideal figure
KV payload8.0 GiB128 KiB × 16,384 × four
Runtime peak outside weights/KV2.0 GiBAssumption to replace with observation
Component demand14.8 GiBApproximation without reserve
Design reserve2.0 GiBExplicit choice for this example
Planning budget16.8 GiBNot a hardware compatibility finding

A 14.8 GiB component sum proves neither that 16 GiB is safe nor that 24 GiB is sufficient. Runtime assumptions, actual model allocation, reported device capacity, competing processes, allocator behavior and block overhead remain to be checked. There is no universal 20% margin rule.

The core arithmetic is small. Keep key/value bytes separate and pass the total tokens resident at once:

GIB = 1024 ** 3

def ideal_weight_gib(parameters, bits_per_weight):
    return parameters * bits_per_weight / 8 / GIB


def kv_gib(layers, kv_heads, head_dim, total_resident_tokens,
           key_bytes, value_bytes):
    return (layers * kv_heads * head_dim * total_resident_tokens
            * (key_bytes + value_bytes) / GIB)

The bundled script reads a hypothetical scenario and reports ideal packed weights separately from the selected model-buffer assumption. It supports only full-attention GQA, one GPU, independent sequences and unpacked two- or four-byte KV. It rejects input plus output beyond the context bound. It does not estimate quantized block overhead, hybrid models, offload or TP.

# Check the supplied scenario’s arithmetic; these are not GPU measurements.
python3 estimate.py scenario.json

Its output deliberately does not declare a GPU suitable or recommend a purchase.

11. Verify loadable, usable and serviceable separately

Loading is the first condition. Generating at the required context makes a configuration usable. Meeting concurrency, latency and quality requirements makes it serviceable.

ScenarioPrimary observationsExecution status
Cold load / warmupWeights, conversion peak, graph captureNot run
Short promptBasic behavior and baseline latencyNot run
Maximum expected promptPrefill peak and actual token countNot run
Long generationKV growth, occupancy duration, context endNot run
Concurrent long requests / burstsKV exhaustion, preemption, queueing, rejectionNot run
Configuration / quantization changesTask quality and performanceNot run

The supplied CSV proposes 4K/8K/16K/32K contexts and selected concurrency levels of one, four and eight. It is an unexecuted measurement plan. Blank OOM cells do not mean “No.” Verify overlapping execution rather than just counting connected clients: short completions may never create the intended full-cache condition.

For NVIDIA GPUs, this proposed sampling command follows device-level usage. [9]

nvidia-smi \
  --query-gpu=timestamp,uuid,memory.total,memory.used,utilization.gpu \
  --format=csv \
  --loop-ms=200

These are observations every 200ms, not a guarantee of catching shorter peaks. Device totals include other processes. Combine samples with runtime OOM logs, device/process information and framework allocated/reserved peaks where available. These observations overlap; do not add them together.

Define whether TTFT includes queueing and whether throughput means aggregate output tokens per second or per-request output rate. Review P95/P99 as well as P50, inter-token latency, failures, preemption, RAM and, where relevant, power and temperature. DCGM/Prometheus collection connects to observability design; this article does not claim an implemented collector or measured dashboard.

12. Tune the component causing pressure

Main constraintChanges to investigate firstPreserve or re-evaluate
Weights dominateWeight quantization, placement, TP, smaller modelTask quality and transfer time
KV dominatesContext/output bounds, concurrency, KV precisionLong-context quality and queueing
Workspace / graphs dominateBatch, microbatch, capture sizes, eager modeTTFT and decode performance
Competing processes / budgetsDevice placement, instance budgets, admissionIsolation and service capacity

Order depends on requirements. Restricting an unused 128K capability to 16K, or queueing requests instead of running all four immediately, can preserve weight quality. But if queueing violates latency requirements, the capacity problem remains.

Keep model, tokenizer, quantization, runtime, backend, effective settings, workload, memory, quality and latency in one reproducible record. Compare changes under the same conditions. Revisit the record after runtime upgrades because defaults and kernels can change.

The related observability case provides operational design context. The GPU configurations, calculations and proposed exercises here are not claimed as delivered or measured in that engagement.

The hardware question is which model, at what context, for how many resident sequences, at what latency and quality? Start with weight arithmetic, then update the budget using actual runtime allocations and workload observations. Choose a GPU that can carry the work, not merely hold the weights.

References

  1. Hugging Face: bitsandbytes — Quantized modules, dtypes and model footprint.
  2. Hugging Face: Caching — KV layout and dynamic, static and sliding-window caches.
  3. llama.cpp server README — Commit 8172e6577ac2b35de1ec1e5d1c0aaad6c4a2129f. Context/slots, cache types, offload, split modes and fit.
  4. vLLM: Engine Arguments — Model length, batching, KV budget and CPU offload.
  5. vLLM: CacheConfig source — Commit 22258a26bc090bccf5473cf681bbe9bac41bd035. Defaults and group-aware capacity.
  6. vLLM: Conserving Memory — Graphs, parallelism, multimodal limits and CPU caches.
  7. vLLM: Quantized KV Cache — FP8, scales and calibration.
  8. vLLM: Parallelism and Scaling — TP/PP/DP and model placement.
  9. NVIDIA System Management Interface — Memory queries and sampling intervals.

llama.cpp and vLLM source revisions are identified below. Latest documentation, defaults and backend support change; reconcile them with the selected binary, container and model before adoption.

T. Asano

More articles by T. Asano

Contact

Tell us about your engineering challenge.

Talk with CoRISE about the design, implementation and operation of your systems.

Start a Conversation