torch-atomic-save 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ from .manager import SlurmAtomicManager, install_slurm_handler
2
+
3
+ __all__ = ["SlurmAtomicManager", "install_slurm_handler"]
@@ -0,0 +1,172 @@
1
+ import os
2
+ import shutil
3
+ import tempfile
4
+ import threading
5
+ import concurrent.futures
6
+ import logging
7
+ import signal
8
+ import torch
9
+ from typing import Any, Optional, Dict, Tuple
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class SlurmAtomicManager:
15
+ """
16
+ Manages asynchronous, atomic checkpoint saving across different filesystems.
17
+ Optimized for Slurm/Lustre environments.
18
+ """
19
+
20
+ def __init__(self, max_workers: int = 4):
21
+ self._executor = concurrent.futures.ThreadPoolExecutor(
22
+ max_workers=max_workers,
23
+ thread_name_prefix="SlurmSaveWorker"
24
+ )
25
+ # path -> (future, cancellation_event)
26
+ self._registry: Dict[str, Tuple[concurrent.futures.Future, threading.Event]] = {}
27
+ self._lock = threading.Lock()
28
+ self._shutdown_event = threading.Event()
29
+
30
+ def __enter__(self):
31
+ return self
32
+
33
+ def __exit__(self, exc_type, exc_val, exc_tb):
34
+ self.shutdown()
35
+
36
+ def wait_for_all(self, timeout: Optional[float] = None):
37
+ """Blocks until all currently pending saves are complete."""
38
+ with self._lock:
39
+ futures = [f for f, _ in self._registry.values()]
40
+ concurrent.futures.wait(futures, timeout=timeout)
41
+
42
+ def save(self, model: torch.nn.Module, path: str, tmp_dir: Optional[str] = None, half_prec: bool = False):
43
+ """
44
+ Main entry point for saving models.
45
+ Moves tensors to CPU and clones them to prevent race conditions.
46
+ """
47
+ path = os.path.abspath(path)
48
+
49
+ # Snapshot weights: Move to CPU and Clone
50
+ if half_prec:
51
+ state_dict = {k: v.half().cpu().clone() for k, v in model.state_dict().items()}
52
+ else:
53
+ state_dict = {k: v.cpu().clone() for k, v in model.state_dict().items()}
54
+
55
+ if tmp_dir is None:
56
+ # Synchronous fallback
57
+ os.makedirs(os.path.dirname(path), exist_ok=True)
58
+ torch.save(state_dict, path)
59
+ else:
60
+ self._atomic_save(state_dict, path, tmp_dir)
61
+
62
+ def _atomic_save(self, obj: Any, path: str, tmp_dir: str) -> None:
63
+ """
64
+ Saves an object to a staging area, then schedules an atomic cross-FS move.
65
+ """
66
+ if self._shutdown_event.is_set():
67
+ logger.warning(f"Manager is shutting down. Ignoring save request for {path}")
68
+ return
69
+
70
+ path = os.path.abspath(path)
71
+ os.makedirs(os.path.dirname(path), exist_ok=True)
72
+
73
+ if not os.path.isdir(tmp_dir):
74
+ raise FileNotFoundError(f"Staging directory missing: {tmp_dir}")
75
+
76
+ # 1. Setup staging dir
77
+ fd, tmp_src = tempfile.mkstemp(dir=tmp_dir, suffix=".pt.staging")
78
+ os.close(fd)
79
+
80
+ # 2. Registry Update & Cancellation
81
+ cancelled = threading.Event()
82
+ with self._lock:
83
+ if path in self._registry:
84
+ prev_f, prev_ev = self._registry[path]
85
+ prev_ev.set() # Signal background thread to skip the move
86
+ prev_f.cancel()
87
+
88
+ future = self._executor.submit(
89
+ self._save_and_copy, obj, tmp_src, path, cancelled
90
+ )
91
+ self._registry[path] = (future, cancelled)
92
+ future.add_done_callback(lambda f: self._cleanup_registry(path, f))
93
+
94
+ def _cleanup_registry(self, path: str, future: concurrent.futures.Future) -> None:
95
+ """Removes the future from registry and logs errors."""
96
+ with self._lock:
97
+ current = self._registry.get(path)
98
+ if current and current[0] is future:
99
+ self._registry.pop(path, None)
100
+
101
+ if not future.cancelled():
102
+ exc = future.exception()
103
+ if exc:
104
+ logger.error(f"Async save to {path} failed: {exc}", exc_info=exc)
105
+
106
+ def _save_and_copy(self, obj, tmp_src, dst, cancelled):
107
+ """Handles both the initial write and the atomic move."""
108
+ try:
109
+ if not cancelled.is_set():
110
+ torch.save(obj, tmp_src)
111
+
112
+ self._atomic_copy_and_cleanup(tmp_src, dst, cancelled)
113
+ except Exception as e:
114
+ # Cleanup tmp_src if torch.save failed
115
+ if os.path.exists(tmp_src):
116
+ os.unlink(tmp_src)
117
+ raise
118
+
119
+ def _atomic_copy_and_cleanup(self, src: str, dst: str, cancelled: threading.Event, max_retries: int = 5) -> None:
120
+ """The background worker logic."""
121
+ dst_dir = os.path.dirname(os.path.abspath(dst))
122
+ try:
123
+ # Check if same device (ST_DEV)
124
+ if _same_filesystem(src, dst):
125
+ if not cancelled.is_set():
126
+ os.replace(src, dst)
127
+ else:
128
+ # Cross-FS: Create sibling tmp in destination's parent
129
+ fd, sibling_tmp = tempfile.mkstemp(dir=dst_dir, suffix=".atomic_tmp")
130
+ os.close(fd)
131
+ try:
132
+ shutil.copy2(src, sibling_tmp)
133
+ if not cancelled.is_set():
134
+ os.replace(sibling_tmp, dst)
135
+ else:
136
+ os.unlink(sibling_tmp)
137
+ except Exception:
138
+ try:
139
+ os.unlink(sibling_tmp)
140
+ except OSError:
141
+ pass
142
+ raise
143
+ finally:
144
+ try:
145
+ os.unlink(src)
146
+ except OSError:
147
+ pass
148
+
149
+ def shutdown(self, wait: bool = True):
150
+ """Cleanly shut down the executor."""
151
+ self._shutdown_event.set()
152
+ self._executor.shutdown(wait=wait)
153
+
154
+
155
+ def install_slurm_handler(manager: SlurmAtomicManager):
156
+ """
157
+ Installs a handler for SIGTERM (Slurm preemption) to ensure
158
+ the manager flushes pending IO before the process exits.
159
+ """
160
+
161
+ def handle_sigterm(signum, frame):
162
+ logger.info("Received SIGTERM/Preemption signal. Flushing IO...")
163
+ manager.shutdown(wait=True)
164
+ # Optional: Re-raise or exit
165
+ # os._exit(0)
166
+
167
+ signal.signal(signal.SIGTERM, handle_sigterm)
168
+
169
+
170
+ def _same_filesystem(path_a: str, path_b: str) -> bool:
171
+ stat_b_target = path_b if os.path.exists(path_b) else os.path.dirname(os.path.abspath(path_b))
172
+ return os.stat(path_a).st_dev == os.stat(stat_b_target).st_dev
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: torch_atomic_save
3
+ Version: 0.1.0
4
+ Summary: Atomic, asynchronous checkpoint saving for Pytorch for Slurm/Lustre environments
5
+ Author-email: Patrick Carnahan <pcarnah@uwo.ca>
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: torch>=2.0.0
11
+ Requires-Dist: numpy
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest; extra == "dev"
14
+ Requires-Dist: pytest-cov; extra == "dev"
15
+ Dynamic: license-file
16
+
17
+ # torch-atomic-save
18
+
19
+ [![Pytest](https://github.com/pcarnah/torch-atomic-save/actions/workflows/test.yml/badge.svg)](https://github.com/pcarnah/torch-atomic-save/actions)
20
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
21
+
22
+ An asynchronous, atomic checkpointing utility for PyTorch, optimized for Slurm and Lustre/NFS environments.
23
+
24
+ ## Key Features
25
+ * **Atomic Moves:** Prevents corrupted checkpoints during Slurm preemption.
26
+ * **Non-Blocking:** Offloads I/O to a background thread pool.
27
+ * **Race Condition Protection:** Automatically clones tensors to CPU before background saving.
28
+ * **Cross-FS Support:** Handles moves between local SSD and network storage safely.
29
+
30
+ ## Installation
31
+ ```bash
32
+ pip install torch-atomic-save
33
+ ```
34
+
35
+
36
+ ## Usage
37
+ ```python
38
+ from torch_atomic_save import SlurmAtomicManager
39
+
40
+ # Initialize the manager
41
+ manager = SlurmAtomicManager(max_workers=4)
42
+
43
+ # In your training loop:
44
+ if epoch % save_interval == 0:
45
+ manager.save(model, "path/to/checkpoints/model.pt", tmp_dir="/scratch/user/tmp")
46
+
47
+ # Ensure all I/O is finished before exiting
48
+ manager.wait_for_all()
49
+ ```
50
+
51
+ ## Attribution
52
+ If you use this software in your research, please cite it using the "Cite this repository" button or the provided CITATION.cff.
@@ -0,0 +1,7 @@
1
+ torch_atomic_save/__init__.py,sha256=NhsLuYY4EffBDJgeShgLEsNrEnl7rXiVlDqBlHN_S8g,123
2
+ torch_atomic_save/manager.py,sha256=XXpNCHpRP8hmxcHIYvHMQkzTnC15wPrKhPl2K9GUxbE,6383
3
+ torch_atomic_save-0.1.0.dist-info/licenses/LICENSE,sha256=WvXpsuVMCjnZIRoaaalqisATp86XcY0_PQSxx7HRkkA,1092
4
+ torch_atomic_save-0.1.0.dist-info/METADATA,sha256=BVcChI39xwIsEdsBsZ1rnlDEdAoPCHe1PVSbAHccZzA,1799
5
+ torch_atomic_save-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
6
+ torch_atomic_save-0.1.0.dist-info/top_level.txt,sha256=h0Omk6Y6-mjulu1PfoOZ7TblXy4rtRT6KRgd5s8gpTA,18
7
+ torch_atomic_save-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patrick Carnahan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ torch_atomic_save