Practical Guide to Local LLM Deployment: Quantization, VRAM, and Model Selection
This article explores the practices and considerations for deploying large language models (LLMs) locally or in private environments. It covers the core motivations for local deployment, VRAM calculation methods, quantization strategies, inference service configurations, and performance evaluation methodologies to help developers make informed decisions based on their specific business constraints.
1. Why Run Large Models Locally?
Deploying large models locally or in private environments is primarily driven by three types of needs. The first is data privacy. If business documents, user conversations, and internal code must remain within an enterprise intranet, local inference is the most straightforward approach. The second is latency and stability. Local services do not rely on external networks, meaning network jitter and third-party service rate limits will not affect the interactive experience. The third is predictable costs. Cloud services charge based on usage volume, making costs difficult to estimate during high traffic fluctuations, whereas local devices involve a one-time investment plus fixed operational and maintenance costs.
However, local deployment also comes with clear trade-offs. Hardware procurement cycles are long, VRAM capacity limits the maximum model size that can be run, and model upgrades, driver maintenance, and service monitoring all require human resources. Therefore, local deployment is more suitable for scenarios with sensitive data, stable call volumes, and latency requirements, or for environments that need to run offline or on edge devices. For tasks with highly irregular call volumes or those requiring the highest quality output, cloud services are generally more appropriate. When selecting a deployment approach, business constraints should be clarified first before deciding on the deployment location.
2. Parameter Count, Precision, and VRAM Calculation
VRAM is the first bottleneck encountered in local deployment. The VRAM occupied by model weights can be estimated using the following formula:
Weight VRAM ≈ Parameter count × Bytes per parameter
Taking a 27B (approximately 27 billion) parameter dense model as an example, the weight usage under different precisions is roughly as follows:
| Precision Format | Bytes per Parameter | Weight VRAM Estimation |
|---|---|---|
| 16-bit Float (FP16/BF16) | 2 | ~54 GB |
| 8-bit Integer Quantization | 1 | ~27 GB |
| 4-bit Integer Quantization | 0.5 | ~13.5 GB |
These figures only account for the weights. During actual runtime, additional overhead is required for activations, the runtime framework, and buffers, typically reserving several more gigabytes of space.
Long contexts introduce another part of VRAM consumption: the KV cache. When generating each new token, the model must read the key-value vectors of all previous tokens. This data grows linearly with context length and the number of concurrent requests. It can be estimated as follows:
KV Cache ≈ 2 × Layers × KV Heads × Head Dimension × Context Length × Bytes per Element × Concurrency
Assume a model has 60 layers, 8 KV heads, a head dimension of 128, uses 16-bit storage, and a context length of 32K. The KV cache for a single request is approximately 8 GB. This is a hypothetical value used to illustrate the calculation method and does not represent the actual data of any specific model. Thus, on the same GPU, as the context expands from 4K to 32K, the supportable concurrency will significantly decrease. When planning deployment, both weights and the KV cache should be considered together.
3. Quantization Scheme Selection
Quantization is a technique that converts high-precision weights into low-precision representations to reduce VRAM usage and bandwidth pressure. Engineering primarily focuses on three aspects.
3.1 Precision and Speed of Weight Quantization
8-bit quantization can usually maintain output quality close to the original precision, making it suitable for scenarios with high-quality requirements and barely sufficient VRAM. 4-bit quantization can compress weight usage to about a quarter of the original, but its impact on quality depends on the task type. Open-ended writing and common sense Q&A generally remain stable, whereas mathematical reasoning, precise code generation, and structured extraction are more sensitive to quantization errors.
Group-wise quantization is a common improvement method. It divides the weight matrix into several groups, with each group using an independent scaling factor. Smaller groups usually yield better precision, but they also store more scaling parameters. In practice, the group size needs to be evaluated balancing both quality and VRAM.
3.2 KV Cache Quantization
In long-context scenarios, the KV cache often exhausts VRAM faster than the weights. Applying 8-bit quantization to the KV cache can significantly improve concurrency with a relatively small quality loss. This optimization is particularly valuable for interactive applications, as the context length of most user requests varies, causing cache pressure to fluctuate over time.
3.3 Trade-offs of Ultra-Low Bit Quantization
1-bit or 2-bit quantization can compress a model to a very small size, but the quality drop is usually quite noticeable. These schemes are suitable for exploratory experiments where output quality is not a priority, or for edge scenarios with extremely limited resources. Before using them in production environments, the results must be validated with real business samples to ensure they are acceptable.
3.4 Selection Principles
The quantization scheme should not be decided solely based on VRAM numbers. The recommended approach is: first establish a quality baseline using the unquantized or 8-bit version, then gradually try lower precisions, comparing each on the same evaluation set. A lower precision should only be adopted if the quality drop is within acceptable business limits and the VRAM or throughput benefits are significant.
4. Inference Service Forms and Key Parameters
Local inference services typically take three forms, corresponding to different usage methods:
- Single-machine interactive service: Used directly by individuals or small teams, focusing on time to first token and single-user output speed.
- API-compatible service deployment: Acts as a model backend for internal applications, requiring handling of multiple concurrent requests, authentication, and rate limiting.
- Offline batch processing: Used for tasks like document summarization and data cleaning that do not require real-time responses, with the core metric being overall throughput.
The parameter settings differ significantly across these forms. The configuration snippet below demonstrates the meaning of several key parameters:
model:weights_path: /models/dense-27b-int4quantization: int4_group128dtype: automax_model_len: 32768runtime:max_num_seqs: 8 # Maximum number of requests processed simultaneouslygpu_memory_utilization: 0.90 # VRAM usage limit, space needs to be reserved for system and fragmentationenable_prefix_caching: true # Reuse KV cache with the same prefixenable_chunked_prefill: true # Split the prefill of long inputs to reduce decoding blockingserver:host: 127.0.0.1port: 8000api_key_env: LOCAL_LLM_API_KEY
There are three parameters that need to be thoroughly understood:
First, max_model_len determines the maximum sequence length allowed for a single request. It directly impacts the reserved space for the KV cache. Setting it much larger than actual business needs will squeeze out concurrency capacity.
Second, max_num_seqs is mutually constrained by the VRAM budget. Higher concurrency means better throughput, but the KV cache for each request also grows. Exceeding the VRAM limit will result in queuing or even failures. It is recommended to start with a lower concurrency, gradually increase it, and observe the VRAM peak simultaneously.
Third, continuous batching is an important mechanism for improving throughput. It allows new requests to join the computation batch while other requests are still being processed, reducing GPU idle time. Most modern inference frameworks support this mechanism, and it should be considered a basic requirement during selection.
API keys should be read via environment variables or a key management service, and should not be written directly into configuration files or code repositories.
5. Engineering Considerations for Long Context and Multimodal Inputs
5.1 Long Context
The context length a model can support is usually determined by its positional encoding design during training. If you need to process inputs longer than the training length, a common practice is to extrapolate the positional encoding, such as adjusting the scaling method of Rotary Position Embedding (RoPE). This method allows the model to accept longer inputs, but it does not guarantee that the quality across all lengths will be consistent with the training length.
Therefore, before enabling long context, two validations should be performed. First, test retrieval-based tasks on inputs of varying lengths, such as locating specific information in a long document, to observe if accuracy drops significantly as length increases. Second, measure the time to first token and VRAM usage under long contexts to ensure the service remains stable under peak load.
For many document Q&A scenarios, you can also bypass relying on ultra-long contexts by using a Retrieval-Augmented Generation (RAG) approach. This involves splitting the document and retrieving relevant chunks first, then feeding a small number of chunks into the model. This solution has lower VRAM costs but requires maintaining an additional retrieval pipeline.
5.2 Multimodal Inputs
When multimodal models process images, a visual encoder typically converts the image into a set of visual tokens, which are then fed into the language model alongside text tokens. Higher image resolutions generate more tokens, leading to greater computational and VRAM overhead. In business applications, the maximum edge length of an image can be set according to task requirements; for instance, UI screenshot recognition usually does not require the original resolution.
Video input generally requires frame extraction, and the extraction frequency and number of frames directly determine the input size. The decoding and scaling in the preprocessing stage also consume CPU resources, which can easily become a bottleneck in high-concurrency scenarios.
For tasks involving charts, documents, and UI screenshots, it is recommended to build a dedicated evaluation set covering sub-tasks like text recognition, numerical reading, and element localization, rather than just looking at an overall score. Comprehensive scores often mask shortcomings in specific tasks.
6. Performance Evaluation Methods
When evaluating a local deployment solution, it is recommended to focus on the following metrics:
- Time to First Token (TTFT): The time from sending a request to returning the first token, directly impacting the interactive experience.
- Output Speed (Tokens per second): Throughput during the generation phase, determining the completion time for long answers.
- Peak VRAM: Including weights, KV cache, and runtime overhead, determining if memory overflow will occur under high load.
- Concurrent Throughput and Tail Latency: Total throughput under target concurrency, as well as P95 and P99 latency.
- Task Quality: Accuracy or human rating on real business samples.
The evaluation process can follow these steps:
- Extract samples from real business operations to form a fixed evaluation set, covering main task types and typical length distributions.
- Record quality and performance data at baseline precision.
- Sequentially try different quantization schemes, comparing quality changes and VRAM benefits on the same evaluation set.
- Conduct context length stress testing on the selected solution to observe latency and VRAM growth under long inputs.
- Perform concurrency stress testing to find the maximum concurrency that meets latency targets.
- Make a decision by integrating quality, cost, and stability.
Below is pseudocode for the evaluation loop, used to illustrate the structure without relying on specific implementations:
for config in candidate_configs:service = start_service(config)for sample in eval_dataset:t0 = now()response = service.generate(sample.prompt)first_token_latency = response.first_token_time - t0total_time = now() - t0record(sample.id, config.name, response.text,first_token_latency, total_time)peak_mem = service.peak_memory()quality = score(eval_dataset, config.name)report(config.name, quality, peak_mem)service.stop()
Evaluation results should retain raw records for future review. Keeping only averages can easily mask individual long-tail issues.
7. Model Selection Decision Reference
The matching of hardware and model scale can be roughly referenced by the table below:
| Hardware Condition | Suitable Deployment Method | Notes |
|---|---|---|
| High-end laptop or unified memory device | 4-bit quantized medium-scale model, single-user interaction | Limited long-context and concurrency capabilities |
