Breaking Down LLM Inference Costs: How to Calculate Cost per Million Tokens
This article explains how to build a practical cost model for large language model inference. It breaks total cost of ownership into hardware, facility and power, operations labor, and depreciation; distinguishes prefill and decode throughput; reviews key software and scheduling optimizations; and provides formulas and code for calculating cost per million tokens and comparing deployments on a consistent basis.
1. Why Inference Costs Need a Fresh Look
As large language models move into large-scale production, inference cost has become one of the most important metrics for service providers. Training is a one-time or periodic investment, while inference generates ongoing costs with every user request. Each doubling of model call volume also increases spending on hardware, power, and data center space. Teams therefore need a stable costing method to judge whether a given optimization or hardware choice is worth the investment.
Two common mistakes appear in discussions of inference cost. The first is looking only at the price of a single accelerator card while ignoring throughput and stable operating hours. The second is looking only at peak throughput while ignoring production concurrency fluctuations, first-token latency constraints, and discount factors. This article breaks cost into components that can be checked item by item, converts throughput into unit cost, and then explains how to make fair side-by-side comparisons.
2. The Four Components of Total Cost of Ownership
Total Cost of Ownership (TCO) is a common method for evaluating infrastructure costs. It usually includes the following four items:
- Hardware purchase cost: The purchase cost of accelerators, servers, switching equipment, and associated storage. For large-volume purchases, unit prices are often below retail quotes; the discount depends on purchase volume, payment terms, and delivery lead time.
- Facility and power cost: Rack rent or depreciation of a self-built data center, cooling, power supply, and network bandwidth. Electricity price differences have a major impact on long-running equipment, so site selection should consider both power prices and climate conditions.
- Operations labor cost: Engineer hours spent on model deployment, version upgrades, troubleshooting, and capacity planning. This part is often underestimated, but it can account for a high share in small and medium-sized clusters.
- Depreciation and residual value: Hardware is usually depreciated over a three-to-five-year period. The calculation should specify the depreciation period and assume either full load or a certain average utilization rate during that period.
A simple expression is:
TCO = hardware purchase cost + facility and power cost + operations labor cost
When calculating, clearly state the statistical basis, such as which year’s prices are used, whether taxes are included, and how many years the depreciation period covers. Comparisons between two data sets are meaningless if their bases differ.
3. What Throughput Means: Prefill and Decode
LLM inference has two stages. In the prefill stage, all tokens in the input prompt are processed at once. The computation is heavy but highly parallelizable. In the decode stage, output tokens are generated one by one; each new token requires reading the previous context cache, so this stage is more constrained by memory bandwidth.
Throughput differs greatly between the two stages. On the same hardware, prefill throughput is usually much higher than decode throughput. If a workload has long inputs and short outputs, such as document summarization or code retrieval, prefill accounts for a larger share. If the workload is mainly long-form text generation, decode accounts for a larger share. A single “tokens per second” number without explaining the phase mix therefore provides limited information.
Suppose prefill throughput is Tp, decode throughput is Td, and prefill tokens account for a share r of total tokens. Blended throughput can then be calculated as a time-weighted value:
def blended_throughput(prefill_ratio: float, tp: float, td: float) -> float:"""prefill_ratio: Share of total tokens handled in the prefill phase, from 0 to 1tp: Prefill throughput (tokens/second)td: Decode throughput (tokens/second)Returns: Blended throughput (tokens/second)"""decode_ratio = 1.0 - prefill_ratioseconds_per_token = prefill_ratio / tp + decode_ratio / tdreturn 1.0 / seconds_per_token
This code illustrates a basic fact: blended throughput is determined by the time spent in both stages, not by a simple average. The throughput of the two stages must be measured separately under the same model, precision, and batching settings.
4. Key Techniques That Affect Throughput
Differences in throughput on the same hardware often come from software and scheduling optimizations. The following practices are relatively common in the industry.
4.1 Batching and Continuous Batching
Combining multiple requests into one batch improves utilization of compute units. Continuous batching allows new requests to fill empty slots in an existing batch, reducing wait time. Larger batches increase throughput, but they may also increase first-token latency for individual requests. Batch size should therefore be set according to latency targets.
4.2 KV Cache
During decoding, the model needs to store key and value vectors for each layer to avoid repeated computation. The KV cache consumes GPU memory but can significantly reduce computation. When multiple requests share the same prefix, such as the same system prompt, a cache hit can skip a large amount of prefill computation. The higher the cache hit rate, the lower the average cost per token.
4.3 Prefill and Decode Disaggregation
Deploying prefill and decode on separate compute resources allows each to use batch sizes and parallelism strategies suited to its own characteristics. This approach can reduce interference between the two types of tasks and make it easier to meet first-token latency and overall throughput targets at the same time. After disaggregation, KV cache transfer between the two types of nodes must be handled properly, and this overhead must be included in the cost calculation.
4.4 Low-Precision Quantization
Converting weights and activations from higher-precision to lower-precision formats can reduce memory usage and improve bandwidth utilization. Quantization introduces some accuracy loss, so accuracy should be evaluated on the target task rather than judging only by throughput gains.
4.5 Multi-Level Caching
When GPU memory cannot hold all historical cache, part of the cache can be placed in host memory or even local solid-state drives. Multi-level caching can improve hit rates, but read latency is also higher. Whether to enable it depends on the request reuse pattern of the workload.
5. From Throughput to Cost per Million Tokens
Once blended throughput is known, unit cost can be calculated. The following function calculates cost per million tokens using straight-line depreciation:
def cost_per_million_tokens(hardware_cost: float,facility_cost_per_year: float,ops_cost_per_year: float,years: float,tokens_per_second: float,utilization: float,) -> float:"""hardware_cost: Total hardware purchase costfacility_cost_per_year: Annual facility and power costops_cost_per_year: Annual operations labor costyears: Depreciation and operating period in yearstokens_per_second: Blended throughput (tokens/second)utilization: Average utilization, from 0 to 1Returns: Cost per million tokens in the same currency unit"""total_cost = hardware_cost + (facility_cost_per_year + ops_cost_per_year) * yearsseconds = years * 365 * 24 * 3600total_tokens = tokens_per_second * seconds * utilizationreturn total_cost / total_tokens * 1_000_000
Three cautions apply when using this function. First, utilization is usually far below theoretical peak; both peaks and troughs in production lower the average. Second, throughput obtained from stress testing often comes from an idealized workload, so it should be multiplied by a discount factor that reflects real traffic. Third, unit cost is highly sensitive: a small change in hardware price, utilization, or throughput can produce a noticeable difference in cost.
6. Principles for Fair Comparisons
When comparing two inference solutions, the following principles are recommended.
- Same model, same precision, same latency constraints. First-token latency, per-request output speed, and batch size should be aligned. Otherwise, measured throughput cannot be compared directly.
- Same input/output distribution. The prefill-to-decode ratio significantly affects results, so test samples should be as close as possible to real online traffic.
- Same cost basis. Hardware prices, electricity prices, depreciation periods, and operations labor should use the same assumptions.
- Explain how equivalence is calculated. If stating that “a certain number of devices of one type are equivalent to one device of another type,” provide unit cost on the same basis or the number of devices at equal throughput, and note the test conditions.
- Separate peak values from production values. Stress-test peaks cannot be directly equated with sustainable online service capacity. Decisions should be based on data under stable load.
7. Engineering Practice Recommendations
For implementation, the following steps can be used.
- Establish a baseline: Use real request logs to measure input length, output length, concurrency, and prefix reuse rate, forming a representative workload profile.
- Run staged load tests: Measure prefill and decode throughput separately, then calculate blended throughput using the workload profile.
- Set latency targets: Define upper limits for first-token latency and overall response time, then choose batch size and parallelism strategy accordingly.
- Monitor continuously: Track cache hit rate, GPU memory usage, queue wait time, and trends in cost per million tokens.
- Review the cost model periodically: Hardware prices, electricity prices, and model versions change, so the cost model should be updated regularly and the assumptions for each calculation should be recorded.
8. Conclusion
Inference cost is determined jointly by hardware, facilities, labor, and software optimization. A single metric rarely tells the whole story. Only by breaking cost into auditable components, specifying the test conditions for throughput, and calculating cost per million tokens on a consistent basis can teams reach conclusions suitable for decision-making. The formulas and code above can be used directly as an evaluation template after replacing the inputs with a team’s own measured data.
