File size: 6,038 Bytes
4df662e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""Where checkpoints live between VMs, so a run stopped on one VM continues on another.

Both stores keep checkpoints/<name>/ plus a checkpoints/latest.json pointer that is
written only after the checkpoint's files are complete: a VM that dies mid-upload leaves
the pointer on the previous, complete checkpoint. download_latest() fetches the newest
complete checkpoint; load_checkpoint() then verifies its sha256 sums. upload_file() puts
small files next to them (the metrics log, for tools/watch.py).

    FolderStore(root)                  a directory (tests; a mounted disk)
    HubStore(repo_id, private=...)     a Hugging Face model repo (token from HF_TOKEN or the
                                       VM's Hugging Face login). The HGpt run uses a public
                                       repo: anyone can download its checkpoints and metrics

Use store.upload as a CheckpointWriter on_saved callback (it runs in the writer's
background thread, so training does not wait for the upload).
"""

import json
import shutil
import threading
from pathlib import Path

POINTER = "checkpoints/latest.json"


class FolderStore:
    def __init__(self, root, keep: int = 2):
        self.root = Path(root)
        self.keep = keep

    def upload(self, path, manifest):
        target = self.root / "checkpoints" / manifest["name"]
        tmp = target.with_name(target.name + ".tmp")
        shutil.rmtree(tmp, ignore_errors=True)
        shutil.copytree(path, tmp)
        shutil.rmtree(target, ignore_errors=True)
        tmp.rename(target)
        self.upload_file(json.dumps({"name": manifest["name"], "step": manifest["step"],
                                     "tokens": manifest["tokens"]}).encode(), POINTER)
        done = sorted(p for p in (self.root / "checkpoints").iterdir()
                      if p.is_dir() and p.name.startswith("step-") and not p.name.endswith(".tmp"))
        for old in done[:-self.keep]:
            if old.name != manifest["name"]:
                shutil.rmtree(old, ignore_errors=True)

    def upload_file(self, data: bytes, path_in_repo: str):
        target = self.root / path_in_repo
        target.parent.mkdir(parents=True, exist_ok=True)
        target.with_suffix(target.suffix + ".tmp").write_bytes(data)
        target.with_suffix(target.suffix + ".tmp").replace(target)

    def download_file(self, path_in_repo: str, dest) -> bool:
        source = self.root / path_in_repo
        if not source.exists():
            return False
        shutil.copyfile(source, dest)
        return True

    def latest_name(self):
        pointer = self.root / POINTER
        return json.loads(pointer.read_text())["name"] if pointer.exists() else None

    def download_latest(self, dest) -> Path | None:
        name = self.latest_name()
        if name is None:
            return None
        target = Path(dest) / name
        shutil.rmtree(target, ignore_errors=True)
        shutil.copytree(self.root / "checkpoints" / name, target)
        return target


class HubStore:
    def __init__(self, repo_id: str, *, private: bool, token: str | None = None, keep: int = 2, api=None):
        """private must be given explicitly: a public repo exposes every checkpoint."""
        from huggingface_hub import HfApi
        self.repo_id, self.keep, self.token = repo_id, keep, token
        self.api = api or HfApi(token=token)
        self.api.create_repo(repo_id=repo_id, repo_type="model", private=private, exist_ok=True)
        self._lock = threading.Lock()  # checkpoint and metrics uploads come from different threads

    def upload(self, path, manifest):
        name = manifest["name"]
        with self._lock:
            self.api.upload_folder(repo_id=self.repo_id, repo_type="model", folder_path=str(path),
                                   path_in_repo=f"checkpoints/{name}", commit_message=f"checkpoint {name}")
        pointer = json.dumps({"name": name, "step": manifest["step"], "tokens": manifest["tokens"]}).encode()
        self.upload_file(pointer, POINTER, message=f"latest -> {name}")
        with self._lock:
            names = sorted({p.split("/")[1] for p in self.api.list_repo_files(self.repo_id, repo_type="model")
                            if p.startswith("checkpoints/step-")})
            for old in names[:-self.keep]:
                if old != name:
                    self.api.delete_folder(path_in_repo=f"checkpoints/{old}", repo_id=self.repo_id,
                                           repo_type="model", commit_message=f"drop checkpoint {old}")

    def upload_file(self, data: bytes, path_in_repo: str, message: str | None = None):
        with self._lock:
            self.api.upload_file(repo_id=self.repo_id, repo_type="model", path_or_fileobj=data,
                                 path_in_repo=path_in_repo, commit_message=message or f"update {path_in_repo}")

    def download_file(self, path_in_repo: str, dest) -> bool:
        if not self.api.file_exists(self.repo_id, path_in_repo, repo_type="model"):
            return False
        from huggingface_hub import hf_hub_download
        shutil.copyfile(hf_hub_download(self.repo_id, path_in_repo, repo_type="model", token=self.token,
                                        force_download=True), dest)
        return True

    def latest_name(self):
        if not self.api.file_exists(self.repo_id, POINTER, repo_type="model"):
            return None
        from huggingface_hub import hf_hub_download
        pointer = hf_hub_download(self.repo_id, POINTER, repo_type="model", token=self.token, force_download=True)
        return json.loads(Path(pointer).read_text())["name"]

    def download_latest(self, dest) -> Path | None:
        name = self.latest_name()
        if name is None:
            return None
        from huggingface_hub import snapshot_download
        snapshot_download(self.repo_id, repo_type="model", token=self.token, local_dir=str(dest),
                          allow_patterns=[f"checkpoints/{name}/*"])
        return Path(dest) / "checkpoints" / name