The Era of Large Models: LLM Compute Economics and Engineering Practices for Cutting Costs

    Large language models are often framed as a capital-intensive race, but the more useful questions for developers and technical decision-makers are where the money actually goes and which costs can be engineered down. This article steps back from valuations to focus on the fundamentals: where LLM costs come from, and where to save. It builds a quantifiable cost model, then walks through training-side optimization (parallelism, memory management, communication, fault tolerance, and data engineering) and inference-side optimization (continuous batching, KV cache management, speculative decoding, quantization, and caching). It closes with cost observability, elastic architecture patterns, and a reference architecture for building an LLM application platform in the enterprise. The takeaway: measure first, optimize what hurts, and let metrics drive governance.

    In recent years, foundation model companies have repeatedly drawn intense attention from capital markets. High valuations, large funding rounds, and enormous compute investments reinforce the impression that large models are a race of extreme “capital density.” The recurring question behind the valuation numbers, however, matters more to developers and technical decision-makers: where does the money actually flow across the technical stack, which costs can be reduced through engineering, and how should a company account for building its own LLM platform?

    This article makes no assessment of any specific company or product. Instead, it returns to the fundamentals: where the cost of large models comes from, and where it should be saved. We start with compute economics, then cover cost optimization on the training side and the inference side, along with the observability, capacity planning, and architectural practices enterprises need to put models into production.

    1. Compute Economics: Do the Math Before Optimizing

    1.1 Why LLM capital expenditure is so high

    Training a frontier-level foundation model requires thousands to tens of thousands of high-performance accelerators running continuously for weeks or even months. Such clusters demand enormous procurement or leasing outlays, plus supporting high-speed networking, storage, power, and cooling. On the income statement, this typically shows up as depreciation and amortization or compute leasing fees.

    The direct consequence of this capital structure is that developing large models is fundamentally a long-horizon, high-uncertainty infrastructure investment. This is the core reason foundation model companies attract sustained attention from capital markets.

    More importantly, whether that capital converts into commercial value depends on two engineering metrics: unit cost per call and task completion quality. For the vast majority of companies, there is no need to train a foundation model from scratch. But the training-side mindset determines how you understand the boundaries of model capability, while inference-side optimization directly determines whether a business works and whether it is profitable.

    1.2 Building a quantifiable cost model

    The prerequisite for cost optimization is converting “compute consumption” into comparable quantities. A widely used training compute estimation formula is:

    1. Total training compute (FLOPs) ≈ 6 × N × D
    2. where: N = number of model parameters, D = total number of training tokens
    3. The factor 6 = forward pass 2 + backward pass 4 (floating-point operations per parameter per token)

    From this we can derive further:

    1. Training time (seconds) ≈ total training compute ÷ (number of accelerators × peak compute per accelerator × MFU)
    2. Cost per token = hourly cost per accelerator × number of accelerators × training time ÷ 3600 ÷ D

    Here, MFU (Model FLOPs Utilization) is the ratio of effective compute actually achieved during training to the hardware’s peak compute. It reflects the combined level of parallelism strategy, communication efficiency, and memory management, and is one of the most intuitive indicators of a training platform’s engineering maturity.

    For two models of similar parameter scale, a platform running at 20% MFU needs nearly twice the training time of one running at 40% MFU. Under hourly billing, that means a directly doubled cost.

    One important caveat: MFU must be read in the context of model architecture. For example, models using fine-grained sparse activation architectures activate far fewer parameters in actual computation than their total parameter count. If you still compute against total parameters, the denominator is artificially inflated and MFU appears significantly lower. Therefore, you must standardize the measurement basis before comparing MFU across platforms.

    1.3 A queuing-theory view of inference resources

    Once a model moves into online serving, inference resources can likewise be understood as a queuing system: requests arrive, queue under finite service capacity, and eventually get a response.

    1. Utilization cuts both ways: As utilization rises from 50% to 80%, throughput improves significantly and the fixed cost amortized per request drops noticeably. But as it approaches 100%, queuing latency rises non-linearly, and timeouts and retries multiply.
    2. Unit cost forms a U-shaped curve: On the horizontal axis is utilization, on the vertical axis is cost per request. At low utilization, idle resources are shared among a few requests, keeping unit cost high. At high utilization, long queues and timeout retries consume extra compute. In practice, keep steady-state utilization in a reasonable range and reserve buffer for traffic spikes.
    3. Training and inference cycles are misaligned: Foundation model companies often need to monopolize large clusters for training, while inference load after launch climbs gradually with user growth. Pooling resources by workload and scheduling them at staggered times within the same resource pool is the most direct way to raise overall utilization.

    For most application teams, when using mature model services, the focus should be on how input/output length, concurrency, and cache hit rate affect the bill. Only when conditions allow building your own inference cluster do you need to drill down into batching strategy and memory management.

    2. Training Side: Getting the Most from Every Accelerator

    2.1 Parallelism: breaking through single-accelerator memory and compute limits

    A single model’s parameters, gradients, and optimizer states often exceed a single accelerator’s memory, so several forms of parallelism must work together:

    • Data parallelism: Each accelerator holds a complete model and processes a different batch of data. The accompanying optimizer state sharding technique (commonly known in the industry as ZeRO-style approaches) partitions optimizer states, gradients, and even parameters across accelerators, sharply reducing per-accelerator memory pressure.
    • Tensor parallelism: A single operator (such as a large matrix multiplication) is split across accelerators by row or column, and every layer’s computation requires cross-accelerator communication. It is highly sensitive to inter-accelerator bandwidth, so it is usually confined within a single machine’s high-speed interconnect.
    • Pipeline parallelism: The model is split by layer into multiple stages, which process different micro-batches like an assembly line. Using a sufficient number of micro-batches compresses the idle time from “pipeline bubbles.”
    • Sequence/context parallelism: For very long context scenarios, the attention computation is split along the sequence dimension, reducing the memory and compute pressure from long text.
    • Expert parallelism: In mixture-of-experts architectures, different experts are distributed across devices, and sparse activation means a single forward pass wakes only a few experts.

    The basic engineering principle is: prioritize data parallelism to raise throughput; introduce tensor parallelism when a single accelerator can’t hold the model; layer on pipeline parallelism when scaling across nodes; and introduce sequence and expert parallelism for long-context or sparse architectures. Every form of parallelism adds communication overhead, so the strategy must match the cluster topology. Avoid “splitting whatever you can.”

    2.2 Memory management: trading compute for space

    • Activation recomputation: Instead of storing intermediate activations during the forward pass, recompute them on demand during backpropagation. The cost is extra computation; the benefit is a large reduction in memory usage. You can use “selective recomputation,” recomputing only the memory-heavy key modules to balance speed and capacity.
    • Mixed precision: Use half-precision formats for computation while maintaining a high-precision copy of the master parameters to ensure numerical stability. Matrix operations can use a mixed mode with low-precision multiply and high-precision accumulation, balancing speed and stability.
    • Memory fragmentation control: Pre-allocate memory pools and manage a unified cache allocator to reduce fragmentation from repeated allocation and release.

    2.3 Communication and storage: avoiding “compute waiting on data”

    • Topology-aware scheduling: Place tasks that communicate frequently within the same high-bandwidth interconnect domain. Cross-domain bandwidth is typically more than an order of magnitude lower than intra-domain bandwidth; once tensor parallelism crosses domains, per-step time can multiply.
    • Overlap and bucketing: Overlap gradient communication with backward computation, and aggregate gradients into buckets to reduce the number of communication operations.
    • Hierarchical collective communication: In a hierarchical network, aggregate within nodes first, then exchange between nodes, reducing cross-domain data volume.
    • Data pipeline feeding: Run prefetching, sharded reads, decoding, and augmentation in parallel across multiple processes to ensure accelerators don’t sit idle waiting on data.

    2.4 Fault tolerance and checkpointing: the lifeline of large-scale training

    In training runs at thousand-accelerator scale lasting weeks, hardware failures are nearly inevitable. A single failure without checkpoint protection can cost hours or even days of compute and money.

    The checkpoint interval can be estimated from the failure rate:

    1. Given a mean time between failures (MTBF) and a single save time C, the approximate optimal interval is:
    2. T_optimal ≈ sqrt(2 × C × MTBF)

    This formula comes from classic optimal checkpoint interval theory; it essentially balances “save overhead” against “failure rollback loss.” In practice, use asynchronous saving to overlap checkpoint writes with training computation, and complete a full save as soon as possible once the training window stabilizes.

    1. # Illustrative code: asynchronous checkpointing
    2. def train_step_with_checkpoint(model, data_loader, ckpt_dir, save_every_steps):
    3. step = 0
    4. for batch in data_loader:
    5. loss = model.train_step(batch)
    6. if step % save_every_steps == 0:
    7. # First snapshot into memory, then hand off to a background thread
    8. # to write to disk so training doesn't wait on I/O
    9. snapshot = model.make_snapshot()
    10. async_save(snapshot, f"{ckpt_dir}/step_{step}.pt")
    11. step += 1

    In addition, training jobs should support automatic restart and resumption from progress: when the scheduler detects a node anomaly, it automatically isolates the faulty node, relaunches the job, and loads the most recent checkpoint. Keep the last several checkpoints as well, to avoid a corrupted file forcing a full rollback.

    2.5 Data engineering: it sets the ceiling on quality

    Compute determines “how fast it can run,” but data determines “how well it can run.” A high-quality data pipeline should have the following capabilities:

    1. Quality filtering: Use rules and model scoring to remove low-quality content, machine-generated noise, and harmful information.
    2. Exact and near deduplication: The former handles fully identical data; the latter uses locality-sensitive hashing methods such as MinHash and SimHash to identify highly similar text, reducing the memorization and overfitting caused by duplicate content.
    3. Mixing and curriculum learning: Dynamically adjust data proportions by domain, language, and difficulty, and order training from easy to hard.
    4. Auditable data lineage: Record the source, processing rules, and version of each piece of data to ensure experiments are reproducible.

    3. Inference Side: the “cost per token” that decides long-term competitiveness

    Inference is the longest-running and highest cumulative-cost phase over a model’s lifecycle. Its optimization space comes almost entirely from understanding the autoregressive generation process.

    3.1 Two phases with very different performance profiles

    • Prefill phase: Processes all input tokens at once and is compute-intensive. Its time is roughly proportional to input length, and it directly determines the time-to-first-token users perceive.
    • Decode phase: Generates output token by token, producing one token per step yet needing to read all model weights and the existing KV cache. It is memory-access-intensive. At low load and small batch sizes, accelerator compute sits largely idle.

    The key to raising decode throughput is increasing batch size: let multiple requests share the same weight read, turning idle compute into actual throughput. This is the fundamental difference in mindset between inference optimization and training optimization.

    3.2 Continuous batching and KV cache management

    Traditional static batching must wait for every request in the batch to finish generating before releasing resources: long-output requests hold up the whole batch, while short-output requests can only wait idle. Continuous batching schedules at iteration granularity, so any request exits the moment it finishes generating and new requests can join at any time.

    Accompanying it is paged KV cache management, which borrows the paging idea from operating system virtual memory: split the cache into fixed-size blocks, allocated on demand and stored non-contiguously. Compared with pre-allocating contiguous memory, this greatly reduces memory waste. Blocks are linked through an index table, which supports dynamic growth and lets requests sharing the same prefix share the same cache blocks.

    1. # Illustrative code: continuous batching scheduling loop (simplified)
    2. while running:
    3. batch = scheduler.form_batch(max_num_seqs=256, max_batched_tokens=8192)
    4. outputs = engine.step(batch)
    5. for req, token in outputs:
    6. stream(req, token) # stream back to the caller
    7. scheduler.release_finished(batch) # free KV cache for finished requests immediately

    3.3 Speculative decoding: trading “drafts” for speed

    The basic speculative decoding flow is:

    1. Use a lightweight draft model to guess several tokens in one shot;
    2. Have the target model verify these tokens in parallel;
    3. Accept the longest correct prefix and generate one additional token at the end.

    It compresses what was originally multiple serial decode steps into a single parallel verification. Mathematically, it guarantees the output distribution matches direct sampling, making it “lossless acceleration.” The benefit is most obvious at small batch sizes and narrows at large batch sizes. On the engineering side, you can also try using the model’s own shallow layers as a draft source, or using retrieved results as candidate fragments.

    3.4 Quantization, distillation, and architecture improvements

    • Quantization: Compress weights, activations, and even the KV cache from high precision to low-precision storage. Going from FP16 to INT8, for example, roughly halves weight memory usage and access volume in theory. This is one of the most effective optimizations for the memory-access-bound decode phase. Calibration is key: use representative data to determine quantization ranges, and pay special attention to numerically sensitive tasks in your evaluation.
    • Distillation: Use a more capable model as the teacher to transfer its output distribution to a smaller student model, achieving near-comparable quality at a smaller cost.
    • Architecture improvements: Replacing multi-head attention with multi-query attention or grouped-query attention lets multiple query heads share the same set of key-value heads, directly reducing KV cache size. Mixture-of-experts architectures extend model capacity through sparse activation, activating only part of the experts per inference, keeping compute manageable as total parameters grow.

    3.5 Prefix caching and request scheduling

    • Prefix caching: The KV cache of shared prefixes such as system prompts and document templates can be reused across requests, and time-to-first-token drops noticeably as the reuse rate rises. When cache capacity is limited, evict entries using policies such as least-recently-used.
    • Load-aware scheduling: Under high concurrency, requests belong to different phases. Arranging compute-intensive prefill and memory-access-intensive decode sensibly prevents long-input requests from blocking requests that are decoding, which would cause stuttering output.

    4. Elastic Architecture and Cost Observability: from “saving cost” to “managing cost”

    4.1 Provisioning resources in tiers by workload profile

    • Workload classification: Classify by throughput requirement into interactive, semi-interactive, and offline batch. Offline jobs can be scheduled to off-peak business hours or run on interruptible, lower-priced elastic compute.
    • Elastic scaling: Auto-scale based on metrics such as concurrency, queue time, and memory utilization, while staying wary of cold starts. LLM service instances take a long time to load weights, so it’s advisable to reserve some headroom or use a pool of pre-warmed instances.
    • Model tiering: Route simple tasks to small models and escalate complex tasks to large models; also set strict limits on input and output length. Controlling context length often cuts costs more immediately than switching models.

    4.2 Building an inference cost-metrics system

    Dimension Key metrics Optimization goal
    Business value Task completion rate, human adoption rate, cost per task Continuously decreasing while maintaining quality
    Latency Time-to-first-token, per-token generation time, end-to-end time Meeting the experience threshold
    Throughput tokens/s per accelerator, maximum concurrent batch size Continuously improving
    Resources Accelerator utilization, memory usage, cache hit rate Reducing idle time and waste
    Cost Cost per thousand tokens, share of cost during idle periods Attributable and comparable

    On cost attribution: Enterprises can tag each call at the gateway layer with the business line, application, environment, model version, and call source. Once billing data is joined with business tags, questions like “which feature burns the most money, and whether a version’s quality improvement is worth the extra compute” become answerable.

    4.3 Semantic caching: benefits come with risks

    For Q&A scenarios with high repetition, semantic caching can map semantically similar questions to existing answers, saving an inference call. But it faces three risks:

    1. Threshold failure: “How do you calculate resistors in parallel” and “how do you calculate resistors in series” look highly similar in wording, yet the answers are entirely different. A threshold set too loose causes incorrect reuse; set too strict, and the benefit is limited.
    2. Knowledge staleness: Cached content becomes outdated as the outside world changes, so cache entries need an expiration policy.
    3. Data isolation: Caches should distinguish tenants and permission scopes to avoid a user’s private data being hit by another request.

    The practical recommendation is to use semantic caching only in relatively stable, low-risk scenarios, backed by human spot-checks and hit-quality monitoring.

    4.4 Storage tiering and log governance

    Inference logs, conversation records, and vector indexes keep growing, and without governance, storage cost can gradually approach compute cost. The following strategies help:

    • Tiered storage: Keep hot data on online storage, move warm data to infrequent-access storage, and archive cold data to archive-class storage;
    • Lifecycle policies: Configure automatic cleanup rules for logs and temporary files;
    • Sampled logging: Fully recording request bodies is both expensive and a privacy risk, so it’s advisable to log metadata by default and enable sampling on demand.

    5. An Enterprise Reference Architecture

    Organizing the above capabilities into a layered architecture is a common starting point for building an enterprise LLM application platform:

    • Access layer: A unified gateway handles authentication, rate limiting, quotas, and cost-accounting tag injection;
    • Orchestration layer: Responsible for task routing, model tiering, semantic caching, and orchestrating capabilities such as retrieval-augmented generation and tool calls;
    • Model layer: Connects external model services and privately deployed model instances, hiding interface differences behind a unified abstraction;
    • Data layer: Composed of vector storage, object storage, and logging services, providing knowledge indexing and data archival;
    • Observability layer: Collects metrics, logs, and traces across the full chain to support capacity planning and cost optimization.

    To reduce lock-in risk, define a unified abstraction at the model-invocation layer. Business code depends only on the minimal contract of “input messages, output text,” while whether the backend is an external service or a privately deployed model is switched via configuration:

    1. # Illustrative code: model invocation abstraction
    2. class LLMBackend:
    3. def chat(self, messages, **options):
    4. raise NotImplementedError
    5. class RemoteModelBackend(LLMBackend):
    6. """Connects to a cloud model service"""
    7. def chat(self, messages, **options):
    8. # Handle retries, timeouts, and rate limiting uniformly
    9. return call_remote_model(messages, **options)
    10. class PrivateModelBackend(LLMBackend):
    11. """Connects to a privately deployed inference cluster"""
    12. def chat(self, messages, **options):
    13. return call_private_endpoint(messages, **options)
    14. # Select the backend via configuration; business code needs no changes
    15. backend = build_backend(config["llm"]["backend"])
    16. answer = backend.chat(messages, max_tokens=1024)

    On security and compliance, enterprises should focus on three points: content safety filtering for inputs and outputs, sensitive-data detection and redaction, and data isolation and operation auditing in multi-tenant scenarios.

    Returning to the opening question: why do capital markets persistently value foundation model companies highly? From a technical standpoint, the reason isn’t complicated. Training a broadly capable model requires long-term, enormous upfront investment; once engineering pushes the unit cost per call low enough, the model can be reused repeatedly across an almost unlimited set of scenarios. This “heavy upfront investment, low marginal cost” structure is the technical root of its valuation logic.

    For developers, three core takeaways:

    1. Do the math before optimizing: Use unified formulas to quantify training and inference costs, avoiding tuning parameters on gut feeling.
    2. Optimize what hurts: On the training side, focus on parallelism, fault tolerance, and data quality; on the inference side, focus on batching, caching, and model compression.
    3. Let metrics drive governance: Bring cost metrics into daily monitoring so every optimization yields quantifiable benefits.

    At the infrastructure level, enterprises can draw on the general capabilities of cloud providers such as Baidu AI Cloud, combining elastic compute, object storage, container platforms, logging services, and monitoring and alerting as needed, and using private and hybrid deployment options to meet compliance requirements, so they can devote more energy to creating business value itself. The second half of the LLM race is decided not only by whose model is stronger, but by who can achieve the same quality at lower cost and deliver more reliably.