Open-Source LLM Local Deployment Guide: Parameters, Memory, and Performance
This guide explains how to deploy open-source large language models locally, covering when local inference makes sense, license checks, model architecture choices, quantization, hardware sizing, capability validation, performance testing, and secure operations. It also describes how to combine local models with cloud services in a layered architecture.
1. Why Deploy Large Language Models Locally?
Deploying an open-source large language model (LLM) on your own machine is not just a fallback when cloud services are considered too expensive. For teams with data security concerns or cost sensitivity, local deployment is becoming a standard option.
Local inference provides four main advantages:
Data stays inside your environment
Conversation records, internal documents, and code do not leave your network. This helps meet data governance requirements in industries such as finance, healthcare, government, and regulated enterprise environments.Marginal inference cost approaches zero
The model runs on your own hardware instead of being billed per token. The more you call it, the more the fixed cost is spread out. This is suitable for high-frequency, batch, or long-text workloads.Latency is controllable and the model can work offline
Inference happens on the local machine, avoiding public-network round trips and network jitter. The system can continue to work in offline environments, and response time is easier to predict.Behavior can be audited and customized
Inputs and outputs can be fully logged. You can also perform domain fine-tuning, quantization, and access control as needed.
However, “zero token cost” does not mean “zero cost.” The following expenses should still be included in the total cost:
- Hardware investment: the cost of purchasing memory, GPUs, or complete machines;
- Ongoing power consumption: electricity cost when desktop-level devices run inference at full load for long periods;
- Operational overhead: model updates, version regression testing, monitoring, and alerting;
- Hidden costs: model iteration cycles are often faster than hardware depreciation cycles.
A more practical judgment is:
- Local deployment has the clearest advantages when call volume is high, data is sensitive, and workloads are stable.
- Calling a cloud model API is often more economical when call volume is low and tasks are complex or frequently changing.
2. Three Evaluation Dimensions Before Deployment
2.1 License: First Confirm Whether Commercial Use Is Allowed
Since 2024, open-source large model licensing policies have become noticeably more divided:
- Permissive open-source licenses: impose no extra restrictions; commercial use, modification, and redistribution are allowed, as long as copyright and license notices are retained.
- Community-style licenses: usually allow commercial use, but may add conditions related to user scale, use case, or attribution.
- Research-only licenses: allow non-commercial use only. Enterprises should have legal review before using them.
When choosing a model, confirm three things:
- Check the license file in the root directory of the model repository.
- Read the usage terms in the model card; they may differ from the code license.
- Confirm whether derivative products need to include additional notices.
2.2 Parameter Scale and Architecture: Can the Model Run?
Parameter scale determines the lower bound; data quality and training methods determine the upper bound.
Within the same model generation, larger-parameter versions usually perform better on complex reasoning and long-context understanding. But more parameters do not automatically mean better quality. Data quality, training mixture, and post-training strategies often matter more than parameter count alone.
Architecturally, models generally fall into two categories:
- Dense models: every token passes through all parameters. Computation grows roughly linearly with parameter count, and inference speed is strongly related to parameter scale.
- Mixture-of-Experts (MoE) models: consist of multiple expert subnetworks plus a routing module. Only a small number of experts are activated for each token. Activated parameters are far smaller than total parameters, so speed can approach that of a smaller model, while quality can approach that of a larger model.
The key trap of MoE models is memory:
During inference, only some experts are activated, but all expert weights must remain resident in memory. MoE saves compute, not memory.
Therefore, MoE models place higher demands on memory bandwidth: for every generated token, the weights of the activated experts must be read from memory into compute units. Data movement is proportional to total parameter count, while computation is much smaller than in a comparable dense model.
2.3 Input Modality and Context Length
- Vision-language models (VLMs): add an image encoder and visual tokens, so memory usage is higher than that of a pure text model of the same size. End-to-end speech models can remove the two-stage pipeline of “speech-to-text + text LLM.”
- Context length: the advertised length is not necessarily the practical usable length. Longer contexts consume more memory, increase time-to-first-token, and can exhibit “lost in the middle” behavior, where information placed in the middle of the context is more easily ignored.
3. Quantization: Trading Precision for Smaller Size
To fit a model into limited local memory, you usually need to quantize it first. This is one of the key steps that determines whether the model can run at all.
A basic estimation formula is:
Weight size (GB) ≈ parameter count (B) × bytes per parameterFP16: 2 bytes; INT8: 1 byte; 4-bit: 0.5 byte (plus a small amount for scale factors)Actual footprint ≈ weight size + runtime overhead (about 15%-30%) + KV Cache
For example, an 8B dense model quantized to 4-bit has about 4 GB of weights and typically uses about 5-6 GB in practice.
Quantization is not free:
- Lower bit-widths usually lead to greater quality loss. Reasoning tasks such as math and code are especially sensitive to quantization.
- High scores published in model cards usually come from full-precision versions. Quantized performance must be validated again with your own data.
- Tool calling depends on structured output and strict formatting. After quantization, models may more easily produce missing fields or invalid parameters.
Recommended workflow: use small models to find direction, and large models to preserve quality.
- Compare 2B, 4B, and 8B models using a few realistic tasks, such as two to four tool calls, to find the smallest model that meets quality requirements.
- Then choose a larger version within the same model family or architecture.
- Re-run the same tasks after quantization and compare quality loss.
- For accuracy-sensitive workloads, use an “8-bit first, 4-bit as fallback” strategy.
4. Parameter Scale and Hardware Selection Quick Reference
Using 4-bit quantization as an example, the approximate footprint of common parameter sizes is shown below. These are rough estimates; always refer to the specific model card for actual numbers.
| Parameter scale | Architecture | Weight size | Estimated actual footprint | Recommended memory | Typical use case |
|---|---|---|---|---|---|
| 2-4B | Dense | 1.5-2.5 GB | 2-3 GB | 4 GB | Edge devices such as phones and single-board computers |
| 7-8B | Dense | 4-5 GB | 5-7 GB | 8 GB | Mainstream office laptops; daily Q&A and rewriting |
| 14B | Dense | 8-9 GB | 9-11 GB | 16 GB | Complex Q&A, structured extraction, tool calling |
| 20-30B | MoE | 11-16 GB | 13-18 GB | 18-24 GB | Main tier balancing speed and quality |
| 30B class | Dense | 17-20 GB | 19-23 GB | 24-32 GB | Complex reasoning and code generation; 24 GB works but is tight |
| 70B class | Dense | 35-40 GB | 38-45 GB | 48 GB or more | Near full-size performance; requires high-end workstation |
A rough rule of thumb is:
4 GB for small models, 8 GB for daily use, 16 GB for advanced tasks, and 20 GB or more for large models.
Note that “memory” means different things on unified-memory devices and discrete-GPU machines. For discrete-GPU systems, you also need to consider VRAM.
In addition to weights, KV Cache is often overlooked. It grows linearly with context length and can be estimated as:
KV Cache (bytes) ≈ 2 × layers × KV heads × head dimension × bytes per value × token count
For example, an 8B-class model with 32 layers, 8 KV heads, head dimension 128, and FP16 precision uses about 128 KB per token. At 128K context, the KV Cache alone is about 16 GB.
Therefore, long-context models can require much more memory than their parameter count suggests. For frequent long-text workloads, prefer inference engines that support paged attention or KV Cache quantization.
5. Capability Validation: Tool Calling, Long Context, and Chinese Performance
Whether a local model can truly support business needs cannot be judged by benchmark scores alone. It is recommended to validate it with four types of tests:
- Function calling: provide two or three local tools and check whether the model can select the correct function and generate valid parameters.
- Long-context needle-in-a-haystack: place key information at different positions in a long document and test whether the model can retrieve it accurately.
- Structured output: require the model to return fixed fields and strict types in JSON, then check the parse success rate.
- Chinese and domain terminology: use your own corpus to verify terminology, formatting, and industry-specific expressions.
An example tool-calling validation script is shown below. The endpoint and field names are illustrative.
import jsonimport requestsBASE = "http://127.0.0.1:8080" # Local inference service addresstools = [{"type": "function","function": {"name": "get_weather","parameters": {"type": "object","properties": {"city": {"type": "string"}},"required": ["city"],},},}]resp = requests.post(f"{BASE}/v1/chat/completions",json={"model": "local-14b","messages": [{"role": "user", "content": "What's the weather in Beijing today?"}],"tools": tools,"tool_choice": "auto",},timeout=60,)message = resp.json()["choices"][0]["message"]print(json.dumps(message.get("tool_calls"), ensure_ascii=False))
Pass criteria:
- The returned
tool_callscontain the correctfunction.name. - The
argumentsare valid JSON that can be parsed byjson.loads, and all required fields are present.
Tool-calling ability is usually positively correlated with parameter scale. For models below 10B, it is safer to add few-shot examples, strict prompt constraints, and post-generation validation. Such models should not be directly entrusted with multi-step agent workflows.
6. Five Steps to Local Deployment
There are two main categories of local runtime:
- Consumer-grade runtimes: a single app can handle model management, inference serving, and API exposure. Suitable for individuals and small teams.
- Production-grade inference frameworks: support multi-GPU tensor parallelism, dynamic batching, paged attention, and multi-model scheduling. Suitable for production environments with high concurrency and throughput requirements.
The deployment process is the same for both, and can be divided into five steps:
- Evaluate hardware: check available memory, GPU VRAM, and remaining disk space. A single 30B-class quantized model may require more than 20 GB of disk space.
- Choose a quantized version: prefer 4-bit when memory is limited. For numerically sensitive tasks, consider 8-bit or higher precision.
- Download and run the model: select the model by tag in the local runtime. The first run requires downloading weights. For an MoE model of about 18 GB, downloading may take about half an hour on 100 Mbps bandwidth or a few minutes on gigabit bandwidth.
- Validate and stress test: first run a sample conversation, then run the tool-calling script and performance tests.
- Integrate with applications: expose the local inference service through an HTTP API. Business applications only need to point their endpoint to the local service. Agent applications can add tool-calling capabilities on top of this API, provided the selected model actually supports function calling.
Example commands:
# The command names depend on the local runtime you use.local-runtime pull model-tag:26b # Pull the quantized modellocal-runtime run model-tag:26b # Run the model and enter interactive modelocal-runtime list # List downloaded modelscurl -s http://127.0.0.1:8080/v1/chat/completions \-H "Content-Type: application/json" \-d '{"model":"model-tag:26b","messages":[{"role":"user","content":"Hello"}],"stream":false}'
7. Performance Acceptance: Three Metrics for “Is It Fast Enough?”
Generation-stage throughput, measured in output tokens per second, is mainly determined by memory bandwidth rather than raw compute. This is also why unified-memory devices can run large models smoothly, while thin laptops with integrated GPUs can serve as good platforms for small models.
To obtain reproducible measurements, use a fixed prompt and take the median across multiple requests.
import timeimport requestsURL = "http://127.0.0.1:8080/v1/completions" # Address is illustrativepayload = {"model": "model-tag:26b","prompt": "Please explain what KV Cache is: " * 8,"max_tokens": 256,"stream": True,}t0, first_token_at = time.perf_counter(), Nonetokens = 0with requests.post(URL, json=payload, stream=True, timeout=120) as r:for line in r.iter_lines():if not line:continuechunk = line.decode("utf-8").removeprefix("data: ").strip()if chunk == "[DONE]":breakif first_token_at is None:first_token_at = time.perf_counter() # Record time to first tokentokens += 1total = time.perf_counter() - t0print(f"First token latency: {(first_token_at - t0) * 1000:.0f} ms")print(f"Decode speed: {(tokens - 1) / (total - (first_token_at - t0)):.1f} tokens/s")print(f"Total time: {total:.1f}s")
Recommended acceptance metrics:
| Metric | Meaning | Reference target |
|---|---|---|
| Time to first token | Time from sending the request to receiving the first token | Within 1 second for interactive use cases |
| Decode speed | Number of tokens generated per second | About 5 tokens/s is acceptable for Chinese reading; 10 tokens/s or more is recommended |
| Peak memory usage | Memory and VRAM usage under full load | Below 90% of available memory, avoiding paging that slows down the system |
Many local runtimes also support OpenAI-compatible APIs. You can query state endpoints such as /api/tags and /api/ps to inspect loaded models and resource usage. However, the “CPU/GPU usage ratio” does not necessarily mean the GPU is being used effectively. On integrated-GPU machines, this metric may show a high GPU share while actual throughput remains low. The final judgment should be based on measured tokens/s.
8. Local and Cloud: Not Either/Or, but Layered Collaboration
Local deployment solves cost and privacy problems. Complex reasoning, very large contexts, and high peak concurrency are still strengths of cloud models. A more practical approach is to build a layered architecture:
Layer 1: local small models
Handle high-frequency, rule-based, and data-sensitive tasks, such as intent recognition, text classification, field extraction, and sensitive-data redaction.Layer 2: local large models or cloud models
Process requests where the local model has low confidence or requests that are explicitly escalated.Layer 3: cloud hosted services
Serve as an elastic fallback for sudden traffic spikes, very long contexts, and complex reasoning.
In practice, layered routing can be implemented using confidence thresholds, rules, and task-type classification. You should also continuously track request volume and quality across each layer. For example, sensitive data can be redacted locally first, and then the cleaned request can be sent to a cloud model for further processing. This balances privacy and quality.
If you need cloud burst capacity or managed large-model services, you can evaluate cloud offerings such as Baidu AI Cloud. Select services based on regional availability, public documentation, and pricing.
Capacity planning is also important. A local inference process can usually handle only one generation request at a time; concurrent requests will queue. When multiple users share the service, estimate required memory based on concurrency and average output length, and configure timeouts and queue limits.
9. Security and Operations: Four Questions Before Launch
Network exposure
Local inference services may not have authentication enabled by default. Bind only to127.0.0.1and avoid listening on0.0.0.0or exposing the service to the public internet through port mapping. For team sharing, place the service behind an internal gateway with authentication and access control.Data residue
Model inference itself generally does not save conversations, but default logs, agent memory, and observability platforms may write plaintext to disk. When handling sensitive data, disable verbose logging and encrypt stored content.Supply chain
Obtain model weights only from the model author’s official repository or trusted channels, and verify file hashes. Deserialization-based weight formats can carry code-execution risks; do not load model files from unknown sources.Version regression
After updating a model, run a fixed evaluation set to regression-test tool calling, structured output, and long-context capabilities, and confirm that performance has not degraded.
10. Conclusion
Deploying an open-source LLM locally is technically a mature path. The difficulty is not “installing” it, but “choosing the right one”:
- Check the license first, then parameter scale: confirm that commercial use is allowed, then choose parameter size based on available memory.
- For MoE models, use total parameters to estimate memory and activated parameters to estimate speed.
- Quantization brings large memory savings, but quality must be validated with your own data.
- Tool calling, long-context ability, and Chinese performance should all be tested directly.
- Combine local and cloud deployments in layers to balance cost, privacy, and quality.
With this approach, edge devices with a few GB of memory, office computers with a dozen or so GB of memory, and workstations with tens of GB of memory can all run suitable open-source models, allowing data-sensitive and frequently called workloads to run reliably on local infrastructure.
