Skip to main content

For Engineers & Researchers

Back-of-envelope estimates before provisioning hardware.

MLSys·im produces quick, type-safe analytical estimates for capacity planning, hardware selection, cost modeling, and sustainability analysis, in seconds and from specifications alone. Equations are documented and tied to the relevant literature; hardware registry specs come from datasheets where available.


Why Use Analytical Models

Before running expensive benchmarks or provisioning cloud instances, an engineer needs directional answers:

  • Will this model fit in GPU memory? Check before renting the GPU
  • Why does training fail when inference fits? Separate weights, gradients, optimizer state, and activations
  • What is the expected TTFT for my LLM? Estimate before building the serving stack
  • How many replicas do I need for a P99 target? Size serving capacity before benchmarking
  • What is the MoE routing tax? Sweep expert imbalance before choosing EP topology
  • How many H100s do I actually need? Model scaling efficiency before buying the cluster
  • What will this cost per year? TCO analysis before signing the contract
  • How often will my training job crash? Reliability modeling before committing to a 30-day run
  • What is the carbon footprint of this deployment? Quantify before the sustainability review

MLSys·im answers these in microseconds using first-order equations. It does not replace profiling, but it shows where to start profiling.

TipTheory Behind the Tools

Each solver implements equations from the Math Foundations page. For the full conceptual framework, see the companion slide decks linked in the Solver-to-Slides Map below.


Quick Start: Roofline Analysis

The Engine implements the Roofline Performance Model (Vol I · Ch 11: Hardware Acceleration · Study sheet · Slides, Williams et al. 2009) to classify workloads as compute-bound or memory-bound.

import mlsysim
from mlsysim import Engine

# Single-node: Is ResNet-50 memory-bound on A100?
profile = Engine.solve(
    model=mlsysim.Models.Vision.ResNet50,
    hardware=mlsysim.Hardware.Cloud.A100,
    batch_size=1, precision="fp16"
)
print(f"{profile.bottleneck}, {profile.latency.to('ms'):~.2f}")
print(f"MFU: {profile.mfu:.1%}, Arithmetic Intensity: {profile.arithmetic_intensity:~.2f}")
Compute, 0.07 ms
MFU: 38.9%, Arithmetic Intensity: 84.55 flop / B

The returned PerformanceProfile reports latency, throughput, bottleneck classification, Model FLOPs Utilization (MFU), arithmetic intensity, energy, and a feasibility flag, which together support a first-pass hardware assessment.


LLM Serving Analysis

The ServingModel models the two-phase LLM inference lifecycle (Vol I · Ch 13: Model Serving · Study sheet · Slides): compute-bound prefill and memory-bound autoregressive decoding on a single device.

import mlsysim
from mlsysim.solvers import ServingModel

serving = ServingModel()
fp16_res = serving.solve(
    model=mlsysim.Models.Language.Llama3_70B,
    hardware=mlsysim.Hardware.Cloud.H100,
    seq_len=4096, batch_size=1, precision="fp16",
)
int4_res = serving.solve(
    model=mlsysim.Models.Language.Llama3_70B,
    hardware=mlsysim.Hardware.Cloud.H100,
    seq_len=4096, batch_size=1, precision="int4",
)
print(f"FP16 on 1xH100 -> Feasible: {fp16_res.feasible} (Mem util: {fp16_res.memory_utilization:.0%})")
print(f"INT4 on 1xH100 -> Feasible: {int4_res.feasible} (Mem util: {int4_res.memory_utilization:.0%})")
print(f"INT4 TTFT: {int4_res.ttft.to('ms'):~.1f}, ITL: {int4_res.itl.to('ms'):~.2f}, KV-cache: {int4_res.kv_cache_size.to('GB'):~.2f}")
FP16 on 1xH100 -> Feasible: False (Mem util: 166%)
INT4 on 1xH100 -> Feasible: True (Mem util: 41%)
INT4 TTFT: 1214.1 ms, ITL: 10.64 ms, KV-cache: 0.34 GB

ServingModel immediately flags that unquantized FP16 Llama-3.1-70B exceeds a single 80 GB H100 (Feasible: False), whereas INT4 quantization fits comfortably on one H100 (or FP16 can be sharded across a multi-GPU node).


Hardware Sweep Pattern

Compare devices programmatically instead of reading datasheets:

import mlsysim
from mlsysim import Engine

model = mlsysim.Models.Vision.ResNet50

for hw in [mlsysim.Hardware.Cloud.H100,
           mlsysim.Hardware.Cloud.A100,
           mlsysim.Hardware.Cloud.T4,
           mlsysim.Hardware.Edge.JetsonOrinNX]:
    p = Engine.solve(model=model, hardware=hw, batch_size=32, precision="fp16")
    print(f"{hw.name:22s}  {p.bottleneck:10s}  {p.latency.to('ms'):>8.2f~}  {p.throughput.to('1/s').magnitude:>8.0f} img/s")
