Skip to main content

Mathematical Foundations

The First-Principles Equations Behind Every MLSys·im Solver

MLSys·im avoids “black box” heuristics. Every output traces back to one of the equations below. Read this page before the code to understand what the solvers compute and why.

TipHow to read this page

Each section corresponds to one MLSys·im solver. Click any solver name to jump to its API docs, or follow the Textbook, Interactive Lab, and Slides links to the full curriculum treatment (or browse the Textbook & Chapter Map).


1. The Roofline Model (Single-Node Performance)

Implemented in mlsysim.solvers.SingleNodeModel. Curriculum: Vol I, Ch 11: Hardware Acceleration · Study sheet · Slides

Intuition: Hardware has two speed limits: how fast it can compute (FLOP/s) and how fast it can feed data to the compute units (bytes/s). Actual throughput is set by whichever limit is reached first. This is why we take the maximum of two terms, not their sum.

1.1 Latency Equation

\[ T = \max \left( \underbrace{\frac{\text{FLOPs}}{\text{Peak\_FLOP/s} \times \eta}}_{\text{compute time}},\; \underbrace{\frac{\text{Bytes}}{\text{Memory\_BW}}}_{\text{memory time}} \right) + \text{Dispatch\_Tax} \]

Symbol Meaning Typical Range
\(\eta\) Achieved compute efficiency 0.30–0.50 (training); ~0.35 (inference). See Accuracy & Validation.
Dispatch_Tax Per-step kernel/runtime launch tax (hardware.dispatch_tax) 0.001–5.0 ms across silicon tiers (0.01 ms default on HardwareNode; per-layer FRAMEWORK_LAYER_TAX_MS defaults to 0.0 ms)

1.2 Arithmetic Intensity and the Ridge Point

The key diagnostic ratio is arithmetic intensity:

\[ I = \frac{\text{FLOPs}}{\text{Bytes Transferred}} \]

The ridge point is the hardware’s theoretical peak crossover intensity:

\[ I^* = \frac{\text{Peak\_FLOP/s}}{\text{Memory\_BW}}, \qquad I^*_{\text{eff}}(\eta) = \frac{\eta \cdot \text{Peak\_FLOP/s}}{\text{Memory\_BW}} \]

When SingleNodeModel evaluates a kernel at compute efficiency \(\eta \in (0, 1]\), effective compute throughput scales to \(\eta \cdot \text{Peak\_FLOP/s}\), shifting the operational compute-vs-memory crossover to \(I^*_{\text{eff}}(\eta)\) (I^* corresponds to \(\eta = 1\)).

If… Regime Action
\(I > I^*_{\text{eff}}(\eta)\) Compute-bound Faster math units, lower precision, or fewer FLOPs
\(I < I^*_{\text{eff}}(\eta)\) Memory-bound Larger batch size, operator fusion, or higher memory bandwidth

A dense layer with 2048→512, FP16, batch=1:

  • FLOPs: \(2 \times 2048 \times 512 = 2.1\text{M}\)
  • Bytes: \(2048 \times 512 \times 2 = 2.1\text{MB}\)
  • Arithmetic Intensity: \(2.1\text{M} / 2.1\text{MB} = 1\) FLOP/byte
  • H100 Ridge Point: \(989\text{ TF} / 3.35\text{ TB/s} \approx 295\) FLOP/byte (vs. \(312\text{ TF} / 2.04\text{ TB/s} \approx 153\) FLOP/byte on A100)

At \(I = 1 \ll 295 = I^*\), this workload is deeply memory-bound. The H100 achieves <1% of peak compute. Increasing to batch=64 raises \(I\) to ~64, recovering significant throughput.

Source: Slide deck worked example, Vol I Ch 11.


2. Distributed Training (3D/4D Parallelism)

Implemented in mlsysim.solvers.DistributedModel. Curriculum: Vol II, Ch 6: Distributed Training (Study sheet · Slides) | Vol II, Ch 5: Collective Communication (Study sheet · Slides)

Real distributed training involves complex interactions between computation, communication, and scheduling. Empirical profiling requires access to expensive multi-GPU clusters and takes hours per configuration. MLSys·im decomposes the problem into independent overheads, each governed by a closed-form equation, so thousands of parallelism configurations can be evaluated in seconds.

2.1 Parallelism Decomposition

MLSys·im supports 4D parallelism. Given a cluster of \(N\) total GPUs:

\[ \text{DP} = \frac{N}{\text{TP} \times \text{PP} \times \text{EP}} \]

Dimension What It Splits Communication Pattern
Data Parallelism (DP) Batch across replicas AllReduce (gradients)
Tensor Parallelism (TP) Individual layers across GPUs Point-to-point (intra-node NVLink)
Pipeline Parallelism (PP) Layer groups across stages Forward/backward activations
Expert Parallelism (EP) MoE experts across GPUs All-to-All (token routing)

2.2 Scaling Efficiency

The solver computes an overall scaling efficiency, the fraction of ideal linear speedup actually achieved:

\[ \eta_{\text{scale}} = \frac{T_{\text{compute}}}{T_{\text{compute}} + T_{\text{dp}} + T_{\text{tp}} + T_{\text{ep}} + T_{\text{bubble}}} \]

