"""Atomic writes shared by checkpoints and feature caches.""" import os import tempfile from pathlib import Path import torch def atomic_save(payload, destination): destination = Path(destination) with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as stream: temporary = stream.name try: torch.save(payload, temporary) os.replace(temporary, destination) finally: Path(temporary).unlink(missing_ok=True)