File size: 2,768 Bytes
1024e04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Download only pinned tensor-only checkpoints and verify every checksum."""
import hashlib
import json
import os
from pathlib import Path

from .dicom import InferenceError

MANIFEST = json.loads(Path(__file__).with_name("manifest.json").read_text())
_verified = {}


def cache_root():
    return Path(os.environ.get("SYNTAX_MODEL_CACHE", str(Path.home() / ".cache" / "syntax-space" / MANIFEST["revision"])))


def status():
    files = MANIFEST["score_weights"] + [MANIFEST["classifier"]]
    root = cache_root()
    cached = sum((root / f["path"]).is_file() and (root / f["path"]).stat().st_size == f["size"] for f in files)
    return {
        "repo_id": MANIFEST["repo_id"], "revision": MANIFEST["revision"],
        "models": 10, "classifier": True, "cached_files": cached,
        "total_files": len(files), "cached": cached == len(files),
        "device": os.environ.get("SYNTAX_DEVICE", "cpu"),
        "loaded": False, "lazy": True,
        "classifier_preprocessing": MANIFEST["preprocessing"]["classifier"],
    }


def weight_file(record, progress=None):
    path = cache_root() / record["path"]
    if not path.is_file():
        if progress:
            progress("download", {"file": record["path"], "message": "Downloading a verified model checkpoint"})
        from huggingface_hub import hf_hub_download
        try:
            path = Path(hf_hub_download(
                repo_id=MANIFEST["repo_id"], filename=record["path"],
                revision=MANIFEST["revision"], local_dir=str(cache_root()), token=False,
            ))
        except Exception as exc:
            raise InferenceError("A required model checkpoint could not be downloaded. Please retry.") from exc
    stat = path.stat()
    if "size" in record and stat.st_size != record["size"]:
        raise InferenceError(f"Model checkpoint is incomplete: {record['path']}.")
    key = (str(path.resolve()), stat.st_size, stat.st_mtime_ns, stat.st_ino)
    if _verified.get(key) != record["sha256"]:
        digest = hashlib.sha256()
        with path.open("rb") as stream:
            for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
                digest.update(chunk)
        if digest.hexdigest() != record["sha256"]:
            raise InferenceError(f"Model checksum mismatch: {record['path']}. The checkpoint was not used.")
        _verified[key] = record["sha256"]
    return path


def calibration(progress=None):
    record = MANIFEST["calibration"]
    source = json.loads(weight_file(record, progress).read_text())
    folds = [{"a": source[f"fold{i}"]["a"], "b": source[f"fold{i}"]["b"]} for i in range(5)]
    if folds != record["folds"]:
        raise InferenceError("Calibration coefficients do not match the pinned model release.")
    return folds