Deploying Open-Source LLMs on Heterogeneous Compute: Practices for Reducing Inference Costs
This article is designed for technical teams aiming to build in-house coding assistants or enterprise code Q&A services. It explores the cost structure of privately deploying open-source large language models (LLMs) and addresses the adaptation, inference, and scheduling challenges encountered when implementing these models on heterogeneous compute resources.
This article is intended for technical teams looking to build in-house coding assistants or internal code Q&A services. It discusses the cost structure of privately deploying open-source large language models (LLMs) and addresses the adaptation, inference, and scheduling challenges encountered when deploying on heterogeneous compute resources.
1. Calculating the Cost Structure
With token-based commercial APIs, costs scale linearly with request volume. The cost of a self-built cluster consists of hardware depreciation, electricity, data center facility fees, and operations and maintenance (O&M) labor. The break-even point between the two approaches depends on the effective throughput of the cluster. To calculate the cost per token, you can use the following formula:
Unit Token Cost = (Hardware Depreciation + Electricity + O&M Labor) ÷ Total Output Tokens in the Billing Cycle
The denominator depends on cluster utilization. If the average daily utilization rate remains low over time, the cost of a self-built cluster will exceed that of an API. Therefore, before deployment, you should use real request logs to estimate peak concurrency, average output length, and utilization rate to determine whether a self-built solution is worthwhile.
2. Verification Checklist for Heterogeneous Compute Adaptation
Specialized AI accelerators and inference chips typically rely on operator libraries and compiler toolchains provided by vendors. For example, the Huawei Ascend platform uses CANN, and its version must match the driver, firmware, and framework plugins. Before deployment, verify the following items one by one:
- Framework Versions: Confirm the compatibility matrix between your PyTorch or inference engine version and the vendor’s plugins.
- Operator Coverage: List all operators used by the model and verify whether the vendor’s library supports each one. Unsupported operators require custom implementation or fallback to CPU execution. Fallback usually slows down inference significantly.
- Precision Regression: Use a fixed evaluation dataset to compare the FP16 baseline with the output from the target hardware, focusing on code pass rates, Q&A accuracy, and numerical errors.
- Multi-Card Communication: Tensor parallelism relies on inter-card or inter-node bandwidth, and RDMA configuration requires separate stress testing.
3. Inference Optimization: Quantization, KV Cache, and Continuous Batching
Quantization is a common method to reduce memory footprint. Converting from FP16 to INT8 reduces weight memory to roughly half, and converting to INT4 reduces it to about a quarter. However, these figures apply only to model weights. End-to-end memory usage also includes KV Cache, activations, and overhead from batch sizes, so actual consumption must be measured empirically. GPTQ, AWQ, and SmoothQuant are common quantization methods. After quantization, a quality assessment is mandatory, especially to check the syntax correctness rate of generated code.
The size of the KV Cache grows with sequence length and concurrency. PagedAttention divides the KV Cache into fixed-size blocks and allocates them on demand, thereby reducing memory fragmentation. Inference frameworks like vLLM and TensorRT-LLM have implemented this mechanism. Since the range of supported models and hardware varies across frameworks, you should consult the documentation for your specific version.
Continuous batching allows requests to join or leave a batch during the generation process, reducing GPU idle time compared to static batching. Code completion requests are usually short, while Q&A and code review requests are typically longer. The benefits of continuous batching are most pronounced when these two types of requests are mixed.
4. High Concurrency Scheduling: Elastic Scaling and Routing
Inference services can be deployed on Kubernetes. CPU and memory metrics often fail to reflect the pressure on LLM services; it is more appropriate to use request queue length or time-to-first-token (TTFT) as the basis for autoscaling. These metrics must first be collected by Prometheus and then converted into custom metrics recognized by Kubernetes via the Prometheus Adapter. Below is an HPA example:
apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata:name: llm-infer-hpaspec:scaleTargetRef:apiVersion: apps/v1kind: Deploymentname: llm-inferminReplicas: 2maxReplicas: 16metrics:- type: Podspods:metric:name: vllm_requests_waitingtarget:type: AverageValueaverageValue: "5"
Here, an averageValue of 5 means that scaling out is triggered when the average number of queued requests per instance exceeds 5. This threshold is just a starting point and should be determined through stress testing. Scaling out takes time, and model loading can take several minutes, so minReplicas should be sufficient to cover daily baseline traffic.
At the gateway layer, requests can be routed by type. Code completion is sensitive to TTFT and is best allocated to instances with lower loads. Long-text reviews are better suited for instances with stronger batch processing capabilities.
5. Semantic Caching: Boundaries of Applicability
Semantic caching uses vector similarity to determine if two requests are equivalent. If the similarity threshold is set too low, incorrect answers may be returned. In coding scenarios, two error messages might be textually similar but have completely different contexts, making cached results inapplicable. It is recommended to enable caching only for general questions. The threshold should be evaluated using a manually labeled sample set, and a cache expiration time should be set.
6. Risks and Unsuitable Scenarios
This article discusses technical solutions and does not cover the following costs and risks: labor investment for heterogeneous adaptation, re-validation after model upgrades, GPU failures and O&M response, data compliance requirements, and open-source model license terms. Code generated by models must undergo security review and testing. For teams with low request volumes or insufficient O&M capabilities, a self-built solution requires separate evaluation.
Conclusion
Deploying open-source models on self-built compute is suitable for teams with stable request volumes, high utilization rates, and the ability to maintain the underlying software stack. To decide whether to build in-house, first calculate the unit cost based on real data before determining the technical roadmap. This article provides an overview of technical solutions and does not constitute procurement, compliance, or security advice.
