Local LLM Deployment: Quantization Selection and Inference Speed Optimization
A practical guide to running 20B–30B open-weight models locally. Learn why memory bandwidth, not compute, limits token generation, how to choose a quantization level that fits fully in VRAM, how to estimate VRAM and KV Cache needs, when to use GUI tools versus the CLI, and which optimizations to apply in order. Includes a model sizing decision framework, a troubleshooting checklist, and guidance on splitting workloads between local and cloud.
1. Background: Why Local LLM Inference Feels Slow
Over the past year, open-weight models in the 20B–30B parameter range have become the mainstream choice for local deployment. They are good enough for general conversation, code completion, and structured extraction, yet small enough to run on personal hardware, unlike models with far larger parameter counts. Still, many developers run into the same issue once they start: the model loads and produces text, but generation is far slower than expected, sometimes worse than calling a remote service.
Understanding this requires looking at where the bottleneck actually sits in local inference. Autoregressive generation is token-by-token computation, and every step reads all model weights from storage into the compute units. So the deciding factor for speed is not peak compute but weight read bandwidth. When the model fits entirely in VRAM, reads go over VRAM bandwidth (typically hundreds of GB/s to the TB/s range). Once some layers are offloaded back to system memory, reads go over memory bandwidth (typically tens of GB/s), a gap that is often more than tenfold. This is why a model that “just barely doesn’t fit” shows a cliff-like drop in speed.
The second commonly overlooked factor is context length. The attention cache (KV Cache) grows linearly with context, so a long context consumes extra VRAM and increases the memory read volume of every step. In a local environment, context length is therefore not a “larger is better” setting; it has to be traded off jointly against quantization precision and parameter count.
2. Quantization: The First Principle of Local Deployment
Quantization represents weights with fewer bits, reducing both size and memory pressure. Common practice offers 4-bit, 5-bit, 6-bit, and 8-bit tiers: higher numbers mean less precision loss and larger size. Quantization is not lossless compression; it introduces numerical precision error, which typically shows up as reduced stability in long-form reasoning and weaker adherence to extreme format requirements, while differences on everyday Q&A and routine code tasks are often unnoticeable.
Three rules of thumb are useful when selecting a tier:
- Prioritize fitting entirely in VRAM over chasing the highest precision. A 4-bit model that fits completely in VRAM usually feels clearly better than an 8-bit model that has to offload half its layers.
- Raise precision according to the task. For structured output, long chains of reasoning, or format-sensitive scenarios, try 6-bit or above; for general chat and completion, 4-bit is enough.
- Leave room for the KV Cache. Do not size against “weights exactly equal to VRAM capacity”; reserve 15%–25% headroom for cache and runtime overhead.
Rough VRAM requirements can be estimated with the sketch below:
def estimate_vram(params_b: float, bits: int, ctx_len: int,layers: int, hidden: int) -> dict:# Weight footprint (GB), approximated from bytes per parameterweight_gb = params_b * 1e9 * (bits / 8) / (1024 ** 3)# Rough KV Cache estimate (GB), fp16 cachekv_gb = 2 * layers * ctx_len * hidden * 2 / (1024 ** 3)total = weight_gb * 1.15 + kv_gb # 1.15 is runtime headroomreturn {"weight": round(weight_gb, 2),"kv_cache": round(kv_gb, 2),"total": round(total, 2)}
This is not an exact formula, since cache layout and fusion strategies differ across implementations, but it answers the most important question: does my device fall into “fits entirely in VRAM” or “must offload”?
3. GUI Tools vs. the Command Line
The local inference ecosystem includes both graphical desktop tools and pure command-line solutions. They often share the same class of inference engine underneath, with the difference mainly in the interaction layer. The value of GUI tools is that they make three things visible: real-time memory and VRAM usage, context length settings, and the number of GPU offloaded layers. For beginners, this observability matters more than tuning tricks, because it turns an abstract “slow” into a concrete “which layer is sitting in memory.”
Command-line solutions, on the other hand, are scriptable and easy to integrate into automated pipelines and container images, which suits batch evaluation and continuous integration. A sensible combination in practice: use GUI tools for exploration and validation to settle on a workable parameter size, quantization tier, and offload layer count; then freeze those conclusions into command-line arguments or a configuration file under version control.
Whichever route you take, local tools generally expose a local service endpoint compatible with mainstream HTTP API conventions. This is important, because it lets a local model be called by upper-layer applications just like a remote service, by only swapping the base URL and a placeholder key:
from openai import OpenAIclient = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key="local")stream = client.chat.completions.create(model="local-model",messages=[{"role": "user", "content": "Explain how quantization affects inference speed"}],stream=True,)for chunk in stream:print(chunk.choices[0].delta.content or "", end="")
4. Systematic Speedups
Once you have confirmed the bottleneck is memory access and offloading, try the following in order; the payoff generally decreases down the list:
- Adjust the offload layer count: put as many layers in VRAM as possible and watch where the speed inflection appears. This is the single biggest win.
- Reduce context length: set it to actual needs instead of maxing it out by default; for long documents, switch to segmented summarization followed by aggregation.
- Enable batching and concurrency: local servers also merge concurrent requests, which improves throughput noticeably but raises peak VRAM usage.
- Choose more efficient sampling parameters: an excessive output limit directly lengthens generation time, so set a reasonable cap per task.
- Operator and backend optimization: inference backends can differ considerably on the same hardware, so benchmarking them is worthwhile.
One caution: do not stack optimizations without measurement. Fix a reproducible evaluation set (fixed prompts, fixed output length), change one variable at a time, and record tokens/s and time to first token.
5. How to Choose a Model Size: A Decision Framework
Selection should not start from “which model is strongest” but from the intersection of task and hardware:
- Define the task type: general conversation, code assistance, document extraction, and multimodal understanding place different demands on parameter count and modality support.
- Measure hardware limits: VRAM capacity determines whether the model fits entirely, memory capacity determines whether offloading is viable, and bandwidth sets the speed ceiling.
- Raise precision within the feasible region: first make it fit, then increase the quantization tier step by step until quality gains flatten out.
- Build a minimal acceptance set: run regression on 20–50 real business samples rather than drawing conclusions from a single session.
6. Where the Boundary Between Cloud and Local Sits
Local deployment solves data residency, offline availability, and controllable marginal cost. For very long contexts, complex multi-step tasks, and multimodal agents, cloud services still hold advantages in elasticity and engineering completeness. A mature architecture is usually layered: sensitive data and high-frequency light tasks run locally, complex tasks are routed to the cloud through a unified interface, and both sides use the same API conventions so business code is not locked in.
For the cloud side, Baidu AI Cloud offers a general capability combination worth considering: object storage for persisting models and datasets, a container platform for elastic scaling of inference services, and logging plus monitoring and alerting for observing latency and throughput metrics, forming a continuous path from local validation to cloud deployment.
7. Troubleshooting Checklist
- Loads fine but extremely slow: almost certainly some layers are offloaded to memory; adjust the offload layer count or lower the quantization tier first.
- Process killed by the system: both VRAM and memory are insufficient; check KV Cache usage and concurrency.
- Unstable output format: try a higher quantization precision, or give clearer structural constraints and examples in the prompt.
- Quality degrades in the later part of long text: shorten the context or switch to a segmented processing strategy.
- Local service cannot be called by the application: verify that the listen address, port, and API path match.
In short, running a mid-size model locally is an engineering trade-off under resource constraints rather than a pure contest of model capability. Put VRAM, memory, bandwidth, context, and quantization precision into a single table, then validate quality with a minimal acceptance set, and you can get a stable, usable inference experience on personal hardware.
