LLM Training Compute Planning and Cost Control: A Practical Guide
Training a large language model can take weeks or months on hundreds or thousands of accelerators, and most failures stem from poor upfront planning. This guide walks through the full planning workflow: estimating compute requirements with the 6ND formula, sizing GPU memory and choosing parallelism strategies, selecting cluster architecture (compute, interconnect, and storage), ensuring training stability through checkpointing and fault recovery, measuring efficiency with MFU, and building a realistic cost budget. Each section includes ready-to-run estimation code that depends only on basic language features, so it can be ported to any stack.
1. Problem Definition
Training a large language model typically takes weeks or even months and occupies hundreds to thousands of accelerator cards. Teams commonly run into three types of problems at the project approval stage: they cannot clearly state how much compute the training will require; the chosen cluster becomes a bottleneck in memory or communication; or mid-training failures cause schedule and budget overruns again and again.
All three problems are fundamentally planning problems. The goal of planning is to quantify the relationships among compute volume, memory, communication, storage, fault recovery, and cost before training begins, producing verifiable estimates. These estimates do not need to be perfectly accurate, but they must guide decisions and be continuously calibrated against actual metrics during training.
The following sections proceed from requirements to cost. Each section provides the reasoning behind its recommendations and includes estimation code you can run directly. The code uses only basic language features and no framework dependencies, so it can be ported to any technology stack.
2. Estimating Compute Requirements
2.1 The Empirical Formula for Training Compute
For dense models built primarily on the Transformer architecture, total training compute can be approximated by:
C ≈ 6 × N × D
where N is the number of model parameters, D is the total number of tokens processed during training, and C is measured in floating-point operations (FLOPs).
The coefficient 6 comes from decomposing the compute of forward and backward passes. The forward pass requires roughly 2 multiply-add operations per parameter per token, and the backward pass is about twice that, totaling roughly 6. This approximation ignores the sequence-length-dependent overhead of the attention mechanism; for common context lengths, the error is usually acceptable. For sparsely activated mixture-of-experts models, N should be replaced by the number of parameters actually activated per token, not the total parameter count.
2.2 Training Duration and Number of Accelerators
Once you have the total compute, you also need to know how much effective compute a single card can deliver. Effective compute equals the accelerator’s peak FLOPS multiplied by model FLOPs utilization (MFU). In real training, MFU is affected by communication overhead, data loading, operator efficiency, and pipeline bubbles; typical values range from 30% to 50%, depending on the parallelism strategy and the level of engineering optimization.
The following code wraps this relationship into a function for estimating required GPU-hours:
def estimate_gpu_hours(params_b, tokens_b, peak_tflops, mfu):"""params_b: model parameter count, in billions (B)tokens_b: number of training tokens, in billions (B)peak_tflops: peak compute per GPU, in TFLOPSmfu: model FLOPs utilization, a decimal between 0 and 1"""total_flops = 6 * params_b * 1e9 * tokens_b * 1e9effective_flops_per_sec = peak_tflops * 1e12 * mfuseconds = total_flops / effective_flops_per_secreturn seconds / 3600# Example: 7B model, 1T training tokens, 300 TFLOPS peak per GPU, MFU of 0.4gpu_hours = estimate_gpu_hours(7, 1000, 300, 0.4)print(f"Estimated consumption: about {gpu_hours:,.0f} GPU-hours")
Under these assumptions, the task requires about 97,000 GPU-hours. With 512 GPUs in parallel, the theoretical wall-clock time is about 190 hours, or roughly eight days. The real timeline must also include debugging, evaluation, and fault recovery, so it is advisable to reserve a 20% to 30% margin on top of the theoretical value.
2.3 Extrapolating from Small-Model Experiments
Before formal training, teams usually run ablation experiments on smaller models to determine data mixture ratios, learning rates, and architectural parameters. The compute for these experiments can be estimated with the same formula, and the results should only serve as a basis for relative comparison. A common industry practice is to fit a power-law relationship between the small model’s loss and compute, then extrapolate to the target scale. Extrapolation carries error—especially when the target scale far exceeds the experimental scale—so treat extrapolated results as ranges rather than single point values.
3. Memory Requirements and Model Sharding
3.1 Main Sources of Memory Usage
During training, GPU memory is mainly composed of four parts: model parameters, gradients, optimizer states, and activations. With the common combination of mixed-precision training and an adaptive optimizer, each parameter typically requires about 16 bytes of static memory, including the half-precision parameter, half-precision gradient, single-precision master weight, and the optimizer’s first- and second-order moments. Activations depend on batch size, sequence length, and the number of layers, and often become the dominant consumer in long-sequence scenarios.
The following function estimates the static memory usage per GPU:
def static_memory_per_gpu_gb(params_b, shard_count, bytes_per_param=16):"""params_b: model parameter count, in billions (B)shard_count: number of shards for parameters, gradients, and optimizer statesbytes_per_param: static memory bytes per parameter"""total_gb = params_b * bytes_per_paramreturn total_gb / shard_countprint(static_memory_per_gpu_gb(7, 1)) # No sharding: about 112 GBprint(static_memory_per_gpu_gb(7, 8)) # 8-way sharding: about 14 GB
The results show that without sharding, the static memory of a 7B model already exceeds the capacity of most single GPUs, so states must be distributed across multiple cards via sharding. Activations, meanwhile, need to be controlled through recomputation, smaller micro-batches, or shorter sequence lengths.
3.2 Principles for Choosing a Sharding Strategy
Common parallelism strategies include the following:
- Data parallelism: each GPU holds a full model replica and processes different data batches. Simple to implement, but a single GPU must hold the entire model, and gradient synchronization introduces communication overhead.
- Optimizer state and gradient sharding: built on data parallelism, this distributes optimizer states and gradients across GPUs, significantly reducing per-GPU static memory at the cost of additional communication for parameter aggregation.
- Tensor parallelism: splits matrix operations within a single layer across multiple GPUs. Communication is frequent and typically requires very high inter-GPU bandwidth, so it is generally confined to a single node.
- Pipeline parallelism: splits the model by layers into stages placed on different GPUs. Cross-node communication is relatively small, but pipeline bubbles occur and must be amortized with enough micro-batches.
- Sequence or expert parallelism: sharding strategies designed for long sequences and mixture-of-experts architectures respectively, suited to specific model forms.
A basic decision order can be followed. First determine whether the model fits on a single GPU or a single node; then use tensor parallelism within nodes to exploit high bandwidth; use pipeline or data parallelism across nodes; and finally apply sharding techniques to compress the remaining static memory. The core idea behind this order is to place the most communication-intensive operations on the highest-bandwidth links.
4. Cluster Architecture Selection
4.1 Compute Units and Memory
An accelerator’s memory capacity determines the size of the model slice a single GPU can hold, and its peak compute determines the upper bound of training speed. Do not select hardware based on peak compute alone. Memory bandwidth, support for low-precision arithmetic, and effective compute per watt all affect real training efficiency. It is advisable to run short benchmarks of the target model on candidate hardware and rely on measured throughput rather than specification sheets.
4.2 Interconnect Network
In large-scale training, the network often becomes the bottleneck before compute does. Focus on three metrics:
- Intra-node bandwidth: determines whether tensor parallelism can run efficiently.
- Inter-node bandwidth and topology: determines the speed of gradient synchronization in data parallelism and cross-node communication in pipeline parallelism. The lower the oversubscription ratio of the topology, the less likely cross-node communication is to be congested.
- Network latency and jitter: these have a major impact on synchronous training, where one slow node can slow down an entire collective communication operation.
4.3 Storage and Data Pipeline
Training data must be fed to the compute units continuously and stably. Slow data reads leave accelerators idle, so pay attention to the throughput of the object storage or parallel file system, and whether data preprocessing is decoupled from training. Checkpoint writes also depend on storage bandwidth; if each write takes too long, it directly consumes training time.
5. Training Stability and Fault Tolerance
5.1 Choosing the Checkpoint Interval
The larger the cluster, the higher the probability of hardware failures. Saving checkpoints too frequently eats into training time and storage bandwidth; saving them too sparsely means recomputing substantial progress after a failure. The classic Young/Daly formula gives an approximately optimal interval:
τ ≈ √(2 × C × M)
where C is the time to write one checkpoint and M is the cluster’s mean time between failures (MTBF). A single node has a long failure interval, but the failure of any node in the cluster interrupts training, so cluster MTBF can be roughly estimated as single-node MTBF divided by the number of nodes.
import mathdef optimal_checkpoint_interval_s(checkpoint_write_s, cluster_mtbf_s):return math.sqrt(2 * checkpoint_write_s * cluster_mtbf_s)# Example: one checkpoint write takes 120 seconds; the cluster experiences an interruption every 24 hours on averageinterval = optimal_checkpoint_interval_s(120, 24 * 3600)print(f"Recommended checkpoint interval: about {interval / 60:.0f} minutes")
This example yields an interval of about 76 minutes. The actual value should be recalculated based on historical failure records and measured storage write times.
5.2 Failure Detection and Automatic Recovery
Stability assurance requires three mechanisms working together:
- Health checks: periodically monitor accelerator temperature, memory error counts, and inter-node communication status, isolating abnormal nodes promptly.
- Automatic restart: when a training process exits abnormally, the scheduling system automatically resumes from the most recent checkpoint, avoiding isolated nodes where possible.
- Data resumption: the data reading position must be recorded precisely during recovery to avoid duplicated or missed samples, which would otherwise compromise the reproducibility of convergence results.
5.3 Key Metrics During Training
The following metrics should be monitored continuously during training, with alert thresholds configured:
- Loss curve: sudden spikes warrant checking the data batches and learning rate schedule.
- Gradient norm: sustained growth often signals numerical instability.
- Throughput (tokens/s): a noticeable drop usually indicates network congestion, a slow node, or a blocked data pipeline.
- Model FLOPs utilization (MFU): reflects how effectively the cluster is being used and is the core metric for measuring engineering optimization results.
6. How to Compute Efficiency Metrics
Model FLOPs utilization (MFU) is defined as the ratio of model compute actually used to the cluster’s peak compute. It is computed as follows:
def compute_mfu(params_b, tokens_per_sec, num_gpus, peak_tflops_per_gpu):"""tokens_per_sec: tokens processed per second across the entire cluster"""achieved_flops = 6 * params_b * 1e9 * tokens_per_secpeak_flops = num_gpus * peak_tflops_per_gpu * 1e12return achieved_flops / peak_flops# Example: 7B model, 64 GPUs, 200K tokens/s cluster-wide, 300 TFLOPS peak per GPUmfu = compute_mfu(7, 2e5, 64, 300)print(f"MFU is about {mfu:.1%}")
This example yields an MFU of about 44%. If an adjustment increases throughput but MFU stays unchanged, the throughput gain came mainly from adding more GPUs rather than from improved efficiency—a distinction that directly affects subsequent cost judgments.
7. Cost Accounting and Budget Control
7.1 Cost Components
The total cost of a training task typically includes the following:
- Compute cost: accelerator occupancy time multiplied by the per-hour rate—the largest component.
- Storage cost: capacity and read/write overhead for training data, checkpoints, and logs.
- Network cost: data transfer fees across nodes or availability zones.
- Labor cost: investment in debugging, evaluation, and on-call monitoring.
- Failure losses: repeated training caused by failure rollbacks, configuration errors, or poor hyperparameters.
Failure losses are the easiest to underestimate. Reserving a certain percentage of redundancy in the budget is a prudent practice.
7.2 Approaches to Budget Management
- Estimate first, then approve: use the method in Section 2 to obtain the GPU
