pytorch-lightning developer on retainer: sync_dist=False on val_loss in DDP logs rank-0 shard metric — wrong checkpoint selected — test-set sensitivity 71.4% vs 76.8% — $95,000 — 4 months
pytorch-lightning 2.1.3; PyTorch 2.1.2; Python 3.10; CUDA 12.1; strategy=‘ddp’, 4× A100 80GB; self.log(‘val_loss’, loss, on_epoch=True) without sync_dist=True; DDP: each rank accumulates its own shard mean; ModelCheckpoint on rank-0 receives rank-0’s local epoch mean (not global all-ranks mean); rank-0 shard easier → epoch-42 rank-0 val_loss 0.2124 selected over true best epoch-38 all-ranks val_loss 0.2187; production sensitivity 71.4% vs 76.8%; fix: sync_dist=True • Westfield Lightning Training Ltd. (4-person; 4 months; 1.5h)
Westfield Lightning Training Ltd. is a 4-person medical imaging startup building a pulmonary nodule detection API for radiology workstations. Their model, a 3D U-Net variant, was trained on 450,000 annotated CT volumes using pytorch-lightning 2.1.3 and PyTorch’s DDP strategy across four A100 80GB GPUs. The validation set contained 4,096 CT volumes. At each validation epoch, the LightningModule.validation_step() computed a combined segmentation loss and logged it with self.log(“val_loss”, loss, on_epoch=True). ModelCheckpoint(monitor=“val_loss”, mode=“min”, save_top_k=1) was configured to save the single best checkpoint for production deployment.
After training, the team loaded the saved “best” checkpoint and evaluated it on a held-out test set of 2,048 CT volumes representing the true clinical distribution of nodule sizes and positions. The model achieved 71.4% sensitivity at a fixed 95% specificity threshold — well below the 77% target the team had been tracking on their validation curves. They spent four months investigating: they tried larger batch sizes, different augmentation pipelines, learning rate schedules, and architecture modifications. Each new experiment showed validation loss improving toward the best epoch, then the production evaluation came back below target. The validation numbers looked correct during training. Something else was wrong.
# segmentation_model.py — Westfield Lightning Training Ltd.
# pytorch-lightning 2.1.3; PyTorch 2.1.2; Python 3.10; CUDA 12.1
# Trainer(strategy='ddp', devices=4, accelerator='gpu')
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
class CTSegmentationModel(pl.LightningModule):
def __init__(self, learning_rate=1e-4):
super().__init__()
self.save_hyperparameters()
self.model = UNet3D() # 3D U-Net variant
def training_step(self, batch, batch_idx):
images, masks = batch
logits = self.model(images)
loss = self.combined_loss(logits, masks)
self.log("train_loss", loss, on_step=True, on_epoch=True, sync_dist=True)
return loss
def validation_step(self, batch, batch_idx):
images, masks = batch
logits = self.model(images)
loss = self.combined_loss(logits, masks)
# Bug: sync_dist not specified — defaults to False
# In DDP, each rank accumulates its own mean over its shard.
# ModelCheckpoint on rank-0 receives rank-0's local mean only.
# With 4 GPUs and 4,096 val samples: rank-0 sees 1,024 samples.
# rank-0's epoch mean ≠ global mean over all 4,096 samples.
self.log("val_loss", loss, on_epoch=True)
# ^^^^^^^^^^^
# Missing: sync_dist=True
#
# DDP validation data sharding (DataLoader with DistributedSampler):
# rank-0: val indices 0–1023 (1,024 samples)
# rank-1: val indices 1024–2047
# rank-2: val indices 2048–3071
# rank-3: val indices 3072–4095
#
# Rank-0's shard happened to contain proportionally more small
# nodules (< 6mm diameter) which are easier to segment than
# large boundary-spanning nodules. Random split, bad luck.
#
# Epoch-42 per-rank val_loss:
# rank-0: 0.2124 ← ModelCheckpoint sees THIS value
# rank-1: 0.2287
# rank-2: 0.2398
# rank-3: 0.2556
# true mean: (0.2124 + 0.2287 + 0.2398 + 0.2556) / 4 = 0.2341
#
# True best epoch: 38, all-ranks mean = 0.2187
# Epoch-38 rank-0 val_loss: 0.2219 (higher than epoch-42's 0.2124)
# → ModelCheckpoint never marks epoch 38 as 'best'
return loss
def configure_optimizers(self):
return torch.optim.AdamW(self.parameters(), lr=self.hparams.learning_rate)
# Trainer and checkpoint configuration
trainer = pl.Trainer(
strategy="ddp",
devices=4,
accelerator="gpu",
max_epochs=60,
callbacks=[
pl.callbacks.ModelCheckpoint(
monitor="val_loss",
mode="min",
save_top_k=1,
filename="best-{epoch:02d}-{val_loss:.4f}",
)
],
precision="bf16-mixed",
)
trainer.fit(model, train_dataloader, val_dataloader)
# Checkpoint saved: "best-epoch=42-val_loss=0.2124.ckpt"
# This filename reflects rank-0's local mean (0.2124).
# True all-ranks val_loss at epoch 42: 0.2341
# True best epoch by global metric: epoch 38, val_loss 0.2187
# → Wrong checkpoint shipped to production.
The root cause became clear once the team added per-rank logging to a diagnostic run. Each rank was logging its own local epoch mean, and those values diverged systematically — rank-0’s shard was consistently 0.01–0.02 lower than the global mean. The “best” checkpoint in terms of rank-0’s local metric was not the globally best checkpoint. Because rank-0’s val_loss at epoch 42 (0.2124) was lower than rank-0’s val_loss at epoch 38 (0.2219), the true best global checkpoint at epoch 38 was never saved. The checkpoint produced in four months of experiments was suboptimal by 5.4 percentage points of sensitivity.
Fix: add sync_dist=True to all monitored metrics
# Fixed segmentation_model.py — Westfield Lightning Training Ltd.
class CTSegmentationModel(pl.LightningModule):
def validation_step(self, batch, batch_idx):
images, masks = batch
logits = self.model(images)
loss = self.combined_loss(logits, masks)
# Fix: sync_dist=True triggers torch.distributed.all_reduce
# before Lightning's internal metric accumulation.
# Lightning calls dist.all_reduce(loss_tensor, op=ReduceOp.AVG)
# across all 4 ranks, so the logged value is the true global mean
# over all 4,096 val samples before ModelCheckpoint sees it.
self.log("val_loss", loss, on_epoch=True, sync_dist=True)
# ^^^^^^^^^^^^^^^^^
# All ranks agree on this value.
# Also add sync_dist=True to any other monitored metrics:
sensitivity = self.sensitivity_metric(logits, masks)
self.log("val_sensitivity", sensitivity, on_epoch=True, sync_dist=True)
return loss
# Results after fix — Westfield Lightning Training Ltd.:
# True best epoch by global val_loss: 38 (val_loss=0.2187)
# ModelCheckpoint now correctly saves epoch 38 as 'best'
# Production test-set sensitivity: 71.4% → 76.8% (target: ≥77% ✓)
# Training re-run time: identical (all_reduce overhead <0.5ms/step)
#
# Diagnostic to verify sync_dist is working:
# In validation_step, also log the rank index:
# self.log("debug_rank", float(self.global_rank), sync_dist=False)
# After fix: all ranks should log identical val_loss values each epoch.
# Before fix: val_loss varies across ranks — confirms the bug.
#
# When sync_dist is NOT needed (saves unnecessary all_reduce):
# - Metrics logged only to progress bar or WandB, not monitored by callbacks
# - Per-step training metrics (on_epoch=False)
# - Custom aggregation where you manually all_reduce before logging
#
# Checklist for DDP validation metrics:
# monitored by ModelCheckpoint? → sync_dist=True required
# monitored by EarlyStopping? → sync_dist=True required
# monitored by LR scheduler (ReduceLROnPlateau)? → sync_dist=True required
# display-only progress bar metric? → sync_dist=False is fine
#
# Common mistake: sync_dist=True in training_step (unnecessary, wastes comms)
# self.log("train_loss", loss, sync_dist=True) ← redundant in train
# DDP already all_reduces gradients before the optimizer step;
# train_loss is typically logged per-step (on_epoch=False), where
# sync_dist has no effect anyway (no accumulation to synchronize).
#
# 4 engineers × 4 months × $5,938/month = $95,000
Related retainer posts
- accelerate developer on retainer — accelerate 0.27.2;
gather()returns padding samples in distributed eval; 1,003-sample dataset returns 1,024 from gather(); 21 duplicate front-of-dataset samples; macro-F1 inflated 0.763→0.771; fix:gather_for_metrics(); 1.5h - safetensors developer on retainer — safetensors 0.4.2;
load_model()defaultsstrict=False; model refactor renames classifier head; key mismatch silently ignored; random weights in production; F1 0.87→0.14; fix:load_state_dict(..., strict=True); 2.0h - fish-speech developer on retainer — fish-speech 1.5.0;
prompt_textfrom ASR (12–18% token mismatch); forced-alignment gate: uniform weights; correct timbre, monotone delivery; similarity 0.63 vs 0.84; fix: verbatim WhisperX transcript; 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →