Demystifying LLM Training and Inference: Compute, Communication, and Cost Logic
This article provides a systematic breakdown of the cost logic behind Large Language Model (LLM) training and inference. By examining the algorithmic, system, and hardware layers, it explains how model parameters and training data impact compute allocation, why inference presents different bottlenecks during input processing versus token generation, and how batching and Mixture of Experts (MoE) architectures affect overall cost and performance. The article further explores how to interpret public API pricing and offers a practical guide for enterprises to build an actionable LLM evaluation and optimization workflow.
1. Understanding LLMs: Establishing a Comprehensive Cost Perspective
Why do real-time and asynchronous API calls for the same model often have different prices? Why doesn’t adding more accelerators always yield proportional performance gains? Why might a model with more parameters consume less compute per inference?
The answers lie not only in the model’s architecture but also in memory access, task scheduling, and network communication. To truly understand LLMs, one must examine three interconnected layers:
First, the algorithmic layer, which includes parameter scale, training data volume, attention mechanisms, and expert routing.
Second, the system layer, encompassing parallelism strategies, batching, cache management, and request scheduling.
Third, the hardware layer, which involves compute capability, memory capacity, memory bandwidth, and interconnect capabilities.
These three layers collectively determine the final training cycle, service throughput, response latency, and per-request cost. Discussing “how large a model is” or “how many tokens it generates per second” in isolation—without considering specific hardware and workloads—rarely leads to reliable conclusions.
2. How Training Compute is Allocated: Bigger Isn’t Always Better for Parameters and Data
2.1 What is Actually Being Computed During Training?
Taking standard autoregressive language models as an example, pre-training typically splits text into tokens and predicts the next token based on existing context. The training process mainly consists of forward computation, loss calculation, backpropagation, and parameter updates.
Forward computation produces predictions, while backpropagation calculates the impact of each parameter on the loss; the optimizer then updates the parameters accordingly. Unlike inference, training must store not only model weights but also gradients, partial intermediate activations, and optimizer states. Consequently, memory requirements are significantly higher than merely loading weights.
For dense models with similar architectures, training compute is often roughly estimated using the following relationship:
C ≈ 6ND
Where C represents the training floating-point operations (FLOPs), N is the parameter count, and D is the number of training tokens. This relationship is primarily used to establish order-of-magnitude intuition and is not a precise formula for all architectures. Long-context attention, additional training objectives, activation recomputation, and different structural designs can all alter actual overhead.
2.2 Balancing Model Size and Data with a Fixed Compute Budget
Assuming a limited training budget, one can choose a larger model with less data, or a smaller model with more data.
The former may result in undertrained parameters, while the latter may be constrained by model capacity, making it difficult to fully utilize the additional data. “Compute-optimal” training typically involves finding a reasonable combination of model scale and training data volume for a given budget and experimental conditions.
However, compute-optimal does not equal commercially optimal.
If a model will handle massive request volumes post-launch, enterprises might be willing to invest more in data and compute during training to achieve a model with fewer parameters and cheaper deployment. In this case, the logical target should be full lifecycle cost:
Total Cost = Data & Training Cost + Deployment Resource Cost + Cumulative Inference Cost + O&M Cost
Therefore, you cannot conclude that a model’s training strategy is “irrational” just because it was trained on more data. You must also know the target request volume and whether more thorough training brought verifiable quality gains.
2.3 Data Quality Determines if Extra Compute is Worthwhile
Adding training tokens does not necessarily increase effective knowledge proportionally. Duplicate content, erroneous information, low-quality synthetic text, and task distribution skew can all diminish training returns.
Practical training pipelines must simultaneously consider deduplication, quality filtering, data mixing ratios, contamination checks, and evaluation set isolation. When evaluating training investments, focus on effective learning signals rather than merely comparing raw data volumes.
3. Inference is Not a Single Phase: Differing Bottlenecks in Input Processing and Token Generation
LLM response generation can generally be divided into two main phases: input preprocessing and sequential token decoding.
3.1 Input Preprocessing Tends to Create Larger Compute Tasks
The model first processes the user-provided context and establishes the necessary intermediate states for subsequent generation. This phase can process multiple input positions in parallel and typically forms large-scale matrix operations more easily.
When the input is long, this phase can significantly impact time-to-first-token (TTFT) latency while consuming considerable compute resources and cache space. The attention implementation, context length, and batching strategy all influence the actual bottleneck.
3.2 Sequential Token Decoding Has Strong Sequential Dependencies
Once in the generation phase, the next token depends on previously generated content. For a single request, output positions generally cannot be computed all at once in parallel like input positions.
To avoid repeatedly computing attention keys and values for historical tokens, the system saves them in a cache, commonly known as the KV cache. This cache reduces redundant computation but occupies memory and generates continuous read/write traffic during generation.
Consequently, under smaller batches, the decoding phase is often more constrained by weight reading and memory bandwidth. Under long-context or high-concurrency conditions, KV cache access, attention computation, and communication can also become primary bottlenecks.
This means that evaluating model speed should at least distinguish between:
- Time-to-First-Token (TTFT) Latency: The time from when a request enters the system until it starts returning content.
- Per-Token Generation Latency: The time required to generate each new token after output begins.
- End-to-End Latency: The total time from request submission to full result return.
- System Throughput: The number of completed requests or generated tokens per unit of time.
These metrics are related but cannot substitute for one another.
4. How Batching Reduces Costs but Impacts User Experience
4.1 Multiple Requests Share Weight Reading Overhead
Assume a model requires reading weight data of size W, and B requests participate in the same decoding batch.
In an ideal scenario, a batch of requests shares a single weight read, so the weight read overhead allocated to each request can be roughly understood as:
Weight read per request ≈ W / B
This is not a complete formula for actual memory traffic, as cache capacity, operator implementation, weight sharding, and repeated reads all affect the result. However, it explains a crucial reason why batching improves efficiency.
A single request might not fully utilize a device’s compute resources; grouping multiple requests together often improves matrix operation efficiency and amortizes fixed overhead.
However, this doesn’t mean “no batching is always several times more expensive.” The actual gap depends on model size, device capability, input/output length, quantization methods, and the original system utilization.
4.2 A Larger Batch Doesn’t Necessarily Mean Shorter User Wait Times
Expanding the batch size may increase queue times or cause each compute cycle to take longer. Improved system throughput does not guarantee that every individual request will complete faster.
Therefore, low-latency services sometimes need to proactively reduce batch sizes, reserve compute power, or even keep resources idle during load fluctuations. These practices improve interactive experience but raise the per-request cost.
This also explains why price increments for certain services might exceed their speed improvements: users are buying not just shorter compute time, but also higher priority, less queueing, and resource redundancy. However, specific pricing is also influenced by business strategy and cannot simply be equated to hardware costs.
4.3 Continuous Batching is Better Suited for Variable-Length Requests
Real-world requests have varying output lengths. If the system must wait for all requests in a batch to finish before accepting new ones, short requests may leave resources idle upon completion.
Continuous batching allows the system to evict completed requests during generation and insert new ones at scheduling boundaries, thereby maximizing resource utilization.
However, the scheduler must also handle fairness between long and short requests, out-of-memory errors, request cancellation, and priority issues. Efficient batching isn’t simply about making batches larger, but dynamically adjusting under latency targets and resource constraints.
5. Mixture of Experts (MoE): Saving Compute Doesn’t Eliminate System Costs
5.1 Total Parameters vs. Activated Parameters are Distinct Concepts
Mixture of Experts (MoE) architectures typically set up multiple expert sub-networks within certain network layers, where a routing module selects a few experts to perform computation for each token.
Thus, it features two scale metrics that must be distinguished:
The total parameter count largely determines overall weight storage requirements.
The activated parameter count per token more directly impacts the compute overhead as the token passes through expert layers.
Sparse activation allows a model to accommodate more parameters without proportionally increasing the compute per token. However, whether the model is better still depends on training methods, data, and routing efficacy, rather than the sheer number of experts.
5.2 Expert Parallelism Introduces All-to-All Communication
When different experts are distributed across different devices, the system must send the token’s hidden state to the device hosting the target expert based on routing results, and then aggregate the results after computation.
This process can form all-to-all communication, where multiple members within a group of devices need to send data to other members.
Communication costs depend not only on the bytes transferred but also on message size, communication rounds, network topology, congestion, and load balancing. For smaller messages, startup latency may dominate; for larger messages, effective bandwidth often becomes the primary limitation.
5.3 Rack Boundaries are Not a Fixed Model Limit
Interconnect capabilities inside and outside a rack may differ significantly, but this difference is not a fixed multiplier, nor does it mean “expert layers must reside within a single rack.”
Actual deployment boundaries depend on interconnect design, network configuration, parallelism groupings, routing strategies, and acceptable communication overhead. Systems can reduce cross-domain communication by limiting the scope of expert parallelism, employing topology-aware placement, adjusting expert replicas, or combining other parallel strategies.
Therefore, a more accurate assessment is: the efficient interconnect range affects the economics of expert parallelism, rather than constituting a universal, immutable physical upper limit.
5.4 Load Imbalance Can Offset Sparse Compute Gains
If a large number of tokens concentrate on a few experts, the devices hosting those experts become hotspots. Other idle devices cannot directly substitute for busy experts.
The training phase generally requires considering routing balance; the deployment phase requires monitoring expert utilization, communication wait times, and shifts in request distribution. Adding replicas for hotspot experts can relieve pressure, but it also increases memory usage and complicates routing and state management.
6. What Public Pricing Reveals—and What It Doesn’t
Price differences for inputs, outputs, cache hits, and asynchronous processing can help illustrate a service’s cost structure, but they are insufficient to uniquely determine the underlying architecture.
For example, higher output prices might relate to sequential decoding, cache access, and low-latency resource allocation; cheaper asynchronous processing might reflect more scheduling flexibility; lower cache hit prices might indicate the reuse of partial historical computations.
However, the same pricing phenomena could also result from market positioning, supply and demand, service commitments, or subsidy strategies.
Thus, a sound analytical approach should be:
Observe pricing and performance phenomena, propose several potential mechanisms, and then use controlled testing to eliminate some explanations.
An irrational approach is to reverse-engineer precise parameter counts, expert numbers, quantization bit-widths, or device scales directly from pricing. Without public disclosures or reproducible experiments, such conclusions remain mere speculation.
7. How Enterprises Can Build an Executable Evaluation and Optimization Process
Step 1: Define Business Objectives.
Interactive Q&A focuses heavily on TTFT and generation speed; offline document processing prioritizes throughput; tasks like code generation and information extraction also require evaluating accuracy, executability, or structured output pass rates.
Step 2: Build a Representative Request Set.
Test data should cover realistic input lengths, output lengths, concurrency levels, and complexities. Avoid using only a few short questions. When dealing with sensitive data, necessary desensitization and access controls should be applied.
Step 3: Record Averages and Tail Performance Simultaneously.
Beyond average latency, observe higher-percentile latencies, queue times, error rates, and timeout rates. User experience is often dictated by a small number of severely delayed requests.
Step 4: Calculate Costs Under Quality Thresholds.
Comparing only the price per token can be misleading. A cheaper solution that frequently requires retries might ultimately cost more to complete a single effective task.
Consider the following business metric:
Cost per effective task = Total cost during testing / Number of tasks meeting quality requirements
If using a self-hosted deployment, equipment depreciation, idle resources, networking, O&M, and fault redundancy should also be factored into the total cost.
Step 5: Optimize Based on Measured Bottlenecks.
If time is mostly spent queueing, adjust capacity or scheduling strategies; if memory is exhausted by long contexts, control invalid historical information and evaluate caching strategies; if communication wait times are prominent, check parallel groupings and expert placement; if task accuracy is insufficient, prioritize improving model selection, prompt design, or data, rather than just chasing hardware utilization.
Conclusion
The core challenge of LLM systems is not maximizing any single metric, but finding a balance that aligns with business needs across quality, latency, throughput, and cost.
The training phase requires weighing model capacity against data investment; the inference phase requires coordinating batching with interactive experience; and MoE architectures require evaluating sparse compute gains alongside communication overhead. Only by analyzing algorithms, systems, hardware, and business workloads together can we explain performance differences and translate technical judgments into verifiable, executable engineering decisions.
