-
Notifications
You must be signed in to change notification settings - Fork 3.6k
[1/2] Add support for early stopping during training epoch end #6944
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
carmocca
merged 18 commits into
Lightning-AI:master
from
ananthsub:feat-early-stop-train
Apr 28, 2021
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
2a8f348
Add support for early stopping during training epoch end
ananthsub 29a5d60
Update early_stopping.py
ananthsub 3995acd
Update test_early_stopping.py
ananthsub f1cbde2
rebase
ananthsub eb17b6e
Update test_early_stopping.py
ananthsub 99d82b3
Update test_early_stopping.py
ananthsub 8351ff7
doc
ananthsub b6e0a1d
Update early_stopping.py
ananthsub 392d7e1
Update test_early_stopping.py
ananthsub 05e5a42
Add support for early stopping during training epoch end
ananthsub 5a2d553
Update early_stopping.py
ananthsub 31f6390
Update test_early_stopping.py
ananthsub 2084d1d
Fix yapf nonsense
carmocca 1691f45
Apply suggestions from code review
carmocca 77706c7
format
Borda 80f5bab
Formatting
carmocca a59c78a
format?
Borda 3b6b606
Update early_stopping.py
ananthsub File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -213,11 +213,13 @@ def test_early_stopping_no_val_step(tmpdir): | |
| assert trainer.current_epoch < trainer.max_epochs - 1 | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("stopping_threshold,divergence_theshold,losses,expected_epoch", [ | ||
| (None, None, [8, 4, 2, 3, 4, 5, 8, 10], 5), | ||
| (2.9, None, [9, 8, 7, 6, 5, 6, 4, 3, 2, 1], 8), | ||
| (None, 15.9, [9, 4, 2, 16, 32, 64], 3), | ||
| ]) | ||
| @pytest.mark.parametrize( | ||
| "stopping_threshold,divergence_theshold,losses,expected_epoch", [ | ||
| (None, None, [8, 4, 2, 3, 4, 5, 8, 10], 5), | ||
| (2.9, None, [9, 8, 7, 6, 5, 6, 4, 3, 2, 1], 8), | ||
| (None, 15.9, [9, 4, 2, 16, 32, 64], 3), | ||
| ] | ||
| ) | ||
| def test_early_stopping_thresholds(tmpdir, stopping_threshold, divergence_theshold, losses, expected_epoch): | ||
|
|
||
| class CurrentModel(BoringModel): | ||
|
|
@@ -338,7 +340,7 @@ def validation_epoch_end(self, outputs): | |
| limit_train_batches=limit_train_batches, | ||
| limit_val_batches=2, | ||
| min_steps=min_steps, | ||
| min_epochs=min_epochs | ||
| min_epochs=min_epochs, | ||
| ) | ||
| trainer.fit(model) | ||
|
|
||
|
|
@@ -359,8 +361,13 @@ def validation_epoch_end(self, outputs): | |
| by_min_epochs = min_epochs * limit_train_batches | ||
|
|
||
| # Make sure the trainer stops for the max of all minimum requirements | ||
| assert trainer.global_step == max(min_steps, by_early_stopping, by_min_epochs), \ | ||
| (trainer.global_step, max(min_steps, by_early_stopping, by_min_epochs), step_freeze, min_steps, min_epochs) | ||
| assert trainer.global_step == max(min_steps, by_early_stopping, by_min_epochs), ( | ||
| trainer.global_step, | ||
| max(min_steps, by_early_stopping, by_min_epochs), | ||
| step_freeze, | ||
| min_steps, | ||
| min_epochs, | ||
carmocca marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
|
|
||
| _logger.disabled = False | ||
|
|
||
|
|
@@ -372,53 +379,69 @@ def test_early_stopping_mode_options(): | |
|
|
||
| class EarlyStoppingModel(BoringModel): | ||
|
|
||
| def __init__(self, expected_end_epoch): | ||
| def __init__(self, expected_end_epoch: int, early_stop_on_train: bool): | ||
| super().__init__() | ||
| self.expected_end_epoch = expected_end_epoch | ||
| self.early_stop_on_train = early_stop_on_train | ||
|
|
||
| def validation_epoch_end(self, outputs): | ||
| def _epoch_end(self) -> None: | ||
| losses = [8, 4, 2, 3, 4, 5, 8, 10] | ||
| val_loss = losses[self.current_epoch] | ||
| self.log('abc', torch.tensor(val_loss)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we log with different keys on val/train for the test ? |
||
| loss = losses[self.current_epoch] | ||
| self.log('abc', torch.tensor(loss)) | ||
| self.log('cba', torch.tensor(0)) | ||
|
|
||
| def training_epoch_end(self, outputs): | ||
| if not self.early_stop_on_train: | ||
| return | ||
| self._epoch_end() | ||
|
|
||
| def validation_epoch_end(self, outputs): | ||
| if self.early_stop_on_train: | ||
| return | ||
| self._epoch_end() | ||
|
|
||
| def on_train_end(self) -> None: | ||
| assert self.trainer.current_epoch == self.expected_end_epoch, 'Early Stopping Failed' | ||
|
|
||
|
|
||
| _ES_CHECK = dict(check_on_train_epoch_end=True) | ||
| _ES_CHECK_P3 = dict(patience=3, check_on_train_epoch_end=True) | ||
| _NO_WIN = dict(marks=RunIf(skip_windows=True)) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| "callbacks, expected_stop_epoch, accelerator, num_processes", | ||
| "callbacks, expected_stop_epoch, check_on_train_epoch_end, accelerator, num_processes", | ||
| [ | ||
| ([EarlyStopping(monitor='abc'), EarlyStopping(monitor='cba', patience=3)], 3, None, 1), | ||
| ([EarlyStopping(monitor='cba', patience=3), | ||
| EarlyStopping(monitor='abc')], 3, None, 1), | ||
| pytest.param([EarlyStopping(monitor='abc'), | ||
| EarlyStopping(monitor='cba', patience=3)], | ||
| 3, | ||
| 'ddp_cpu', | ||
| 2, | ||
| marks=RunIf(skip_windows=True)), | ||
| pytest.param([EarlyStopping(monitor='cba', patience=3), | ||
| EarlyStopping(monitor='abc')], | ||
| 3, | ||
| 'ddp_cpu', | ||
| 2, | ||
| marks=RunIf(skip_windows=True)), | ||
| ([EarlyStopping('abc'), EarlyStopping('cba', patience=3)], 3, False, None, 1), | ||
| ([EarlyStopping('cba', patience=3), EarlyStopping('abc')], 3, False, None, 1), | ||
| pytest.param([EarlyStopping('abc'), EarlyStopping('cba', patience=3)], 3, False, 'ddp_cpu', 2, **_NO_WIN), | ||
| pytest.param([EarlyStopping('cba', patience=3), EarlyStopping('abc')], 3, False, 'ddp_cpu', 2, **_NO_WIN), | ||
| ([EarlyStopping('abc', **_ES_CHECK), EarlyStopping('cba', **_ES_CHECK_P3)], 3, True, None, 1), | ||
| ([EarlyStopping('cba', **_ES_CHECK_P3), EarlyStopping('abc', **_ES_CHECK)], 3, True, None, 1), | ||
| pytest.param([EarlyStopping('abc', **_ES_CHECK), | ||
| EarlyStopping('cba', **_ES_CHECK_P3)], 3, True, 'ddp_cpu', 2, **_NO_WIN), | ||
| pytest.param([EarlyStopping('cba', **_ES_CHECK_P3), | ||
| EarlyStopping('abc', **_ES_CHECK)], 3, True, 'ddp_cpu', 2, **_NO_WIN), | ||
|
Comment on lines
+415
to
+424
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I mean this @carmocca from #6944 (comment) |
||
| ], | ||
| ) | ||
| def test_multiple_early_stopping_callbacks( | ||
| tmpdir, callbacks: List[EarlyStopping], expected_stop_epoch: int, accelerator: Optional[str], num_processes: int | ||
| tmpdir, | ||
| callbacks: List[EarlyStopping], | ||
| expected_stop_epoch: int, | ||
| check_on_train_epoch_end: bool, | ||
| accelerator: Optional[str], | ||
| num_processes: int, | ||
| ): | ||
| """Ensure when using multiple early stopping callbacks we stop if any signals we should stop.""" | ||
|
|
||
| model = EarlyStoppingModel(expected_stop_epoch) | ||
| model = EarlyStoppingModel(expected_stop_epoch, check_on_train_epoch_end) | ||
|
|
||
| trainer = Trainer( | ||
| default_root_dir=tmpdir, | ||
| callbacks=callbacks, | ||
| overfit_batches=0.20, | ||
| max_epochs=20, | ||
| accelerator=accelerator, | ||
| num_processes=num_processes | ||
| num_processes=num_processes, | ||
| ) | ||
| trainer.fit(model) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
Uh oh!
There was an error while loading. Please reload this page.