gguf-repro-harness / fetch_inputs.py
CyberNative's picture
Add a runner for a public model you choose, with a sharded example receipt
3030105 verified
Raw History Blame Contribute Delete
9.82 kB
#!/usr/bin/env python3
"""Fetch one public model and the pinned evaluation inputs without credentials."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import shutil
import struct
import sys
import urllib.request
import zipfile
from pathlib import Path
from huggingface_hub import HfApi
from huggingface_hub.errors import RepositoryNotFoundError, RevisionNotFoundError
HERE = Path(__file__).resolve().parent
MAX_PARAMETERS = 8_000_000_000
WIKI_URL = "https://huggingface.co/datasets/ggml-org/ci/resolve/927b3642933080f1b0e811e2f916e14c292992f9/wikitext-2-raw-v1.zip"
HELLASWAG_URL = "https://raw.githubusercontent.com/klosax/hellaswag_text_data/5eba56b9ced146c37dc683bead159c5ebcd82cde/hellaswag_val_full.txt"
TOKENIZER_NAMES = {
"tokenizer.json", "tokenizer_config.json", "special_tokens_map.json",
"added_tokens.json", "vocab.json", "merges.txt", "tokenizer.model",
"spiece.model", "sentencepiece.bpe.model", "tokenizer.model.v3",
}
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def tensor_count(header: bytes) -> int:
"""Count tensor elements in a safetensors header, excluding metadata."""
fields = json.loads(header)
count = 0
for name, value in fields.items():
if name == "__metadata__":
continue
shape = value["shape"]
elements = 1
for dimension in shape:
if not isinstance(dimension, int) or dimension < 0:
raise ValueError(f"invalid tensor shape for {name}")
elements *= dimension
count += elements
return count
def read_range(url: str, start: int, length: int) -> bytes:
request = urllib.request.Request(url, headers={"Range": f"bytes={start}-{start + length - 1}"})
with urllib.request.urlopen(request, timeout=60) as response:
if response.status != 206:
raise RuntimeError(f"server did not honor byte range for {url.split('?')[0]}")
data = response.read(length + 1)
if len(data) != length:
raise RuntimeError("incomplete safetensors header response")
return data
def remote_tensor_count(url: str) -> int:
size = struct.unpack("<Q", read_range(url, 0, 8))[0]
if size == 0 or size > 100_000_000:
raise RuntimeError(f"invalid safetensors header size: {size}")
return tensor_count(read_range(url, 8, size))
def model_url(repo: str, revision: str, name: str) -> str:
return f"https://huggingface.co/{repo}/resolve/{revision}/{name}"
def select_shards(names: list[str], repo: str, revision: str) -> list[str]:
available = set(names)
index_name = "model.safetensors.index.json"
if index_name in available:
with urllib.request.urlopen(model_url(repo, revision, index_name), timeout=60) as response:
index_bytes = response.read(10_000_001)
if len(index_bytes) > 10_000_000:
raise ValueError("safetensors index is too large")
index = json.loads(index_bytes)
shards = sorted(set(index["weight_map"].values()))
elif "model.safetensors" in available:
shards = ["model.safetensors"]
else:
shards = sorted(name for name in names if re.fullmatch(r"model-\d+-of-\d+\.safetensors", name))
if not shards or any(name not in available or "/" in name or not name.endswith(".safetensors") for name in shards):
raise ValueError("model has no valid root-level safetensors shard set")
return shards
def preflight(repo: str, revision: str, api: HfApi | None = None) -> tuple[list[str], list[str], str, int, dict[str, str], str | None]:
if not re.fullmatch(r"[0-9a-f]{40}", revision):
raise ValueError("revision must be a 40-character commit SHA")
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repo) or any(part in (".", "..") for part in repo.split("/")):
raise ValueError("model must be a Hugging Face owner/repository name")
try:
info = (api or HfApi(token=False)).model_info(repo, revision=revision, files_metadata=True)
except RevisionNotFoundError as exc:
raise ValueError(f"revision does not resolve: {repo}@{revision}") from exc
except RepositoryNotFoundError as exc:
raise ValueError(f"model is private or unavailable: {repo}") from exc
except Exception as exc:
raise ValueError(f"cannot inspect model before weight download: {repo}@{revision} ({type(exc).__name__})") from exc
if info.sha != revision:
raise ValueError(f"revision did not resolve to the requested commit: {revision}")
if info.private or info.gated:
raise ValueError(f"model is private or gated: {repo}@{revision}")
names = [item.rfilename for item in info.siblings]
shards = select_shards(names, repo, revision)
count = 0
for name in shards:
count += remote_tensor_count(model_url(repo, revision, name))
if count > MAX_PARAMETERS:
raise ValueError(f"model has {count:,} parameters in safetensors headers; limit is 8,000,000,000")
auxiliary = sorted(name for name in names if "/" not in name and (name in TOKENIZER_NAMES or name in {"config.json", "generation_config.json", "model.safetensors.index.json"}))
if "config.json" not in auxiliary:
raise ValueError("model has no config.json")
license_name = info.card_data.get("license") if info.card_data else None
expected = {item.rfilename: item.lfs.sha256 for item in info.siblings if item.rfilename in shards and item.lfs}
card_yaml = info.card_data.to_yaml() if info.card_data else None
return shards, auxiliary, str(license_name) if license_name else "not declared", count, expected, card_yaml
def download(url: str, target: Path) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
partial = target.with_name(target.name + ".part")
try:
with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": "gguf-repro-harness"}), timeout=120) as response, partial.open("wb") as output:
shutil.copyfileobj(response, output, 1 << 20)
partial.replace(target)
finally:
partial.unlink(missing_ok=True)
def fetch_eval(evidence: Path, inputs: dict) -> None:
cache = Path(os.environ["EVAL_CACHE_DIR"]) if os.environ.get("EVAL_CACHE_DIR") else None
for key in ("ppl", "hellaswag"):
entry = inputs[key]
target = evidence / entry["file"]
if target.exists() and sha256_file(target) == entry["sha256"]:
continue
target.parent.mkdir(parents=True, exist_ok=True)
cached = cache / entry["file"] if cache else None
if cached and cached.exists() and sha256_file(cached) == entry["sha256"]:
shutil.copyfile(cached, target)
elif key == "hellaswag":
download(HELLASWAG_URL, target)
else:
archive = evidence / "data" / "wikitext-2-raw-v1.zip"
download(WIKI_URL, archive)
with zipfile.ZipFile(archive) as zipped, zipped.open("wikitext-2-raw/wiki.test.raw") as source, target.open("wb") as output:
shutil.copyfileobj(source, output)
archive.unlink()
actual = sha256_file(target)
if actual != entry["sha256"]:
raise RuntimeError(f"{key} SHA-256 mismatch: {actual}, expected {entry['sha256']}")
def fetch(repo: str, revision: str, evidence: Path, quant: str) -> Path:
shards, auxiliary, license_name, count, expected, card_yaml = preflight(repo, revision)
source_dir = evidence / "sources" / repo
source_dir.mkdir(parents=True, exist_ok=True)
for name in auxiliary + shards:
target = source_dir / name
if name in expected and target.exists() and sha256_file(target) == expected[name]:
continue
print(f"download {name}", flush=True)
download(model_url(repo, revision, name), target)
if name in expected and sha256_file(target) != expected[name]:
target.unlink()
raise RuntimeError(f"downloaded shard SHA-256 mismatch: {name}")
# The converter reads card front matter for GGUF metadata. Reconstruct it
# from the API response so no extra model file is fetched.
if card_yaml:
(source_dir / "README.md").write_text("---\n" + card_yaml.rstrip() + "\n---\n")
base = json.loads((HERE / "inputs.json").read_text())
fetch_eval(evidence, base)
base["quant"]["type"] = quant
base["models"] = {
"owned": {
"hf_repo": repo, "hf_revision": revision, "license": license_name,
"parameter_count": count, "dir": str(source_dir.relative_to(evidence)),
"shards": [{"file": name, "sha256": sha256_file(source_dir / name)} for name in shards],
}
}
destination = evidence / "derived-inputs.json"
destination.write_text(json.dumps(base, indent=2, sort_keys=True) + "\n")
print(f"prepared {repo}@{revision}: {count:,} parameters, {len(shards)} shard(s), license {license_name}")
return destination
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", required=True)
parser.add_argument("--revision", required=True)
parser.add_argument("--evidence-dir", type=Path, default=Path.cwd() / "evidence")
parser.add_argument("--quant", choices=("Q4_K_M", "Q5_K_M", "Q8_0"), default="Q4_K_M")
args = parser.parse_args()
try:
fetch(args.model, args.revision, args.evidence_dir.resolve(), args.quant)
except Exception as exc:
print(f"refused: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())