saef-api / download_model.py
m4az19's picture
Upload 10 files
174cc12 verified
Raw History Blame Contribute Delete
4.08 kB
"""Download the original, pinned Microsoft BiomedCLIP checkpoint (no quantization)."""
from __future__ import annotations
import argparse
import hashlib
import json
import time
from pathlib import Path
import requests
MODEL_ID = "microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224"
MODEL_REVISION = "9f341de24bfb00180f1b847274256e9b65a3a32e"
TEXT_ID = "microsoft/BiomedNLP-BiomedBERT-base-uncased-abstract"
TEXT_REVISION = "d673b8835373c6fa116d6d8006b33d48734e305d"
WEIGHT_NAME = "open_clip_pytorch_model.bin"
WEIGHT_BYTES = 783705670
WEIGHT_SHA256 = "52cc993c5c5ff962bd0c60931874bc001e7e9b41666a385530f4a036294576be"
DEFAULT_DIR = Path(__file__).resolve().parent / "model"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(4 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def download(url: str, target: Path, expected_hash: str | None = None) -> None:
if target.is_file() and (expected_hash is None or sha256(target) == expected_hash):
return
target.parent.mkdir(parents=True, exist_ok=True)
partial = target.with_suffix(target.suffix + ".part")
for attempt in range(3):
try:
with requests.get(url, stream=True, timeout=(30, 180)) as response:
response.raise_for_status()
count = 0
report_at = 64 * 1024 * 1024
with partial.open("wb") as output:
for chunk in response.iter_content(4 * 1024 * 1024):
if not chunk:
continue
output.write(chunk)
count += len(chunk)
if count >= report_at:
print(f"{target.name}: {count / 1048576:.0f} MiB", flush=True)
report_at += 64 * 1024 * 1024
if expected_hash and sha256(partial) != expected_hash:
raise ValueError(f"Checksum mismatch: {target.name}")
partial.replace(target)
return
except (requests.RequestException, OSError, ValueError):
if attempt == 2:
raise
time.sleep(1 + attempt)
def ensure_model(directory: Path = DEFAULT_DIR) -> dict:
directory = directory.resolve()
directory.mkdir(parents=True, exist_ok=True)
base = f"https://huggingface.co/{MODEL_ID}/resolve/{MODEL_REVISION}"
files = [WEIGHT_NAME, "open_clip_config.json", "tokenizer.json", "tokenizer_config.json",
"special_tokens_map.json", "vocab.txt", "LICENSE.md"]
for name in files:
print(f"Checking {name}", flush=True)
download(f"{base}/{name}", directory / name,
WEIGHT_SHA256 if name == WEIGHT_NAME else None)
# The full CLIP checkpoint contains the text weights already. Only the BERT
# architecture config is needed; do not download a second BERT checkpoint.
download(f"https://huggingface.co/{TEXT_ID}/resolve/{TEXT_REVISION}/config.json",
directory / "config.json")
if (directory / WEIGHT_NAME).stat().st_size != WEIGHT_BYTES:
raise ValueError("The full Microsoft checkpoint has an unexpected size.")
manifest = {
"model_id": MODEL_ID, "revision": MODEL_REVISION,
"text_config_id": TEXT_ID, "text_config_revision": TEXT_REVISION,
"quantized": False, "files": {
path.name: {"bytes": path.stat().st_size, "sha256": sha256(path)}
for path in sorted(directory.iterdir())
if path.is_file() and path.name in files + ["config.json"]
},
}
(directory / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
print(f"Full checkpoint verified: {directory / WEIGHT_NAME}", flush=True)
return manifest
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model-dir", type=Path, default=DEFAULT_DIR)
ensure_model(parser.parse_args().model_dir)