NVIDIA H100             Compute         0.54 ms     59189 img/s
NVIDIA A100             Compute         1.70 ms     18856 img/s
NVIDIA T4               Compute         8.10 ms      3949 img/s
NVIDIA Jetson Orin NX   Compute        21.19 ms      1510 img/s

Distributed Training Analysis

The DistributedModel models 4D parallelism (Vol II · Ch 6: Distributed Training · Study sheet · Slides) with communication overhead from collective reductions (Vol II · Ch 5: Collective Communication · Study sheet · Slides) and 1F1B pipeline bubbles.

import mlsysim
from mlsysim.solvers import DistributedModel

dist = DistributedModel()
result = dist.solve(
    model=mlsysim.Models.Language.Llama3_70B,
    fleet=mlsysim.Systems.Clusters.Research_256,
    batch_size=512, precision="fp16",
    tp_size=8, pp_size=4, microbatch_count=16
)
print(f"Scaling efficiency:  {result.scaling_efficiency:.1%}")
print(f"DP all-reduce:       {result.dp_communication_latency.to('ms'):~.1f}")
print(f"TP overhead:         {result.tp_communication_latency.to('ms'):~.1f}")
print(f"Pipeline bubble:     {result.bubble_fraction:.1%}")
print(f"Step latency:        {result.step_latency_total.to('ms'):~.1f}")
Scaling efficiency:  64.3%
DP all-reduce:       618.5 ms
TP overhead:         668.7 ms
Pipeline bubble:     15.8%
Step latency:        5453.7 ms

Tune tp_size, pp_size, and microbatch_count to find the parallelism configuration that maximizes scaling efficiency for a given cluster topology.


Composing Solvers for Real Questions

The core solvers are designed to chain. Three common engineering workflows follow.

Serving Llama-70B on H100s within budget

import math
import mlsysim
from mlsysim.solvers import EconomicsModel, ServingCapacityModel
from mlsysim.systems.types import Fleet

# Step 1: Size INT4 H100 replicas for 40 QPS under a 2,500 ms P99 SLA
cap = ServingCapacityModel().solve(
    model=mlsysim.Models.Language.Llama3_70B,
    hardware=mlsysim.Hardware.Cloud.H100,
    qps=40.0,
    target_p99_latency_ms=2500.0,
    max_seq_len=4096,
    mean_request_tokens=1024,
    output_tokens=256,
    precision="int4",
)

# Step 2: Pack replicas onto 8-GPU DGX H100 nodes and compute annual TCO
nodes_needed = math.ceil(cap.required_replicas / mlsysim.Systems.Nodes.DGX_H100.accelerators_per_node)
serving_fleet = Fleet(
    name="Serving Pod",
    node=mlsysim.Systems.Nodes.DGX_H100,
    count=nodes_needed,
    fabric=mlsysim.Systems.Fabrics.InfiniBand_NDR,
)
cost = EconomicsModel().solve(
    fleet=serving_fleet,
    duration_days=365,
    kwh_price=0.08,
)
print(f"Replicas needed: {cap.required_replicas} GPUs ({nodes_needed}x DGX H100 nodes)")
print(f"Annual TCO:      ${cost.tco_usd:,.0f} (CapEx ${cost.capex_usd:,.0f} + OpEx ${cost.total_opex_usd:,.0f})")
Replicas needed: 1024 GPUs (128x DGX H100 nodes)
Annual TCO:      $10,375,947 (CapEx $8,533,333 + OpEx $1,842,613)

Choosing a training region to minimize carbon

import mlsysim
from mlsysim.solvers import SustainabilityModel

sustain = SustainabilityModel()
for grid in [mlsysim.Infrastructure.Grids.Quebec, mlsysim.Infrastructure.Grids.US_Avg,
             mlsysim.Infrastructure.Grids.Poland]:
    r = sustain.solve(
        fleet=mlsysim.Systems.Clusters.Research_256,
        duration_days=30,
        datacenter=grid
    )
    carbon_tons = r.carbon_footprint.to("metric_ton").magnitude
    print(f"{grid.name:16s}  {carbon_tons:8.1f} tCO2e  "
          f"PUE={r.pue:.2f}  Water={r.water_usage_liters:,.0f} L")
Quebec (Hydro)         2.7 tCO2e  PUE=1.06  Water=0 L
US Average            62.0 tCO2e  PUE=1.12  Water=232,243 L
Poland (Coal)        167.2 tCO2e  PUE=1.58  Water=232,243 L

For the theory behind PUE, WUE, carbon intensity, and the energy hierarchy, see Vol II · Ch 15: Sustainable AI (Study sheet · Slides).

Reliability of a 30-day training run on 256 GPUs

import mlsysim
from mlsysim.solvers import ReliabilityModel

