nodehop 0.2.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.
nodehop/pairing.py ADDED
@@ -0,0 +1,217 @@
1
+ """Pairing two machines with a copy-paste token, so an agent can do it unattended.
2
+
3
+ Machine A runs `nodehop invite` (or `nodehop setup`) and gets a token holding
4
+ its name, SSH user, the host names it may be reached at and NodeHop's public
5
+ key. Machine B runs `nodehop pair <token>`: it authorizes A's key in
6
+ ~/.ssh/authorized_keys, records A as a peer and prints its own token, which A
7
+ pairs with in turn. Only public keys travel; no password is ever involved.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import getpass
14
+ import json
15
+ import socket
16
+ from pathlib import Path
17
+ from typing import Callable, List, Optional
18
+
19
+ from nodehop import __version__
20
+ from nodehop.config import Config, ConfigError, Peer
21
+ from nodehop.runner import Runner
22
+
23
+ TOKEN_PREFIX = "nodehop1:"
24
+ KEY_TAG = "nodehop-peer:"
25
+
26
+
27
+ # ---- keys -------------------------------------------------------------------
28
+ def ensure_key(cfg: Config, runner: Runner) -> Path:
29
+ """Create NodeHop's own SSH key (no passphrase: it must work unattended at sleep time)."""
30
+ key = cfg.ssh_key_path()
31
+ if key.exists():
32
+ return key
33
+ runner.run(["mkdir", "-p", str(key.parent)])
34
+ runner.run(["chmod", "700", str(key.parent)])
35
+ runner.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", f"nodehop-{cfg.machine}", "-f", str(key)])
36
+ return key
37
+
38
+
39
+ def public_key(cfg: Config) -> str:
40
+ pub = Path(str(cfg.ssh_key_path()) + ".pub")
41
+ if not pub.exists():
42
+ raise ConfigError(f"no public key at {pub}: run `nodehop setup` first")
43
+ parts = pub.read_text().split()
44
+ return " ".join(parts[:2]) # type and key, without the comment
45
+
46
+
47
+ def authorized_keys_path() -> Path:
48
+ return Path.home() / ".ssh" / "authorized_keys"
49
+
50
+
51
+ def authorize(peer: str, pubkey: str, dry_run: bool = False, path: Optional[Path] = None) -> bool:
52
+ """Let `peer` log in here with `pubkey`. Idempotent; returns True if the file changed."""
53
+ path = path or authorized_keys_path()
54
+ kind_and_key = " ".join(pubkey.split()[:2])
55
+ if len(kind_and_key.split()) != 2 or not kind_and_key.startswith(("ssh-", "ecdsa-")):
56
+ raise ConfigError("the token holds no valid public key")
57
+ # `restrict`: no port, agent or X11 forwarding, no terminal, no ~/.ssh/rc. NodeHop only runs
58
+ # non-interactive commands (nodehop, rsync, tmux), so it needs none of them.
59
+ line = f"restrict {kind_and_key} {KEY_TAG}{peer}"
60
+ existing = path.read_text().splitlines() if path.exists() else []
61
+ # Drop older copies of this key: tagged ones, and the untagged copy `ssh-copy-id` leaves.
62
+ new = [
63
+ l for l in existing
64
+ if not l.endswith(f" {KEY_TAG}{peer}")
65
+ and not (l.startswith(kind_and_key + " nodehop-") or l == kind_and_key) # left by ssh-copy-id
66
+ ] + [line]
67
+ if new == existing:
68
+ return False
69
+ if dry_run:
70
+ return True
71
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
72
+ path.write_text("\n".join(new) + "\n")
73
+ path.chmod(0o600)
74
+ return True
75
+
76
+
77
+ def revoke(peer: str, dry_run: bool = False, path: Optional[Path] = None) -> bool:
78
+ path = path or authorized_keys_path()
79
+ if not path.exists():
80
+ return False
81
+ lines = path.read_text().splitlines()
82
+ kept = [l for l in lines if not l.endswith(f" {KEY_TAG}{peer}")]
83
+ if len(kept) == len(lines):
84
+ return False
85
+ if not dry_run:
86
+ path.write_text("\n".join(kept) + ("\n" if kept else ""))
87
+ return True
88
+
89
+
90
+ def is_authorized(peer: str, path: Optional[Path] = None) -> bool:
91
+ path = path or authorized_keys_path()
92
+ return path.exists() and any(l.endswith(f" {KEY_TAG}{peer}") for l in path.read_text().splitlines())
93
+
94
+
95
+ # ---- how this machine can be reached ----------------------------------------
96
+ TAILSCALE_APP_CLI = "/Applications/Tailscale.app/Contents/MacOS/Tailscale"
97
+
98
+
99
+ def tailscale_status(runner: Runner) -> Optional[dict]:
100
+ """`tailscale status --json`, from the PATH or the macOS app; None if not running."""
101
+ for exe in ("tailscale", TAILSCALE_APP_CLI):
102
+ if exe.startswith("/") and not Path(exe).exists():
103
+ continue
104
+ result = runner.run([exe, "status", "--json"], check=False, timeout=10, mutating=False)
105
+ if result.returncode != 0:
106
+ continue
107
+ try:
108
+ data = json.loads(result.stdout)
109
+ except ValueError:
110
+ continue
111
+ if data.get("BackendState") == "Running":
112
+ return data
113
+ return None
114
+
115
+
116
+ def tailnet_peers(runner: Runner) -> List[dict]:
117
+ """Other machines on the tailnet: [{name, host, os, online}], online ones first."""
118
+ data = tailscale_status(runner) or {}
119
+ peers = []
120
+ for p in (data.get("Peer") or {}).values():
121
+ host = (p.get("DNSName") or "").rstrip(".")
122
+ if host:
123
+ peers.append({"name": p.get("HostName") or host, "host": host, "os": p.get("OS", ""), "online": bool(p.get("Online"))})
124
+ return sorted(peers, key=lambda p: (not p["online"], p["os"] != "macOS", p["name"].lower()))
125
+
126
+
127
+ def local_hosts(runner: Runner) -> List[str]:
128
+ """Names other machines may reach this one at, best first."""
129
+ hosts: List[str] = []
130
+ ts = tailscale_status(runner)
131
+ if ts:
132
+ dns = (ts.get("Self") or {}).get("DNSName", "").rstrip(".")
133
+ if dns:
134
+ hosts.append(dns)
135
+ local = runner.run(["scutil", "--get", "LocalHostName"], check=False, timeout=10, mutating=False)
136
+ if local.returncode == 0 and local.stdout.strip():
137
+ hosts.append(local.stdout.strip() + ".local")
138
+ name = socket.gethostname()
139
+ if name:
140
+ hosts.append(name)
141
+ seen = set()
142
+ return [h for h in hosts if not (h in seen or seen.add(h))]
143
+
144
+
145
+ def suggested_name(raw: str) -> str:
146
+ """'Mac mini de Alice' / 'mac-mini-de-alice.tail1.ts.net' -> 'mac-mini-de-alice'."""
147
+ base = raw.split(".")[0].lower()
148
+ return "-".join(w for w in "".join(c if c.isalnum() else " " for c in base).split()) or "machine"
149
+
150
+
151
+ def tcp_open(host: str, port: int = 22, timeout: float = 3.0) -> bool:
152
+ try:
153
+ with socket.create_connection((host, port), timeout=timeout):
154
+ return True
155
+ except OSError:
156
+ return False
157
+
158
+
159
+ def pick_host(hosts: List[str], probe: Optional[Callable[[str], bool]] = None) -> Optional[str]:
160
+ probe = probe or tcp_open
161
+ for host in hosts:
162
+ if probe(host):
163
+ return host
164
+ return None
165
+
166
+
167
+ # ---- tokens -----------------------------------------------------------------------
168
+ def make_token(cfg: Config, hosts: List[str]) -> str:
169
+ info = {
170
+ "name": cfg.machine,
171
+ "user": getpass.getuser(),
172
+ "hosts": hosts,
173
+ "key": public_key(cfg),
174
+ "primary": cfg.primary == cfg.machine,
175
+ "version": __version__,
176
+ }
177
+ raw = json.dumps(info, separators=(",", ":")).encode()
178
+ return TOKEN_PREFIX + base64.urlsafe_b64encode(raw).decode().rstrip("=")
179
+
180
+
181
+ def parse_token(token: str) -> dict:
182
+ token = token.strip()
183
+ if not token.startswith(TOKEN_PREFIX):
184
+ raise ConfigError("not a NodeHop token (it should start with 'nodehop1:')")
185
+ body = token[len(TOKEN_PREFIX):]
186
+ try:
187
+ info = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
188
+ except ValueError as exc:
189
+ raise ConfigError(f"damaged token: {exc}")
190
+ for field in ("name", "user", "hosts", "key"):
191
+ if not info.get(field):
192
+ raise ConfigError(f"damaged token: missing {field}")
193
+ return info
194
+
195
+
196
+ # ---- pairing itself ---------------------------------------------------------------
197
+ def pair_with(cfg: Config, info: dict, host: Optional[str] = None, default: bool = False, dry_run: bool = False) -> dict:
198
+ """Record the machine described by `info` (a parsed token) as a peer.
199
+
200
+ The always-on machine also authorizes the other's key, since the primary
201
+ connects to it. The primary authorizes nobody: it only makes outgoing
202
+ connections, so it needs no SSH server and lets no one in.
203
+ Does not save the config: the caller does (and skips it in dry-run).
204
+ """
205
+ name = info["name"]
206
+ if name == cfg.machine:
207
+ raise ConfigError("that token is this machine's own: pair with it on the OTHER machine")
208
+ if info.get("primary") and cfg.primary != cfg.machine:
209
+ cfg.primary = name
210
+ changed = False
211
+ if cfg.primary != cfg.machine:
212
+ changed = authorize(name, info["key"], dry_run=dry_run)
213
+ host = host or pick_host(info["hosts"]) or info["hosts"][0]
214
+ cfg.peers[name] = Peer(name=name, host=host, user=info["user"])
215
+ if default or (cfg.primary == cfg.machine and not cfg.default_target):
216
+ cfg.default_target = name
217
+ return {"peer": name, "host": host, "user": info["user"], "authorized_here": cfg.primary != cfg.machine, "authorized_changed": changed}
nodehop/runner.py ADDED
@@ -0,0 +1,72 @@
1
+ """Thin wrapper around subprocess so every command can be logged, dry-run or faked in tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shlex
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Callable, Optional, Sequence
11
+
12
+ from nodehop.config import home_dir
13
+
14
+
15
+ class CommandError(Exception):
16
+ def __init__(self, argv: Sequence[str], result: subprocess.CompletedProcess):
17
+ self.argv = list(argv)
18
+ self.result = result
19
+ detail = (result.stderr or result.stdout or "").strip()
20
+ super().__init__(f"command failed ({result.returncode}): {shlex.join(self.argv)}\n{detail}")
21
+
22
+
23
+ class Runner:
24
+ def __init__(self, dry_run: bool = False, verbose: bool = False, log_file: Optional[Path] = None):
25
+ self.dry_run = dry_run
26
+ self.verbose = verbose
27
+ self.log_file = log_file if log_file is not None else home_dir() / "nodehop.log"
28
+ self.sleep: Callable[[float], None] = time.sleep
29
+
30
+ def log(self, message: str) -> None:
31
+ line = f"{time.strftime('%Y-%m-%d %H:%M:%S')} {message}"
32
+ print(line, file=sys.stderr)
33
+ if self.dry_run:
34
+ return
35
+ try:
36
+ self.log_file.parent.mkdir(parents=True, exist_ok=True)
37
+ with open(self.log_file, "a") as fh:
38
+ fh.write(line + "\n")
39
+ except OSError:
40
+ pass
41
+
42
+ def run(
43
+ self,
44
+ argv: Sequence[str],
45
+ check: bool = True,
46
+ timeout: Optional[float] = None,
47
+ mutating: bool = True,
48
+ interactive: bool = False,
49
+ ) -> subprocess.CompletedProcess:
50
+ """Run argv. Read-only probes (mutating=False) still run in dry-run mode.
51
+
52
+ interactive=True leaves the terminal to the command (e.g. ssh asking for a password).
53
+ """
54
+ argv = [str(a) for a in argv]
55
+ if self.verbose or self.dry_run:
56
+ prefix = "[dry-run] " if (self.dry_run and mutating) else "$ "
57
+ print(prefix + shlex.join(argv), file=sys.stderr)
58
+ if self.dry_run and mutating:
59
+ return subprocess.CompletedProcess(argv, 0, "", "")
60
+ try:
61
+ if interactive:
62
+ result = subprocess.run(argv, text=True, timeout=timeout)
63
+ result.stdout, result.stderr = result.stdout or "", result.stderr or ""
64
+ else:
65
+ result = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
66
+ except subprocess.TimeoutExpired:
67
+ result = subprocess.CompletedProcess(argv, 124, "", "timed out")
68
+ except FileNotFoundError:
69
+ result = subprocess.CompletedProcess(argv, 127, "", f"{argv[0]}: not found")
70
+ if check and result.returncode != 0:
71
+ raise CommandError(argv, result)
72
+ return result
nodehop/state.py ADDED
@@ -0,0 +1,120 @@
1
+ """Who owns each project right now, plus a lock so two handoffs never overlap."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import fcntl
7
+ import json
8
+ import os
9
+ import signal
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Iterator, Optional
13
+
14
+ from nodehop.config import home_dir
15
+
16
+
17
+ class State:
18
+ def __init__(self, path: Optional[Path] = None):
19
+ self.path = path or home_dir() / "state.json"
20
+ self.data = {"projects": {}}
21
+ if self.path.exists():
22
+ self.data = json.loads(self.path.read_text())
23
+ self.data.setdefault("projects", {})
24
+
25
+ def reload(self) -> None:
26
+ """Re-read the file: a long-running watcher must see what other commands wrote."""
27
+ if self.path.exists():
28
+ self.data = json.loads(self.path.read_text())
29
+ self.data.setdefault("projects", {})
30
+
31
+ def peer(self, name: str) -> dict:
32
+ return self.data.setdefault("peers", {}).get(name, {})
33
+
34
+ def update_peer(self, name: str, **fields) -> None:
35
+ with self._fresh():
36
+ self.data.setdefault("peers", {}).setdefault(name, {}).update(fields)
37
+
38
+ def local(self) -> dict:
39
+ """This machine's own bookkeeping (last copy time, …)."""
40
+ return self.data.setdefault("local", {})
41
+
42
+ def update_local(self, **fields) -> None:
43
+ with self._fresh():
44
+ self.local().update(fields)
45
+
46
+ def get(self, project: str) -> dict:
47
+ return self.data["projects"].get(project, {})
48
+
49
+ def owner(self, project: str, default: str) -> str:
50
+ return self.get(project).get("owner", default)
51
+
52
+ def update(self, project: str, **fields) -> None:
53
+ with self._fresh():
54
+ entry = self.data["projects"].setdefault(project, {})
55
+ entry.update({k: v for k, v in fields.items()})
56
+ entry["updated"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
57
+
58
+ @contextlib.contextmanager
59
+ def _fresh(self) -> Iterator[None]:
60
+ """Read-modify-write under a file lock: several NodeHop processes (sync, on-wake,
61
+ commands over SSH) write this file; each must change only its own fields."""
62
+ self.path.parent.mkdir(parents=True, exist_ok=True)
63
+ with open(self.path.with_suffix(".lock"), "w") as fh:
64
+ fcntl.flock(fh, fcntl.LOCK_EX)
65
+ try:
66
+ self.reload()
67
+ yield
68
+ self.save()
69
+ finally:
70
+ fcntl.flock(fh, fcntl.LOCK_UN)
71
+
72
+ def save(self) -> None:
73
+ self.path.parent.mkdir(parents=True, exist_ok=True)
74
+ tmp = self.path.with_suffix(".tmp")
75
+ tmp.write_text(json.dumps(self.data, indent=2) + "\n")
76
+ tmp.replace(self.path)
77
+
78
+
79
+ @contextlib.contextmanager
80
+ def locked(timeout: float = 120.0, role: str = "work", preempt: bool = False) -> Iterator[None]:
81
+ """Process-wide lock: a sleep handoff and a watcher handback must not race.
82
+
83
+ A routine pre-sync holds it with role "sync"; `preempt=True` (going to sleep)
84
+ stops such a sync instead of waiting for its copy to finish.
85
+ """
86
+ lock_path = home_dir() / "lock"
87
+ owner_path = home_dir() / "lock.owner"
88
+ lock_path.parent.mkdir(parents=True, exist_ok=True)
89
+ with open(lock_path, "w") as fh:
90
+ deadline = time.monotonic() + timeout
91
+ preempted = False
92
+ while True:
93
+ try:
94
+ fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
95
+ break
96
+ except BlockingIOError:
97
+ if preempt and not preempted:
98
+ preempted = _stop_sync_holder(owner_path)
99
+ if time.monotonic() > deadline:
100
+ raise TimeoutError("another NodeHop operation is still running")
101
+ time.sleep(0.2)
102
+ try:
103
+ owner_path.write_text(f"{os.getpid()} {role}\n")
104
+ except OSError:
105
+ pass
106
+ try:
107
+ yield
108
+ finally:
109
+ fcntl.flock(fh, fcntl.LOCK_UN)
110
+
111
+
112
+ def _stop_sync_holder(owner_path: Path) -> bool:
113
+ try:
114
+ pid, role = owner_path.read_text().split()[:2]
115
+ if role == "sync" and int(pid) != os.getpid():
116
+ os.kill(int(pid), signal.SIGTERM)
117
+ return True
118
+ except (OSError, ValueError):
119
+ pass
120
+ return False
nodehop/system.py ADDED
@@ -0,0 +1,41 @@
1
+ """What differs between macOS and Linux: how to turn the SSH server on, sleep hooks, keeping agents alive."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import sys
7
+ from pathlib import Path
8
+
9
+
10
+ def os_name() -> str:
11
+ if sys.platform == "darwin":
12
+ return "macos"
13
+ if sys.platform.startswith("linux"):
14
+ return "linux"
15
+ return "other"
16
+
17
+
18
+ def ssh_server_fix() -> str:
19
+ """How to turn the SSH server on, including on a machine with no screen."""
20
+ if os_name() == "macos":
21
+ return (
22
+ "turn on System Settings > General > Sharing > Remote Login; on a Mac with no screen, from an "
23
+ "admin account (Screen Sharing or a terminal): `sudo systemsetup -setremotelogin on` "
24
+ "(macOS may require Full Disk Access for the terminal) — an agent cannot do it without sudo"
25
+ )
26
+ if os_name() == "linux":
27
+ return (
28
+ "install and start the SSH server: `sudo apt install -y openssh-server && sudo systemctl enable --now ssh` "
29
+ "(Fedora/Arch: package openssh, service sshd); or, with Tailscale, `sudo tailscale up --ssh` "
30
+ "(no SSH server or key needed) — an agent cannot do it without sudo"
31
+ )
32
+ return "install and start an OpenSSH server"
33
+
34
+
35
+ def sleep_hook_path() -> Path:
36
+ """Linux: scripts here run (as root) right before sleep and right after wake-up."""
37
+ return Path("/usr/lib/systemd/system-sleep/nodehop")
38
+
39
+
40
+ def has_systemd_run() -> bool:
41
+ return os_name() == "linux" and shutil.which("systemd-run") is not None
nodehop/train.py ADDED
@@ -0,0 +1,200 @@
1
+ """Helpers for training scripts run by NodeHop (standard library only; PyTorch is optional).
2
+
3
+ A script that uses them can be stopped on one machine and resumed on another,
4
+ at that machine's own scale:
5
+
6
+ from nodehop import train
7
+
8
+ job = train.Job("checkpoints") # Ctrl-C / SIGTERM now ask for a clean stop
9
+ plan = train.batch_plan(256, mb_per_sample=12) # micro-batch + accumulation that fit here
10
+ state = job.load() # latest checkpoint (dict) or None
11
+ for step in range(state["step"] if state else 0, total):
12
+ ...train on `plan.accum` micro-batches of `plan.micro`...
13
+ job.report(step=step, total=total, loss=loss)
14
+ if job.due(step) or job.stop_requested:
15
+ job.save({"step": step + 1, ...}, step + 1) # atomic, keeps the last few
16
+ if job.stop_requested:
17
+ job.exit() # exit code 0: NodeHop moves it
18
+
19
+ NodeHop runs the script inside its tmux session with NODEHOP_MACHINE and,
20
+ after a handoff, NODEHOP_RESUMED=1. Checkpoints live in the project folder,
21
+ so they travel with it.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import pickle
29
+ import platform
30
+ import signal
31
+ import subprocess
32
+ import sys
33
+ import time
34
+ from dataclasses import dataclass
35
+ from pathlib import Path
36
+ from typing import Any, Callable, Dict, Optional
37
+
38
+
39
+ # ---- what this machine can do ------------------------------------------------
40
+ def memory_gb() -> float:
41
+ try:
42
+ if sys.platform == "darwin":
43
+ out = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True).stdout
44
+ return int(out.strip()) / 1024 ** 3
45
+ with open("/proc/meminfo") as fh:
46
+ for line in fh:
47
+ if line.startswith("MemTotal:"):
48
+ return int(line.split()[1]) / 1024 ** 2
49
+ except (OSError, ValueError):
50
+ pass
51
+ return 8.0
52
+
53
+
54
+ def device() -> str:
55
+ """Best PyTorch device here: cuda, mps (Apple GPU) or cpu."""
56
+ try:
57
+ import torch # noqa: WPS433 (optional dependency)
58
+
59
+ if torch.cuda.is_available():
60
+ return "cuda"
61
+ if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
62
+ return "mps"
63
+ except ImportError:
64
+ pass
65
+ return "cpu"
66
+
67
+
68
+ def accelerator_memory_gb() -> float:
69
+ """Memory the training can count on: GPU memory with CUDA, else (Apple, CPU) system memory."""
70
+ try:
71
+ import torch
72
+
73
+ if torch.cuda.is_available():
74
+ return torch.cuda.get_device_properties(0).total_memory / 1024 ** 3
75
+ except ImportError:
76
+ pass
77
+ return memory_gb()
78
+
79
+
80
+ def machine() -> str:
81
+ return os.environ.get("NODEHOP_MACHINE") or platform.node().split(".")[0]
82
+
83
+
84
+ @dataclass
85
+ class BatchPlan:
86
+ micro: int # samples per forward/backward pass on this machine
87
+ accum: int # passes accumulated before each optimizer step
88
+ target: int # effective batch size, the same on every machine
89
+
90
+ def __str__(self) -> str:
91
+ return f"{self.micro} × {self.accum} = {self.micro * self.accum} samples per step"
92
+
93
+
94
+ def batch_plan(target: int, mb_per_sample: float, budget_fraction: float = 0.25,
95
+ memory: Optional[float] = None) -> BatchPlan:
96
+ """Split the effective batch `target` into micro-batches that fit this machine.
97
+
98
+ `mb_per_sample` is the training memory one sample needs (activations,
99
+ gradients); `budget_fraction` of the machine's memory is allowed. A smaller
100
+ machine gets smaller micro-batches and more accumulation steps, so the
101
+ effective batch, and thus the training, stays the same.
102
+ """
103
+ mem = memory if memory is not None else accelerator_memory_gb()
104
+ fits = max(1, int(mem * 1024 * budget_fraction / max(mb_per_sample, 1e-6)))
105
+ micro = 1
106
+ while micro * 2 <= min(fits, target):
107
+ micro *= 2
108
+ while target % micro:
109
+ micro //= 2
110
+ return BatchPlan(micro=micro, accum=target // micro, target=target)
111
+
112
+
113
+ # ---- the job: clean stop, checkpoints, progress -------------------------------
114
+ class Job:
115
+ def __init__(self, directory: str = "checkpoints", every_seconds: float = 60.0, keep: int = 2):
116
+ self.dir = Path(directory)
117
+ self.dir.mkdir(parents=True, exist_ok=True)
118
+ self.every = every_seconds
119
+ self.keep = keep
120
+ self.stop_requested = False
121
+ self._last_save = time.monotonic()
122
+ self.resumed = os.environ.get("NODEHOP_RESUMED") == "1"
123
+ for sig in (signal.SIGINT, signal.SIGTERM, getattr(signal, "SIGHUP", signal.SIGTERM)):
124
+ signal.signal(sig, self._on_signal)
125
+
126
+ def _on_signal(self, signum, frame) -> None:
127
+ if self.stop_requested: # second signal: the person really wants out
128
+ raise KeyboardInterrupt
129
+ self.stop_requested = True
130
+ print(f"\n[nodehop] stop requested on {machine()}: saving a checkpoint, then exiting", flush=True)
131
+
132
+ # checkpoints -----------------------------------------------------------
133
+ def due(self, step: int = 0) -> bool:
134
+ return time.monotonic() - self._last_save >= self.every
135
+
136
+ def save(self, state: Dict[str, Any], step: int,
137
+ writer: Optional[Callable[[Any, str], None]] = None) -> Path:
138
+ """Atomically write checkpoint `step` (torch.save when available, pickle otherwise)."""
139
+ writer = writer or _default_writer()
140
+ final = self.dir / f"ckpt-{step:09d}.pt"
141
+ tmp = final.with_suffix(".tmp")
142
+ writer(dict(state, _nodehop={"machine": machine(), "time": time.time(), "step": step}), str(tmp))
143
+ os.replace(tmp, final)
144
+ for old in sorted(self.dir.glob("ckpt-*.pt"))[:-self.keep]:
145
+ old.unlink(missing_ok=True)
146
+ self._last_save = time.monotonic()
147
+ return final
148
+
149
+ def latest(self) -> Optional[Path]:
150
+ found = sorted(self.dir.glob("ckpt-*.pt"))
151
+ return found[-1] if found else None
152
+
153
+ def load(self, reader: Optional[Callable[[str], Any]] = None) -> Optional[Dict[str, Any]]:
154
+ """Load the latest checkpoint. torch.load / pickle run code stored in the file:
155
+ only load checkpoints your own jobs wrote."""
156
+ path = self.latest()
157
+ if not path:
158
+ return None
159
+ state = (reader or _default_reader())(str(path))
160
+ info = state.get("_nodehop", {})
161
+ print(f"[nodehop] resuming from {path.name} (step {info.get('step')}, saved on {info.get('machine')})",
162
+ flush=True)
163
+ return state
164
+
165
+ def exit(self) -> None:
166
+ print(f"[nodehop] checkpoint saved, exiting cleanly on {machine()}", flush=True)
167
+ sys.exit(0)
168
+
169
+ # progress (shown by `nodehop resolve` and `nodehop status`) -----------------
170
+ def report(self, **fields: Any) -> None:
171
+ path = Path(".nodehop") / "progress.json"
172
+ path.parent.mkdir(exist_ok=True)
173
+ data = dict(fields, machine=machine(), time=time.time())
174
+ tmp = path.with_suffix(".tmp")
175
+ tmp.write_text(json.dumps(data, default=str))
176
+ os.replace(tmp, path)
177
+
178
+
179
+ def _default_writer() -> Callable[[Any, str], None]:
180
+ try:
181
+ import torch
182
+
183
+ return lambda obj, path: torch.save(obj, path)
184
+ except ImportError:
185
+ def write(obj, path):
186
+ with open(path, "wb") as fh:
187
+ pickle.dump(obj, fh)
188
+ return write
189
+
190
+
191
+ def _default_reader() -> Callable[[str], Any]:
192
+ try:
193
+ import torch
194
+
195
+ return lambda path: torch.load(path, map_location="cpu", weights_only=False)
196
+ except ImportError:
197
+ def read(path):
198
+ with open(path, "rb") as fh:
199
+ return pickle.load(fh)
200
+ return read