An efficiency of 80% on 256 GPUs delivers the throughput of ~205 GPUs; the rest is lost to communication and pipeline bubbles. For the GPT-3 175B reference job (eight-way tensor and eight-way pipeline parallelism on HDR InfiniBand, fixed GPT-3 batch of 1,536 sequences), the solver predicts about 93% at 64 GPUs, 92% at 256, 86% at 1,024, and 55% at 8,192, where the pipeline bubble dominates. Production systems with larger batches and interleaved pipelines retain more. MegaScale’s 175B MFU falls only from 59.1% to 55.2% between 3,072 and 12,288 GPUs [1].

2.3 Ring All-Reduce (Data Parallelism)

Curriculum: Vol II, Ch 5: Collective Communication · Study sheet · Slides

After each training step, every GPU must synchronize gradients. The standard algorithm is ring all-reduce, which arranges \(N\) GPUs in a logical ring and passes gradient chunks in two phases (scatter-reduce, then all-gather).

Using the \(\alpha\)-\(\beta\) communication model (\(\alpha\) = per-message latency, \(\beta\) = bandwidth):

\[ T_{\text{ring}} = 2(N-1) \cdot \alpha \;+\; \frac{2(N-1)}{N} \cdot \frac{M}{\beta} \]

Symbol Meaning
\(M\) Total gradient size in bytes
\(N\) Number of GPUs in the ring
\(\alpha\) Per-message startup latency
\(\beta\) Per-link bandwidth (bytes/s)

Why ring all-reduce scales well: The bandwidth term \(\frac{2(N-1)}{N} \cdot \frac{M}{\beta}\) approaches \(\frac{2M}{\beta}\) as \(N\) grows, so it is asymptotically constant in the number of GPUs. Total data transferred per GPU is always ~\(2M\), regardless of cluster size. The latency term \(2(N-1) \cdot \alpha\) grows linearly, but is negligible for large messages.

MLSys·im also implements tree all-reduce (latency-optimal for small messages):

\[ T_{\text{tree}} = 2 \lceil \log_2 N \rceil \cdot \alpha \;+\; 2 \lceil \log_2 N \rceil \cdot \frac{M}{\beta} \]

Equating \(T_{\text{ring}} = T_{\text{tree}}\) gives the exact crossover payload \(M_{\text{cross}} = \frac{((N - 1) - \lceil \log_2 N \rceil) \cdot \alpha \cdot \beta}{\lceil \log_2 N \rceil - (N - 1)/N}\), which simplifies for large \(N\) to \(M_{\text{cross}} \approx \frac{N \cdot \alpha \cdot \beta}{\log_2 N}\) (calc_ring_tree_crossover_size). Below this size, tree wins (startup latency dominates); above it, ring wins (bandwidth dominates).

A 70B-parameter model in FP16 produces a 140 GB gradient. On a 1,024-GPU cluster with InfiniBand NDR (\(\beta = 50\) GB/s, \(\alpha = 2\;\mu\)s):

  • Bandwidth term: \(\frac{2 \times 1023}{1024} \times \frac{140}{50} \approx\) 5.6 s
  • Latency term: \(2 \times 1023 \times 2\;\mu\text{s} \approx 4\) ms (negligible)
  • Total gradient synchronization time: ~5.6 s, bandwidth-dominated as expected for large messages.

Upgrading from 100 Gb Ethernet (~12.5 GB/s, ~22.4 s sync) to NDR (~50 GB/s, ~5.6 s sync) cuts gradient synchronization time 4.0×.

2.4 Pipeline Parallelism Bubble

Curriculum: Vol II, Ch 6: Distributed Training · Study sheet · Slides

Pipeline parallelism splits a model’s layers across \(P\) stages. At the start of each batch, downstream stages sit idle while upstream stages produce output. This idle time is the pipeline bubble.

Intuition: The speed of light is fixed, but the software schedule can change. Assigning multiple virtual stages (\(V\)) to each GPU interleaves execution: while a GPU waits for one virtual stage’s next microbatch, it computes a different virtual stage’s microbatch, hiding latency behind useful work.

With \(P\) pipeline stages, \(M\) microbatches, and \(V\) virtual stages per GPU:

\[ \text{Bubble Fraction} = \frac{P - 1}{V \times M + P - 1} \]

Configuration Bubble Fraction
\(P=4, M=16, V=1\) \(3/19 =\) 15.8%
\(P=4, M=16, V=2\) \(3/35 =\) 8.6%
\(P=8, M=32, V=1\) \(7/39 =\) 17.9%
\(P=16, M=16, V=1\) \(15/31 =\) 48.4% (unacceptable)

Keeping the bubble below 5% with standard 1F1B (\(V=1\)) requires \(M \geq 19 \times (P - 1)\) microbatches. Interleaved schedules (\(V \geq 2\)) cut this requirement proportionally.

2.5 Expert Parallelism (Mixture of Experts)

Intuition: Dense Transformers obey a strict “Iron Law”: doubling parameters doubles both memory and compute. Mixture of Experts (MoE) breaks this law by routing tokens to specific expert subnetworks. The memory bound is set by the total parameters, but the compute bound is set by the much smaller active parameters. The physical tradeoff is a network bandwidth tax (All-to-All communication) to route tokens across the cluster.

