Skip to content
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

Add support to avoid overwriting trained models #411

Merged
merged 3 commits into from
Nov 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions torch_em/trainer/default_trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -524,13 +524,21 @@ def load_checkpoint(self, checkpoint="best"):

return save_dict

def _verify_if_training_completed(self, checkpoint="latest"):
save_path = os.path.join(self.checkpoint_folder, f"{checkpoint}.pt")
save_dict = torch.load(save_path) if os.path.exists(save_path) else None
if save_dict and self.max_iteration == save_dict.get("iteration"):
return True
return False

def fit(
self,
iterations=None,
load_from_checkpoint=None,
epochs=None,
save_every_kth_epoch=None,
progress=None,
overwrite_training=True,
):
"""Run neural network training.

Expand All @@ -544,8 +552,24 @@ def fit(
The corresponding checkpoints will be saved with the naming scheme 'epoch-{epoch}.pt'. (default: None)
progress [progress_bar] - optional progress bar for integration with external tools.
Expected to follow the tqdm interface.
overwrite_training [bool] - Whether to overwrite the trained model.
"""
best_metric = self._initialize(iterations, load_from_checkpoint, epochs)

if not overwrite_training:
if load_from_checkpoint is not None:
raise ValueError(
"We do not support 'overwrite_training=False' and 'load_from_checkpoint' at the same time."
)

if self._verify_if_training_completed():
print(
f"The model is trained for {self.max_iteration} iterations / {self.max_epoch} epochs "
"and 'overwrite_training' is set to 'False'."
)
print(f"The checkpoints are located at '{os.path.abspath(self.checkpoint_folder)}'.")
return

print(
"Start fitting for",
self.max_iteration - self._iteration,
Expand Down