Fix silent data corruption when ranks log different metric keys with sync_dist=True #21434
+1,194
−3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What does this PR do?
Fixes #21409
When different ranks log different metric keys with
sync_dist=True, theall_reduceoperations become mismatched across ranks, causing silent data corruption where values from different metrics get averaged together.Solution
This PR implements key consistency validation at controlled synchronization points:
Added
_assert_sync_dist_metric_keys_consistency()function - Usesall_gather_objectto collect metric keys from all ranks and validates they're identical. Raises a clearMisconfigurationExceptionif a mismatch is detected.Added
sync_on_step_metrics()method in_ResultCollection- Called after each training/validation step completes. Foron_step=Truemetrics:update()time to a controlled sync pointAdded
sync_on_epoch_metrics()method in_ResultCollection- Called at epoch end before metrics are consumed. Foron_epoch=Truemetrics:compute()(which includes sync) in deterministic orderHook points in loops:
sync_on_step_metrics()after step,sync_on_epoch_metrics()before epoch metrics consumedsync_on_step_metrics()after step,sync_on_epoch_metrics()before dataloader outputs storedKey Design Decisions
on_stepmetrics, sync is deferred via_forward_cache_syncedflag until after the step completeson_epochmetrics, validation happens beforecompute()is calledExample Error Message
MisconfigurationException: When logging with `sync_dist=True`, all processes must log the same metric keys in the same order within a given hook. Detected a mismatch during `training_step`. Synchronized metric keys per rank: rank=0: ['training_step.loss', 'training_step.metric_a'] rank=1: ['training_step.loss', 'training_step.metric_b'] Either log the same keys on all ranks (for example by logging dummy values), or set `sync_dist=False` and manually synchronize (for example using `all_gather`).📚 Documentation preview 📚: https://pytorch-lightning--21434.org.readthedocs.build/en/21434/