When \(\text{EP} > 1\), the solver adds an All-to-All communication penalty for token routing:

\[ T_{\text{all-to-all}} = (N-1) \cdot \alpha \;+\; \frac{N-1}{N} \cdot \frac{M}{\beta} \]

where \(N\) is the EP degree. Compared to AllReduce, All-to-All creates \(O(N^2)\) point-to-point connections, making it latency-sensitive. A 4 KB token routing message is latency-bound, while a 140 GB gradient sync is bandwidth-bound.

MoE routing is rarely perfectly balanced. MLSys·im exposes a single routing-imbalance factor \(\gamma \ge 1\):

\[ E_{\text{active,eff}} = \min(E_{\text{total}}, \gamma \cdot E_{\text{top-k}}) \]

\[ P_{\text{active,eff}} = P_{\text{active}} \cdot \frac{E_{\text{active,eff}}}{E_{\text{top-k}}} \]

MoERoutingModel reports the effective active experts, effective active parameters, routed bytes, and optional expert-parallel all-to-all latency. This is a first-order hot-expert proxy, not a router simulation; it is intended to capture the load-balancing concern surfaced by sparsely-gated MoE, GShard, and Switch-style systems [2], [3], [4].


3. Training Scaling Laws

Used by mlsysim.physics.calc_transformer_training_flops. Curriculum: Vol I, Ch 8: Model Training · Study sheet · Slides

The 6PD rule estimates total training FLOPs for a Transformer:

\[ C \approx 6 \times P \times D \]

Symbol Meaning
\(C\) Total training FLOPs
\(P\) Number of model parameters
\(D\) Number of training tokens

The factor of 6 is 2 FLOPs per parameter per token (forward pass multiply-accumulate) × 3 passes (forward + backward for weights + backward for activations). Combined with the roofline model (Section 1), this gives training time:

\[ T_{\text{train}} = \frac{6PD}{\text{Peak\_FLOP/s} \times \eta} \]

GPT-3 175B trained on 300B tokens:

  • Total FLOPs: \(6 \times 175 \times 10^9 \times 300 \times 10^9 = 3.15 \times 10^{23}\)
  • On 1,024 A100s (\(312\text{ TF each} \times 0.5\) MFU): \(3.15 \times 10^{23} / (1024 \times 312 \times 10^{12} \times 0.5) \approx 1.97 \times 10^6\text{ s} \approx 23\text{ days}\)

Narayanan et al. estimate about 34 days for this configuration [5]. The gap from 23 days is not a scaling loss. Their estimate counts 8 FLOPs per parameter per token, because activation recomputation repeats the forward pass, and it uses a measured 140 TFLOP/s per GPU (about 45% of peak), which already includes communication and pipeline losses.

3.1 Training Memory Accounting

Implemented in mlsysim.solvers.TrainingMemoryModel.

Inference memory is mostly weights plus KV cache. Training memory adds gradients, optimizer state, saved activations, and communication buffers:

\[ M_{\text{train}} = M_{\text{weights}} + M_{\text{grad}} + M_{\text{opt}} + M_{\text{act}} + M_{\text{comm}} \]

For mixed-precision Adam training, the default per-parameter state is:

Component Default bytes / parameter ZeRO sharding
Weights 2 Stage 3
Gradients 2 Stage 2+
Adam optimizer state 12 Stage 1+

Tensor, pipeline, and expert parallelism first shard the model states across model-parallel ranks. ZeRO then shards data-parallel states [6]. Activation memory scales with local microbatch size, sequence length, hidden dimension, and the chosen activation-checkpointing strategy [7].


4. LLM Serving Lifecycle

Implemented in mlsysim.solvers.ServingModel. Curriculum: Vol I, Ch 13: Model Serving (Study sheet · Slides) | Vol II, Ch 10: Serving at Scale (Study sheet · Slides)| Vol III, Ch 5: KV Cache Management

LLM autoregressive inference has two physically distinct phases. Capacity planning depends on knowing which phase dominates.

4.1 Pre-fill Phase (Compute-Bound)

The initial forward pass processes all prompt tokens in parallel, combining linear projection work (\(2 P S B\)) with quadratic self-attention matrix products across \(L\) layers of attention width \(d_{\text{attn}}\):

\[ \text{TTFT} = \frac{\left(2 P S + c_{\text{attn}} L d_{\text{attn}} S^2\right) B}{\text{Peak\_FLOP/s} \times \eta} + \text{Dispatch\_Tax} \]

Symbol Meaning
\(P\) Number of model parameters
\(S\) New prompt tokens processed (\(S - S_{\text{cache}}\) when prefix caching is active)
\(B\) Batch size
\(L, d_{\text{attn}}\) Transformer layer count and query-attention width (\(H \times d_{\text{head}}\))
\(c_{\text{attn}}\) \(2\) for causal autoregressive attention (causal=True, default); \(4\) for full bidirectional attention (causal=False)

The linear factor of 2 counts both the multiply and the add in each multiply-accumulate (MAC) operation; causal masking halves the \(4 L d_{\text{attn}} S^2\) full-matrix \(\mathbf{Q}\mathbf{K}^\top\) and \(\mathbf{A}\mathbf{V}\) products over an uncached prompt (with cached prefix \(S_{\text{cache}} > 0\), each new query also attends across the cached keys).

