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

Added atomic checkpoint creation #689

Merged
merged 2 commits into from
Jan 20, 2020
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
25 changes: 21 additions & 4 deletions pytorch_lightning/trainer/training_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,17 +255,34 @@ def term_handler(self, signum, frame):
# --------------------
# MODEL SAVE CHECKPOINT
# --------------------
def _atomic_save(self, checkpoint, filepath):
fgerzer marked this conversation as resolved.
Show resolved Hide resolved
fgerzer marked this conversation as resolved.
Show resolved Hide resolved
"""Saves a checkpoint atomically, avoiding the creation of incomplete checkpoints.

This will create a temporary checkpoint with a suffix of ``.part``, then copy it to the final location once
saving is finished.

Args:
checkpoint (object): The object to save.
Built to be used with the ``dump_checkpoint`` method, but can deal with anything which ``torch.save``
accepts.
filepath (str|pathlib.Path): The path to which the checkpoint will be saved.
This points to the file that the checkpoint will be stored in.
"""
tmp_path = str(filepath) + ".part"
torch.save(checkpoint, tmp_path)
os.replace(tmp_path, filepath)

def save_checkpoint(self, filepath):
checkpoint = self.dump_checkpoint()

# do the actual save
try:
torch.save(checkpoint, filepath)
self._atomic_save(checkpoint, filepath)
except AttributeError:
if 'hparams' in checkpoint:
del checkpoint['hparams']

torch.save(checkpoint, filepath)
self._atomic_save(checkpoint, filepath)

def restore(self, checkpoint_path, on_gpu):
# if on_gpu:
Expand Down Expand Up @@ -412,12 +429,12 @@ def hpc_save(self, folderpath, logger):
# do the actual save
# TODO: fix for anything with multiprocess DP, DDP, DDP2
try:
torch.save(checkpoint, filepath)
self._atomic_save(checkpoint, filepath)
except AttributeError:
if 'hparams' in checkpoint:
del checkpoint['hparams']

torch.save(checkpoint, filepath)
self._atomic_save(checkpoint, filepath)

return filepath

Expand Down