Download src/pat/checkpoint.py from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 6.97 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/checkpoint.py
- Command line
-
hf download hf://ICLRPAT27/PAT-code/src/pat/checkpoint.py
-
curl -L -o checkpoint.py https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/checkpoint.py
6.97 kB
| """Portable, hash-verified model checkpoints with tensor-only serialization.""" | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import re | |
| import shutil | |
| import tempfile | |
| from pathlib import Path | |
| import torch | |
| from safetensors.torch import load_file, save_file | |
| from .config import PATConfig | |
| from .tokenizer import Tokenizer | |
| FORMAT = "pat-checkpoint-v1" | |
| WEIGHTS = "model.safetensors" | |
| REQUIRED_FILES = ("config.json", WEIGHTS, "tokenizer.json", "TOKENIZER_LICENSE.txt", "metadata.json") | |
| def sha256(path: str | Path) -> str: | |
| digest = hashlib.sha256() | |
| with Path(path).open("rb") as stream: | |
| for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def verify_checkpoint(directory: str | Path) -> dict: | |
| """Verify the entire inference bundle before loading its weights.""" | |
| directory = Path(directory) | |
| manifest = json.loads((directory / "manifest.json").read_text()) | |
| if manifest.get("format") != FORMAT: | |
| raise ValueError("Unsupported checkpoint format.") | |
| files = manifest.get("files", {}) | |
| if not set(REQUIRED_FILES).issubset(files): | |
| raise ValueError("Incomplete checkpoint manifest.") | |
| for name, expected in files.items(): | |
| if Path(name).name != name or name in (".", ".."): | |
| raise ValueError("Checkpoint filenames must be simple basenames.") | |
| path = directory / name | |
| if not path.is_file() or path.stat().st_size != expected["size_bytes"]: | |
| raise ValueError(f"Missing or incomplete checkpoint file: {name}") | |
| if sha256(path) != expected["sha256"]: | |
| raise ValueError(f"Checkpoint SHA-256 mismatch: {name}") | |
| Tokenizer(directory / "tokenizer.json") | |
| return manifest | |
| def load_checkpoint( | |
| directory: str | Path, | |
| device: str | torch.device = "cpu", | |
| dtype: torch.dtype | None = None, | |
| ): | |
| """Load a released model in evaluation mode, preserving tied embeddings. | |
| The default retains the stored precision. Passing ``dtype=torch.bfloat16`` | |
| casts weights for inference; autocast can instead preserve FP32 weights. | |
| """ | |
| from .model import PATModel | |
| directory = Path(directory) | |
| verify_checkpoint(directory) | |
| config = PATConfig.from_dict(json.loads((directory / "config.json").read_text())) | |
| weights = load_file(str(directory / WEIGHTS), device="cpu") | |
| if "lm_head.weight" in weights: | |
| raise ValueError("The tied output embedding must be stored only once.") | |
| weights["lm_head.weight"] = weights["token_embed.weight"] | |
| with torch.device("meta"): | |
| model = PATModel(config) | |
| model.load_state_dict(weights, strict=True, assign=True) | |
| model.lm_head.weight = model.token_embed.weight | |
| model = model.to(device=device, dtype=dtype) | |
| return model.eval() | |
| def save_weights( | |
| config: PATConfig, | |
| state: dict[str, torch.Tensor], | |
| directory: str | Path, | |
| metadata: dict | None = None, | |
| ) -> Path: | |
| """Write a new inference bundle atomically; never overwrite an existing one. | |
| The metadata is application supplied JSON. Optimizer and data cursor state | |
| belong to the separate training resume file written by the trainer. | |
| """ | |
| directory = Path(directory) | |
| if directory.exists(): | |
| raise FileExistsError(directory) | |
| directory.parent.mkdir(parents=True, exist_ok=True) | |
| if "token_embed.weight" not in state: | |
| raise ValueError("Missing token embedding.") | |
| if "lm_head.weight" in state and not torch.equal(state["token_embed.weight"], state["lm_head.weight"]): | |
| raise ValueError("Checkpoint requires tied input and output embeddings.") | |
| stage = Path(tempfile.mkdtemp(prefix=f".{directory.name}.", dir=directory.parent)) | |
| try: | |
| clean_state = { | |
| name: tensor.detach().cpu().contiguous() | |
| for name, tensor in state.items() if name != "lm_head.weight" | |
| } | |
| save_file(clean_state, str(stage / WEIGHTS), metadata={"format": FORMAT}) | |
| (stage / "config.json").write_text(json.dumps(config.to_dict(), indent=2) + "\n") | |
| (stage / "metadata.json").write_text(json.dumps(metadata or {}, indent=2) + "\n") | |
| shutil.copyfile(Path(__file__).parent / "assets" / "tokenizer.json", stage / "tokenizer.json") | |
| shutil.copyfile( | |
| Path(__file__).parent / "assets" / "tokenizer_license.txt", | |
| stage / "TOKENIZER_LICENSE.txt", | |
| ) | |
| manifest = {"format": FORMAT, "files": { | |
| name: {"sha256": sha256(stage / name), "size_bytes": (stage / name).stat().st_size} | |
| for name in REQUIRED_FILES | |
| }} | |
| (stage / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") | |
| stage.rename(directory) | |
| except BaseException: | |
| shutil.rmtree(stage, ignore_errors=True) | |
| raise | |
| return directory | |
| def save_checkpoint(model, directory: str | Path, metadata: dict | None = None) -> Path: | |
| """Save model weights, architecture, tokenizer, and caller supplied metadata.""" | |
| return save_weights(model.config, model.state_dict(), directory, metadata) | |
| def download_checkpoint(repo_id: str, revision: str, directory: str | Path) -> Path: | |
| """Download an explicitly selected immutable Hub model revision and verify it.""" | |
| from huggingface_hub import snapshot_download | |
| if not re.fullmatch(r"[0-9a-f]{40}", revision): | |
| raise ValueError("Use the full 40-character commit revision, not a moving branch.") | |
| directory = Path(directory) | |
| if directory.exists(): | |
| raise FileExistsError(directory) | |
| directory.parent.mkdir(parents=True, exist_ok=True) | |
| stage = Path(tempfile.mkdtemp(prefix=f".{directory.name}.", dir=directory.parent)) | |
| try: | |
| snapshot_download(repo_id, revision=revision, local_dir=stage, token=False, | |
| allow_patterns=[*REQUIRED_FILES, "manifest.json"]) | |
| verify_checkpoint(stage) | |
| shutil.rmtree(stage / ".cache", ignore_errors=True) | |
| stage.rename(directory) | |
| except BaseException: | |
| shutil.rmtree(stage, ignore_errors=True) | |
| raise | |
| return directory | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| download = sub.add_parser("download", help="Download a pinned Hub model bundle.") | |
| download.add_argument("--repo", required=True) | |
| download.add_argument("--revision", required=True, help="Full immutable commit hash.") | |
| download.add_argument("--output", required=True, type=Path) | |
| verify = sub.add_parser("verify", help="Verify all files of a local bundle.") | |
| verify.add_argument("directory", type=Path) | |
| args = parser.parse_args() | |
| if args.command == "download": | |
| print(download_checkpoint(args.repo, args.revision, args.output)) | |
| else: | |
| verify_checkpoint(args.directory) | |
| print("Checkpoint verified.") | |
| if __name__ == "__main__": | |
| main() | |