4.2 Decoding Phase (Compute and Memory Bounds)

Each decode step streams model weights and the filled KV cache. The solver compares that memory time with the time needed for linear layers and attention:

\[ T_m = \frac{|W|+M_{\mathrm{KV}}}{\mathrm{BW}} \]

Here \(|W|\) is the weight payload, \(M_{\mathrm{KV}}\) is filled KV storage, and \(\mathrm{BW}\) is memory bandwidth. With compute time \(T_c\):

\[ \mathrm{ITL}=\max(T_c,T_m)+T_{\mathrm{layer}}. \]

The compute term divides forward operations by the precision-specific peak FLOP/s times the declared compute efficiency. It includes both attention matrix products. Batch-one decode is commonly memory-limited; larger batches amortize weight reads and can become compute-limited. ServingModel and ContinuousBatchingModel share this accounting. Efficiency does not derate memory bandwidth, and the layer tax is an explicit runtime assumption.

Single-token decode, batch=1 (70.6B parameters, 141.2 GB in FP16):

  • Compute: 2 × 70.6 B ÷ 989 TFLOP/s = 0.14 ms (0.3% of memory time)
  • Memory: 141.2 GB ÷ 3.35 TB/s = 42.1 ms
  • Weight-only bandwidth floor: ~42 ms/token → ~24 tokens/s

This weight-only floor excludes KV traffic, runtime overhead, and inter-device communication. The model does not fit on a single H100 at this precision, so these terms are a bandwidth illustration, not a feasible single-device serving prediction.

Source: Compute Infrastructure slides (Vol II, Ch 2).

4.3 KV-Cache Size

\[ \text{KV\_Bytes} = 2 \times L \times H_{\text{kv}} \times d_{\text{head}} \times S \times B \times b_{\text{elem}} \]

Symbol Meaning
\(L\) Number of Transformer layers
\(H_{\text{kv}}\) Number of KV attention heads (equals \(H\) for MHA; smaller for GQA/MQA)
\(d_{\text{head}}\) Dimension per head
\(S\) Sequence length
\(B\) Batch size
\(b_{\text{elem}}\) Bytes per element (2 for FP16/BF16)

The factor of 2 accounts for both the K and V tensors. With Grouped-Query Attention (GQA), \(H_{\text{kv}} < H\), which reduces cache size. Llama-3 70B uses 8 KV heads vs. 64 query heads, an 8× reduction.

Llama-3 70B: 80 layers, 8 KV heads (GQA), \(d_{\text{head}} = 128\), FP16:

  • Per-token: \(2 \times 80 \times 8 \times 128 \times 2 = 327.7\text{ KB}\)
  • Batch=16, seq=4096: \(327.7\text{K} \times 16 \times 4096 = 21.5\text{ GB}\)
  • Batch=32, seq=4096: \(327.7\text{K} \times 32 \times 4096 = 42.9\text{ GB}\)

Weights (35.3 GB at INT4) + KV-cache (42.9 GB at FP16) = 78.2 GB, which barely fits on an 80 GiB H100. At batch=64 or longer contexts, the model must be sharded across multiple GPUs.

Source: Inference at Scale slides (Vol II, Ch 10).

4.4 Chunked Prefill and Decode Interference

Production serving systems often mix new prefill work with ongoing decode iterations. Long prefills can stall decode unless the scheduler bounds the amount of prefill work admitted per iteration. MLSys·im models this with an optional prefill chunk size. Let \(S_{\text{new}} = S - S_{\text{cache}}\), with \(0 \le S_{\text{cache}} < S\) and \(S_{\text{chunk}} > 0\):

\[ C = \left\lceil \frac{S_{\text{new}}}{S_{\text{chunk}}} \right\rceil \]

\[ \text{TTFT}_{\text{chunked}} = \text{TTFT}_{\text{compute}} + C \times \text{Dispatch\_Tax} \]

\[ \text{Decode\_Stall}_{\max} \approx \max_i\left(T_{\text{chunk},i}\right) \]

Here \(T_{\text{chunk},i}\) is the compute time for chunk \(i\) plus one dispatch tax.

Symbol Meaning
\(C\) Number of prefill chunks
\(S_{\text{new}}\) Prompt tokens that still require prefill computation
\(S_{\text{cache}}\) Prompt tokens already covered by prefix caching
\(S_{\text{chunk}}\) Maximum prefill tokens admitted per scheduler iteration

This estimates a coarse scheduling proxy used by chunked-prefill systems: smaller chunks do not reduce total prefill compute, but they reduce the largest decode stall caused by a co-scheduled prefill. MLSys·im does not implement Sarathi-Serve’s full scheduler. Disaggregated systems such as Splitwise and DistServe mitigate prefill/decode interference by assigning the phases to separate resources, trading scheduler interference for KV-cache transfer and resource-partitioning costs [8], [9], [10].

4.5 KV Allocation and Batch Capacity

Implemented in mlsysim.solvers.ContinuousBatchingModel.

Batching amortizes weight reads across requests, and the KV-cache allocator determines how many requests fit. Throughput gains stop scaling when compute becomes the limiting resource. Let \(M_{\text{KV}}\) be the HBM left after the weights and \(k\) the KV bytes per token (KV-Cache Size). A static allocator reserves the maximum sequence length \(S_{\max}\) for every request. A paged allocator divides the budget into blocks of \(p\) tokens and hands a request of \(S\) tokens \(\lceil S/p \rceil\) of them on demand:

