LLM Cost Optimization: A Guide to Training and Inference Strategy
This guide explains how to reduce the cost of large language model projects through proper cost measurement, efficiency metrics, and proven optimization techniques. It covers total cost accounting, data quality management, distributed parallelism strategies, Mixture-of-Experts architectures, and inference optimizations such as continuous batching, KV caching, quantization, and speculative decoding, with a practical checklist and rollout order for each approach.
1. Align on Cost Definitions Before Optimizing
The economics of an LLM project cannot be judged by the cost of a single training run. Publicly reported training dollar figures or GPU hours usually cover only the final training run and exclude architecture exploration, ablation experiments, data collection and cleaning, engineering labor, and failed training attempts. Comparing models directly on these numbers produces unreliable conclusions. Before selecting any approach, teams should recompute their own costs using a consistent definition.
Total cost can be broken into three parts:
Total cost = Training cost + Inference cost + Engineering and operations cost
- Training cost: the sum of compute, data processing, and experimental iteration. Failed and exploratory experiments must be included.
- Inference cost: the compute consumed per response after the service goes live. It accumulates continuously with user volume, and over the long term often exceeds training cost.
- Engineering and operations cost: distributed cluster maintenance, incident handling, monitoring, and team effort.
Hardware cost should be treated differently for owned versus rented infrastructure. An owned cluster requires accounting for depreciation periods and utilization; rented capacity is billed per hour or per token. Utilization should be tracked as a standalone metric. With the same hardware, moving utilization from a low level to a high level can significantly reduce unit cost.
2. How to Calculate Efficiency Metrics
The following four metrics are the most common basis for comparing options.
- Cost per million inference tokens = total inference cost over a period ÷ total tokens in that period × 1,000,000. Before comparing two services, confirm that token accounting is consistent: whether system prompts are included, whether cache-hit tokens are billed at full price or discounted, and whether input and output tokens are counted separately.
- Time to first token (TTFT): the time from sending a request to receiving the first output token. It is affected by queuing, prefill computation, and networking. Reports should state the input length, concurrency level, and whether streaming is used.
- Time per output token (TPOT) = (end-to-end latency − TTFT) ÷ (number of output tokens − 1). It reflects how smoothly output is generated.
- Model FLOPs utilization (MFU) = actual achieved compute throughput ÷ theoretical peak hardware throughput. It measures whether hardware is fully utilized during training. Reports should note the compute precision (such as BF16), sequence length, and batch size.
Online chat and offline batch processing prioritize different metrics:
| Scenario | Primary metrics | Secondary metrics | Notes |
|---|---|---|---|
| Online chat | TTFT, TPOT | Cost per million tokens | Queuing raises TTFT as concurrency increases |
| Offline batch | Throughput, cost per million tokens | TPOT | Higher per-request latency is acceptable if total throughput is maximized |
| Training | MFU, cost per sample | Utilization, communication share | Sequence length and batch size must be fixed |
The two categories of metrics are not interchangeable. When selecting an approach, first determine which category the workload belongs to, then decide which metrics serve as acceptance criteria.
3. Reducing Training Cost
3.1 Data Quality Management
Data is a hidden lever for reducing training cost. With the same compute budget, high-quality data can reach similar results with fewer tokens, and upfront processing investment often reduces wasted training downstream. Common steps include:
- Cleaning: remove garbled text and HTML residue, filter samples that are too short or too long, and unify encoding and formatting.
- Deduplication: perform near-duplicate removal at the document, paragraph, or sentence level, commonly with MinHash. The threshold needs sample-based calibration: too low deletes valid data by mistake; too high leaves duplicates that cause over-memorization.
- Mixing ratios: adjust sampling proportions by domain, language, and task type. Ratios directly affect the capability distribution, so run small-scale ablations and compare on a fixed evaluation set rather than relying on intuition.
- Quality scoring: score samples with rules or a small model and keep high-scoring data. Scorers have their own biases and require periodic manual review. For example, randomly sample a fixed number of items per batch to check the false-removal rate, and adjust the scorer when it exceeds the team’s threshold.
- Toxicity and privacy filtering: remove harmful content, personal information, and copyrighted fragments. Each rule should have its version, hit count, and sampled false-positive rate recorded.
- Data lineage: keep the source, version, processing script version, and owner for each data batch so problematic data can be traced.
A template for recording filter rules:
| Rule ID | Rule version | Hit count | Sampled items | False-positive rate | Notes |
|---|---|---|---|---|---|
3.2 Parallel Training
When a model does not fit on a single GPU, or training speed is insufficient, a parallelism strategy is required. Common options:
- Data parallelism (DP): each GPU holds a full model replica, processes different data batches, and synchronizes gradients. Simple to implement, but every GPU stores the full parameters, creating memory pressure.
- Sharded data parallelism (ZeRO, FSDP): shards parameters, gradients, and optimizer states across GPUs. Reduces per-GPU memory at the cost of parameter gathering and additional communication.
- Tensor parallelism (TP): splits matrix operations within a single layer across GPUs. Communication-intensive, so it is typically kept within a node with high bandwidth.
- Pipeline parallelism (PP): splits the model by layers into stages assigned to different GPUs. Only activations are passed between stages, which suits cross-node scaling, but it creates pipeline bubbles that reduce utilization.
- Expert parallelism (EP): used only for Mixture-of-Experts models, distributing experts across GPUs and requiring All-to-All communication.
When selecting a strategy, consider in order: whether the model fits on a single GPU, whether a single node is sufficient, and whether cross-node scaling is needed. Activation checkpointing trades extra computation for memory, and gradient accumulation enlarges the effective batch without increasing per-GPU memory. Long training runs also need periodic checkpoints and a validated checkpoint-recovery procedure.
Parallel strategies carry three main risks: excessive communication share degrading scaling efficiency, debugging difficulty growing with each added parallel dimension, and hardware failure rates increasing with scale. Acceptance testing should measure scaling efficiency — the actual throughput gain as GPUs are added — and compare it against the theoretical value.
3.3 Mixture-of-Experts Architecture
A dense model activates all parameters on every forward pass, so compute scales roughly in proportion to parameter count. Mixture-of-Experts (MoE) splits the feed-forward network into multiple expert subnetworks, with a router selecting a few experts per token. Total parameters can be large while the parameters actually activated per token remain few, so per-token compute can be lower than that of a dense model with the same total parameters.
Three core MoE mechanisms:
- Routing strategy: top-k selection is common — each token picks k experts, and outputs are merged weighted by gating scores.
- Capacity factor: limits the maximum tokens each expert can process in a batch. Excess tokens are dropped or rerouted. There is no universal recommended value; tune it against batch size, token distribution, and memory stress tests, watching both drop rate and memory usage.
- Load balancing: if the router always sends tokens to a few experts, the rest sit idle. Training usually adds an auxiliary loss to encourage even distribution, but too much weight interferes with the main task; determine it through ablation.
MoE has clear costs. When experts are distributed across GPUs, tokens must be sent to their experts via All-to-All communication and results returned. Communication volume directly affects throughput. Evaluate intra-node and inter-node bandwidth separately, and compute the share of communication time within a single training step. If communication dominates, the theoretical compute savings are canceled. MoE training is also more sensitive than dense training: routing distribution, expert load variance, loss spikes, and expert collapse all need continuous monitoring with alert thresholds set against the team’s baseline.
Applicability boundaries: MoE suits training and serving scenarios with ample compute budget, large batches, and sufficient interconnect bandwidth. Gains are often negligible for small-scale deployment, single-GPU inference, or very low concurrency. If communication share stays high in production or benefits are unstable, fall back to a dense solution to keep the service reliable.
4. Reducing Inference Cost
4.1 Batching and Continuous Batching
GPU utilization is very low when each request is processed alone. Merging multiple requests into one batch improves throughput and amortizes unit cost. Continuous batching lets requests dynamically join or leave the batch during generation, which suits requests with highly variable lengths better than static batching. The tradeoff is potential queuing time that hurts TTFT, so batch size limits should be set separately for online and offline scenarios.
4.2 KV Cache and Prefix Caching
During autoregressive generation, the model caches key-value (KV) vectors of historical tokens to avoid recomputation. The KV cache consumes GPU memory and grows with context length. Prefix caching lets requests with identical prefixes reuse already-computed KV, which suits fixed system prompts, multi-turn conversations, and document Q&A. Before launch, record the cache hit rate and confirm how cache-hit tokens are priced in cost accounting.
4.3 Quantization
Quantization converts weights or activations from high precision (such as BF16) to lower precision (such as INT8, INT4, or FP8), reducing memory usage and potentially improving throughput. The KV cache can also be quantized. The risk is accuracy degradation, and sensitivity varies by task. Acceptance testing should compare results before and after quantization on the business’s own evaluation set, with a defined acceptable degradation threshold. Passing generic benchmarks is not sufficient proof that a business scenario will work.
4.4 Speculative Decoding
Speculative decoding uses a smaller draft model to propose several candidate tokens, which the large model then verifies in a single pass. Verified tokens are adopted directly, reducing the large model’s serial forward passes. The benefit depends on the acceptance rate: the closer the draft model’s output distribution is to the target model’s, the higher the acceptance rate. At very large batch sizes, compute may already be saturated, reducing the benefit. Measure acceptance rate and end-to-end latency on real traffic samples before launch.
4.5 Tiered Request Routing
Not every request needs the strongest model. Rules or a classifier can route simple requests to a smaller model and send complex ones to the large model. The benefit depends on classification accuracy; misclassification harms quality, so a fallback path to the large model must be retained.
5. Selection Checklist
The table below lists the main cost-reduction techniques with their metrics, applicable scenarios, risks, acceptance criteria, and fallback plans.
| Technique | Metrics | Applicable scenarios | Main risks | Acceptance criteria | Fallback plan |
|---|---|---|---|---|---|
| Data management | Deduplication rate, filter hit rate, evaluation score | Large training data with uneven quality | Valid data removed by mistake, skewed mixing ratios | No worse than baseline on fixed evaluation set; sampled false-positive rate within threshold | Restore previous data version |
| Data parallelism and sharding | Scaling efficiency, per-GPU memory | Model fits on one GPU or fits after sharding | Increased communication overhead | Throughput gain from added GPUs reaches target ratio | Reduce GPU count or switch parallel dimension |
| Tensor and pipeline parallelism | MFU, bubble ratio | Single layer or total layers exceed single-GPU capacity | Complex debugging, communication-sensitive | MFU meets team baseline; training results match single-GPU run | Reduce parallel dimensions, shrink scale |
| Mixture-of-Experts | Cost per million tokens, communication share, drop rate | Ample compute, large batches, sufficient bandwidth | Communication cancels gains, unstable training | Lower cost than dense baseline at equal quality | Switch to dense model |
| Continuous batching | Throughput, TTFT, TPOT | Highly variable request lengths, high concurrency | Queuing raises time to first token | Throughput improves while latency targets are met | Cap batch size |
| Prefix caching | Cache hit rate, memory usage | Fixed system prompts or multi-turn dialogue | Higher memory use; no benefit at low hit rates | Hit rate and cost savings verifiable in reports | Disable caching |
| Quantization | Business evaluation score, memory, throughput | Memory-constrained or cost-sensitive deployments | Accuracy degradation | Business evaluation degradation within threshold | Revert to original precision |
| Speculative decoding | Acceptance rate, end-to-end latency | Latency-sensitive single requests, small batches | No benefit at low acceptance rates, extra memory | Latency drops on real traffic with acceptable output quality | Disable speculative decoding |
Beyond the table, confirm the following before starting a project:
- Whether the workload is online, offline, or training, and whether priority metrics are defined.
- Whether cost comparisons use a consistent definition, and whether training cost includes failed and exploratory experiments.
- Whether the evaluation set is fixed and consistent with the real business distribution.
- Whether inter-node bandwidth has been measured for multi-node plans, and whether communication share is acceptable.
- Whether every cost-reduction technique has a written fallback plan that can be switched quickly when quality or latency issues arise.
- Whether data versions, model versions, and configuration versions are traceable.
6. Rollout Order
First align on cost definitions and establish a baseline, then advance lower-risk techniques such as data management and quantization, and finally evaluate MoE and complex parallelism. Compare every step using the same metrics and evaluation set — that is the only way to tell whether the savings are real.
