"""Fetch and verify the pinned Musci and Qwen weights.""" import hashlib import json import os from pathlib import Path import time UP = Path(__file__).resolve().parent MODELS = os.environ["KM_MODELS_DIR"] def log(*args): print(*args, flush=True) def digest(path, kind): h = hashlib.sha256() if kind == 'sha256' else hashlib.sha1() if kind == 'git': h.update(b'blob %d\0' % os.path.getsize(path)) with open(path, 'rb') as f: for block in iter(lambda: f.read(1 << 24), b''): h.update(block) return h.hexdigest() def stage_models(): from concurrent.futures import ThreadPoolExecutor spec = json.load(open(f'{UP}/models.json')); jobs = [] for name, m in spec.items(): for fn, meta in m['files'].items(): jobs.append((name, m, fn, meta, os.path.join(MODELS, name, fn))) def good(job): name, m, fn, meta, p = job; kind = 'sha256' if 'sha256' in meta else 'git' return os.path.isfile(p) and os.path.getsize(p) == meta['size'] and digest(p, kind) == meta[kind] t = time.time() with ThreadPoolExecutor(4) as ex: have = list(ex.map(good, jobs)) todo = [j for j, ok in zip(jobs, have) if not ok] log(f'{len(jobs) - len(todo)} of {len(jobs)} files already present and verified ({time.time() - t:.0f} s)') if todo: from huggingface_hub import hf_hub_download for name, m, fn, meta, p in todo: t1 = time.time(); os.makedirs(os.path.dirname(p), exist_ok=True) if os.path.exists(p): os.remove(p) hf_hub_download(repo_id=m['repo'], filename=fn, revision=m['revision'], local_dir=os.path.join(MODELS, name)) log(f'downloaded {m["repo"]}@{m["revision"][:8]} {fn} {meta["size"] / 1e6:.0f} MB in {time.time() - t1:.0f} s') with ThreadPoolExecutor(4) as ex: bad = [j[4] for j, ok in zip(todo, ex.map(good, todo)) if not ok] if bad: raise SystemExit(f'KM_FATAL: checksum mismatch after download: {bad}') for name, m in spec.items(): log(f'MODEL_OK {name}: {m["repo"]} @ {m["revision"]} ({len(m["files"])} files) in {os.path.join(MODELS, name)}') if __name__ == "__main__": stage_models()