Fault Tolerance & Scalability for Distributed Training
Lesson opener
In one line: Make a distributed training job survive failures and scale for the right reasons, using checkpointing, restart and elastic training, straggler and network diagnosis, observability and capacity planning, and capture it all in a scalability, reliability and recovery runbook.
Why it matters: The more machines a job uses, the more likely one of them fails during the run, and a synchronous job stops when any worker stops. The same job can also scale badly without failing at all: stragglers, communication and input bottlenecks quietly waste most of the money. A team that cannot tell which problem it has either overspends or loses days of training.
Before this lesson: Distributed Model Training: Patterns, Synchronization & Scalability chose the pattern and estimated communication cost. Experiment tracking is in MLflow Tracking and monitoring habits are in Monitoring & Data Drift; this lesson applies them to training jobs rather than serving. Cost thinking for cloud workloads is in Security, Governance, and Cost Management. Treat checkpoints and training data as governed data assets: see Cybersecurity Foundations for Data, AI & Analytics.
Northline Consumer Goods (illustrative) moved its catalog-encoder training from 16 to 64 GPUs to meet a deadline. Throughput rose only about 2.7× instead of 4×, and roughly every second day a node drops out. The job saves a checkpoint only at the end of each epoch, so each failure sends it back several hours. The platform team must stabilise the job, explain where the money goes and write a runbook that any on-call engineer can follow.
What you will be able to do
- Plan checkpointing and restart, and choose a checkpoint interval from failure and write-cost estimates.
- Diagnose stragglers, communication overhead and network bottlenecks from per-worker measurements.
- Explain all-reduce cost, gradient accumulation, mixed-precision awareness and distributed data loading at concept level.
- Describe elastic training and how data is resharded when the worker count changes.
- Define observability signals, capacity and cost-performance comparisons, and a stop condition.
- Produce a scalability, reliability and recovery runbook.
Deliverable: a scalability, reliability and recovery runbook with failure modes, detection signals, first actions, recovery steps, thresholds, capacity and cost view, owners, escalation and a review cadence.
Prerequisites
| Prerequisite | Why it matters |
|---|---|
| Distributed Model Training: Patterns, Synchronization & Scalability | Parallelism patterns, synchronous updates, all-reduce and scaling efficiency. |
| MLflow Tracking | Runs, parameters and artifacts for checkpoints and results. |
| Monitoring & Data Drift | Alert and dashboard habits reused for training-job signals. |
| Security, Governance, and Cost Management | Cloud cost controls that capacity planning builds on. |
Plain English
Worker failure. In large clusters failures are routine: a node reboots, a GPU errors, a network link flaps, a spot or pre-emptible machine is reclaimed. In a synchronous job one lost worker stalls all others, so the job must either stop and restart or continue with fewer workers.
Checkpointing. A checkpoint is a saved copy of everything needed to continue: model weights, optimizer state, learning-rate schedule position, step or epoch counter, data-loader position and random-number state. Save to durable shared storage, not only to a node's local disk, and write atomically (write to a temporary name, flush, then rename) so a crash cannot leave a half-written file that looks valid. Keep more than one checkpoint and verify them when loading. PyTorch provides distributed checkpointing (torch.distributed.checkpoint) so each rank can write its own shard; see Sources.
Restart. Restart means a new process group loads the latest valid checkpoint and continues. Work done since that checkpoint is lost. If randomness is derived from the seed and step, the resumed run can match an uninterrupted run, which the worked example shows. The checkpoint interval is a trade-off: frequent saves cost time, rare saves lose more work. A first-order estimate (Young, Daly) puts the best interval near the square root of 2 × checkpoint cost × mean time between failures; treat it as a starting point and measure.
Stragglers. A straggler is a worker that is persistently slower than its peers because of a hardware fault, thermal throttling, a noisy neighbour, a slow disk or an uneven data shard. In synchronous training the step time is the maximum over workers, so one straggler slows everyone. Detect it by comparing each worker's recent median step time to the cluster median.
Communication overhead and network bottlenecks. The all-reduce moves a gradient-sized tensor per step. When that exchange cannot hide behind backward computation, GPUs idle. Common causes: low bandwidth between nodes, too many small messages, oversubscribed switches, a mismatch between the framework's communication backend and the hardware, and gradients that are larger than necessary. Libraries such as NCCL and the framework's bucketing and overlap settings affect the result; check your versions' documentation. Smaller gradients (mixed precision, gradient compression where supported) and fewer exchanges (gradient accumulation) both reduce communication per sample.
Gradient accumulation. Instead of an all-reduce after every micro-batch, a worker runs several micro-batches, adds their gradients (each loss scaled by 1/k) and synchronizes once. This gives a larger effective batch without more memory and reduces communication frequency. In PyTorch DDP, the no_sync() context manager skips synchronization for the intermediate micro-batches. Unequal micro-batches need weighting.
Mixed-precision awareness. Using 16-bit floating point for much of the computation cuts memory and traffic, but a 16-bit float has a narrow range: tiny gradients underflow to zero and large values overflow. Frameworks offer automatic mixed precision with loss scaling (torch.amp), which multiplies the loss by a scale, skips steps that overflow and lowers the scale. Support for formats such as bfloat16 depends on hardware. Awareness here means knowing the failure signatures (NaN loss, skipped steps, silent underflow) and testing convergence, not assuming speed-ups.
Distributed data loading. Each worker must read a disjoint part of the data each epoch, with a seeded shuffle that all workers agree on. Failure modes: duplicated or missing samples after a resize, one slow storage path for all workers, CPU-bound decoding and loaders that start late. Prefetching, local caching and sharded files help; measure loader wait time per step.
Elastic training. An elastic job can change its number of workers during a run: it detects membership change, re-forms the process group, reloads state and reshards data. PyTorch's torchrun supports a minimum and maximum node count and restarts on failure; Horovod has an elastic mode. Elasticity does not remove the need for checkpoints, and changing the worker count changes the global batch size unless you compensate (for example by adjusting accumulation).
Consistency. After any restart or resize, every replica must hold identical weights and optimizer state. Rank 0 broadcasting loaded state, or each rank loading the same checkpoint, enforces this; a worker loading an older checkpoint produces silent divergence.
Observability. Track per worker: step time, samples per second, GPU utilisation and memory, data-loader wait, all-reduce time, network errors; per job: loss, gradient norm and NaN counts, checkpoint age and duration, restart count. Use MLflow Tracking for run history and a metrics dashboard for live signals; the alerting ideas in Monitoring & Data Drift apply.
Capacity planning and cost-performance. Cost = GPU-hours × price. Doubling GPUs with 70% efficiency is 40% more expensive per sample, even if faster. Choose the cheapest configuration that meets the deadline, and include failure and checkpoint overhead. For LLM-scale serving and cost questions, see Cost, Performance & Capacity Management for LLM Applications; this lesson covers training compute.
Trends (directional; verify before relying). Sharded training, asynchronous or sharded checkpoint writing, elastic scheduling, lower-precision formats and tighter Spark-to-training integration (for example Spark's TorchDistributor, available from Spark 3.4) keep maturing. Capabilities differ by framework, version and hardware; confirm each in current documentation.
Safe guidance. Test failure handling in non-production by killing a worker on purpose, with approval from the cluster owner. Checkpoints can contain information derived from training data and must follow the same access rules.
Teacher walkthrough
Build the Northline runbook in this order.
- Owner. The ML platform lead owns the runbook; on-call platform engineers execute it; the data engineering lead owns the data path.
- Scope. Training jobs on the 16 to 64 GPU clusters; serving is out of scope (see MLflow Tracking and the MLOps course).
- Classify the two problems. "Fails intermittently" is a reliability problem (checkpoints, restart). "Scales poorly" is an efficiency problem (stragglers, communication, input). Separate them in the document.
- Reliability first. Move checkpoints to shared durable storage, add an interval from the estimate, keep the last three, verify on load and test a forced restart.
- Efficiency measurements. Collect per-worker step time, loader wait and all-reduce time at 16 and 64 GPUs; compare to the dai9 estimate.
- Straggler policy. Flag a worker whose recent median step time exceeds 1.3 times the cluster median; cordon and replace it at the next checkpoint.
- Batch policy for elasticity. Decide whether to hold global batch fixed using accumulation when workers change.
- Capacity and cost. Compare 8, 16, 32 and 64 GPUs with efficiency, hours and cost; choose by deadline.
- Alerts. Checkpoint older than twice the interval, restart count above a threshold, utilisation below target, NaN loss.
- Validation. Run a planned failure drill and a resize drill; record time to recover and steps lost.
- Escalation and stop condition. Repeated restarts from the same checkpoint, a corrupt checkpoint or NaN loss stops the job and pages the platform lead.
- Fallback. Resume at a smaller worker count with accumulation; keep the previous model as the production model.
- Review. After each failure, add what was learned; review quarterly and when hardware or library versions change.
Worked example
All blocks use only the Python standard library and model concepts, not a specific framework.
1. Checkpoint, fail, resume, and choose an interval. Randomness is derived from (seed, step), so a resumed run matches an uninterrupted one. Checkpoints are written atomically with a checksum; a corrupt newer file is skipped.
import json
import math
import os
import random
import tempfile
import zlib
SEED, TOTAL, EVERY = 11, 100, 10
def step_value(step):
return random.Random(SEED * 100_003 + step).random() # randomness derived from (seed, step)
def apply_step(state):
state["w"] += 0.05 * (step_value(state["step"]) - state["w"])
state["step"] += 1
def save(state, directory):
body = json.dumps(state, sort_keys=True)
record = json.dumps({"crc": zlib.crc32(body.encode()), "body": body})
tmp = os.path.join(directory, "ckpt.tmp")
with open(tmp, "w") as f:
f.write(record)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, os.path.join(directory, "ckpt-%05d.json" % state["step"]))
def load_latest(directory):
for name in sorted((n for n in os.listdir(directory) if n.startswith("ckpt-")), reverse=True):
try:
rec = json.load(open(os.path.join(directory, name)))
if zlib.crc32(rec["body"].encode()) == rec["crc"]:
return json.loads(rec["body"])
except (ValueError, KeyError):
continue # corrupt file: fall back to an older one
return {"step": 0, "w": 0.0}
def run(directory, fail_at=None):
state = load_latest(directory)
start = state["step"]
while state["step"] < TOTAL:
if fail_at is not None and state["step"] == fail_at:
raise RuntimeError("worker lost at step %d" % fail_at)
apply_step(state)
if state["step"] % EVERY == 0:
save(state, directory)
return state, start
with tempfile.TemporaryDirectory() as clean_dir, tempfile.TemporaryDirectory() as crash_dir:
clean, _ = run(clean_dir)
try:
run(crash_dir, fail_at=47)
except RuntimeError as err:
print("failure:", err)
with open(os.path.join(crash_dir, "ckpt-00050.json"), "w") as f:
f.write('{"crc": 1, "body": "{broken') # a corrupt newer file must be skipped
resumed, start = run(crash_dir)
print("resumed from step", start, "| steps recomputed:", 47 - start)
assert start == 40
assert resumed == clean
print("final state identical to uninterrupted run:", resumed["step"], round(resumed["w"], 6))
def optimal_interval(ckpt_cost_s, mtbf_s):
return math.sqrt(2 * ckpt_cost_s * mtbf_s) # first-order Young/Daly estimate
def waste_fraction(interval_s, ckpt_cost_s, mtbf_s):
return ckpt_cost_s / interval_s + interval_s / (2 * mtbf_s)
node_mtbf_h, nodes, ckpt_cost = 400.0, 16, 60.0 # assumptions
job_mtbf = node_mtbf_h * 3600 / nodes
best = optimal_interval(ckpt_cost, job_mtbf)
print("job MTBF %.1f h | suggested interval %.0f s" % (job_mtbf / 3600, best))
for interval in (300, best, 7200):
print("interval %6.0f s -> waste %.1f%%" % (interval, 100 * waste_fraction(interval, ckpt_cost, job_mtbf)))
assert waste_fraction(best, ckpt_cost, job_mtbf) < min(waste_fraction(300, ckpt_cost, job_mtbf), waste_fraction(7200, ckpt_cost, job_mtbf))Expected result: the job fails at step 47, skips the corrupt ckpt-00050.json, resumes from step 40, recomputes 7 steps and ends identical to the clean run. With 16 nodes of an assumed 400-hour per-node MTBF the job MTBF is 25 hours, the suggested interval is about 3,300 seconds and estimated waste is about 3.7%, against about 20% for a 5-minute interval and about 4.8% for a 2-hour interval. All figures are assumptions.
2. Detect a straggler. Sixteen synchronous workers, one 1.8× slower. The step time is the maximum, so utilisation collapses; a median rule flags exactly that worker.
import random
import statistics
random.seed(5)
WORKERS, STEPS = 16, 40
BASE = 1.00
SLOW = {5: 1.8} # worker 5 runs 1.8x slower (hardware or noisy neighbour)
def worker_times():
return [[BASE * SLOW.get(w, 1.0) * random.uniform(0.95, 1.05) for _ in range(STEPS)] for w in range(WORKERS)]
times = worker_times()
step_time = [max(times[w][s] for w in range(WORKERS)) for s in range(STEPS)]
mean_busy = [statistics.mean(times[w][s] for w in range(WORKERS)) for s in range(STEPS)]
sync_eff = sum(mean_busy) / sum(step_time)
print("sync step time %.2f s | average busy %.2f s | utilisation %.0f%%" % (
statistics.mean(step_time), statistics.mean(mean_busy), 100 * sync_eff))
def flag_stragglers(times, window=10, ratio=1.3):
recent = [statistics.median(t[-window:]) for t in times]
cluster = statistics.median(recent)
return [w for w, r in enumerate(recent) if r > ratio * cluster]
flagged = flag_stragglers(times)
print("flagged workers:", flagged)
assert flagged == [5]
healthy = [t for w, t in enumerate(times) if w not in flagged]
step_after = statistics.mean(max(t[s] for t in healthy) for s in range(STEPS))
tp_before = WORKERS / statistics.mean(step_time)
tp_after = len(healthy) / step_after
print("throughput before %.1f, after dropping worker %s: %.1f (relative units)" % (tp_before, flagged, tp_after))
assert tp_after > tp_before
print("removing one slow worker beat keeping it, in this model")Expected result: step time about 1.8 s against about 1.05 s average busy time (utilisation near 59%), worker 5 is the only one flagged, and throughput rises from about 9.0 to about 14.4 relative units without it. Dropping a worker also changes the global batch, so adjust accumulation or learning rate.
3. Gradient accumulation and mixed-precision awareness. Accumulating four scaled micro-batch gradients equals the large-batch gradient. The 16-bit range is shown with struct's half-precision format.
import struct
def grad_mean(xs, ys, w):
return sum(2 * ((w * x) - y) * x for x, y in zip(xs, ys)) / len(xs)
xs = [(i % 17 - 8) / 8 for i in range(64)]
ys = [2.0 * x for x in xs]
w = 0.5
full = grad_mean(xs, ys, w)
accum = 4
micro = [grad_mean(xs[i::accum], ys[i::accum], w) for i in range(accum)]
accumulated = sum(g / accum for g in micro) # scale each micro-batch loss by 1/accum
print("large batch %.8f | accumulated %.8f" % (full, accumulated))
assert abs(full - accumulated) < 1e-12
def to_fp16(x):
return struct.unpack("<e", struct.pack("<e", x))[0]
tiny = 1e-8
print("fp16(1e-8) =", to_fp16(tiny))
assert to_fp16(tiny) == 0.0
scale = 1024.0
scaled = to_fp16(tiny * scale)
recovered = scaled / scale
print("scaled by %d -> %.3e, unscaled %.3e" % (scale, scaled, recovered))
assert scaled > 0 and abs(recovered - tiny) / tiny < 0.05
try:
to_fp16(70000.0)
except OverflowError:
print("70000 overflows fp16 (max 65504): a scaler would skip this step and lower the scale")
scale = 65536.0
for grad in (0.5, 0.9, 4.0, 0.7): # synthetic gradient magnitudes
try:
to_fp16(grad * scale)
print("scale %8.0f ok" % scale)
except OverflowError:
scale /= 2
print("overflow at grad %.1f -> step skipped, scale lowered to %.0f" % (grad, scale))
assert scale < 65536.0Expected result: both gradients print -1.06787109. A value of 1e-8 becomes 0.0 in 16-bit; scaled by 1,024 it survives and unscales to about 1.0e-8. 70,000 overflows, and the toy scaler halves the scale once, at the gradient of 4.0. Real loss scalers (for example in torch.amp) are more elaborate, and their defaults depend on the version.
4. Elastic resharding without losing or duplicating samples. Four workers each finish three samples; one is lost; the remaining samples are resharded across three workers.
import random
def epoch_order(n, seed, epoch):
rng = random.Random(seed * 1_000_003 + epoch)
idx = list(range(n))
rng.shuffle(idx)
return idx
N, WORLD, SEED = 20, 4, 3
order = epoch_order(N, SEED, epoch=0)
slices = [order[r::WORLD] for r in range(WORLD)]
processed = []
for r in range(WORLD):
processed += slices[r][:3] # each rank finishes 3 samples, then rank 3 is lost
remaining = [i for i in order if i not in set(processed)]
new_world = 3
new_slices = [remaining[r::new_world] for r in range(new_world)]
print("processed before resize:", len(processed), "| remaining:", len(remaining))
print("new slice sizes:", [len(s) for s in new_slices])
everything = processed + [i for s in new_slices for i in s]
assert sorted(everything) == list(range(N))
assert len(everything) == N
steps_ok = min(len(s) for s in new_slices)
print("equal-length steps possible:", steps_ok, "| leftover samples carried to next epoch:", len(remaining) - steps_ok * new_world)Expected result: 12 samples processed, 8 remaining, new slices of 3, 3 and 2; every sample is covered exactly once. Synchronous steps need equal-length slices, so two samples carry to the next epoch (or you pad, accepting duplicates). Decide the policy in the runbook.
A second workplace case
Northline's demand-forecasting job runs on Spark executors for feature preparation and a single GPU node for training. A Spark executor loss is handled by Spark re-running lost tasks from lineage (see the Spark documentation), while the training node has its own checkpoints. The runbook therefore has two recovery paths: the data-preparation stage restarts tasks automatically and is checked via job metrics, and the training stage restarts from the latest valid checkpoint. The common error is assuming one mechanism covers both.
Failure example
Symptom: After a node failure on day two of a training run, the Northline job restarts from step 0 and loses 14 hours. Two days later a different run resumes from a checkpoint but its loss jumps up and later becomes NaN.
Diagnosis: The first job saved checkpoints only at epoch end, and rank 0 wrote them to its node's local disk, which was the failed node. The second job resumed with one worker that loaded an older checkpoint than the others (a stale file left in a shared directory), so replicas started with different weights and the all-reduce averaged inconsistent states.
Correction: Write checkpoints to durable shared storage at an interval derived from the failure and write-cost estimate; use atomic writes with checksums and keep the last three; have all ranks load the same checkpoint id chosen by one coordinator and verify weights match (for example by comparing a checksum across ranks) before resuming; stop the run on the first NaN and restore the last good checkpoint.
Validation: Kill a worker on purpose in staging and confirm the job resumes from the expected step within the target time with a loss curve that rejoins the baseline; corrupt the newest checkpoint on purpose and confirm the fallback; record steps lost and recovery time in the tracked run.
Prevention: Add checkpoint age and restart count alerts, a rank-consistency check at every restart, a quarterly failure drill and a review of every incident with the runbook updated afterwards.
Guided practice
Scenario: Compare 8, 16, 32 and 64 GPUs for the Northline run (12 million samples, 3 epochs) using pilot throughput of 300, 560, 980 and 1,500 samples/s, an assumed price of 2.5 currency units per GPU-hour and 7% overhead for checkpoints and restarts. Choose the configuration for a 48-hour and a 24-hour deadline, then outline the runbook.
Hints:
- Compute hours = total samples / (throughput × (1 − overhead)) / 3600.
- Efficiency is measured throughput divided by the 8-GPU rate scaled by GPU count.
- Pick the cheapest option that meets the deadline.
- Which alerts and drills belong in the runbook?
PILOT = {8: 300, 16: 560, 32: 980, 64: 1500} # measured samples/s at each GPU count (assumption)
PRICE = 2.5 # currency units per GPU-hour (assumption)
SAMPLES, EPOCHS = 12_000_000, 3
OVERHEAD = 0.07 # checkpoint writes + expected restarts (assumption)
def plan(deadline_h):
rows = []
base = PILOT[8] / 8
for gpus, tp in sorted(PILOT.items()):
hours = SAMPLES * EPOCHS / (tp * (1 - OVERHEAD)) / 3600
cost = hours * gpus * PRICE
eff = tp / (base * gpus)
rows.append((gpus, tp, eff, hours, cost, hours <= deadline_h))
return rows
for deadline in (48, 24):
rows = plan(deadline)
print("deadline %d h" % deadline)
print("GPUs samples/s efficiency hours cost meets")
for gpus, tp, eff, hours, cost, ok in rows:
print("%4d %9d %9.0f%% %5.1f %5.0f %s" % (gpus, tp, eff * 100, hours, cost, "yes" if ok else "no"))
choice = min((r for r in rows if r[5]), key=lambda r: r[4])
print("-> cheapest option that meets the deadline: %d GPUs" % choice[0])
assert min((r for r in plan(48) if r[5]), key=lambda r: r[4])[0] == 8
assert min((r for r in plan(24) if r[5]), key=lambda r: r[4])[0] == 16
assert plan(48)[3][2] < 0.7Complete solution:
- Decision: for a 48-hour deadline use 8 GPUs (about 35.8 hours, cost about 717); for a 24-hour deadline use 16 GPUs (about 19.2 hours, about 768). Efficiency falls from 93% at 16 GPUs to 62% at 64 GPUs, so the 64-GPU run costs about 60% more than the 8-GPU run for a faster result that the deadline may not need.
- Runbook scope and owners: training clusters, platform lead as owner, on-call engineers as executors.
- Detection: alerts for checkpoint older than twice the interval, restart count above two in 24 hours, per-worker step time above 1.3 times the median, loader wait above an agreed share of step time, NaN loss, utilisation below target.
- First actions by symptom: worker lost, check the process group and checkpoint age, confirm that the job resumes from the latest valid checkpoint; slow job, compare per-worker step time (straggler), loader wait (input) and all-reduce time (network); NaN loss, stop, restore the last good checkpoint and compare gradient norms.
- Recovery: resume at the same size if capacity allows, otherwise at fewer workers with accumulation to hold global batch; verify rank consistency; record steps lost.
- Capacity and cost: table above refreshed with each pilot; decision by deadline and cost.
- Drills: quarterly forced worker kill and resize; checkpoint-corruption fallback test.
- Escalation and stop condition: three restarts from the same checkpoint, a corrupt latest checkpoint with no valid fallback, or divergent loss pages the platform lead and stops the run.
- Security: checkpoints stored in an access-controlled location with the dataset's class; see Cybersecurity Foundations for Data, AI & Analytics.
- Review: after every incident and quarterly.
Independent practice
Write a scalability, reliability and recovery runbook for a different illustrative job: a Northline nightly image-embedding job on 24 GPUs that sometimes hangs for hours without any error message and costs more each month.
Acceptance criteria
- Separates reliability problems from efficiency problems and names owners.
- Specifies checkpoint contents, location, atomic write, verification, retention and interval with the estimate shown.
- Defines a restart procedure including rank-consistency checks and data-loader position.
- Defines straggler detection with a threshold and an action, and a hang detection rule (no progress for a stated time).
- Lists observability signals per worker and per job, alert thresholds and dashboards or tracked runs.
- Covers communication and network diagnosis, gradient accumulation, mixed-precision failure signatures and elastic resize policy including the batch-size effect.
- Includes a capacity and cost comparison with efficiency, hours and cost, and a decision rule tied to the deadline.
- Includes drills, escalation, stop condition, fallback and review cadence; all figures are labelled as assumptions or measurements.
Common mistakes
- Checkpointing only at epoch end, or only to a node's local disk.
- Writing checkpoints non-atomically and trusting any file with the right name.
- Restarting without checking that all ranks loaded the same state.
- Treating a straggler as a network problem.
- Resizing the worker count without adjusting batch size or learning rate.
- Enabling mixed precision and assuming convergence is unchanged.
- Forgetting that loader decode and storage throughput limit the job.
- Adding GPUs to meet a deadline without computing the cost per sample.
- Having no hang detection, so a silent stall burns hours.
- Never rehearsing a failure.
Quick check
- What must a checkpoint contain besides model weights?
- Why does one straggler slow a synchronous job?
- What does gradient accumulation change about communication?
- Why can a 16-bit gradient be a problem, and what does loss scaling do?
- Why compare cost per sample and not only time?
Answers:
- Optimizer state, learning-rate schedule position, step or epoch counter, data-loader position and random-number state or the seed and step from which it is derived.
- The step finishes when the slowest worker finishes, so the step time equals the maximum over workers.
- It synchronizes once per several micro-batches, so there are fewer all-reduces per sample, and it gives a larger effective batch without more memory.
- Small gradients underflow to zero in 16-bit floats and large ones overflow; loss scaling multiplies the loss so gradients stay in range and the scaler skips overflowing steps and lowers the scale.
- Lower efficiency at larger sizes means each sample costs more, so the fastest option is rarely the cheapest; the deadline decides how much extra cost is justified.
Quiz alignment
The quiz (QUIZ_DAI10) covers worker failure, checkpointing and restart, stragglers, communication overhead, all-reduce, gradient accumulation, mixed-precision awareness, elastic training, distributed data loading, observability, capacity planning and cost-performance, using Northline scenarios.
Lesson summary
Large jobs fail and scale poorly for different reasons. Make failure cheap with frequent, atomic, verified checkpoints on durable storage, a tested restart path and consistency checks across ranks. Find inefficiency with per-worker measurements: stragglers, loader wait and communication. Use accumulation, mixed precision and elastic training knowing their side effects on batch size and numerical range. Choose capacity by cost per sample and the deadline, and write the whole thing as a runbook with alerts, drills, owners and a stop condition.
Bridge to the next lesson
Next, Industry Applications: FinTech, E-Commerce & EdTech applies distributed data and training patterns to three industries and compares the solutions side by side. For registry and serving of trained models, revisit the MLOps course, starting with MLflow Tracking.
Sources
- PyTorch, Distributed Checkpoint (
torch.distributed.checkpoint): https://pytorch.org/docs/stable/distributed.checkpoint.html - PyTorch, Elastic launch (
torchrun): https://pytorch.org/docs/stable/elastic/run.html - PyTorch,
DistributedDataParallelAPI (includingno_sync): https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html - PyTorch, Automatic Mixed Precision package (
torch.amp): https://pytorch.org/docs/stable/amp.html - Horovod, Elastic Horovod: https://horovod.readthedocs.io/en/stable/elastic_include.html
- NVIDIA, NCCL User Guide: https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/index.html
- Apache Spark, RDD Programming Guide (fault tolerance and lineage): https://spark.apache.org/docs/latest/rdd-programming-guide.html
- Apache Spark documentation: https://spark.apache.org/docs/latest/
- J. W. Young, A first order approximation to the optimum checkpoint interval, Communications of the ACM, 1974; J. T. Daly, A higher order estimate of the optimum checkpoint interval for restart dumps, Future Generation Computer Systems, 2006 (checkpoint-interval background).
- Python 3 standard library: https://docs.python.org/3/ (examples tested with Python 3.11+, standard library only)
Northline Consumer Goods, its jobs, cluster sizes, failure rates, prices and throughput figures are illustrative assumptions. Framework features, defaults and hardware support vary by version; confirm them in current official documentation. Thresholds and intervals must be set from your own measurements by the accountable owners.