Engineering Practices for Cost Optimization in LLM Training and Inference
As large language models (LLMs) transition from experimentation to production, compute costs can rapidly exceed initial budgets. This guide explores practical engineering strategies to reduce costs and improve efficiency across both training and inference phases. It covers how to build a cost ledger, optimize data quality and memory management for training, implement dynamic batching and caching for inference, and establish elastic scheduling and comprehensive measurement systems to ensure sustained operational efficiency.
1. Background: Why Cost is a Core Metric
As large language models transition from experimentation to production, compute costs can rapidly exceed early budgets. Cluster utilization during training, continuous calls during inference, and associated storage, network, and operations personnel collectively constitute the total cost. Many teams find that once model performance meets the standard, the cost per request cannot support the business scale. Therefore, cost optimization must advance in parallel with performance optimization.
The essence of the cost problem is the input per unit of output. For LLM services, common unit metrics include the inference cost per 1,000 tokens, the compute consumption per training iteration, and the comprehensive cost per valid business request. Only by breaking down costs into measurable units can optimization directions be justified.
2. Cost Structure Breakdown
Before diving into optimization, it is essential to establish a cost ledger, dividing total expenditures into the following categories:
- Training costs: Accelerator occupancy duration, data preprocessing time, and waste from failed task reruns.
- Inference costs: Resident fees for accelerators or inference instances, peak scaling fees, and compute overhead per request.
- Storage and network costs: Storage consumption for training data, model weights, and checkpoints, as well as cross-region or cross-availability zone data transfer.
- Engineering costs: Human time invested in model iteration, troubleshooting, and monitoring infrastructure.
After this breakdown, you will find that most teams’ waste is concentrated in three areas: long-term occupation of idle resources, repeated calculations without reuse, and low-value requests occupying high-value resources. Optimization should prioritize these three issues rather than immediately pursuing single-point performance limits.
3. Training-Side Optimization
3.1 Data Quality Over Data Scale
The cleaning, deduplication, and filtering of training data directly affect the number of effective training steps. Duplicate samples cause the model to consume compute on invalid information. It is recommended to complete the following tasks before training:
- Use text fingerprints for approximate deduplication to reduce the proportion of duplicate samples.
- Set length and quality filtering rules to remove obvious noise.
- Apply stratified sampling to the dataset to ensure coverage of key domains, avoiding blind expansion of total data volume.
3.2 Precision and Memory Management
Mixed precision training can reduce memory usage and increase throughput in most scenarios, but it requires stability measures such as loss scaling. Gradient accumulation can maintain an equivalent batch size when memory is limited. Activation recomputation trades extra compute for memory space. These three methods must be evaluated in combination with hardware and model size; they cannot simply be stacked together.
3.3 Checkpoints and Fault Tolerance
Long-running training tasks must have recovery capabilities. Too high a checkpoint frequency increases storage and write overhead, while too low a frequency results in significant progress loss during failures. A common practice is to calculate the optimal interval based on the failure rate and the time taken for a single save. Checkpoints should be written to object storage with retention policies configured to control storage costs.
4. Inference-Side Optimization
Inference is a continuous expense; any minor efficiency improvement will be amplified by scale, making the returns in this area usually the most obvious.
4.1 Batching
Processing single requests one by one keeps compute units in a low-utilization state for extended periods. Dynamic batching merges requests arriving within a short timeframe and executes them together, improving throughput within an acceptable latency range. The key parameters are the maximum batch size and the maximum wait time, both of which need to be jointly adjusted according to the business’s latency budget.
Below is an example of micro-batching based on an asynchronous queue. It collects requests within a maximum wait time and then calls the inference function uniformly:
import asyncioclass MicroBatcher:"""Collects requests within a maximum wait time and batches them to the inference function."""def __init__(self, handler, max_batch=8, max_wait=0.02):self._handler = handler # async def handler(prompts: list[str]) -> list[str]self._max_batch = max_batchself._max_wait = max_waitself._queue: asyncio.Queue = asyncio.Queue()self._task = Nonedef start(self):self._task = asyncio.create_task(self._run())async def submit(self, prompt: str) -> str:fut = asyncio.get_running_loop().create_future()await self._queue.put((prompt, fut))return await futasync def _run(self):loop = asyncio.get_running_loop()while True:prompt, fut = await self._queue.get()batch = [(prompt, fut)]deadline = loop.time() + self._max_waitwhile len(batch) < self._max_batch:remaining = deadline - loop.time()if remaining <= 0:breaktry:item = await asyncio.wait_for(self._queue.get(), remaining)batch.append(item)except asyncio.TimeoutError:breakprompts = [p for p, _ in batch]try:results = await self._handler(prompts)for (_, f), r in zip(batch, results):if not f.done():f.set_result(r)except Exception as exc:for _, f in batch:if not f.done():f.set_exception(exc)
The caller only needs to create an instance, call start(), and then await submit(prompt) in the business logic.
4.2 Caching and Request Deduplication
Certain businesses have a large number of duplicate or highly similar requests, such as Q&A with fixed templates or multiple summaries of the same document. Caching identical inputs is the most direct approach. Note the following points:
- The cache key must include the model version and key parameters; otherwise, outdated results will be read after a model upgrade.
- Content involving user privacy should not be shared across users in the cache.
- Set a reasonable expiration time to prevent time-sensitive content from lingering.
Below is a simple response cache with an expiration time. The cache key is determined jointly by the model identifier and the hash of the input content:
import hashlibimport timefrom typing import Optionalclass ResponseCache:def __init__(self, ttl_seconds: int = 300):self._ttl = ttl_secondsself._store: dict[str, tuple[float, str]] = {}@staticmethoddef _key(model: str, prompt: str) -> str:raw = f"{model}\n{prompt}".encode("utf-8")return hashlib.sha256(raw).hexdigest()def get(self, model: str, prompt: str) -> Optional[str]:key = self._key(model, prompt)item = self._store.get(key)if item is None:return Noneexpires_at, value = itemif time.time() > expires_at:self._store.pop(key, None)return Nonereturn valuedef set(self, model: str, prompt: str, value: str) -> None:key = self._key(model, prompt)self._store[key] = (time.time() + self._ttl, value)
In production environments, this cache is typically replaced with a distributed caching service, adding capacity limits and eviction policies, but the interface design concept remains the same.
4.3 Tiered Routing
Not all requests require the most powerful model. You can first use rules or a lightweight classifier to determine the request difficulty, assigning simple tasks to a small model and escalating complex tasks to a large model. The routing strategy needs to be validated using an offline evaluation set to confirm that the quality loss after downgrade is within an acceptable range.
4.4 Quantization and Inference Engine Selection
Weight quantization can reduce memory usage, allowing a single card to handle larger batches or more replicas. Quantization introduces some accuracy loss, so it is necessary to compare the performance metrics before and after quantization on the target task before deciding on the deployment scope. The choice of inference engine also affects throughput; benchmark tests should be conducted using the actual request length distribution of the business.
5. Elastic Scheduling and Resource Governance
Inference loads usually exhibit clear time-based fluctuations. Provisioning resources for peak loads over the long term will cause significant idleness. The following mechanisms can be combined to reduce waste:
- Auto-scaling based on request queue length and utilization metrics, with a minimum number of replicas set to guarantee baseline latency.
- Scheduling offline tasks, such as batch summarization and data labeling, to low-priority resource pools, isolated from online services.
- Using a container platform to uniformly manage deployment and resource quotas, preventing a single service from occupying the cluster without limits.
- Managing model weights and datasets through object storage, setting lifecycle rules based on access frequency to migrate cold data to lower-cost storage tiers.
Auto-scaling strategies need a cooldown period to prevent frequent start/stop cycles triggered by metric fluctuations, as frequent start/stop cycles themselves generate additional costs and latency.
6. Measurement System
Without measurement, it is impossible to determine whether optimization is effective. It is recommended to establish the following metrics and monitor them continuously:
- Cost metrics: Cost per token, cost per valid request, and cost per unit of progress for training tasks.
- Performance metrics: Time to first token (TTFT), percentiles of overall response latency, and system throughput.
- Quality metrics: Offline evaluation scores, online manual spot-check results, and the proportion of negative user feedback.
- Stability metrics: Error rate, timeout rate, and number of scaling triggers.
Cost metrics must be viewed in conjunction with quality metrics. If the unit cost drops but quality metrics significantly decline, it indicates a wrong optimization direction. Logging services and monitoring alert systems should set thresholds for key metrics and notify the responsible personnel promptly when anomalies occur.
7. Implementation Roadmap and Risk Control
Cost optimization is best advanced in phases, with clear acceptance criteria for each stage:
Phase 1 involves completing cost breakdown and basic monitoring to clarify optimization priorities. Phase 2 implements low-risk optimizations, such as batching, caching, and resource quotas, observing the effects through canary releases. Phase 3 introduces changes requiring evaluation support, like tiered routing and quantization, with a rollback plan kept for every change.
The main risks include: stale results caused by caching, quality fluctuations due to routing downgrades, and edge-case degradation caused by quantization. The countermeasure is to establish a fixed evaluation set, run comparisons before and after each change, and design change toggles as configuration items that can be quickly turned off.
Cost optimization is not a one-time project but a continuous operational process. Teams should regularly review the cost ledger and adjust strategies in line with business growth and technological evolution, keeping inputs matched with business value.
