engine.solvers.training
engine.solvers.training
Training memory, checkpointing, and scaling-law solvers.
Domain implementations behind mlsysim.solvers (the public import path, derived from engine.solvers.__init__); kept per-domain so the logic stays reviewable.
Classes
| Name | Description |
|---|---|
| CheckpointModel | Analyzes the storage constraints and I/O burst penalties of saving model states. |
| ScalingModel | Analyzes the ‘Scaling Physics’ of model training (Chinchilla Laws). |
| TrainingMemoryModel | Decomposes per-accelerator training memory into teachable components. |
| TrainingRunModel | Wall-clock time of a training run, from peak throughput to delivered time. |
| TrainingStateModel | Persistent mixed-precision Adam state and how parallelism shards it. |
CheckpointModel
engine.solvers.training.CheckpointModel()Analyzes the storage constraints and I/O burst penalties of saving model states.
Training massive models requires saving hundreds of gigabytes (Weights + Optimizer States) to persistent storage. This model calculates the time spent blocked on I/O, subtracting from the cluster’s Model FLOPs Utilization.
Literature Source: 1. Eisenman et al. (2022), “Check-N-Run: A Checkpointing System for Training Large Language Models.”
Methods
| Name | Description |
|---|---|
| solve | Estimate synchronous checkpoint size, write time, and stall fraction. |
solve
engine.solvers.training.CheckpointModel.solve(
model,
hardware,
optimizer='adam',
checkpoint_interval_hours=4.0,
n_writers=1,
filesystem_limit_gbs=500.0,
)Estimate synchronous checkpoint size, write time, and stall fraction.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| model | Workload | Workload whose parameter count sets the checkpoint payload. | required |
| hardware | HardwareNode | Device with storage bandwidth in bytes/second. Missing or zero storage bandwidth uses the declared fallback in engine.calibration. |
required |
| optimizer | str | "adam" selects mixed-precision Adam checkpoint bytes; other names use the SGD convention. Gradients are not persisted. |
'adam' |
| checkpoint_interval_hours | float | Hours between checkpoints. A nonpositive interval returns a stall fraction of one; positive intervals use write time divided by interval. | 4.0 |
| n_writers | int | Positive number of writers sharing the checkpoint payload. | 1 |
| filesystem_limit_gbs | float | Positive aggregate filesystem ceiling in decimal GB/second. | 500.0 |
Returns
| Name | Type | Description |
|---|---|---|
| CheckpointResult | Checkpoint size in GB, write duration in seconds, and a dimensionless stall fraction in mfu_penalty_pct (not multiplied by 100). storage_bottleneck flags writes longer than one minute; it does not certify that a checkpoint schedule fits the interval. |
See Also
mlsysim.physics.memory.calc_checkpoint_size : Persisted state accounting.
Notes
Equation: M = P b; bandwidth = min(n_writers * device_bandwidth, filesystem_limit); write_time = M / bandwidth. The penalty is write_time / checkpoint_interval for a positive interval.
Assumptions: writers partition one payload without duplicated writes; checkpointing synchronously blocks useful training. Byte conventions come from engine.calibration and are separate from storage rates.
Excludes: asynchronous overlap, filesystem metadata, serialization CPU work, network contention, and checkpoint recovery. The penalty can exceed one when a write takes longer than its configured interval.
References
Derivation: payload size is parameter count times persisted bytes per parameter; elapsed transfer time is payload divided by available rate. The writer minimum is a shared-bandwidth capacity constraint.
Examples
>>> from mlsysim import Models, Hardware
>>> result = CheckpointModel().solve(Models.Language.Llama3_8B, Hardware.Cloud.H100)
>>> result.checkpoint_size.to("GB").magnitude > 0
True
>>> result.write_time_seconds.to("second").magnitude > 0
TrueScalingModel
engine.solvers.training.ScalingModel()Analyzes the ‘Scaling Physics’ of model training (Chinchilla Laws).
This model determines the optimal model size (P) and dataset size (D) given a compute budget (C), following the compute-optimal training regime where D ≈ 20P.
Literature Source: 1. Hoffmann et al. (2022), “Training Compute-Optimal Large Language Models.” 2. Kaplan et al. (2020), “Scaling Laws for Neural Language Models.” 3. McCandlish et al. (2018), “An Empirical Model of Large-Batch Training.”
Methods
| Name | Description |
|---|---|
| solve | Allocate a training compute budget between parameters and tokens. |
solve
engine.solvers.training.ScalingModel.solve(
compute_budget,
target_model_size=None,
)Allocate a training compute budget between parameters and tokens.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| compute_budget | Quantity | Finite positive training work in FLOPs, or a finite positive duration interpreted as reference-H100 compute time at the declared sustained efficiency. Any compatible FLOP prefix is accepted and normalized before calculation. | required |
| target_model_size | Quantity | Finite positive fixed parameter count. If omitted, use the registered compute-optimal tokens-per-parameter ratio. | None |
Returns
| Name | Type | Description |
|---|---|---|
| ScalingResult | Modeled parameter and token counts, compute budget, and dimensionless tokens per parameter. The result does not include a quality estimate or a memory-feasibility decision. |
Notes
Equation: C = k P D, where k is the registered compute coefficient. With D = r P, P = sqrt(C / (k r)); when P is fixed, D = C / (k P). A time input becomes C = duration * reference_peak * reference_MFU.
Assumptions: parameter-dominated dense training work and a constant registered optimal token ratio. The time conversion uses a declared reference accelerator rather than an arbitrary fleet supplied by a user.
Excludes: inference cost, data-quality variation, architecture-dependent loss prediction, attention work, and hardware memory capacity.
References
Hoffmann et al. (2022), “Training Compute-Optimal Large Language Models.” https://arxiv.org/abs/2203.15556 (bibliography key: hoffmann2022chinchilla). The fixed-ratio allocation is the package’s simplified accounting form.
Examples
>>> result = ScalingModel().solve(Q_(1200000, "flop"))
>>> result.optimal_parameters.to("count").magnitude > 0
True
>>> result.optimal_tokens.to("count").magnitude > 0
TrueTrainingMemoryModel
engine.solvers.training.TrainingMemoryModel()Decomposes per-accelerator training memory into teachable components.
This model answers a different question than SingleNodeModel. Roofline feasibility asks whether a workload’s inference weights fit; training feasibility must also account for gradients, optimizer state, activations, and communication buffers. The accounting follows the common mixed-precision state breakdown used by Megatron-LM and ZeRO.
Literature Source: 1. Shoeybi et al. (2019), “Megatron-LM” (tensor/pipeline parallel state). 2. Rajbhandari et al. (2020), “ZeRO” (data-parallel state sharding). 3. Korthikanti et al. (2023), activation recomputation accounting.
Formula contract: - parameter states are sharded by TP * PP * EP before ZeRO sharding. - ZeRO-1 shards optimizer state, ZeRO-2 also shards gradients, and ZeRO-3 also shards weights across DP. - activation memory is based on local microbatch, layers per pipeline stage, hidden dimension, and the actual bytes per element for the precision.
Methods
| Name | Description |
|---|---|
| solve | Estimate per-accelerator training memory from local state and activations. |
solve
engine.solvers.training.TrainingMemoryModel.solve(
model,
hardware,
batch_size,
seq_len=2048,
precision='fp16',
optimizer='adam',
activation_checkpointing='selective',
tp_size=1,
pp_size=1,
dp_size=1,
ep_size=1,
zero_stage=0,
gradient_accumulation_steps=1,
trainable_fraction=1.0,
communication_buffer_fraction=0.05,
sequence_parallel=True,
)Estimate per-accelerator training memory from local state and activations.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| model | TransformerWorkload | Parameter count, layer count, hidden width, and attention-head geometry. | required |
| hardware | HardwareNode | Device memory capacity used for the residency comparison. | required |
| batch_size | int | Global sequence count per update; must be at least one. | required |
| seq_len | int | Tokens per sequence; must be at least one. | 2048 |
| precision | str | Parameter and gradient storage precision, resolved to bytes/element. | 'fp16' |
| optimizer | str | Optimizer storage convention supported by optimizer_state_bytes. |
'adam' |
| activation_checkpointing | ('none', 'selective', 'full') | Activation retention strategy passed to the activation-memory model. | 'none' |
| tp_size | int | Tensor-parallel degree, at least one. | 1 |
| pp_size | int | Pipeline-parallel degree, at least one. | 1 |
| dp_size | int | Data-parallel degree, at least one. | 1 |
| ep_size | int | Expert-parallel degree, at least one. | 1 |
| zero_stage | (0, 1, 2, 3) | Cumulative DP sharding: optimizer state, then gradients, then weights. | 0 |
| gradient_accumulation_steps | int | Positive number of sequential microbatches per update. | 1 |
| trainable_fraction | float | Fraction in [0, 1] receiving gradients and optimizer state. | 1.0 |
| communication_buffer_fraction | float | Gradient staging buffer as a fraction in [0, 1] of local gradients. | 0.05 |
| sequence_parallel | bool | If true, split stored activations across the TP group. If false, retain the unsharded activation estimate as a conservative bound. | True |
Returns
| Name | Type | Description |
|---|---|---|
| TrainingMemoryResult | Weights, gradients, optimizer state, activations, buffers, and total memory in GB. feasible compares that modeled total with device capacity; it excludes unmodeled runtime reserves. |
See Also
mlsysim.physics.memory.calc_activation_memory : Activation retention model. mlsysim.physics.memory.optimizer_state_bytes : Optimizer storage convention.
Notes
Equation: total = weights + gradients + optimizer + activations + communication_buffers. Parameter state first shards via model.sharded_parameter_count(tp_size, pp_size, ep_size) (splitting shared MoE parameters by TP * PP and routed experts by TP * PP * EP); ZeRO then divides selected terms by DP. Local microbatch is max(1, ceil(global_batch / (DP * accumulation_steps))). Layers per stage are max(1, ceil(layers / PP)). Activation bytes follow calc_activation_memory and divide by TP when sequence parallelism is enabled. Buffers contain a gradient fraction plus send/receive pipeline boundary activations.
Assumptions: balanced parameter sharding and uniform layer geometry. The precision byte count rescales the activation model’s FP16 baseline. ZeRO stages are cumulative. Trainable fraction affects gradients and optimizer state but not resident weights.
Excludes: allocator reserves, implementation workspaces, fragmentation, uneven expert placement, and detailed interleaved pipeline lifetimes. A capacity pass does not guarantee a runnable deployment.
References
Rajbhandari et al. (2020), “ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.” https://arxiv.org/abs/1910.02054 (bibliography key: rajbhandari2020). Korthikanti et al. (2023), “Reducing Activation Recomputation in Large Transformer Models.” https://arxiv.org/abs/2205.05198 (bibliography key: korthikanti2023).
Examples
>>> from mlsysim import Models, Hardware
>>> result = TrainingMemoryModel().solve(Models.Language.Llama3_8B,
... Hardware.Cloud.H100, batch_size=1, seq_len=128)
>>> result.total_memory.to("GB").magnitude > 0
True
>>> result.feasible == (result.total_memory <= result.available_memory)
TrueTrainingRunModel
engine.solvers.training.TrainingRunModel()Wall-clock time of a training run, from peak throughput to delivered time.
The chain starts from the 6PD training FLOPs at every device’s peak, divides by the local compute efficiency (the compute-only baseline), then by the scaling efficiency (communication and pipeline bubbles), then multiplies by each operational overhead in order (checkpointing, failures and restarts, maintenance), each relative to the subtotal before it.
Literature Source: 1. Kaplan et al. (2020) and Hoffmann et al. (2022), the 6PD rule. 2. Narayanan et al. (2021), scaling efficiency at cluster scale.
Methods
| Name | Description |
|---|---|
| solve | Compose compute, scaling, and operational factors into training time. |
solve
engine.solvers.training.TrainingRunModel.solve(
model,
fleet,
local_efficiency,
scaling_efficiency,
overheads,
precision='fp8',
tokens=None,
)Compose compute, scaling, and operational factors into training time.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| model | Workload | Parameter count and, when tokens is omitted, training-token count. | required |
| fleet | Fleet | Accelerator count and per-device peak compute at the chosen precision. | required |
| local_efficiency | float | Positive dimensionless fraction of local peak throughput, usually at most one. It acts before cluster scaling losses. | required |
| scaling_efficiency | float | Positive fraction of compute throughput retained after communication and pipeline effects, usually at most one. | required |
| overheads | dict | Ordered mapping from stage name to nonnegative fractional time overhead. Each fraction applies to the preceding subtotal. | required |
| precision | str | Compute precision key; unsupported keys use the hardware’s base peak. | 'fp8' |
| tokens | Quantity | Positive total training-token count overriding model.training_tokens. | None |
Returns
| Name | Type | Description |
|---|---|---|
| TrainingRunResult | Work in FLOPs and peak, compute, scaled, intermediate, and total times in hours. Delivered fraction is peak time divided by total time; this calculation does not check model residency. |
See Also
mlsysim.physics.transformer.calc_transformer_training_flops : Training work. mlsysim.physics.performance.dTime : Work divided by effective compute rate.
Notes
Equation: F = 6 P D; T_peak = F / (N peak); T_compute = T_peak / eta; T_scaled = T_compute / scaling_efficiency. Each overhead f multiplies its preceding subtotal by (1 + f).
Assumptions: homogeneous accelerator throughput and supplied efficiencies that already summarize kernel and cluster behavior. The overhead mapping is an ordered accounting scenario, not a measured trace.
Excludes: overlap among overhead stages, explicit communication schedules, activation residency, data starvation, and changing efficiency during a run.
References
Derivation: work divided by aggregate rate gives elapsed compute time; sequential fractional overheads multiply the running subtotal. Parameter-dominated training work follows the cited contract in mlsysim.physics.transformer.calc_transformer_training_flops.
Examples
>>> from mlsysim import Models, Systems
>>> result = TrainingRunModel().solve(Models.Language.Llama3_8B,
... Systems.Clusters.Research_256, local_efficiency=0.5,
... scaling_efficiency=0.8, overheads={"checkpoint": 0.1},
... tokens=Q_(1000, "count"))
>>> result.total_time > result.scaled_time > result.peak_time
TrueTrainingStateModel
engine.solvers.training.TrainingStateModel()Persistent mixed-precision Adam state and how parallelism shards it.
Per parameter: FP16 weights and gradients (2 B each), FP32 master weights (4 B), and two FP32 Adam moments (4 B each), 16 B in all. Tensor parallelism splits every term across the TP group; ZeRO-style sharding further splits the optimizer moments across the data-parallel replicas. Activations are a stated total, not derived (they depend on sequence length, microbatch, and recomputation).
Literature Source: 1. Rajbhandari et al. (2020), “ZeRO” (16 B/param accounting, sharding). 2. Shoeybi et al. (2019), “Megatron-LM” (tensor parallelism).
Methods
| Name | Description |
|---|---|
| solve | Account for mixed-precision Adam state under selected sharding choices. |
solve
engine.solvers.training.TrainingStateModel.solve(
model,
tp_size,
dp_size,
activations,
)Account for mixed-precision Adam state under selected sharding choices.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| model | Workload | Model parameter count; this accounting uses FP16 weights and gradients. | required |
| tp_size | int | Positive tensor-parallel degree splitting each state term. | required |
| dp_size | int | Positive data-parallel degree additionally splitting Adam moments in the reported moments-sharded comparison. | required |
| activations | Quantity | Nonnegative total activation storage in bytes, supplied by the caller rather than derived from a batch shape. | required |
Returns
| Name | Type | Description |
|---|---|---|
| TrainingStateResult | Full and per-device state components in GB, including TP-only, offloaded, and moments-sharded comparisons. These totals do not imply device feasibility because no capacity is supplied. |
See Also
mlsysim.engine.solvers.training.TrainingMemoryModel.solve : Full state budget.
Notes
Equation: W = G = 2 P bytes; master = 4 P bytes; moments = 8 P bytes. Persistent state is W + G + master + moments. TP-only total is (persistent + activations) / TP. The moments-sharded term is moments / (TP * DP); weights remain W / TP in that comparison.
Assumptions: uniform dense parameter storage and even sharding. The moments-only comparison does not shard the master copy and must not be read as a complete implementation of every ZeRO state transition.
Excludes: communication buffers, activation recomputation, allocator reserve, offload transfer latency, and a hardware capacity check.
References
Rajbhandari et al. (2020), “ZeRO: Memory Optimizations Toward Training Trillion Parameter Models.” https://arxiv.org/abs/1910.02054 (bibliography key: rajbhandari2020). The moments-only output is a declared partial-sharding comparison; TrainingMemoryModel provides cumulative ZeRO-stage accounting.
Examples
>>> from mlsysim import Models
>>> result = TrainingStateModel().solve(Models.Language.Llama3_8B,
... tp_size=2, dp_size=4, activations=Q_(1, "GB"))
>>> result.zero_moments_per_device < result.tp_moments_per_device
True