File size: 2,221 Bytes
d35e174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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