Open-Weight LLMs: From API Calls to Self-Hosted Deployment
This article explains how open-weight large language models change the choice between API access and self-hosting. It covers how to decide whether to self-host, how to estimate GPU memory and KV cache before deployment, how to build and govern an inference service, which performance levers matter, how to compare costs at break-even, what security and compliance duties apply, and how to roll out in phases.
1. Why Open Weights Change the Selection Logic
Most teams have used large language models in one way: they send requests to a cloud API, pay per call, and have no visibility into the model’s parameters, architecture, or training details. This approach is fast to adopt and requires no infrastructure to maintain, which makes it well suited to early product validation.
Open weights change this premise. Because the weight files can be downloaded, developers can load, run, and fine-tune the model themselves, provided they have enough compute. The range of options grows, and teams need to answer three questions:
- Data compliance: Can business data leave the internal network? Finance, healthcare, and government sectors have explicit restrictions on data transfer and third-party processing, so self-hosting is often the only viable path.
- Cost structure: API fees grow linearly with usage, while self-hosting involves relatively fixed hardware and operations costs. Which option is cheaper depends on the actual call volume.
- Room for customization: Does the team need to fine-tune for a specific domain, modify inference logic, or prune the model? These operations are usually restricted in API mode.
None of these three questions has a universal answer. A common approach is to validate results quickly through an API first, then decide whether to move to an environment the team controls, based on data, cost, and customization needs.
2. Capacity Assessment Before Deployment
Before downloading weights, determine whether existing hardware can handle the target model. Capacity assessment mainly covers three areas: GPU memory, concurrency, and context length.
2.1 GPU Memory for Model Weights
You can estimate weight memory with the following approximate formula:
Weight memory (GB) ≈ parameters (billions) × bytes per parameter
Bytes per parameter at common precisions:
| Precision | Bytes per Parameter | Notes |
|---|---|---|
| FP32 | 4 | Common for training; usually unnecessary for inference |
| FP16 / BF16 | 2 | Common baseline precision for inference |
| INT8 | 1 | Usually small accuracy loss after quantization |
| INT4 | About 0.5 | Smallest memory footprint; accuracy risk requires dedicated evaluation |
Actual usage also includes runtime overhead, such as activations, framework-internal buffers, and memory fragmentation. In practice, teams usually reserve 10% to 20% headroom.
2.2 KV Cache
During text generation, the model caches the attention keys and values of each layer so that later tokens can reuse them. The memory for this cache is proportional to:
- The number of concurrent requests
- The context length of each request
- The model’s layer count and attention head configuration
Longer contexts and higher concurrency increase KV cache usage, which can sometimes exceed the size of the weights themselves. For this reason, calculate peak usage using “maximum context length × maximum concurrency,” not average values.
2.3 Example Script
The script below shows how to turn these estimates into a reusable check function. All parameters are example values and should be replaced with the actual configuration of the target model.
def estimate_weight_memory_gb(params_billion: float, bytes_per_param: float) -> float:"""Estimate the GPU memory used by model weights, in GB."""return params_billion * bytes_per_paramdef estimate_kv_cache_gb(num_layers: int,num_kv_heads: int,head_dim: int,context_len: int,concurrency: int,bytes_per_elem: int = 2,) -> float:"""Estimate the KV cache memory usage, in GB. The factor 2 accounts for caching both K and V."""total_bytes = (2 * num_layers * num_kv_heads * head_dim* context_len * concurrency * bytes_per_elem)return total_bytes / (1024 ** 3)def fits_on_device(device_memory_gb: float, weight_gb: float,kv_gb: float, headroom: float = 0.15) -> bool:"""Check whether the hardware can hold the model, with runtime headroom reserved."""required = (weight_gb + kv_gb) * (1 + headroom)return required <= device_memory_gbif __name__ == "__main__":weight = estimate_weight_memory_gb(params_billion=70, bytes_per_param=2)kv = estimate_kv_cache_gb(num_layers=80, num_kv_heads=8, head_dim=128,context_len=8192, concurrency=16,)print(f"Weights: about {weight:.1f} GB, KV cache: about {kv:.1f} GB")print("Fits on a single device:", fits_on_device(80, weight, kv))
The 70B parameter count and 80 GB single-device capacity in the example are illustrative numbers only. For real planning, use the structural parameters published for the target model, and validate the result with load testing.
3. Building the Inference Service
Once capacity is confirmed, move on to serving the model. A working inference service typically includes the following steps.
3.1 Weight Acquisition and Verification
Download the weights from an official source and verify the file hashes to guard against corruption or tampering. Also read the accompanying license terms to confirm the permitted commercial uses, redistribution limits, and attribution requirements. This is a compliance prerequisite, so complete it when the project is approved, not just before launch.
3.2 Choosing an Inference Engine
The inference engine loads the weights, schedules requests, and manages the KV cache. When selecting one, consider the following:
- Support for the target model’s architecture
- Batching and continuous batching capabilities
- Compatibility with quantization formats
- Integration cost with existing monitoring and logging systems
- Community activity and responsiveness to issues
Confirm the choice with a small-scale benchmark rather than relying only on documentation.
3.3 Designing the External Interface
For internal services, provide an HTTP interface that matches the common chat completion API format. This allows application code to switch between a cloud API and a self-hosted service by changing only the endpoint URL and key.
A client example:
import osimport requestsINFERENCE_URL = os.environ["INFERENCE_URL"] # for example, an internal gateway addressAPI_KEY = os.environ["INFERENCE_API_KEY"] # injected from a secrets management servicedef chat(messages: list[dict], max_tokens: int = 512, timeout: float = 30.0) -> str:payload = {"messages": messages,"max_tokens": max_tokens,"temperature": 0.7,}headers = {"Authorization": f"Bearer {API_KEY}"}resp = requests.post(INFERENCE_URL, json=payload,headers=headers, timeout=timeout)resp.raise_for_status()return resp.json()["choices"][0]["message"]["content"]if __name__ == "__main__":answer = chat([{"role": "user", "content": "Briefly explain the role of the KV cache."}])print(answer)
Pass keys in through environment variables so that no credentials are stored in the code. Always set timeouts explicitly to prevent request backlogs from overwhelming the caller.
3.4 Service Governance
Before launch, the service should have at least the following capabilities:
- Health checks: Detect whether the model loaded successfully and whether GPU memory is behaving abnormally.
- Rate limiting and queuing: Requests that exceed capacity should fail quickly with a clear error, not queue indefinitely.
- Authentication: Distinguish callers, and record usage for quota management.
- Fallback strategy: When the inference service is unavailable, the application should switch to a backup option or show a clear message to users.
4. Performance Optimization
After deployment, performance work usually focuses on three metrics: latency, throughput, and cost.
4.1 Quantization
Quantization reduces memory use by lowering the precision of the weights, and it can also improve throughput. INT8 is generally a reliable balance between accuracy and gains. INT4 reduces memory further, but its impact varies widely across tasks. After quantization, compare output quality on your own evaluation set. Do not rely on average metrics alone.
4.2 Batching
Batching combines multiple requests into a single computation, which can substantially improve GPU utilization. Continuous batching lets requests join or leave during generation, which reduces queuing time. The trade-off is that latency for individual requests may increase, so set a batch size limit based on the business’s latency tolerance.
4.3 Prefix Reuse
Many workloads share the same system prompt or document prefix. If the inference engine supports prefix caching, it can reuse the cached KV results for that prefix and avoid repeated computation. This optimization is especially effective for long system prompts and retrieval-augmented generation scenarios.
4.4 Parallelism
When a model is too large for a single GPU, use tensor parallelism or pipeline parallelism to split computation across multiple GPUs. Parallelism adds communication overhead between GPUs, and adding GPUs does not always produce a proportional increase in throughput. Use benchmarks to find the point of diminishing returns before launch.
4.5 Metrics and Monitoring
Continuously collect the following metrics:
- Time to first token and total generation latency
- Tokens generated per second
- Peak GPU memory usage and fragmentation
- Request success rate and timeout rate
- Hardware cost per request
Group metrics by model version, hardware type, and business scenario. Aggregated numbers can hide problems.
5. Cost Estimation and Break-Even Analysis
To decide whether self-hosting is worth it, compare API fees and self-hosting costs on the same basis.
5.1 Monthly API Cost
Let T be the total number of input and output tokens per day, and P be the price per million tokens. The monthly API cost is:
Monthly API cost = T × 30 × P / 1,000,000
Actual billing usually separates input and output tokens at different prices, so calculate each one separately.
5.2 Monthly Self-Hosting Cost
Self-hosting costs mainly include:
- Hardware: depreciation on purchased equipment, or the ongoing cost of rented GPU instances
- Power and data center costs: required when you operate your own facility
- Operations staff: the labor needed for deployment, monitoring, upgrades, and incident response
- Other expenses: networking, storage, and backup
Monthly self-hosting cost can be written as:
Monthly self-hosting cost = monthly hardware and power cost + monthly operations labor cost
5.3 Break-Even Point
When the API cost equals the self-hosting cost, the corresponding average monthly token volume is the break-even point:
Break-even token volume = monthly self-hosting cost × 1,000,000 / P
If actual usage stays consistently above this value, self-hosting has a cost advantage. If usage fluctuates widely, with large peak-to-trough differences, fixed costs can go to waste. In that case, a hybrid approach works better: route regular traffic to the self-hosted service and overflow peak traffic to the API.
Calculations should use real prices and actual hardware quotes, not numbers borrowed from others. Hardware utilization also directly affects unit cost. If utilization falls below expectations, the break-even point shifts noticeably further out.
6. Security and Compliance
Self-hosting shifts responsibility for model security to your own team, which means covering the following areas.
6.1 Access Control
Deploy the inference service on the internal network, and open it only to authorized business services. Separate management interfaces from inference interfaces, and grant management permissions on a least-privilege basis.
6.2 Data Handling
Input and output logs may contain user private data by default. Redact logs before storing them, then archive or delete them according to the retention policy. Any scenario where training data flows back into the system requires separate approval.
6.3 Output Risk Control
Model output may contain factual errors, inappropriate content, or instructions that a user has manipulated the model into producing. Add input validation, output filtering, and sensitive content review on the server side, and keep a human review step for critical business results.
6.4 Licensing and Supply Chain
Regularly check the model license version, security advisories for dependencies, and the sources of container images. Store weight files in controlled storage, and record their versions and hashes for traceability.
7. Recommended Rollout
Proceed in the following order, and define a clear exit condition for each step.
- Build an evaluation set: Draw several hundred samples from real business traffic, covering common questions, edge cases, and high-risk scenarios. The evaluation set serves as the shared benchmark for comparing the API and self-hosted options.
- Validate at small scale: Deploy in a test environment and confirm that latency, throughput, stability, and output quality meet business requirements.
- Roll out gradually: Route a small share of traffic to the new service, monitor the metrics, and increase the share step by step. Keep the ability to fall back to the API.
- Operate continuously: Track model version updates, cost changes, and hardware utilization, and review the selection decision on a regular schedule.
The core of a technical decision is stating the constraints clearly. Whether data can leave the organization, how much traffic the system handles, and whether the team can support operations are the three answers that determine the trade-off between API and self-hosted deployment. Record these judgments in the evaluation document so that future changes can be traced back to the reasoning behind them.