\[ N_{\text{static}} = \left\lfloor \frac{M_{\text{KV}}}{k\,S_{\max}} \right\rfloor \qquad N_{\text{paged}} = \left\lfloor \frac{\lfloor M_{\text{KV}} / (k\,p) \rfloor}{\mathbb{E}\left[\lceil S/p \rceil\right]} \right\rfloor \]

The scheduler’s maximum batch size caps both. Request lengths are \(S = \min(X, S_{\max})\) with \(X\) exponential, scaled so that \(\mathbb{E}[S] = \bar{S}\): most requests are short, and the rare long one is cut off at the context window. Summing tail probabilities gives the expected block count in closed form

\[ \mathbb{E}\left[\lceil S/p \rceil\right] = \sum_{j=0}^{K-1} P(S > jp) = \frac{1 - r^{K}}{1 - r}, \qquad r = e^{-p/\mu},\quad K = \lceil S_{\max}/p \rceil \]

The unused share of each allocation (internal fragmentation) is \(1 - \bar{S}/S_{\max}\) for static reservation and \(1 - \bar{S}/\left(p\,\mathbb{E}[\lceil S/p \rceil]\right)\) for paging. The paged tail averages about \(p/2\) tokens per request, so page size matters even when \(S_{\max}\) divides evenly by \(p\). Memory-bound decode streams only the tokens requests have filled, so for either allocator

\[ T_m = \frac{|W| + N\,\bar{S}\,k}{\mathrm{BW}} \]

Using the compute/memory maximum and layer overhead from Decoding Phase,

\[ R_{\text{tok}} = \frac{N}{t_{\text{step}}} \]

and speedup_vs_static is \(R_{\text{tok}}\) at \(N_{\text{paged}}\) divided by \(R_{\text{tok}}\) at \(N_{\text{static}}\).

Symbol Meaning
\(M_{\text{KV}}\) HBM capacity left for the KV cache after the weights
\(k\) KV bytes per token
\(S_{\max}\) Longest context a request may reach (max_seq_len)
\(\bar{S}\) Mean tokens a request fills (mean_request_tokens; defaults to \(S_{\max}\))
\(p\) Block (page) size in tokens (page_size)
\(\mu\) Exponential scale chosen so that \(\mathbb{E}[\min(X, S_{\max})] = \bar{S}\)

FP16 KV costs \(k = 131\,072\) bytes per token, so the H100’s KV budget holds about 532,831 tokens. With \(S_{\max} = 8192\) and \(\bar{S} = 2048\):

  • Static reservation: \(\lfloor 532\,831 / 8192 \rfloor = 65\) requests, with 75% of every reservation unused
  • Paged, \(p = 16\): about 128.5 blocks per request, so 259 requests with 0.4% unused
  • Paged, \(p = 2048\): 165 requests with 36% unused
  • Decode throughput: paged at \(p = 16\) runs about 1.56× static

Allocation policy matters only when memory binds. If the scheduler caps the batch below 65, both allocators admit the same requests and the speedup is 1.

Source: ContinuousBatchingModel. The Monte Carlo allocators in the KV-cache tutorial admit the same 65 and 259 requests; the tutorial’s throughput ratio is lower because its single random draw happens to give the first 65 requests a below-average length.

Kwon et al. profile contiguous pre-allocation and find that only 20.4% to 38.2% of KV-cache memory holds token states. The rest is reserved slots for future tokens, internal fragmentation from over-provisioning for the maximum length, and external fragmentation from the allocator. PagedAttention limits each request’s waste to one block [11]. The static baseline here is max-length reservation, which captures the first two kinds of waste and is modeled without external fragmentation. Exact-size and power-of-two contiguous allocators, which trade reservation waste for external fragmentation, are not modeled. Sizing both allocators with every request at its full length is a peak-occupancy view: a request mid-generation holds fewer paged blocks, so paged capacity is conservative.

4.6 Serving Capacity Planning

Implemented in mlsysim.solvers.ServingCapacityModel.

Capacity planning composes three first-order quantities:

  1. base request latency from ServingModel;
  2. per-replica token throughput from ContinuousBatchingModel;
  3. queueing delay from TailLatencyModel.

For an average response length \(G\) tokens and per-replica decode throughput \(R_{\text{tok}}\), the first-order request capacity is:

\[ Q_{\text{replica}} = \frac{R_{\text{tok}}}{G} \]

The required replica count is the smallest \(c\) such that traffic intensity remains stable and:

\[ P99_{\text{request}} \approx T_{\text{base}} + P99_{\text{queue}}(Q, Q_{\text{replica}}, c) \le T_{\text{target}} \]

Per-replica throughput \(R_{\text{tok}}\) comes from paged allocation in KV Allocation and Batch Capacity, so passing mean_request_tokens below max_seq_len raises the batch each replica can hold. Base latency is then evaluated at the mean request length. This is deliberately a capacity model. It does not simulate request arrivals, preemption, or scheduler internals.

4.7 Serving Cost Dominance

At production scale, serving costs dominate training:

