Self-Hosting Open-Weight Large Language Models: From Inference Architecture to Compute Selection
With major model vendors now releasing full open weights, developers and enterprises can move beyond API-only access and run models on their own infrastructure. This article provides a practical guide to self-hosted LLM inference. It compares managed APIs with self-deployment and explains when each fits, then walks through the decisions that make self-hosting work: estimating VRAM from weights, KV cache, and activations; optimizing inference through quantization, continuous batching, prefix caching, and speculative decoding; structuring a layered gateway with routing, degradation, and observability; and handling security, licensing, evaluation, and gray rollout. It also covers diverse hardware adaptation, device-cloud collaboration, and industry trends, and closes with a phased roadmap from requirements assessment to scaled rollout. Readers will come away with a controllable, observable, and reusable approach to deploying open-weight models.
Self-Hosting Open-Weight Large Language Models: From Inference Architecture to Compute Selection
In recent years, leading model vendors have released the complete weights of their large language models. Developers and enterprises are no longer limited to calling models over a network API; they can download the weights and, given sufficient compute, deploy and run them on their own infrastructure, then apply custom optimizations for their business needs. This marks a shift in how large models are used, from “API-only access” toward a world where “access and self-hosting coexist.”
For enterprise engineering teams, open weights are both an opportunity and a new set of engineering challenges: where to deploy, how to estimate resources, how to optimize inference, and how to ensure quality and security. This article addresses those questions and lays out a practical, deployable self-hosted inference approach.
1. From API Calls to Self-Deployment: What Actually Changes
1.1 The core difference: a transfer of control
Calling a managed API and self-hosting weights are two different engineering models, and the key difference is who holds control.
- Managed API: The provider owns model iteration, scaling, and failure recovery. Enterprise-side integration is low-cost and fast to launch, which suits scenarios with highly variable demand or a focus on rapid validation.
- Self-hosting: The enterprise owns the model version, runtime environment, and scheduling policy. The tradeoff is that it must take on hardware, operations, and stability responsibilities.
1.2 Typical scenarios for self-hosting
- Data-sensitive workloads: In financial risk control, medical assistance, and government/enterprise office scenarios, data should not leave the private environment. Local inference keeps data flow under physical control.
- Dense, steady traffic: When request volume per unit time is high and the peak-to-valley difference is small, a self-built cluster’s long-term unit cost is usually easier to estimate and control.
- Deep customization: When an enterprise needs domain continued pre-training on a base model, instruction fine-tuning, or integration with internal tools and business systems, self-hosting provides full room for modification.
- Latency-sensitive workloads: For online businesses with strict end-to-end latency requirements, deploying compute in the same region or availability zone as the service reduces jitter from public-network round trips.
1.3 A decision framework: evaluate dimension by dimension
Whether to self-host should not be a blanket decision. Evaluate the following dimensions:
- Data compliance requirements: Is data egress allowed?
- Daily call scale: Request volume and token consumption.
- Load variability: Peak-to-valley ratio and predictability of scaling cycles.
- Customization depth: Prompt-level, fine-tuning-level, or pre-training-level.
- Team capability: Does the team have inference operations and performance-tuning experience?
For exploratory projects with low call volume and modest compliance requirements, calling a managed API is often the more pragmatic choice. Most enterprises end up with a hybrid model: high-frequency, sensitive, stable tasks run self-hosted, while low-frequency, long-tail, or complex tasks go through a managed API, with a unified gateway serving as the front door.
2. Resource Planning: Start by Estimating VRAM
When deploying a large model, whether VRAM is sufficient directly determines whether the plan is viable, and it is the first step in capacity planning. VRAM usage comes mainly from three parts: model weights, intermediate activations during inference, and the key-value cache (KV Cache) produced by the attention mechanism.
2.1 Weight footprint
Weight VRAM ≈ parameter count × bytes per parameter. Common byte sizes by precision are: 2 bytes for FP16/BF16, 1 byte for FP8, 1 byte for INT8, and 0.5 byte for INT4. Take a 10B-parameter dense model as an example: in FP16 the weights alone need roughly 20GB of VRAM, dropping to about 5GB after INT4 quantization.
2.2 KV cache
The KV cache grows with the number of concurrent requests and the context length, and in long-context scenarios it can far exceed the weight footprint. The formula is:
def kv_cache_gb(layers, kv_heads, head_dim, seq_len, concurrency, bytes_per_elem):"""Estimate KV cache VRAM (K = Key, V = Value, hence the factor of 2)layers: number of model layerskv_heads: number of KV heads (far smaller than attention heads when using GQA)head_dim: dimension of each attention headseq_len: max context length of a single requestconcurrency: number of concurrent requestsbytes_per_elem: bytes per cache element"""elements = 2 * layers * kv_heads * head_dim * seq_len * concurrencyreturn elements * bytes_per_elem / 1024**3
Two points to note:
- For models using Grouped-Query Attention (GQA) or Multi-Query Attention (MQA), the number of KV heads is far smaller than the number of attention heads, so the KV cache shrinks significantly. This is an important prerequisite for long-context inference.
- A single card’s VRAM must hold the weights, the KV cache, and the activations simultaneously, with some headroom reserved. “The weights fit” does not mean “the service will run.”
2.3 Compute and interconnect
- Inter-card interconnect: When a single card’s VRAM is insufficient, tensor parallelism can split the weights across multiple cards. Because this partitioning requires inter-card communication at every layer, it is very sensitive to interconnect bandwidth. Keep the parallel group within the same machine and the same high-speed interconnect domain whenever possible.
- Cross-machine scaling: For larger workloads, use tensor parallelism within a machine and pipeline parallelism across machines. Pipelines introduce “bubbles” (idle stalls); during scheduling, interleave micro-batches from different requests to fill them and reduce idle time.
- Storage and network: Weight files ranging from tens to hundreds of GB need reliable access. It is recommended to keep multiple weight versions in object storage, then use a local high-performance cache disk to accelerate loading, while avoiding direct public-network connections.
3. Inference Optimization: Spend Compute Where It Counts
3.1 Quantization
- Post-training quantization (PTQ) is the most common approach. Industry practice shows that quantizing weights alone yields noticeable VRAM savings and memory-bandwidth benefits; quantizing activations and the KV cache offers larger gains but requires evaluating the accuracy loss.
- Weight quantization is essentially “trading space for speed”: it pays off most in scenarios that are constrained by VRAM or bandwidth but have spare compute, and offers limited improvement when compute is the bottleneck.
- After quantization, always run a regression on the business evaluation set to confirm task metrics stay within an acceptable range.
3.2 Batching and scheduling
- Continuous batching: Unlike the traditional approach of “waiting for a full batch,” continuous batching dynamically adjusts batch membership at each decoding step. New requests join at any time and completed requests leave at any time, markedly improving GPU utilization.
- Prefix caching: Repeated prefixes such as system prompts, long documents, and few-shot examples can be reused without recomputation. This suits scenarios like intelligent customer service, where there are many fixed prompts.
3.3 Speculative decoding
Speculative decoding uses a lightweight draft model to guess several consecutive tokens, which the target model then verifies in a single pass. The higher the draft’s accuracy and acceptance rate, the more pronounced the speedup. Deployment requires maintaining the draft model additionally, and measuring whether the end-to-end latency benefit is actually positive.
4. Serving Architecture: Make Self-Deployment Manageable
4.1 A layered gateway
It is recommended to add a unified gateway between business applications and models, so that back-end differences are hidden and business code becomes model-agnostic:
Business applications│ unified request / streaming-response protocol▼┌─────────────────────────────────────┐│ Gateway: routing / rate limiting / ││ authentication / metering │└─────────────────────────────────────┘│ │▼ ▼Self-hosted inference Managed model APIs(sensitive, high-freq, (long-tail, low-freq,stable) elastic)
4.2 Routing and degradation
- Routing strategy: Select a model tier by task type. Route simple tasks to lightweight models and complex reasoning to large models, balancing quality against cost.
- Degradation strategy: When the self-hosted cluster approaches its capacity limit, temporarily shift non-sensitive requests to a managed API so the core path stays available.
- Rate limiting and quotas: Set rate limits per tenant or application to prevent individual callers from crowding out shared resources.
4.3 Observability
- Performance metrics: Time to first token (TTFT), time per output token (TPOT), throughput, queue time, VRAM usage, cache hit rate, and error rate. TTFT and TPOT respectively determine the user’s “first-word wait” and “reading speed” experience.
- Business metrics: Adoption rate, human-review ratio, and task completion rate, used to judge whether model updates deliver real business value.
- Supporting capabilities: Centralize inference logs in a logging service, and cover key signals such as VRAM water level, queue backlog, and sudden error-rate spikes with monitoring and alerting. These are common general capability categories on cloud platforms and can be integrated according to the specific documentation of the chosen platform.
5. Security, Evaluation, and Continuous Iteration
5.1 Security and licensing
- License terms: Open weights do not mean no constraints. Different release methods carry different commercial-use scopes, redistribution conditions, and attribution requirements, so legal and security teams must verify each one before launch.
- Data protection: Desensitize prompts and outputs across the transmission, storage, and logging stages, to avoid long-term retention of sensitive data such as personal information and account credentials.
- Content safety: Filter both inputs and outputs, and defend against risks such as prompt injection and unauthorized calls to internal tools.
- Supply chain verification: Hash-check downloaded weight files to confirm a trusted source and untampered content.
5.2 Evaluation and gray release
- Offline evaluation: Build an evaluation set from real business samples. Run the same test cases for pre- and post-quantization models, different inference engines, and different hardware.
- Online gray release: Have the new version take a small share of traffic first, compare key business and performance metrics, and ramp up gradually only after confirming there is no regression.
- Version management: Bind the weights, the quantization scheme, and the inference engine version into a single release unit. Any change to any of them must go through the full evaluation and rollback process.
6. Hardware Adaptation and Industry Trends
6.1 Adapting to diverse compute
The AI accelerator ecosystem is increasingly diverse. Beyond general-purpose GPUs, there are inference-specific accelerators and locally developed chips. Adaptation costs vary widely:
- A unified programming model, mature operator libraries, and a robust framework ecosystem can significantly lower migration costs.
- When selecting hardware, look beyond headline compute figures to the maturity of the framework and inference engine, operator coverage, quantization tool support, and responsiveness of technical support.
6.2 Device-cloud collaboration
On-device AI inference capability in SoCs continues to grow. Handling lightweight tasks on the device reduces latency, protects privacy, and lowers bandwidth consumption. Cloud-side large models handle complex reasoning while on-device models handle lightweight steps such as wake-word detection and intent recognition, and the two together optimize overall cost and experience. As on-device AI features become widespread, the compute specs and memory configurations of device-side SoCs are improving in parallel.
6.3 The industry-chain ripple effect
- Inference demand: Demand is shifting from “a few calls per user per month” toward “agents running autonomously and continuously.” Inference demand is moving from volatile consumption to a more stable base load, which changes the demand structure for inference chips and inference servers.
- Storage and advanced logic: Growth in model and context size pushes up demand for storage such as HBM and enterprise-grade SSDs. Continued expansion of advanced logic process nodes and advanced-packaging capacity directly drives the equipment, components, and materials segments.
- Local substitution: As domestic storage and logic production lines expand and processes advance, they create domestic-validation opportunities for equipment and components, while materials demand is released gradually as capacity ramps and product categories expand.
- Risk note: The transmission of industry-chain prosperity lags behind. End demand, technology roadmaps, and the pace of capacity release can all deviate from expectations, so enterprises should keep flexibility in their compute investment plans and avoid locking in overly heavy fixed assets all at once.
7. A Phased Rollout Roadmap
| Phase | Goal | Key actions | Completion marker |
|---|---|---|---|
| Phase 0: Requirements assessment | Decide whether self-hosting is needed | Sort out data compliance requirements, call volume and peak-to-valley ratio, latency targets, and team capability | A deployment decision and license-compliance conclusion |
| Phase 1: Proof of concept | Confirm the model is usable and resources are estimable | Complete deployment, quantization, and basic evaluation on a small amount of compute | Business evaluation metrics met, with a single-request resource profile |
| Phase 2: Pilot launch | Get serving and stability working end to end | Build the gateway, monitoring/alerting, and gray-release and rollback processes | Pilot business runs stably, with error rate and SLA on target |
| Phase 3: Scale rollout | Optimize cost and efficiency | Hybrid routing, elastic scaling, speculative decoding, prefix caching, and more | Lower unit call cost, with reproducible capacity prediction |
Conclusion
Releasing full open weights turns a model from a “black-box service” into a “deployable asset,” significantly lowering the barrier for enterprises to build their own AI capabilities. At the same time, it shifts engineering complexity onto the enterprise. VRAM estimation determines whether a plan is viable, inference optimization determines its cost, the gateway and monitoring determine service reliability, and security and evaluation determine whether the business can trust it. Enterprises should start from their own data-compliance requirements and workload characteristics: estimate first, then validate, then roll out, building a controllable, observable, and reusable self-hosted inference pipeline. On the cloud, general capabilities such as compute, containers, object storage, and logging and monitoring/alerting can be introduced phase by phase, and the general capability categories offered by Baidu AI Cloud, such as compute scheduling and model serving, can also be included in the technology-selection comparison. For specific capability boundaries and billing rules, refer to each cloud platform’s official documentation.
