File size: 6,969 Bytes
643267a | 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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | """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()
|