LLM Training and Inference: A Deep Dive into Underlying System Logic

    This article explores the underlying system engineering logic of large language models (LLMs) from training to inference. It examines why leading models deviate from compute-optimal configurations by using redundant training data, how Mixture of Experts (MoE) architectures balance model capacity and computational cost through sparse activation, and why batch processing creates a thousandfold difference in inference costs. By understanding the interplay between compute power, memory bandwidth, and batching, readers can gain deeper insights into model architectures, API pricing structures, and the sustainable economics of AI deployment.

    I. Why a Systems Engineering Perspective Matters

    When discussing large models, most articles focus on “how powerful the model is.” However, what truly determines the model’s architecture, service pricing, and iteration speed is the underlying logic of hardware and software co-design. A senior chip engineer once used a blackboard and a few equations to deduce the entire pipeline of frontier large models from training to inference. The core insight was: once you understand the relationship between compute, memory bandwidth, and batching, why large models look the way they do today—architecture, pricing, and pace of progress—makes complete sense.

    The value of this type of analysis lies in reverse-engineering architectural details that vendors prefer not to disclose, using public API pricing. It reveals several key conclusions: batch processing can create a thousandfold difference in single inference costs; pre-training data volumes are often tens to hundreds of times the theoretical optimum; and the Mixture of Experts (MoE) architecture strikes a balance between large capacity and low cost through sparse activation. Let’s break down these mechanisms one by one.

    II. Pre-training: Compute-Optimality and Data Redundancy

    2.1 Chinchilla Optimality vs. Reality

    Given a specific compute budget, there is a theoretically “most cost-effective” ratio between model parameters and training data, commonly referred to in the industry as the compute-optimal ratio. According to this theory, for every doubling of model parameters, the data volume should grow roughly in tandem so that both consume compute proportionally.

    However, current frontier models almost universally deviate from this theoretical point—training data volumes typically reach tens or even hundreds of times the theoretical optimum. Based on publicly discussed magnitudes, the number of pre-training tokens for leading models far exceeds the “optimal” level calculated based on parameter count.

    2.2 Why Deviate from the Optimal?

    This deviation is not a waste but a rational trade-off for three reasons:

    1. Inference Costs Overwhelm Training Costs. Training is a one-time expense, whereas inference is an ongoing operational cost lasting for years. A smaller model that “eats more” is cheaper on every invocation after deployment. Spending extra training compute buys inference economics throughout the entire service lifecycle.
    2. Time Value of Compute. The compute-optimal standard measures “how much loss reduction per joule of compute,” but it does not consider training time. Redundant data training can approach lower loss in fewer training epochs, shortening the model’s time to market—in a competitive environment, time itself is a cost.
    3. Slower Marginal Decay of Data Quality Dividends. High-quality corpora that have been cleaned, deduplicated, and ratio-tuned yield higher returns upon repeated use than early theoretical estimates, meaning “feeding several times more data” still provides positive returns.

    2.3 A Simplified Compute Estimation

    The classic approximation formula for pre-training compute is:

    1. Training compute (FLOPs) ≈ 6 × parameters × training tokens

    This formula explains why vendors are so cautious when choosing between “adding parameters” and “adding data”: both consume compute linearly, but their impact on inference cost and model capability is entirely different. Understanding this multiplicative relationship clarifies why “parameter count” is no longer the sole metric for measuring model capability.

    III. Mixture of Experts: The Economics of Sparse Activation

    3.1 Basic Mechanism of MoE

    The core idea behind the Mixture of Experts (MoE) architecture is to replace the originally dense feedforward network layers in a Transformer with multiple parallel “expert” sub-networks, introducing a router that dynamically selects a small number of experts to participate in the computation for each token.

    Taking a typical configuration publicly disclosed in the industry as an example: a certain open-source frontier model features 256 experts, but only activates 32 of them per token during inference—roughly one-eighth of the computational paths. This means:

    • The total capacity (parameters) of the model is large, allowing it to accommodate richer knowledge and capabilities;
    • The actual computation per forward pass is small, meaning inference latency and cost are only related to the number of activated experts.

    3.2 Routing and Load Balancing Challenges

    MoE is not a free lunch; it introduces several engineering problems that must be solved:

    1. Routing Drift and Training Instability. During early training, the router might show favoritism, sending all tokens to a few experts and leaving others untrained. The standard industry practice is to introduce auxiliary load-balancing losses to penalize imbalanced loads among experts.
    2. Expert Parallelism and Communication Overhead. During training, experts are distributed across different devices, and tokens must be routed across devices (All-to-All communication). This constitutes one of the primary communication bottlenecks in distributed training, directly impacting the network design of the training cluster.
    3. Misalignment Between Memory Footprint and Compute Consumption. A profound cost of MoE is that all expert parameters must reside in memory, but only a small fraction is computed at any given moment. This makes MoE models a quintessential example of being “memory bandwidth-bound”—which is a crucial clue for the inference optimization discussed later.

    Here is a pseudo-code snippet illustrating the operational logic of an MoE layer:

    1. def moe_layer(x, experts, router, top_k):
    2. # x: [batch, seq_len, d_model]
    3. probs = softmax(router(x), dim=-1) # Score each token against 256 experts
    4. topk_probs, topk_idx = probs.topk(top_k) # Select only the top_k experts with highest weights
    5. out = 0
    6. for p, idx in zip(topk_probs, topk_idx):
    7. out += p * experts[idx](x) # Only activate the selected experts
    8. return out

    IV. Inference: Why Batching is Worth a Thousandfold Difference

    4.1 Two Phases and Two Bottlenecks of Inference

    Generative inference for large models is divided into two phases:

    • Prefill: Processes all input tokens from the user at once. It is compute-intensive and primarily constrained by compute power.
    • Decode: Generates tokens autoregressively one by one. Each step requires reading the full model weights and KV cache, making it primarily constrained by memory bandwidth.

    The contradiction in the Decode phase is that generating a single token requires very few multiply-accumulate operations, yet it forces the transfer of tens or even hundreds of GB of weights from memory. The compute units sit largely idle, and the money is spent “moving data.”

    4.2 Batching: Key to Amortizing Data Transfer Costs

    The solution is to bundle multiple user requests into a batch and perform the forward pass simultaneously. Since this batch of requests shares the same model weights, a single weight transfer can serve dozens or hundreds of requests at once. The bottleneck then shifts from “transferring weights” to “executing compute,” significantly boosting hardware utilization.

    This is the root cause of why the cost of a single inference can vary by a thousandfold:

    1. When batch size B = 1: Cost per token ∝ weight bytes / B (Bandwidth-bound, highly wasteful)
    2. When batch size B = 256: Weight transfer cost amortized across 256 requests (Utilization approaches compute ceiling)

    Conversely, this explains several product phenomena:

    1. Why token-based billing is much cheaper than “dedicated instances”—the former essentially lets you share the amortization benefits of batching with other users.
    2. Why various APIs generally offer batch discount tiers—asynchronous, time-permitting requests can be aggregated into larger, more regular batches.
    3. Why context length has become a critical pricing dimension—long contexts imply massive KV caches, exacerbating bandwidth and memory pressure, thereby shrinking the benefits of batching.

    4.3 Reverse-Engineering Architecture from Public Pricing

    Inference costs can be modeled quite accurately at the engineering level: the theoretical cost of a single inference is approximately equal to (“bytes of weights transferred” + “KV cache read/write volume”) divided by the hardware’s memory bandwidth, plus the constraints of compute ceilings and cluster overhead. When comparing this model against public API pricing, you can reverse-engineer the model’s hidden architectural features—such as whether it uses sparse activation, the magnitude of activated parameters, and context caching mechanisms. This is the unique “detective ability” of system-level analysis: pricing is the shadow of architecture.

    V. Co-design of Training and Inference

    Piecing together the previous analysis reveals a clear decision chain:

    1. Inference costs dictate architectural choices—to reduce computation per call, MoE with sparse activation is adopted, trading large capacity for small computation.
    2. Inference costs also dictate parameter scaling strategies—rather than strictly adhering to compute-optimality, developers increase parameters and data (deviating from the optimum) to ensure the deployed model is smaller and faster.
    3. Hardware constraints feed back into training strategies—the memory residency pressure and expert parallelism communication overhead introduced by MoE directly impact the topology design and parallelization schemes of training clusters (combinations of data parallelism, expert parallelism, and pipeline parallelism).
    4. Batching and scheduling are the last mile—inference serving technologies like KV cache management, continuous batching, and speculative decoding determine whether architectural dividends can actually translate into low token prices.

    This suggests that developers and enterprises evaluating or integrating large model services should look beyond surface-level cost per million tokens. They should also pay attention to: how context caching is billed, the discount margins for batch interfaces, and the trade-off tiers between throughput and latency. Behind these parameters lies the embodiment of the system logic described above. When building in-house inference services, priority should be given to optimizing batch scheduling, KV cache reuse, and memory bandwidth utilization—their impact on cost often far exceeds the differences in model selection itself.

    VI. Conclusion

    Large models are not black magic, but rather a system shaped jointly by the laws of physics (memory bandwidth, compute ceilings, communication overhead) and economics (one-time training, continuous inference). The redundancy of pre-training data, the sparse activation of MoE, and the thousandfold cost difference brought by inference batching—these seemingly independent phenomena all point to the same main thread: using investments on the training and architecture side to exchange for sustainable economics on the inference side. By mastering this thread, whether in model selection, tuning, or cost accounting, you can see one layer deeper than those merely chasing benchmark scores.