LLM Training and Inference Architectures: An Engineering Breakdown
The training and inference of large language models (LLMs) are often shrouded in mystery, but from an engineering perspective, their cost, latency, and capacity are ultimately governed by a few physical constraints: compute volume, memory bandwidth, VRAM capacity, communication overhead, and batch efficiency. This article provides an analytical framework for developers and architects to demystify architectural choices through quantitative estimations. It covers reverse-engineering architectures from public API pricing, the joint optimization of training data and inference costs, the impact of batching and KV cache on long-context serving, and the capacity-compute trade-offs in Mixture of Experts (MoE). By understanding these constraints, teams can make verifiable decisions in model design, selection, and capacity planning.
The training and inference of cutting-edge large language models (LLMs) are often mystified. However, from an engineering perspective, their cost, latency, and capacity are ultimately governed by a few physical constraints: compute volume, memory bandwidth, VRAM capacity, communication overhead, and batch efficiency. By using equations and charts for order-of-magnitude estimations, we can demystify “why models are designed this way” and reduce it to verifiable engineering problems. This article provides an analytical framework for developers and architects, focusing on training data scale, inference batching, KV cache, sparse activation in Mixture of Experts (MoE), and a method to reverse-engineer architectures from public pricing.
1. From Public Pricing to Architectural Constraints: Building a Cost Equation
Public API pricing is the result of productization, encompassing compute, memory, network, operations, and a reasonable profit margin, so it cannot be directly equated with underlying costs. However, it provides valuable constraints: input/output price differentials, long-context premiums, cache hit discounts, and batching assumptions all leave traces in the pricing structure. When analyzing, first establish a simplified cost model:
- Training compute is approximately proportional to “parameter count × training tokens.”
- The inference prefill phase processes input tokens in parallel, resulting in high compute density.
- The decode phase generates tokens autoregressively, which is often memory-bandwidth bound.
- KV cache grows linearly with context length, batch size, and number of layers, creating a memory wall.
- MoE models have large total parameters but only activate a fraction of experts per token, separating compute and memory requirements.
These equations are not exact performance models but order-of-magnitude tools. They can answer key questions: Does the input/output price difference stem from decoding seriality? Does the long-context premium reflect KV cache pressure? Do low-price, high-throughput services imply large batching or sparse activation? Reverse-engineering only makes sense when pricing is broken down into four parts: compute, memory, communication, and batch amortization.
2. Training Side: Joint Optimization of Training and Inference
Industry scaling laws show that under a fixed compute budget, there is an approximate optimal ratio between parameter count and training tokens. However, theoretical optimality does not equal product optimality: if a model is intended to serve massive request volumes in the future, moderately “over-training”—using more tokens to train a relatively smaller model—can significantly reduce inference costs. Some frontier models may use token volumes far exceeding the theoretical optimum, possibly up to a hundredfold. This is not merely to chase training metrics but to shift costs to the training phase in exchange for cheaper long-term inference.
Therefore, the decision on training data scale should be treated as a joint optimization problem:
- Training costs grow with the number of tokens, but data quality, deduplication, and curriculum determine marginal returns.
- Inference costs grow with parameter count; smaller models are more memory- and bandwidth-efficient at the same throughput.
- Over-training can improve small model capabilities but is limited by data quality and training stability.
- If business request volumes are huge, extra investment in training can be quickly amortized by savings on the inference side.
- If business requests are sparse, over-training may not be worth the cost.
Engineering-wise, one should first use small-scale ablation experiments to estimate the “data volume—capability—inference cost” curve, and then conduct capacity planning based on business QPS and SLAs. You cannot judge pros and cons solely by parameter scale, nor treat “theoretically optimal token count” as a hard target.
3. Inference Side: Batching is a Cost Lever, but Constrained by Latency SLAs
Inference is divided into prefill and decoding. The prefill phase processes the input context all at once, making it compute-intensive and suitable for parallelization. The decode phase generates one token at a time, repeatedly reading model weights and KV cache, making it often memory-bandwidth bound. If each user request is processed individually, accelerator utilization is low, and the cost per request could be up to three orders of magnitude higher. Batching merges multiple requests for computation, increases arithmetic intensity, and amortizes weight-reading costs across more tokens, significantly lowering the cost per token.
However, bigger batches are not always better. Increasing batch size improves throughput but may inflate time-to-first-token (TTFT) and per-token latency. Production systems typically use continuous batching: requests dynamically join and exit, balancing throughput and latency. The cost model can be simplified as:
Cost per token ≈ Total resource cost ÷ (Batch size × Effective throughput × Time utilization)
Here, effective throughput is affected by KV cache capacity, memory bandwidth, expert routing imbalance, and network communication. If you only pursue peak throughput and ignore tail latency, user experience will degrade; if the batch size is too small, costs spiral out of control. A reasonable approach is tiering based on business SLAs: use small batches for low-latency interactive requests and large batches for high-throughput offline processing, continuously calibrating via monitoring.
4. KV Cache and Long Context: The Memory Wall Determines Service Form
Autoregressive decoding requires caching the key-value states of historical tokens to avoid redundant computation. The KV cache size grows with the number of layers, hidden dimensions, sequence length, and batch size. Long contexts quickly devour VRAM, thereby limiting batch size and concurrency. This explains why long-context services are usually more expensive: it’s not that the input token compute itself is unaffordable, but that the cache occupation degrades batching efficiency.
Optimization directions include paged cache management, prefix cache reuse, quantized cache, on-demand eviction, and request grouping. Prefix caching is particularly important: identical system prompts or document prefixes can reuse the cache, reducing prefill costs, which is the engineering foundation for cache hit discounts in some pricing structures. Architects should treat “cache hit rate” as a core metric rather than just looking at the average token price.
5. Mixture of Experts: Trading Sparse Activation for Capacity
Mixture of Experts (MoE) models contain multiple expert networks, where a router selects a few experts to activate for each token. A certain class of models might have hundreds of experts but only activate dozens at a time. This allows for a very large total parameter count while maintaining relatively small per-token compute, achieving “large capacity, compute-efficient.” The trade-off is increased system complexity: the router needs load balancing, experts may be distributed across different devices, and cross-device communication becomes a bottleneck. During inference, although only a fraction of experts are activated, the VRAM must still accommodate all experts or perform tiered offloading.
Therefore, the cost of MoE cannot be assessed solely by the activated parameter count. Attention should be paid to expert load variance, capacity factor, all-to-all communication volume, intra-batch routing distribution, and expert parallelism. If routing is uneven, some devices will be overloaded while others sit idle, negating the batching benefits. Engineering often uses load balancing loss, capacity limits, and dynamic routing strategies, though this must be done without degrading model quality. For service providers, MoE is suitable for high-throughput scenarios but requires stronger scheduling and monitoring capabilities.
6. Reverse-Engineering Architecture from Pricing: An Executable Method
Reverse-engineering is not guessing; it’s hypothesis testing. Follow these steps:
- Collect input price, output price, long-context tiered pricing, cache discounts, and batch API pricing.
- Calculate the input/output price difference to determine the cost proportion from decoding seriality.
- Observe the long-context premium curve to estimate KV cache pressure and the drop in batch size.
- Compare unit prices of models with similar capabilities to infer whether sparse activation is used.
- Use load testing to fit the throughput-latency curve and validate batching assumptions.
- Build a unit token cost model and compare it with public pricing across intervals.
The pseudo-code can be expressed as:
def estimate_cost(input_len, output_len, batch, cache_hit, unit_price):# Calculate the number of tokens for prefill (considering cache hits) and decodeprefill_tokens = input_len * (1 - cache_hit)decode_tokens = output_len# Estimate compute and memory costs based on respective factorscompute = prefill_tokens * prefill_factor + decode_tokens * decode_factormemory = (input_len + output_len) * batch * kv_factor# Max of compute and memory represents the bottleneck, divided by batch to get per-request cost, plus overheadcost = max(compute, memory) / batch + overheadreturn cost * unit_price
This model is strictly for order-of-magnitude analysis and cannot replace real load testing. However, it helps teams understand: why output prices are generally higher than input prices, why long contexts cost more, why cache hits lower prices, and why high-throughput services must rely on batching and sparse activation.
7. Engineering Implementation: Metrics, Load Testing, and Cloud Hosting
When landing in production, establish a set of observable metrics: TTFT, per-token latency, throughput, batch size distribution, KV cache hit rate, VRAM utilization, expert load variance, accelerator utilization, network communication proportion, and error rate. Load testing should cover short-input/short-output, long-input/short-output, long context, traffic bursts, and cache hit/miss scenarios. Capacity planning should be constrained by P95/P99 latency and cost ceilings, rather than just average throughput.
At the deployment level, cloud computing platforms (such as Baidu AI Cloud’s container platforms, object storage, logging services, and monitoring alerting capabilities) can be leveraged to host training tasks and inference services. However, the specific architecture still depends on the model structure, business SLAs, and cost objectives. The key is not simply stacking resources, but jointly optimizing batching, caching, sparse activation, and scheduling strategies.
Conclusion
The training and inference of large models are not unexplainable black boxes. By capturing compute, memory, bandwidth, and communication constraints with a few equations, and combining them with public pricing for hypothesis testing, we can understand the engineering logic behind architectural choices: batching is the order-of-magnitude lever for inference cost, over-training is the joint optimization of training and inference, KV cache determines the form of long-context serving, and MoE trades sparse activation for capacity. Understanding these constraints allows for verifiable decisions in design, selection, and capacity planning.