\[ C_{\text{total}} = C_{\text{training}} + C_{\text{serving}} \times T_{\text{deploy}} \times Q_{\text{rate}} \]

As an illustrative example, a 70B model costing $2M to train and serving 1M daily users at 50 requests/day (\(18.25\text{B}\) requests/year) at an assumed $0.001/request costs ~$18.3M/year in inference — ~9× the training cost in year one. This is why inference optimization (batching, quantization, speculative decoding) has outsized economic impact.


5. Datacenter Sustainability

Implemented in mlsysim.solvers.SustainabilityModel. Curriculum: Vol II, Ch 15: Sustainable AI · Study sheet · Slides

5.1 Total Energy

\[ P_{\text{chip}} = P_{\text{TDP}}\left(0.30 + 0.70 \cdot \text{MFU}\right), \qquad E_{\text{IT}} = N_{\text{chip}} P_{\text{chip}} \times \text{Hours}, \qquad E = E_{\text{IT}} \times \text{PUE} \]

Power Usage Effectiveness (PUE) accounts for cooling and facility overhead, while energy proportionality models idle silicon draw (~30% of TDP) plus dynamic switching power (~70% of TDP scaled by MFU). A PUE of 1.0 is theoretical perfect efficiency; hyperscale datacenters achieve 1.05–1.12 (liquid-cooled) to 1.4–1.6 (air-cooled). A facility PUE of 1.58 means 37% of total facility energy goes to cooling and power distribution rather than computation.

5.2 Carbon Footprint

\[ C = \frac{E \times \text{Carbon\_Intensity}}{1000} + C_{\text{embodied}} \]

Where operational carbon \(C\) is in kg CO₂e, \(E\) is in kWh, Carbon_Intensity is in g CO₂e/kWh (divided by 1,000 for kg), and \(C_{\text{embodied}}\) is hardware manufacturing carbon (kg CO₂e).

5.3 Water Usage Effectiveness (WUE)

\[ W = E_{\text{IT}} \times \text{WUE}_{\text{site}} \]

Per the Green Grid standard, site-based Water Usage Effectiveness (\(\text{WUE}_{\text{site}}\), in liters/kWh) is normalized against IT equipment energy (\(E_{\text{IT}}\)), not PUE-inflated total facility energy (\(E\)), so cooling overhead is never double-counted. For example, 8,602 kWh of IT energy at a hyperscale \(\text{WUE}_{\text{site}} = 1\.8\) L/kWh consumes 15,483 L of cooling water.

64 GPUs × 400W × 336 hours = 8,602 kWh. With PUE 1.2 = 10,322 kWh.

Grid Region Carbon Intensity CO₂ Emissions
Quebec (hydro) 20 g/kWh 206 kg
US Average 429 g/kWh 4,428 kg
Poland (coal) 820 g/kWh 8,464 kg

Geographic choice alone creates a ~41× difference for identical workloads. Combined with hardware choice (5×) and quantization (4×), the total optimization lever is up to 800×.

Source: Sustainable AI slides (Vol II, Ch 15).


6. Total Cost of Ownership (TCO)

Implemented in mlsysim.solvers.EconomicsModel. Curriculum: Vol II, Ch 2: Compute Infrastructure · Study sheet · Slides

\[ \text{TCO} = \underbrace{\frac{\text{Hardware\_Cost}}{\text{Depreciation\_Years}} \times \frac{\text{Duration\_Days}}{365}}_{\text{CapEx (prorated)}} + \underbrace{E \times \text{Electricity\_Rate}}_{\text{OpEx (power)}} + \underbrace{\text{Hardware\_Cost} \times r_{\text{maint}} \times \frac{\text{Duration\_Days}}{365}}_{\text{OpEx (maintenance)}} \]

Metric On-Prem (H100 Node) Cloud On-Demand
Unit cost $350K (amortize over 3 yr + 5%/yr maint.) N/A
Annual cost (80% util) ~$140K/node/yr ~$224K/node/yr
Effective GPU-hour rate ~$2.49 ~$4.00

Break-even occupancy: ~49%. Below 49% sustained occupancy, cloud is cheaper. At 20% occupancy, on-prem costs ~$9.78/GPU-hour, which is more expensive than cloud on-demand.

The right metric is cost per useful TFLOP-hour, not cost per GPU-hour. An H100 delivers 3.2× the FP16 TFLOP/s of an A100 (or 6.3× comparing H100 FP8 to A100 FP16), so a higher sticker price may yield a lower effective cost.

Source: Compute Infrastructure slides (Vol II, Ch 2).


7. Cluster Reliability (The Young-Daly Model)

Implemented in mlsysim.solvers.ReliabilityModel. Curriculum: Vol II, Ch 7: Fault Tolerance · Study sheet · Slides

Intuition: When training on thousands of GPUs for months, hardware failures are a statistical certainty. If a node fails, the job loses all progress since the last checkpoint. Checkpointing too often wastes time writing; checkpointing too rarely wastes time recomputing. The Young-Daly model finds the optimal balance.

7.1 Cluster MTBF

Individual component reliability degrades linearly with scale:

\[ \text{MTBF}_{\text{cluster}} = \frac{\text{MTBF}_{\text{component}}}{N} \]

