LLM Local Inference: VRAM Optimization and Latency in Practice
This article explains how to optimize VRAM usage and latency for large language model inference in local or private environments. It separates inference into prefill and decode stages, introduces a practical VRAM budgeting formula, and examines how Mixture-of-Experts architectures, quantization, and KV cache compression affect throughput and time to first token. It also outlines a reusable tuning workflow and discusses when to combine local inference with cloud infrastructure.
1. Background: “Can It Run” and “Does It Run Smoothly” Are Two Different Questions
When deploying large generative models in local or private environments, teams rarely struggle with whether the model loads. The real problem is the gap in experience after it loads: text streams out token by token, but speed fluctuates; short prompts respond acceptably, while long contexts stall immediately; VRAM fits the model weights exactly, yet a second concurrent request causes an out-of-memory failure.
To explain these issues clearly, break inference into two independent stages and measure each separately.
The first stage is prefill, which processes the entire input prompt at once. It is compute-intensive and highly parallel, and it determines time to first token (TTFT). The second stage is decode, which generates output autoregressively token by token. It is constrained mainly by VRAM bandwidth and cache access patterns, and it determines the sustained output rate (tok/s).
Many complaints that “the model is slow” actually conflate these two metrics. Slow prefill is a compute and batching strategy problem; slow decode is usually a bandwidth and cache layout problem. The optimization techniques for the two barely overlap.
2. VRAM Budget: Start With a Verifiable Capacity Estimate
The first step in any deployment plan should be a VRAM calculation, not downloading weights and trying them out. A practical estimation framework:
Total VRAM ≈ weights + KV cache + runtime overhead + safety marginWeights ≈ parameter count × bytes per parameterKV cache ≈ 2 × layers × hidden dimension × context length × batch size × bytes per element
“Bytes per parameter” is determined by the numerical format: roughly 2 bytes for half precision, about 1 byte for 8-bit quantization, and about 0.5 bytes for 4-bit quantization, plus a small additional overhead from dequantization and group scaling factors. Runtime overhead includes temporary activations, communication buffers, and VRAM fragmentation, and it is usually not negligible. A safety margin of 10–20% is recommended to avoid peak overflow under long contexts.
The most commonly underestimated item is the KV cache. It grows linearly with context length and is multiplied by batch size during batched inference. A 35B-class model in half precision already approaches roughly 70GB for weights alone, but after 4-bit quantization it can be compressed to the low teens in GB, making interactive use possible on laptop platforms with 8GB of VRAM. For ultra-large scales such as 284B to 753B parameters, even low-bit quantization typically requires more than 32GB of desktop VRAM or a single professional-grade high-VRAM accelerator card to hold the bulk of the weights. These conclusions are not exclusive capabilities of specific hardware; they are the inevitable result of capacity arithmetic.
3. Key Variable 1: Mixture-of-Experts Architecture and “Active Parameters”
An important design trend in recent years decouples total parameter count from the number of parameters actually involved in computation per token. Take a configuration with 35B total parameters and about 3B active parameters: all expert weights must still reside in VRAM, but each token passes through only a few expert paths, so the compute volume during decode drops significantly.
This explains an apparently contradictory phenomenon: a model can have a large total size yet sustain output speeds in the tens of tok/s, while a dense model of moderate size under similar VRAM conditions may only reach the low twenties in tok/s.
There is an engineering cost: expert routing introduces irregular memory access and load imbalance. During batching, different requests may hit different experts, reducing effective parallelism. Routing strategy, expert capacity factor, and how requests are aggregated within a batch all directly affect measured throughput. When evaluating this architecture, use two metrics—measured decode rate and long-context stability—rather than parameter count alone.
4. Key Variable 2: Quantization, Cache Compression, and Time to First Token
Quantization optimizes both VRAM and bandwidth: a lower bit width reduces weight footprint and the amount of data moved per token, which benefits the bandwidth-bound decode stage especially. A common tradeoff in practice is to apply low-bit quantization to weights only while keeping a high-precision compute path, in order to control accuracy loss. Whether to quantize activations should be evaluated against the specific task to avoid unacceptable error in numerically sensitive layers.
Time to first token needs separate treatment. If the input prompt is very long, prefill becomes the bottleneck. Options include chunked prefill, prompt prefix cache reuse, and retrieval-based trimming of extremely long inputs. In practice, constraining worst-case TTFT to an acceptable upper bound in seconds (for example, within tens of seconds) is more valuable than a nice-looking average, because user perception depends on the worst experience. Left unmanaged, TTFT in long-context scenarios commonly climbs into the hundreds of seconds, making interactive use effectively unusable.
5. A Reusable Tuning Workflow
- Define scenario boundaries: input length distribution, output length distribution, concurrency, acceptable TTFT, and the lower bound for tok/s.
- Run the capacity calculation: estimate VRAM usage under three numerical formats using the formulas above, and choose a configuration with headroom.
- Fix a baseline: record decode rate and TTFT with weight format, context length, and batch size held constant.
- Tune one variable at a time: adjust quantization bit width, cache precision, batch size, and chunked prefill granularity in sequence, changing only one item each time.
- Stress-test the worst case: combine the longest prompt with the highest concurrency and verify latency stays within the limit.
- Build a regression dashboard: bring throughput, latency percentiles, and peak VRAM into continuous monitoring and log-based alerting.
A sample evaluation record can be very simple:
{"model_scale": "35B-total / 3B-active","weight_format": "4bit","context_len": 8192,"batch": 4,"decode_tok_s": [77, 83],"ttft_worst_s": 44,"vram_peak_gb": 7.4}
6. Cloud and Local: Put Capability in the Right Place
The value of local inference lies in keeping data within its domain and in predictable fixed cost. It suits development and debugging, sensitive data processing, and offline scenarios. When elastic concurrency, very long contexts, or larger parameter scales are needed, general cloud capabilities can fill the gap: container platforms to host inference services and scale elastically, object storage to distribute model weights and datasets, message queues to smooth request spikes, and logging plus monitoring and alerting to observe latency percentiles and peak VRAM. Baidu AI Cloud provides exactly these general infrastructure categories in such scenarios, helping teams turn “getting one model working” into “a service that can be operated sustainably.”
7. Conclusion
Achieving interactive LLM inference on limited VRAM is essentially a resource allocation problem: first confirm feasibility with the capacity formula, then judge the upper bound of decode speed based on architecture characteristics (dense or sparse activation), and finally address the bandwidth bottleneck and time to first token separately through quantization, cache management, and prefill strategy. Treating worst-case latency as a hard constraint and continuously regressing against it with monitoring is what makes a hybrid local-and-cloud inference setup reliably usable in production.
