jbilcke's picture
Publish all four Timestral MLX FP32 models, pipeline, original licences and validation
d35e174 verified
Raw History Blame Contribute Delete
2.22 kB
"""Strict local/Hub loading of converted MLX checkpoints."""
import hashlib
import json
from pathlib import Path
import mlx.core as mx
from huggingface_hub import hf_hub_download
from .config import TimestralConfig
from .model import TimestralModel
VARIANTS = ("5M", "28M", "123M", "209M")
BUNDLE_FILES = ("config.json", "model.safetensors", "LICENSE", "manifest.json")
def sha256(path):
h = hashlib.sha256()
with Path(path).open("rb") as f:
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def load_model(path_or_repo_id, *, variant=None, revision=None, cache_dir=None, token=None, local_files_only=False):
if variant is not None and variant not in VARIANTS:
raise ValueError(f"variant must be one of {VARIANTS}")
base = Path(path_or_repo_id).expanduser()
if base.is_dir():
path = base / variant if variant else base
files = {name: path / name for name in BUNDLE_FILES}
else:
if variant is None:
raise ValueError("specify variant='5M', '28M', '123M' or '209M' for the Hub repository")
files = {name: Path(hf_hub_download(str(path_or_repo_id), f"{variant}/{name}", revision=revision,
cache_dir=cache_dir, token=token, local_files_only=local_files_only))
for name in BUNDLE_FILES}
manifest = json.loads(files["manifest.json"].read_text())
if manifest.get("format") != "timestral-mlx-fp32-v1":
raise ValueError("unsupported checkpoint format")
if variant is not None and manifest.get("variant") != variant:
raise ValueError("checkpoint variant does not match requested variant")
for name in BUNDLE_FILES[:-1]:
expected = manifest["files"][name]
if files[name].stat().st_size != expected["bytes"] or sha256(files[name]) != expected["sha256"]:
raise ValueError(f"checkpoint integrity check failed: {name}")
config = TimestralConfig.load(files["config.json"])
model = TimestralModel(config)
model.load_weights(list(mx.load(str(files["model.safetensors"])).items()), strict=True)
mx.eval(model.parameters())
model.eval()
return model