Deploying Open-Weight LLMs: From Weights to a Stable Inference Service
When a model provider releases the full weights of a model, the engineering team is no longer dealing with "just swapping an API endpoint"—it is taking over an entire inference pipeline. This article walks through the complete workflow for turning open-weight files into a stable inference service: calibrating assumptions, planning capacity, a seven-step deployment path, quality and cost assurance, security and governance, and a cloud reference architecture. It shows how to estimate VRAM across weights, KV cache, and framework overhead; plan latency budgets around TTFT and TPOT; choose precision, quantization, and parallelism strategies; and protect quality with layered evaluation and regression testing.
When a model provider releases the full weights of a model, the engineering team is no longer dealing with “just swapping an API endpoint”—it is taking over an entire inference pipeline. The availability of parameters, architecture definitions, and inference code turns a model from a black-box service into an asset you can deploy, tune, and govern yourself. At the same time, VRAM capacity, parallel partitioning, quantization precision, evaluation regression, and compliance review all land on the engineering side. This article follows the sequence “calibration → capacity planning → deployment path → quality and cost assurance → cloud reference architecture” to lay out a complete engineering method for going from weight files to a stable inference service.
1. First, Calibrate Your Assumptions: Open Weights ≠ Out of the Box
“Open weights” usually only means the model parameters are available; it does not mean the training data, training recipe, and fine-tuning scripts are released alongside them. This boundary directly shapes the nature of the work: reproducing inference is feasible, but reproducing training capability is a different matter. There are three common misconceptions to rule out up front:
- License and redistribution boundaries: Terms for commercial use, modification, redistribution, attribution, and use-case restrictions must be checked item by item and recorded in a compliance ledger.
- Version and update cadence: Released weights are often just a single snapshot, and subsequent iterations are not necessarily synchronized. Production environments should pin the weight version, record checksums, and apply version management to prompts and service configuration as well.
- Deployment threshold: Available weights do not mean an available service. VRAM capacity, inter-GPU interconnect bandwidth, inference framework compatibility, and tuning effort together determine the true total cost of ownership.
2. Capacity Planning: Figure Out Whether It Runs and Whether It Runs Cost-Effectively
2.1 VRAM Usage Comes From Three Parts
The VRAM footprint of single- or multi-GPU inference is roughly composed of three parts:
- Model weights: parameter count × bytes per parameter. Half precision (BF16/FP16) is 2 bytes, 8-bit float is 1 byte, and 4-bit integer quantization is theoretically about 0.5 bytes, though in practice you must also account for metadata such as quantization scale factors.
- KV cache: grows approximately linearly with context length and concurrent requests. In long-context, multi-turn conversation scenarios, it often exceeds the weights themselves and is the most easily underestimated component.
- Activations and framework overhead: intermediate operator results, communication buffers, memory fragmentation, and so on—empirically estimated at another 10%–20% on top of the sum of weights and cache.
def estimate_vram_gb(params_b, # parameter count (billions)bytes_per_param=2, # weight precision: half 2, 8-bit float 1, 4-bit quant ~0.5layers=80, # number of layerskv_heads=8, # KV heads: GQA uses the group count, MQA is 1head_dim=128, # dimension per headbytes_per_kv=2, # KV cache precision: half 2, 8-bit quant 1context=32768, # max context length per requestconcurrency=32, # number of concurrent requestsoverhead=0.15, # activation and framework overhead factor):weights = params_b * 1e9 * bytes_per_paramkv_cache = 2 * layers * kv_heads * head_dim * bytes_per_kv * context * concurrencyreturn (weights + kv_cache) * (1 + overhead) / 1024**3
Take a dense model on the order of 70 billion parameters, with an 80K-token context and 16-way concurrency as an example:
- Half-precision weights come to about 131 GiB.
- An 8-GPU configuration with 80 GB per card can hold this at the weight level, but headroom becomes very tight once the KV cache is added.
- If the context is stretched to 128K tokens and concurrency raised to 64-way, KV cache demand will rise to roughly 3× the original.
- At that point you either reduce precision, expand the resource pool, or cap per-instance concurrency.
These parameters are illustrative only; actual values should be based on the VRAM profiling tools provided by your target inference framework.
2.2 The Latency Budget Should Be Split Into Two Parts
The perceived latency of a large-model service can be broken into two metrics:
- Time to First Token (TTFT): the time from sending a request to receiving the first token, determined by queue wait time and prefill compute. It directly drives the first impression of whether the service “feels laggy.”
- Time Per Output Token (TPOT): the average generation interval per token after the first token. It determines output smoothness; end-to-end latency is approximately TTFT plus output length multiplied by TPOT.
The two metrics should have targets set per scenario:
| Scenario | TTFT Reference Target | TPOT Reference Target | Typical Optimization |
|---|---|---|---|
| Interactive chat | < 1 s | < 50 ms | Session-level prefix caching, output length limits |
| Code completion | < 300 ms | Secondary | File-context prefix reuse, small-model draft speculative decoding |
| Batch document processing | Seconds acceptable | Secondary | Larger dynamic batching, off-peak scheduled runs |
One often-overlooked point: the low latency of a single request during load testing degrades under real concurrency because requests wait on each other within a batch. Capacity evaluation should use load-test results at the target concurrency, with p95 and p99 percentiles as the acceptance criteria.
3. From Weight Files to an Inference Service: A Seven-Step Path
Step 1: Obtain weights and verify integrity. Check file checksums and source signatures; confirm the shard count, index file, and configuration metadata are complete. Set up an internal model repository that records the version, license, and checksum for each set of weights.
Step 2: Align metadata and verify loading. Before loading, check how the model’s own configuration maps to the inference framework’s parameters, including layer count, hidden dimension, attention heads, KV heads, vocabulary size, and so on. After loading, run a small-scale forward pass with a fixed input to check whether the output is reasonable, catching load misalignments or silent precision issues caused by “framework version not matching the weight architecture” as early as possible.
Step 3: Decide on precision and quantization strategy. Common options include:
- Half-precision baseline: minimal precision loss, highest VRAM and bandwidth cost.
- 8-bit float or W8A8 quantization: balances precision and throughput.
- 4-bit weight quantization: significantly reduces VRAM usage, but capability regression is more noticeable on some tasks.
- KV cache quantization: substantial gains in long-context, high-concurrency scenarios.
It is advisable to keep both half-precision and quantized images, and route between them by scenario.
Step 4: Choose a parallel partitioning strategy.
- Tensor parallelism: splits a single matrix operation across multiple GPUs; suited to high-bandwidth interconnect within a single machine, at the cost of communication synchronization at every layer.
- Pipeline parallelism: partitions by layer across different nodes, amortizing pipeline bubbles through micro-batch scheduling.
- Expert parallelism: for sparse mixture-of-experts (MoE) models, distributes experts across devices and requires attention to load balancing.
More parallelism is not always better; every GPU must carry weight shards, communication buffers, and framework overhead. As a rule of thumb, keep a single instance within one machine, and use cross-machine setups mainly for scaling out rather than for partitioning.
Step 5: Tune the inference engine. A set of general optimizations has emerged for large-model characteristics:
- Continuous batching: new requests can join a running batch during decode gaps, avoiding the need to “wait for the slowest request to finish.”
- Paged KV cache management: organizes the cache in fixed-size blocks, reducing VRAM fragmentation and providing a basis for prefix sharing.
- Prefix cache reuse: fixed prefixes such as system prompts, long documents, and code-repository context are computed only once, and later requests hit the cache directly.
- Speculative decoding: a lightweight draft model predicts several candidate tokens in a row, which the target model then verifies in parallel, yielding clear gains on tasks with predictable output.
Step 6: Elastic scaling and traffic governance.
- Deploy online inference and offline batch processing in separate pools, so large batch jobs do not crowd out interactive traffic.
- Use SLOs, queue length, and VRAM utilization as scaling signals, and set cooldown windows to prevent flapping.
- Implement multi-model routing, tenant-level rate limiting, and quotas at the API gateway so that an individual caller cannot bring down the whole service.
Step 7: Build observability. Establish a unified observability system spanning metrics, logs, and traces:
- Performance metrics: TTFT, TPOT, end-to-end latency percentiles, output throughput, queue time.
- Resource metrics: VRAM usage and fragmentation rate, GPU utilization, communication wait time.
- Quality metrics: output truncation rate, format parse failure rate, refusal rate.
At the same time, set up tiered alerts and degradation plans. Some long-context or high-load requests can be automatically routed to standby instances or smaller models.
4. Quality and Cost: Guard the Quality Baseline With an Evaluation System
4.1 Layered Evaluation Sets
- Public benchmarks: used for side-by-side comparison across weight versions.
- Business evaluation sets: sampled from historical real requests—hundreds to thousands of entries covering high-frequency intents and long-tail scenarios, scored by humans or rules. This is the core basis for deciding whether to go live.
- Adversarial sets: cover risk scenarios such as prompt injection, unauthorized tool calls, and sensitive content output.
4.2 Regression After Quantization and Version Changes
Every precision adjustment, parallel-strategy change, or weight upgrade must complete a regression on the business evaluation set, with particular attention to long-tail capability:
- Whether structured output (such as JSON) can still be parsed reliably.
- Whether tool-call arguments are accurate.
- Whether information at intermediate positions in a long context can be correctly recalled.
- Whether code indentation and long outputs are being truncated.
4.3 A Two-Dimensional Cost Model
It is advisable to maintain two cost perspectives:
- Token cost: priced separately for input and output tokens, making it easy to compare against an API-usage model.
- GPU card-hour cost: useful for resource-pool planning and capacity budgeting.
The core comparison logic is as follows:
Self-hosted effective per-GPU-hour cost = instance depreciation + power and datacenter cost + amortized ops labor + idle lossSelf-hosted cost per token = effective per-GPU-hour cost / measured output tokens per second
Output throughput varies significantly with concurrency and input length, so use measured values under a real business traffic profile rather than a vendor’s advertised peak numbers. A common pattern is that high-concurrency batch jobs more easily amortize fixed costs, while low-traffic long-tail scenarios are better served by on-demand managed services or elastic resources.
5. Security and Governance: From Weight Files to Runtime
- Supply chain security: obtain weights only from trusted channels, verify integrity and source signatures, and register license terms and usage scope in the compliance ledger.
- Loading-stage risks: some weight serialization or scripting formats can execute code during deserialization. Prefer pure data formats and load them in an isolated environment with restricted network access and least privilege.
- Runtime isolation: inference containers should restrict outbound network and filesystem permissions to prevent malicious instructions in model output from triggering unauthorized tool calls.
- Data and auditing: record desensitized request and response samples for regression evaluation, and manage them per data-retention policies. Complete access logs should be paired with key management and least-privilege access control.
6. Cloud Reference Architecture: Practical Recommendations for Baidu AI Cloud
Building an open-weight model service on Baidu AI Cloud can follow this layered architecture:
| Layer | Key Capabilities | Engineering Notes |
|---|---|---|
| Model asset layer | Object storage | Version and archive weights, decoupled from compute resources |
| Compute layer | Container platform + elastic GPU resources | Node pools segmented by GPU type, with elastic scaling |
| Service layer | Containerized inference engine + API gateway | Unified entry, multi-model routing, tenant rate limiting and quotas |
| Observability layer | Logging service + monitoring alerts | Collect performance metrics and configure tiered alerts |
| Security layer | Key management + network isolation | Private network deployment, sensitive configuration managed in a key service |
A few engineering conventions worth implementing first:
- Decouple model from image: store weights in object storage, and keep only the runtime and engine configuration in the container image, so switching versions does not require rebuilding the image.
- Multi-spec instance pools: segment instance types by VRAM capacity and inter-GPU interconnect capability, and schedule tensor-parallel instances within the same high-bandwidth node.
- Attribute cost to tenants: tag by caller at the gateway, and attribute token usage and resource consumption to business lines, providing a basis for capacity planning and budget allocation.
7. Industry Perspective: How Open Weights Reshape Compute Demand
The spread of open-weight models is reshaping AI infrastructure demand. This translates into several transmission paths:
- Inference compute becomes the norm: shifting from “calling an API” to “local deployment,” inference workloads change from bursty to long-running steady-state, raising the bar for sustained server throughput and operational efficiency.
- VRAM and bandwidth become key constraints: long contexts and multi-turn conversations keep inflating the KV cache, increasing the importance of storage capacity, memory bandwidth, and I/O capability.
- Intra-machine and cluster interconnect upgrades: tensor parallelism relies on high-bandwidth intra-machine interconnect, while large-scale cluster training tests the stability and bandwidth density of network interconnect and optical components.
- Edge and on-device inference rises: as model compression, quantization, and distillation mature, local inference demand on smart terminals and edge devices is gradually unlocked, driving development of edge chips and supporting software stacks.
- Hardware ecosystem adaptation deepens: as models migrate to more hardware backends, this continually drives compatibility work such as operator libraries, compiler optimization, and quantization-precision alignment. The depth of ecosystem adaptation is often the key variable determining whether alternative compute can be deployed at scale.
For engineering teams, the more worthwhile investment is reusable deployment capability: a standardized system for weight management, evaluation regression, and elastic scheduling can significantly reduce the switching cost of subsequent model iterations.
8. Deployment Checklist at a Glance
- Check license terms and usage boundaries, and register weight versions and checksums.
- Use an estimation script to compute weights, KV cache, and framework overhead, then work backward to instance types and a parallel strategy.
- After loading, complete metadata verification and small-scale forward validation.
- Decide on a precision approach, and keep both half-precision and quantized images for scenario-based routing.
- Enable general optimizations such as continuous batching and prefix caching, and load-test at the target concurrency.
- Enforce rate limiting, quotas, degradation, and cost attribution at the gateway.
- Build business evaluation sets and adversarial sets, and run a regression after every change.
- Complete supply chain verification, runtime isolation, and audit-log configuration.