Cluster Size (\(N\)) System MTBF (50,000 hr/GPU)
8 GPUs ~8 months
1,000 GPUs 50 hours
10,000 GPUs 5 hours
16,000 GPUs ~3 hours (Llama-3 scale: 419 failures in 54 days)

7.2 Optimal Checkpoint Interval

\[ \tau_{\text{opt}} = \sqrt{2 \times \delta \times M} \]

Symbol Meaning
\(\delta\) Time to write one checkpoint
\(M\) Mean Time Between Failures (cluster MTBF)

7.3 Wasted Compute Fraction

The first-order fraction of wall-clock time lost to checkpointing and rollback recovery has two components:

\[ \text{Waste}(\tau) = \underbrace{\frac{\delta}{\tau}}_{\text{checkpoint writes}} + \underbrace{\frac{\tau}{2M}}_{\text{lost work on failure}} \]

Setting \(\frac{d}{d\tau}\text{Waste}(\tau) = -\frac{\delta}{\tau^2} + \frac{1}{2M} = 0\) yields \(\tau_{\text{opt}} = \sqrt{2 \delta M}\), at which both terms equal \(\sqrt{\frac{\delta}{2M}}\) and total waste is minimized at \(\sqrt{\frac{2\delta}{M}}\).

16,384 GPUs, \(\delta = 2\) min, cluster MTBF \(M = 180\) min:

\[\tau_{\text{opt}} = \sqrt{2 \times 2 \times 180} = \sqrt{720} \approx 27\text{ min}\]

Checkpoint Interval (\(\tau\)) Write + Rollback Waste
10 min (too frequent) 22.8%
27 min (optimal) 14.9%
60 min (too rare) 20.0%

On a cluster costing $10M/month, 14.9% synchronous waste equals ~$1.5M/month. Asynchronous checkpointing (staging state to host DRAM in seconds so effective \(\delta \ll 2\) min) cuts the checkpoint write stall dramatically.

Source: Fault Tolerance (Vol II, Ch 7) and Young (1974).


8. Failure Probability

Implemented in mlsysim.physics.calc_failure_probability.

The probability of at least one failure during a job of duration \(T\) follows an exponential model:

\[ P(\geq 1\text{ failure}) = 1 - e^{-T / \text{MTBF}} \]

For a 30-day training run on a cluster with MTBF of 5 hours: \(P = 1 - e^{-720/5} \approx 1.0\), so failure is virtually certain. This is why checkpointing (Section 7) is not optional at scale.


9. Effective FLOPS (Fleet Goodput)

Implemented in mlsysim.physics.calc_effective_flops. Curriculum: Vol II, Ch 9: Fleet Efficiency · Study sheet · Slides

The actual useful computation delivered by a fleet after all overheads:

\[ \text{Effective\_FLOP/s} = \text{Peak\_FLOP/s} \times \underbrace{\text{MFU}}_{\text{per-GPU}} \times \underbrace{\eta_{\text{scale}}}_{\text{comm overhead}} \times \underbrace{\frac{\text{Goodput}}{\text{Rawput}}}_{\text{failure waste}} \]

Each factor in the cascade represents a distinct loss mechanism. Illustrative ranges for large-scale training: MFU ≈ 0.30–0.50, \(\eta_{\text{scale}}\) ≈ 0.40–0.85, Goodput/Rawput ≈ 0.85–0.97. Their product means a fleet delivers roughly 10–41% of its theoretical peak.


10. Compression, Privacy & Cyber-Physical Extensions

  • Group Quantization (CompressionModel, Vol I, Ch 10): With \(b_{\text{scale}}\)-bit group scales per \(g\) weights, effective bitwidth is \(b_{\text{eff}} = b_{\text{target}} + b_{\text{scale}} / g\), and compression against \(b_0\)-bit baseline weights is \(b_0 / b_{\text{eff}}\).
  • Subsampled Gaussian DP-SGD (ResponsibleEngineeringModel, Vol I, Ch 15): Under Poisson subsampling rate \(q\) over \(T\) steps for \((\varepsilon, \delta)\)-DP, the first-order Gaussian noise multiplier is \(\sigma = \frac{q\sqrt{2T\ln(1.25/\delta)}}{\varepsilon}\) [12], while per-sample gradient clipping multiplies step latency by \(1 + \text{clipping\_step\_overhead}\).
  • Agentic & Embodied Physics (mlsysim.physics.agents, mlsysim.physics.robotics): Closed-form equations for horizon success compounding (\(p^H\)), accepted-task economics, kinematic stopping envelopes (\(d_{\text{stop}} = v \tau + \frac{v^2}{2 a_{\text{eff}}}\)), phase-lag stability margins, and deterministic fieldbus cycle bounds.Covered in Volume III: Agents and Volume IV: Physical AI.

NoteLimitations of First-Order Models

These equations are first-order analytical models. They assume: (1) aggregate memory traffic, (2) no explicit cache hierarchy, (3) no network contention under heavy load, and (4) idealized overlap of compute and memory. Batching throughput is bounded by both compute and memory capacity.

Real systems deviate from these assumptions. Use MLSys·im to reason about bottlenecks and compare configurations under stated assumptions. Calibration checks do not establish an accuracy guarantee for unseen workloads. See Calibration and validation scope for executable checks and their limitations.


