Deploying Open-Weight LLMs: A Practical Guide to Compute, Customization, and Operations
As large language model teams increasingly release complete model weights, organizations face the choice between using remote APIs and self-hosting open-weight models. This article provides a practical guide for deploying open-weight LLMs, covering critical aspects such as build-vs-buy evaluation, hardware and VRAM estimation, inference optimization techniques, model customization strategies, security compliance, and an engineering go-live checklist to help technical teams successfully transition to fully controlled, self-hosted deployments.
1. Background: From API Calls to Open Weights
In the past, most teams utilized large language models (LLMs) by calling remote APIs. This approach offers rapid integration and requires no hardware maintenance, but the model version, inference behavior, and data flow are controlled by the service provider. Recently, several LLM teams have publicly released complete model weights, providing an additional option: downloading the weight files, deploying them on self-owned or rented compute infrastructure, and optimizing and customizing them according to business needs.
The direct impact of open weights is the transfer of control. Teams can lock the model version to prevent output drift caused by remote model updates. They can host the inference service within an internal network to reduce the risk of sensitive data exposure. Teams can also fine-tune the model for specific tasks. The tradeoff is that the team must independently manage deployment, scaling, performance monitoring, and security updates.
2. Evaluation: Self-Hosted Deployment vs. Remote API
Before choosing a path, evaluate the following dimensions rather than just looking at the unit price.
| Evaluation Dimension | Remote API | Self-Hosted Open-Weight Model |
|---|---|---|
| Data Sensitivity | Data passes through external services | Data can stay in the intranet |
| Request Volume & Cost | Pay-per-call, more cost-effective for low traffic | Higher fixed cost, lower unit cost for high and stable traffic |
| Version Control | Provider may update the model | Weight versions can be locked |
| Customization | Limited by exposed API parameters | Fine-tuning and inference logic changes allowed |
| Ops Requirements | Low | Requires dedicated personnel for hardware, services, and monitoring |
| Latency & Availability | Depends on network and provider | Can deploy locally, but depends on internal ops capability |
When deciding, it is recommended to calculate the break-even point using actual bills and load testing data. If the request volume is low and the requirements are general, API calls are usually more cost-effective. If the request volume is high and stable, data cannot leave the domain, or a fixed version and deep customization are required, self-hosted deployment is more advantageous.
3. Hardware and VRAM Estimation
Before deployment, VRAM must be estimated. The VRAM occupied by model weights can be roughly calculated using the following formula:
Weight VRAM ≈ Number of Parameters × Bytes per Parameter
Under common precisions, the bytes per parameter are roughly as follows: FP16 or BF16 is 2 bytes, INT8 is 1 byte, and INT4 is about 0.5 bytes. Taking a 70B (70 billion) parameter model as an example, weights in BF16 precision require about 140 GB, INT8 requires about 70 GB, and INT4 requires about 35 GB.
def estimate_weight_memory_gb(params_billion: float, bytes_per_param: float) -> float:"""Estimate VRAM occupied by model weights (in GB)."""total_bytes = params_billion * 1e9 * bytes_per_paramreturn total_bytes / (1024 ** 3)# Example: VRAM usage for a 70B parameter model at different precisionsfor name, bpp in [("BF16", 2.0), ("INT8", 1.0), ("INT4", 0.5)]:print(f"{name}: {estimate_weight_memory_gb(70, bpp):.1f} GB")
Weights are just the starting point. During inference, VRAM is also needed to store activations and the KV cache. The KV cache grows with context length and concurrent request volume. In high-concurrency, long-context scenarios, it often becomes a bottleneck earlier than the weights. Therefore, planning should reserve a large margin for runtime overhead and observe the actual VRAM curve during load testing.
4. Inference Optimization
Getting the model to run is only the first step. To achieve acceptable throughput and latency for the service, the following types of optimizations are typically required.
- Continuous Batching: Dynamically merges requests arriving at different times into the same batch for computation to improve GPU utilization. It significantly boosts throughput but increases queuing time for individual requests, requiring parameter tuning based on latency goals.
- Quantization: Reducing weight precision decreases VRAM and bandwidth usage. The accuracy loss introduced by quantization must be validated using a fixed evaluation set; you cannot just look at the VRAM numbers.
- KV Cache Management: Uses paged cache allocation to reduce VRAM fragmentation. It also limits the maximum context length to prevent a single ultra-long request from exhausting resources.
- Speculative Decoding: Uses a smaller draft model to first generate candidate tokens, which are then batch-verified by the main model. It can reduce generation latency in certain scenarios, but the benefit depends on the match between the draft model and the main model.
- Prefix Caching: Caches computation results for identical system prompts or document prefixes, suitable for businesses like knowledge base Q&A where repetitive prefixes are common.
Before the service goes live, load testing should be conducted using real traffic distribution, recording Time to First Token (TTFT), tokens generated per second, and error rates as a baseline for subsequent optimizations.
5. Customization and Fine-Tuning
There are multiple paths for customizing models, with varying relationships between cost and effect. It is recommended to try them in the following order:
- Prompt Engineering: Optimize instruction structure, examples, and output formats. This has the lowest cost and should be done first.
- Retrieval-Augmented Generation (RAG): Index enterprise documents and inject relevant fragments into the context during inference. This is suitable for scenarios where knowledge is frequently updated, as updating the knowledge base does not require retraining.
- Parameter-Efficient Fine-Tuning (PEFT): Trains only a small fraction of new parameters, such as Low-Rank Adaptation (LoRA). It requires much less compute and storage than full fine-tuning, making it suitable for adapting style, format, and specific tasks.
- Full Fine-Tuning: Updates all parameters. It has a high ceiling for performance but also the highest cost and data requirements, and it easily introduces catastrophic forgetting, so it should be used with caution.
Regardless of the chosen path, data quality is more critical than quantity. Training samples should be deduplicated, formatted uniformly, and re-annotated. Additionally, the team needs to maintain a fixed evaluation set for regression testing after each modification to ensure the new version does not degrade on older tasks.
Below is a simplified skeleton of an evaluation process. In actual projects, this can be replaced with the team’s own scoring criteria.
from dataclasses import dataclass@dataclassclass EvalCase:prompt: strexpected_keywords: list[str]def run_eval(generate, cases: list[EvalCase]) -> float:"""generate is the function calling the model, returns the proportion of samples hitting keywords."""passed = 0for case in cases:output = generate(case.prompt)if all(kw in output for kw in case.expected_keywords):passed += 1return passed / len(cases)
Keyword matching is only the simplest scoring method. For open-ended questions, teams can use manual scoring, rule-based validation, or auxiliary scoring by another model, but the scoring method itself also requires sample-based validation.
6. Security and Compliance
Open weights do not mean unconditional use. The following tasks should be completed before deployment:
- License Review: Carefully read the license agreement attached to the model to confirm commercial use scope, attribution requirements, and usage restrictions. Legal personnel should interpret the terms.
- Weight Integrity Check: After downloading, verify the file hash to ensure it matches the checksum published by the provider, preventing tampering during transmission.
- Input and Output Filtering: Validate user input for length and format, and detect sensitive content in the output.
- Prompt Injection Protection: When the model can call tools or read external documents, document content should be treated as data rather than instructions, and the range of tools the model can call should be restricted.
- Access Control and Log Masking: The inference interface requires authentication and rate limits for callers. User inputs and outputs in logs should be masked before storage.
7. Engineering Go-Live Checklist
Check the following items before going live:
- Cost measurement for self-hosting vs. API calls is complete, with conclusions based on actual bills or load testing data.
- Model version, weight hash value, and license version are recorded and placed under configuration management.
- VRAM planning includes weights, KV cache, and runtime overhead, and has been validated under maximum concurrency.
- Alert thresholds for Time to First Token (TTFT), throughput, and error rates are configured.
- The fixed evaluation set covers major business scenarios, and regression tests are executed after every model or parameter change.
- The inference service has authentication, rate limiting, and log masking capabilities.
- A rollback plan is in place to switch back to the previous stable version within minutes.
8. Choosing a Deployment Platform
If you choose to deploy on Baidu AI Cloud, you can use a general container platform to orchestrate inference services, object storage to save weight files and evaluation data, and logging services plus monitoring alerts to track latency, error rates, and VRAM usage. These capabilities fall under general infrastructure categories. Teams should select the appropriate resource specifications and deployment methods based on their own operational systems and cost budgets.
