Local LLM VRAM Guide: Quantization, Context Length, and Model Selection

    Planning VRAM for local LLM deployment goes far beyond multiplying parameter count by bytes per parameter. This guide breaks down the four real sources of VRAM consumption—weights, KV cache, activations, and runtime overhead—shows how to estimate each with a reusable script, and explains how quantization, context length, concurrency, model shape (dense vs. sparse/MoE), and hardware tier change the outcome. It includes quick-reference tables for parameter and VRAM tiers, guidance for unified-memory devices where bandwidth rather than capacity sets the ceiling, a practical measurement methodology, a troubleshooting checklist, and criteria for when a cloud solution makes more sense than staying local.

    1. First, a Common Misconception: The Official VRAM Number Is Not the VRAM You Need

    When deploying LLMs locally, many users hit “insufficient VRAM,” “OOM,” or “crashes as soon as a long conversation starts.” The most common cause is treating the theoretical value from parameter count × bytes per parameter as the VRAM requirement. That calculation isn’t wrong, but it only covers one item in total VRAM consumption: the weights.

    What actually determines whether you can run a model stably is this inequality:

    1. weights + KV cache + activations/intermediate buffers + runtime overhead ≤ physical VRAM × safety factor (0.8–0.9)

    The safety factor on the right exists because VRAM allocation suffers from fragmentation, driver context overhead, and temporary peaks during inference. In practice, planning around 80%–85% of usable VRAM is more reliable than picking a model that hugs 100% of capacity.

    In this article, weights and KV in the formulas are counted in bytes; the GB figures in Sections 5, 6, and 7 are mostly decimal approximations. If you use a script based on 1024**3, the output is usually called GiB, and the values will be slightly lower than decimal GB.

    2. The Four Sources of VRAM Consumption

    2.1 Weights: The Only Precisely Calculable Part

    Weight usage is the only one of the four items you can predict exactly:

    1. weight bytes = total parameter count × bytes per parameter

    Empirical values for different precision schemes:

    Precision scheme Bytes per parameter (approx) Compression vs. BF16
    BF16 / FP16 2.0 1×
    8-bit symmetric/asymmetric quantization 1.03–1.10 ≈1.9×
    4-bit group quantization (group size 32–128) 0.55–0.62 ≈3.4×
    Mixed bit-width (higher precision on key layers) 0.65–0.85 ≈2.6×

    Note that 4-bit is not “0.5 bytes per parameter.” Group quantization must store the scale factor and zero point for each group: smaller groups mean higher precision but more overhead. In common implementations, group size 128 is about 0.52 bytes/parameter and group size 32 is about 0.56 bytes/parameter—roughly an 8% increase—depending on the bit-width of the scale/zero values and the quantization scheme. In long-context scenarios, this tradeoff is often more worth watching than simply chasing the smallest model.

    2.2 KV Cache: The Invisible Heavyweight That Grows Linearly with Context Length

    During inference, every generated or ingested token must cache its Key and Value in the attention layers. KV size is independent of weights and depends only on model architecture, sequence length, and concurrency:

    1. KV bytes = 2 × layers × KV heads × head_dim × sequence length × concurrency × KV precision bytes

    Example: a model with 32 layers, 8 KV heads after grouped-query attention, head_dim of 128, and KV stored in BF16:

    • Per-token overhead = 2 × 32 × 8 × 128 × 2 = 131072 bytes ≈ 128 KiB
    • Single sequence at 32K context ≈ 4.0GB
    • Single sequence at 128K context ≈ 16GB

    In other words, for a model whose weights are only a dozen-plus GB, the KV cache under very long context can easily exceed the weights themselves. Many VRAM tables only give numbers for short context and single concurrency, so long conversations naturally tend to overflow.

    Common mitigations include:

    • Grouped-query attention (GQA) / multi-query attention (MQA): reduce the number of KV heads to compress KV
    • KV quantization: dropping KV from 16-bit to 8-bit roughly halves the cache, at a slight accuracy cost on long sequences
    • Sliding window / layered caching: keep full KV only for recent segments and summary layers
    • Paged KV management: reduce fragmentation so usable capacity is closer to the nominal figure
    • Limiting max concurrency: KV usage scales roughly linearly with concurrency, so doubling concurrency is roughly like doubling context

    2.3 Activations and Intermediate Buffers

    During the forward pass, each layer produces temporary tensors such as the attention score matrix, the FFN intermediate dimension, and sampling candidate distributions. Taking QK^T as an example, in an unoptimized implementation its size can be approximated as:

    1. batch × attention heads × sequence length² × 2 bytes

    So activations blow up quickly as batch grows or sequence length increases. With fused attention implementations like Flash Attention, the QK^T score matrix is usually not materialized in VRAM, and memory pressure drops noticeably.

    Activations raise the VRAM peak, affecting first-token latency and compute demand in the prefill stage. In single-sequence, short-context cases they are usually not the capacity bottleneck, but in batch inference they can become a faster-growing item than KV.

    2.4 Runtime and Framework Overhead

    Runtime overhead includes CUDA context creation, VRAM pool preallocation, communication buffers, sampling, and temporary kernel workspaces. The empirical figure is about 5%–15% of the weights, more significant the smaller the model. This is why 2B–4B small models often “just barely don’t fit” on a 4GB card.

    For single-card deployment, you also need to deduct display output and desktop environment usage. On Windows and Linux desktops, this is often overlooked, and actual available VRAM may be noticeably lower than the nominal value shown by nvidia-smi.

    3. A Reusable Estimation Script

    Write the four items as a function and you can judge feasibility before downloading a model. Whether you use Ollama, llama.cpp, or a self-built inference service, this accounting logic applies.

    1. GB = 1024 ** 3
    2. def estimate_vram(
    3. total_params, # total parameters (including inactive experts)
    4. bytes_per_param=0.57, # empirical value for 4-bit group quantization
    5. n_layers=32,
    6. n_kv_heads=8,
    7. head_dim=128,
    8. seq_len=8192,
    9. batch=1,
    10. kv_bytes=2, # KV in BF16
    11. overhead=0.12, # runtime and fragmentation overhead
    12. ):
    13. weights = total_params * bytes_per_param
    14. kv = 2 * n_layers * n_kv_heads * head_dim * seq_len * batch * kv_bytes
    15. total = (weights + kv) * (1 + overhead)
    16. return {
    17. "weights_GB": round(weights / GB, 2),
    18. "kv_GB": round(kv / GB, 2),
    19. "total_GB": round(total / GB, 2),
    20. }
    21. # 31 billion dense parameters, 4-bit, 8K context
    22. print(estimate_vram(31e9))
    23. # {'weights_GB': 16.46, 'kv_GB': 1.0, 'total_GB': 19.55}
    24. # the same model pushed to 32K context
    25. print(estimate_vram(31e9, seq_len=32768))
    26. # {'weights_GB': 16.46, 'kv_GB': 4.0, 'total_GB': 22.91}

    For the same model and the same quantization, raising context from 8K to 32K alone increases total demand from 19.55 to 22.91—about an extra 3.6GB by conservative estimate. When selecting a model, compute against your target context length, not the default.

    4. How Model Shape Changes the Conclusion

    4.1 Dense Models vs. Sparse (Mixture-of-Experts) Models

    Many recent mid-sized models use a sparse structure, often named in forms like “26 billion total parameters, about 4 billion activated per token.” These models require distinguishing two sets of metrics:

    • VRAM usage is based on total parameters: all expert weights must stay resident in VRAM.
    • Inference speed is affected by activated parameters: each token reads only the routed subset of experts, but during actual decoding all resident expert weights pass through memory bandwidth. Real speed falls between a dense model with the same total parameters and one with the same activated parameters, and is usually still clearly slower than a dense model with the same activation level.

    The exception is high-concurrency, large-batch serving inference, where compute share rises and activated parameters become a more useful reference for throughput.

    To judge whether it can run, look at total parameters; to judge whether it runs fast, look at activated parameters, total resident weights, memory bandwidth, and concurrency mode.

    4.2 Large Vocabularies and the Output Layer Cannot Be Ignored

    For models with large vocabularies, the input embedding and output projection layers can account for 10%–20% of total parameters. Small models under 4B are most affected. If the framework supports weight sharing or output-layer quantization, you can save VRAM, but don’t assume it is necessarily enabled during selection.

    4.3 Diminishing Returns of Precision Choice

    Going from BF16 to 4-bit typically gives about 3.4× compression; going from 8-bit to 4-bit gives only about 1.8×, yet the quality loss may be more noticeable. The empirical ranking is:

    • 4-bit group quantization: suitable for the vast majority of local scenarios
    • 8-bit: reserved for tasks sensitive to numerical stability
    • Mixed bit-width: suitable when VRAM is stuck in the middle and you’re unwilling to sacrifice precision on key layers

    A reminder: 4-bit quality varies by quantization method and by model. Models labeled 4-bit by some sources don’t necessarily match BF16 conversation quality, so it’s best to run a small-scale comparison on your target task first.

    5. Quick Reference by Parameter Tier

    The table below is for initial screening; the final answer should still be based on the results from the Section 3 script.

    Model tier 4-bit weights With 8K context + overhead Hardware starting point Use case
    2B dense 1.2–1.8GB ~2–4GB 4GB VRAM tier Validating a minimal working path, lightweight on-device tasks
    4B dense 2.3–3.0GB ~4–6GB 6GB VRAM tier / 16GB unified memory Daily chat, a first local experience
    26B sparse (~4B active) 14–17GB ~15–19GB 16GB needs caution, 24GB is safer Wanting stronger reasoning without the heaviest models
    31B dense 17–19GB ~18–23GB 24GB and up Generation quality, coding ability, long context

    Differences in layer count, KV heads, and vocabulary size across models can shift actual values by 1–2GB, so be sure to plug your own model’s architecture parameters into the formula.

    6. Selecting by VRAM Tier

    4–6GB Tier

    Run only 2B-class models and keep context within 4K. Don’t try to quantize larger models in this tier: even if the weights barely fit, runtime overhead and KV will keep it from starting; and even if it starts, frequent paging makes it unusable in speed.

    8–12GB Tier

    4B-class models can run stably with headroom to increase context. 26B-class weights already exceed 12GB, so this tier isn’t worth attempting; drop to a 4B-class model, or go with unified memory / CPU offload.

    12–16GB Tier

    26B sparse models enter a serious evaluation range, but keep them to 8K context, single or low concurrency, and leave at least 2GB of headroom. If your target context is longer or concurrency is higher, 24GB is more stable. The most important insight here: being able to load is not the same as being able to infer stably.

    24GB and Up

    31B dense models become worth the investment. But at this tier the real bottleneck shifts from “does it fit” to “how fast does it read,” so pay particular attention to memory bandwidth and decode speed.

    7. Unified-Memory Devices: Memory Is Enough, Bandwidth Is the Ceiling

    On ARM thin-and-light laptops and unified-memory architecture devices, the judgment logic is completely different. The CPU and the accelerator share the same memory pool, with no dedicated VRAM, so keep three points in mind.

    Available Memory Is Less Than Nominal Capacity

    The operating system, display, and other processes consume a substantial share of memory. The memory actually allocatable to inference is usually noticeably lower than the nominal figure. You can check available memory via system interfaces like psutil.virtual_memory().available, and the allocation limits of dedicated inference tools also need to be confirmed by measurement.

    Memory Bandwidth Sets the Decode Speed Ceiling

    When generating token by token for a single request, each step requires reading the participating weights from memory once, so:

    1. decode speed ceiling ≈ effective memory bandwidth / resident weight bytes read per token per request

    This formula applies only to memory-bound dense models under single-sequence decoding; MoE and batch serving must be estimated separately against total resident weights and the actual batch.

    Example: a device with 400GB/s bandwidth running a 4-bit 4B-class model with about 2.6GB of weights has a theoretical ceiling of about 150 token/s; at 60%–75% efficiency, that’s about 90–110 token/s. This is a theoretical estimate—actual results depend on the framework, batch size, and access efficiency.

    Swap to a 26B sparse model at the same bandwidth and speed drops significantly, because all resident expert weights create bandwidth contention, and a sparse structure on unified memory can’t fully avoid swapping whole weight blocks in and out.

    Don’t Cross the Physical Memory Boundary

    Once the memory inference needs exceeds available physical memory, the system starts swapping and performance falls off a cliff: from tens of tokens per second down to less than one token per second, with slow recovery. Better to downgrade to a smaller model than to stay long-term at the critical point.

    Rough guidance: start a 16GB unified-memory device from 4B-class models; 32GB can run 4B-class smoothly and attempt 26B-class; 64GB and up can put 26B and 31B-class models on the candidate list, but still set speed expectations by bandwidth, not capacity.

    8. The Hidden Costs of Context Length and Concurrency

    This is the part most easily underestimated during selection.

    1. Plan by maximum context, not default context. If the workload needs 32K input, plug 32K into the KV formula, not 4K.
    2. Concurrency is a multiplicative cost. KV usage for 4 concurrent sequences at 32K context is roughly four times that of a single 32K sequence. Doubling concurrency is roughly like doubling context, and page-block rounding and fragmentation push the actual value slightly higher.
    3. Prioritize KV quantization and paged management. They have a small accuracy impact and a large capacity improvement—the highest return-on-investment of the two optimizations.
    4. Confirm the model’s native context length. Windows beyond the training length usually rely on RoPE extrapolation or interpolation; enough VRAM doesn’t mean long-text quality is usable, so validate effectiveness at your target length first.

    9. A Practical Measurement Methodology

    Estimates must be followed by real measurement. Here’s a repeatable measurement flow. The pseudocode below is illustrative; specific APIs vary by framework:

    1. # pseudocode: actual APIs vary by framework
    2. baseline = mem_allocated() # resident usage after loading weights only
    3. peak_short = run(generate, max_new=128) # short-sequence peak
    4. peak_long = run(generate, input=32_000) # long-input peak
    5. print(baseline, peak_short, peak_long)
    6. print("≈KV upper bound (incl. long-input prefill activations)=", peak_long - baseline)
    7. print("approx. after subtracting short output:", (peak_long - peak_short) * 32000 / (32000 - 128))

    The key action is to back-calculate KV from measurements to reverse-engineer the formula’s error. If the measured value is clearly higher than theory, it’s usually because KV isn’t quantized, or the framework preallocates the cache at maximum length; if it’s clearly lower, the framework may have paged allocation enabled.

    Also mind the difference in measurement basis: torch.cuda.max_memory_allocated typically reflects memory the allocator has already allocated, while nvidia-smi also includes driver context, display, and other processes, so its numbers are usually higher. It’s best to also record first-token latency, decode speed, and stability at your target concurrency, not just VRAM.

    10. When Not to Insist on Local Deployment

    The value of local deployment lies in keeping data on-premises, having no network dependency, and controllable marginal cost. But consider a cloud solution in these situations:

    • You need to serve multiple users at once or handle higher concurrency, and local VRAM can’t hold enough KV cache
    • You need 30B+ parameters with hard quality requirements
    • Demand shows clear peaks and troughs, making it uneconomical to hold hardware long-term
    • You need to frequently switch between different models for effect comparison

    Mainstream cloud platforms typically provide container orchestration, object storage, monitoring and alerting, and logging services. If you adopt managed inference services, watch VRAM utilization, first-token latency, throughput, and error rate; you should monitor the same metrics for a self-built inference service. A sensible architecture is often layered: on-device or local small models handle high-frequency lightweight tasks and privacy-sensitive data, while cloud large models handle complex reasoning and peak traffic.

    When you hit a VRAM-related failure, checking in this order is most efficient:

    1. Confirm whether it’s weights that don’t fit or KV that overflows: compare usage after loading weights only against usage after adding long input.
    2. Lower the context length: if it’s relieved immediately, the problem is KV, not weights.
    3. Enable KV quantization: this usually frees about half the cache.
    4. Check other processes: browsers, editors, and inference processes not released from a previous run.
    5. Limit concurrency to 1: confirm whether a single sequence works, then add concurrency back step by step.
    6. Confirm quantization actually took effect: if weight usage is close to BF16, quantization may not have been fully applied.
    7. Check VRAM fragmentation: OOM after long running but normal after a restart usually points to fragmentation rather than insufficient capacity.

    Conclusion

    Judging whether a local model can run is fundamentally a resource-accounting exercise: calculate weights, KV cache, activations, and runtime overhead separately, then compare against the hardware’s safe usable capacity. Parameter-tier and VRAM comparison tables are only for initial screening—the real basis is your own model’s architecture parameters, target context length, and measured data.

    Three conclusions most worth remembering: 4-bit group quantization is the best value-for-money default; the cost of long context comes mainly from the KV cache, not the weights; and on unified-memory devices, speed is determined by memory bandwidth, not nominal capacity.