rel = ReliabilityModel()
result = rel.solve(
    fleet=mlsysim.Systems.Clusters.Research_256,
    job_duration_hours=720,       # 30 days
    checkpoint_time_s=120.0       # 2 minutes per checkpoint
)
print(f"Fleet MTBF:              {result.fleet_mtbf.to('hour'):~.1f}")
print(f"P(failure before done):  {result.failure_probability:.1%}")
print(f"Optimal ckpt interval:   {result.optimal_checkpoint_interval.to('minute'):~.1f}")
print(f"Expected failures:       {result.expected_failures:.1f}")
Fleet MTBF:              146.5 h
P(failure before done):  99.3%
Optimal ckpt interval:   187.5 min
Expected failures:       4.9

This solver implements the Young-Daly checkpoint model (Vol II · Ch 7: Fault Tolerance · Study sheet · Slides), which sets the optimal checkpoint interval for long training jobs.


Writing Custom Solvers

Subclass ForwardModel and return a frozen Pydantic result model to integrate cleanly with pipelines and differential explainers:

import pint
from pydantic import BaseModel, ConfigDict
from mlsysim.hardware.types import HardwareNode
from mlsysim.solvers import ForwardModel

class PowerEfficiencyResult(BaseModel):
    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)
    device: str
    flops_per_watt: pint.Quantity

class PowerEfficiencyModel(ForwardModel):
    def solve(self, hardware: HardwareNode) -> PowerEfficiencyResult:
        flops_per_watt = (hardware.compute.peak_flops / hardware.tdp).to("TFLOPs/s/kW")
        return PowerEfficiencyResult(device=hardware.name, flops_per_watt=flops_per_watt)

See Writing a Custom Solver for the full guide.


Type Safety

All quantities are pint.Quantity objects. Unit conversions are explicit, and dimensional errors are caught at runtime:

import mlsysim
hw = mlsysim.Hardware.Cloud.A100
print(hw.compute.peak_flops.to("TFLOPs/s"))
print(hw.memory.bandwidth.to("TB/s"))
try:
    hw.memory.bandwidth.to("second")
except Exception as err:
    print(f"{type(err).__name__}: bytes per second can never become seconds")
312.0 TFLOPs/s
2.039 TB/s
DimensionalityError: bytes per second can never become seconds

Pint catches physical-dimension mismatches (bytes per second can never become seconds). Since 2026-06, compute work also has its own pint dimension, so a bare .to("flop/s") on a bandwidth raises DimensionalityError directly, as does adding a FLOP rate to a memory bandwidth:

for label, attempt in [
    ("FLOP rate + bandwidth", lambda: hw.compute.peak_flops + hw.memory.bandwidth),
    ("bandwidth -> TFLOPs/s", lambda: hw.memory.bandwidth.to("TFLOPs/s")),
]:
    try:
        attempt()
        print(f"{label}: accepted (unexpected)")
    except Exception as err:
        print(f"{label}: {type(err).__name__}")
FLOP rate + bandwidth: DimensionalityError
bandwidth -> TFLOPs/s: DimensionalityError

Bytes, counts, parameters, and dollars remain dimensionless aliases, so MLSys·im additionally enforces unit-family checks at every schema boundary (require_unit_family in mlsysim.core.types) to keep those distinct. A field declared as memory bandwidth rejects a count rate, and vice versa.


Solver-to-Curriculum Map

Each MLSys·im solver maps to canonical chapters, study sheets, and lecture decks in the Machine Learning Systems textbook (see the Cross-Volume Textbook Map for all chapters and physics threads).

MLSys·im Solver What It Models Textbook · Study Sheet · Slides
Engine / SingleNodeModel Roofline analysis, compute vs. memory bottleneck Vol I · Ch 11: Hardware Acceleration (Study sheet · Slides)
CompressionModel Group quantization overhead, sparsity, accuracy delta Vol I · Ch 10: Model Compression (Study sheet · Slides)
ServingModel / ServingCapacityModel TTFT, ITL, KV-cache memory, QPS/P99 replica sizing Vol I · Ch 13: Model Serving (Study sheet · Slides), Vol II · Ch 10: Serving at Scale (Study sheet · Slides)
DistributedModel 4D parallelism, all-reduce, 1F1B pipeline bubbles Vol II · Ch 6: Distributed Training (Study sheet · Slides), Vol II · Ch 5: Collective Communication (Study sheet · Slides)
EconomicsModel CapEx, OpEx, total cost of ownership, cloud break-even Vol II · Ch 2: Compute Infrastructure (Study sheet · Slides)
SustainabilityModel Energy, carbon footprint, site water usage Vol II · Ch 15: Sustainable AI (Study sheet · Slides)
ReliabilityModel Fleet MTBF, Young-Daly checkpointing & waste Vol II · Ch 7: Fault Tolerance (Study sheet · Slides)

Volume I: Introduction to Machine Learning Systems

Read Vol I | Study Sheets | Slides | PDF Zip

Volume II: Scaling Machine Learning Systems

Read Vol II | Study Sheets | Slides | PDF Zip

Volume III: Agentic Machine Learning Systems

Preview Vol III

Volume IV: Physical AI: Machine Learning Systems That Sense and Act

Preview Vol IV


Next Steps

Back to top