generated from Quantum-Accelerators/template
-
Notifications
You must be signed in to change notification settings - Fork 1
Add optional HuggingFace Hub checkpoint uploading #95
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
Open
forklady42
wants to merge
11
commits into
main
Choose a base branch
from
betsy/huggingface
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
8802778
Add optional HuggingFace Hub checkpoint uploading
forklady42 4aea650
Name HF uploads by epoch and fix callback hook ordering
forklady42 1304594
Address comments
forklady42 942636e
Update src/electrai/callbacks/hf_upload.py
forklady42 a03a169
Update src/electrai/callbacks/hf_upload.py
forklady42 6d3937b
Address comments
forklady42 dd6af61
Address comments
forklady42 cb60f70
Address comments
forklady42 161b884
Clarify --clean help text to mention best-model checkpoints
forklady42 6cdee93
Merge remote-tracking branch 'q/main' into betsy/huggingface
ryan-williams f782897
Fix checkpoint hook ordering and `ImportError` handling in HF callback
ryan-williams File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from electrai.callbacks.hf_upload import HuggingFaceCallback | ||
|
|
||
| __all__ = ["HuggingFaceCallback"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import logging | ||
| import shutil | ||
| from pathlib import Path | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from lightning.pytorch.callbacks import Callback | ||
|
|
||
| if TYPE_CHECKING: | ||
| from types import SimpleNamespace | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| MANIFEST_FILENAME = "hf_upload_manifest.json" | ||
|
|
||
|
|
||
| class HuggingFaceCallback(Callback): | ||
| """Tracks saved checkpoints for deferred upload to HuggingFace Hub. | ||
|
|
||
| On clusters without internet (e.g. Princeton Della), checkpoints are | ||
| queued in a JSON manifest and uploaded later via ``electrai hf-push``. | ||
| When ``hf.upload_immediate`` is True, uploads are attempted inline | ||
| (failures are logged but never crash training). | ||
| """ | ||
|
|
||
| def __init__(self, cfg: SimpleNamespace) -> None: | ||
| super().__init__() | ||
| hf = cfg.hf | ||
| self.repo_id: str = hf["repo_id"] | ||
| self.every_n_epochs: int = hf.get("upload_every_n_epochs", 5) | ||
| self.upload_immediate: bool = hf.get("upload_immediate", False) | ||
| self.ckpt_path = Path(getattr(cfg, "ckpt_path", "./checkpoints")) | ||
| self.manifest_path = self.ckpt_path / MANIFEST_FILENAME | ||
| self._manifest: list[dict] = [] | ||
| self._load_existing_manifest() | ||
|
|
||
| def _load_existing_manifest(self) -> None: | ||
| if self.manifest_path.exists(): | ||
| with self.manifest_path.open(encoding="utf-8") as f: | ||
| self._manifest = json.load(f) | ||
|
|
||
| def _save_manifest(self) -> None: | ||
| self.ckpt_path.mkdir(parents=True, exist_ok=True) | ||
| with self.manifest_path.open("w", encoding="utf-8") as f: | ||
| json.dump(self._manifest, f, indent=2) | ||
ryan-williams marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def _queue_checkpoint( | ||
| self, ckpt_file: Path, epoch: int | None, *, path_in_repo: str | None = None | ||
| ) -> None: | ||
| entry = { | ||
| "path": str(ckpt_file), | ||
| "path_in_repo": path_in_repo or ckpt_file.name, | ||
| "epoch": epoch, | ||
| "repo_id": self.repo_id, | ||
| "uploaded": False, | ||
| } | ||
| self._manifest.append(entry) | ||
| self._save_manifest() | ||
| logger.info("Queued checkpoint for HF upload: %s", ckpt_file.name) | ||
|
Comment on lines
+49
to
+61
|
||
|
|
||
| def on_validation_end(self, trainer, pl_module) -> None: # noqa: ARG002 | ||
| if trainer.sanity_checking: | ||
| return | ||
| epoch = trainer.current_epoch | ||
| if (epoch + 1) % self.every_n_epochs != 0: | ||
| return | ||
forklady42 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if trainer.global_rank != 0: | ||
| return | ||
|
|
||
| last_ckpt = self.ckpt_path / "last.ckpt" | ||
| if not last_ckpt.exists(): | ||
| return | ||
|
|
||
| # Copy to a stable filename so later hf-push uploads the correct | ||
| # snapshot even after last.ckpt is overwritten by subsequent epochs. | ||
| stable_name = f"last_epoch{epoch + 1:03d}.ckpt" | ||
| stable_path = self.ckpt_path / stable_name | ||
| shutil.copy2(last_ckpt, stable_path) | ||
ryan-williams marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| self._queue_checkpoint(stable_path, epoch, path_in_repo=stable_name) | ||
|
|
||
|
|
||
| if self.upload_immediate: | ||
| _upload_single(self._manifest[-1]) | ||
| if self._manifest[-1]["uploaded"]: | ||
| stable_path.unlink(missing_ok=True) | ||
| self._save_manifest() | ||
|
|
||
| def on_train_end(self, trainer, pl_module) -> None: # noqa: ARG002 | ||
| if trainer.global_rank != 0: | ||
| return | ||
| # Queue best checkpoints that haven't been queued yet | ||
| queued_paths = {e["path"] for e in self._manifest} | ||
| had_immediate = False | ||
| for ckpt_file in self.ckpt_path.glob("ckpt_*.ckpt"): | ||
| if str(ckpt_file) not in queued_paths: | ||
| self._queue_checkpoint(ckpt_file, epoch=None) | ||
| if self.upload_immediate: | ||
| _upload_single(self._manifest[-1]) | ||
| had_immediate = True | ||
| if had_immediate: | ||
| self._save_manifest() | ||
|
|
||
| pending = sum(1 for e in self._manifest if not e["uploaded"]) | ||
| if pending: | ||
| logger.info( | ||
| "%d checkpoint(s) pending upload. " | ||
| "Run 'electrai hf-push --ckpt-path %s' from a node with " | ||
| "internet access.", | ||
| pending, | ||
| self.ckpt_path, | ||
| ) | ||
|
|
||
|
|
||
| def _upload_single(entry: dict) -> None: | ||
| """Attempt to upload a single checkpoint. Logs errors, never raises.""" | ||
| path = Path(entry["path"]) | ||
| try: | ||
| from huggingface_hub import upload_file | ||
|
|
||
| if not path.exists(): | ||
| logger.warning("Checkpoint file not found, skipping: %s", path) | ||
| return | ||
| path_in_repo = entry.get("path_in_repo", path.name) | ||
| upload_file( | ||
| path_or_fileobj=str(path), | ||
| path_in_repo=path_in_repo, | ||
| repo_id=entry["repo_id"], | ||
| ) | ||
| entry["uploaded"] = True | ||
| logger.info("Uploaded %s to %s", path.name, entry["repo_id"]) | ||
| except Exception: | ||
| logger.warning( | ||
| "HF upload failed for %s (will retry with hf-push)", | ||
| path.name, | ||
| exc_info=True, | ||
| ) | ||
ryan-williams marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def hf_push(ckpt_path: str, *, clean: bool = False) -> None: | ||
| """Upload pending checkpoints from a manifest file. | ||
|
|
||
| Run this from a login node or machine with internet access. | ||
| """ | ||
| ckpt_dir = Path(ckpt_path) | ||
| manifest_path = ckpt_dir / MANIFEST_FILENAME | ||
| if not manifest_path.exists(): | ||
| raise SystemExit(f"No manifest found at {manifest_path}") | ||
|
|
||
| with manifest_path.open(encoding="utf-8") as f: | ||
| manifest = json.load(f) | ||
|
|
||
| pending = [e for e in manifest if not e["uploaded"]] | ||
| if not pending: | ||
| logger.info("All checkpoints already uploaded.") | ||
| return | ||
|
|
||
| logger.info("Uploading %d pending checkpoint(s)...", len(pending)) | ||
| for entry in pending: | ||
| _upload_single(entry) | ||
|
Comment on lines
+147
to
+167
|
||
| if clean and entry["uploaded"]: | ||
| Path(entry["path"]).unlink(missing_ok=True) | ||
|
|
||
| with manifest_path.open("w", encoding="utf-8") as f: | ||
| json.dump(manifest, f, indent=2) | ||
|
|
||
| still_pending = sum(1 for e in manifest if not e["uploaded"]) | ||
| if still_pending: | ||
| logger.warning("%d checkpoint(s) still failed to upload.", still_pending) | ||
| else: | ||
| logger.info("All checkpoints uploaded successfully.") | ||
ryan-williams marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| import logging | ||
|
|
||
| import torch | ||
|
|
||
|
|
@@ -23,6 +24,7 @@ def main() -> None: | |
| RuntimeError | ||
| if no command was input | ||
| """ | ||
| logging.basicConfig(level=logging.INFO) | ||
| parser = argparse.ArgumentParser(description="Electrai Entry Point") | ||
| subparsers = parser.add_subparsers(dest="command", required=True) | ||
|
|
||
|
|
@@ -32,14 +34,28 @@ def main() -> None: | |
| test_parser = subparsers.add_parser("test", help="Evaluate the model") | ||
| test_parser.add_argument("--config", type=str, required=True) | ||
|
|
||
| hf_push_parser = subparsers.add_parser( | ||
| "hf-push", help="Upload pending checkpoints to HuggingFace Hub" | ||
| ) | ||
| hf_push_parser.add_argument( | ||
| "--ckpt-path", type=str, required=True, help="Path to checkpoint directory" | ||
| ) | ||
| hf_push_parser.add_argument( | ||
| "--clean", | ||
| action="store_true", | ||
| help="Delete local checkpoint files after successful upload (includes best-model checkpoints)", | ||
| ) | ||
|
|
||
| args = parser.parse_args() | ||
|
|
||
| if args.command == "train": | ||
| train(args) | ||
| elif args.command == "test": | ||
| test(args) | ||
| else: | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Removed because argparse with |
||
| raise ValueError(f"Unknown command: {args.command}") | ||
| elif args.command == "hf-push": | ||
| from electrai.callbacks.hf_upload import hf_push | ||
|
|
||
| hf_push(args.ckpt_path, clean=args.clean) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.