References

The equations above are grounded in the following peer-reviewed sources:

  1. Williams, Waterman & Patterson (2009). “Roofline: An Insightful Visual Performance Model for Multicore Architectures.” Communications of the ACM. → Section 1
  2. Kaplan et al. (2020). “Scaling Laws for Neural Language Models.” arXiv:2001.08361. → Section 3
  3. Narayanan et al. (2021). “Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM.” SC ’21. → Section 2.4
  4. Shoeybi et al. (2019). “Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism.” arXiv:1909.08053. → Section 2
  5. Patarasuk & Yuan (2009). “Bandwidth Optimal All-Reduce Algorithms for Clusters of Workstations.” Journal of Parallel and Distributed Computing. → Section 2.3
  6. Shazeer et al. (2017). “Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer.” ICLR. → Section 2.5
  7. Rajbhandari et al. (2020). “ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.” SC. → Section 3.1
  8. Korthikanti et al. (2023). “Reducing Activation Recomputation in Large Transformer Models.” MLSys. → Section 3.1
  9. Fedus, Zoph & Shazeer (2022). “Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity.” JMLR. → Section 2.5
  10. Lepikhin et al. (2020). “GShard: Scaling Giant Models with Conditional Computation and Automatic Sharding.” arXiv:2006.16668. → Section 2.5
  11. Young (1974). “A First-Order Approximation to the Optimum Checkpoint Interval.” Information Processing Letters. → Section 7
  12. Daly (2006). “A Higher Order Estimate of the Optimum Checkpoint Interval for Restart Dumps.” Future Generation Computer Systems. → Section 7
  13. Patterson et al. (2021). “Carbon Emissions and Large Neural Network Training.” arXiv:2104.10350. → Section 5
  14. Barroso, Clidaras & Hölzle (2018). “The Datacenter as a Computer.” Synthesis Lectures on Computer Architecture. → Section 6
Back to top

References

[1]
Z. Jiang et al., “MegaScale: Scaling large language model training to more than 10,000 GPUs,” in 21st USENIX symposium on networked systems design and implementation (NSDI 24), USENIX Association, 2024, pp. 745–760. Available: https://www.usenix.org/conference/nsdi24/presentation/jiang-ziheng
[2]
N. Shazeer et al., “Outrageously large neural networks: The sparsely-gated mixture-of-experts layer,” in International conference on learning representations (ICLR), OpenReview.net, 2017.
[3]
D. Lepikhin et al., “GShard: Scaling giant models with conditional computation and automatic sharding,” arXiv preprint arXiv:2006.16668, 2020, Available: https://arxiv.org/abs/2006.16668
[4]
W. Fedus, B. Zoph, and N. Shazeer, “Switch transformers: Scaling to trillion parameter models with simple and efficient sparsity,” Journal of Machine Learning Research, vol. 23, no. 120, pp. 1–39, 2022, Available: https://jmlr.org/papers/v23/21-0998.html
[5]
D. Narayanan et al., “Efficient large-scale language model training on GPU clusters using Megatron-LM,” in Proceedings of the international conference for high performance computing, networking, storage and analysis, ACM, 2021, pp. 1–15. doi: 10.1145/3458817.3476209.
[6]
S. Rajbhandari, J. Rasley, O. Ruwase, and Y. He, “ZeRO: Memory optimizations toward training trillion parameter models,” in SC20: International conference for high performance computing, networking, storage and analysis, IEEE, 2020, pp. 1–16. doi: 10.1109/sc41405.2020.00024.
[7]
V. A. Korthikanti et al., “Reducing activation recomputation in large transformer models,” Proceedings of Machine Learning and Systems, vol. 5, 2023, Available: https://proceedings.mlsys.org/paper_files/paper/2023/hash/80083951326cf5b35e5100260d64ed81-Abstract-mlsys2023.html
[8]
A. Agrawal, A. Panwar, J. Mohan, N. Kwatra, B. S. Gulavani, and R. Ramjee, “Efficient LLM inference via chunked prefills,” ACM SIGOPS Operating Systems Review, vol. 59, no. 1, pp. 9–16, 2025, doi: 10.1145/3759441.3759444.
[9]
P. Patel et al., “Splitwise: Efficient generative LLM inference using phase splitting,” in 2024 ACM/IEEE 51st annual international symposium on computer architecture (ISCA), IEEE, 2024, pp. 118–132. doi: 10.1109/isca59077.2024.00019.
[10]
Y. Zhong et al., “DistServe: Disaggregating prefill and decoding for goodput-optimized large language model serving,” in 18th USENIX symposium on operating systems design and implementation (OSDI 24), USENIX Association, Jul. 2024, pp. 193–210. Available: https://www.usenix.org/conference/osdi24/presentation/zhong-yinmin
[11]
W. Kwon et al., “Efficient memory management for large language model serving with PagedAttention,” in Proceedings of the 29th symposium on operating systems principles, ACM, 2023, pp. 611–626. doi: 10.1145/3600006.3613165.
[12]
M. Abadi et al., “Deep learning with differential privacy,” in Proceedings of the 2016 ACM SIGSAC conference on computer and communications security, in CCS ’16. ACM, 2016, pp. 308–318. doi: 10.1145/2976749.2978318.