micro / faisi /src /prepare_models.py
ppJustin's picture
Add files using upload-large-folder tool
8d435e8 verified
Raw History Blame Contribute Delete
8.09 kB
"""Download and verify pinned Hugging Face snapshots before publishing read-only."""
import argparse
import concurrent.futures
import hashlib
import fcntl
import json
import os
from pathlib import Path
import shutil
import subprocess
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
MODELS = {
"Qwen2.5-14B-Instruct": "cf98f3b3bbb457ad9e2bb7baf9a0125b6b88caa8",
"Qwen2.5-7B-Instruct": "a09a35458c702b33eeacc393d103063234e8bc28",
"Qwen2.5-Coder-32B-Instruct": "381fc969f78efac66bc87ff7ddeadb7e73c218a7",
}
def digest(path, algorithm, prefix=b""):
hasher = hashlib.new(algorithm)
hasher.update(prefix)
with path.open("rb") as file:
while chunk := file.read(8 * 1024 * 1024):
hasher.update(chunk)
return hasher.hexdigest()
def download_weights(urls, partial, size):
chunk_size = 32 * 1024 * 1024
chunk = partial.with_suffix(".chunk")
headers = partial.with_suffix(".headers")
with partial.open("ab") as output:
offset = output.tell()
while offset < size:
end = min(offset + chunk_size, size) - 1
expected = end - offset + 1
for attempt in range(8):
url = urls[(attempt // 3) % len(urls)]
result = subprocess.run([
"curl", "--noproxy", "*", "-fLsS", "--connect-timeout", "6",
"--max-time", "30", "--range", f"{offset}-{end}",
"--dump-header", str(headers), "--output", str(chunk), url,
], capture_output=True)
if result.returncode:
continue
marker = f"content-range: bytes {offset}-{end}/{size}"
lines = headers.read_text(errors="replace").lower().splitlines()
if marker in lines and chunk.stat().st_size == expected:
with chunk.open("rb") as source:
shutil.copyfileobj(source, output, 1024 * 1024)
output.flush()
offset += expected
break
else:
raise RuntimeError(f"Unable to download checked range {offset}-{end} of {partial.name}")
headers.unlink(missing_ok=True)
chunk.unlink(missing_ok=True)
def download_file(endpoint, model, revision, metadata, staging, target, mirror):
name = metadata["rfilename"]
relative = Path(name)
if relative.is_absolute() or ".." in relative.parts:
raise ValueError(name)
path = staging / relative
path.parent.mkdir(parents=True, exist_ok=True)
partial = path.with_name(path.name + ".part")
repo_path = f"/Qwen/{model}/resolve/{revision}/{quote(name)}"
sources = [endpoint + repo_path]
if endpoint != "https://hf-mirror.com":
sources.insert(0, "https://hf-mirror.com" + repo_path)
lfs = metadata.get("lfs")
if mirror:
mirror_url = f"{mirror}/models/Qwen/{model}/resolve/master/{quote(name)}"
sources.insert(0 if lfs else 1, mirror_url)
size = metadata["size"]
shared_tokenizer = Path("/cpfs01/models/Qwen/Qwen2.5-32B-Instruct") / relative
if name in ("merges.txt", "tokenizer.json", "vocab.json") and not (target / relative).is_file():
if shared_tokenizer.is_file():
target = shared_tokenizer.parent
for attempt in range(6):
if not path.is_file():
if attempt == 0 and (target / relative).is_file():
shutil.copyfile(target / relative, path)
else:
if lfs:
try:
download_weights(sources, partial, size)
except RuntimeError as error:
print(f"{model}: {error}; retrying from disk", flush=True)
continue
else:
result = subprocess.run([
"curl", "-fLsS", "--connect-timeout", "6", "--max-time", "18",
"--output", str(partial), sources[attempt % len(sources)],
])
if result.returncode:
continue
partial.replace(path)
sha256 = digest(path, "sha256")
if path.stat().st_size == size and (
sha256 == lfs["sha256"] if lfs
else digest(path, "sha1", f"blob {size}\0".encode()) == metadata["blobId"]
):
print(f"{model}/{name} {size} bytes SHA256 {sha256}", flush=True)
return {"name": name, "size": size, "sha256": sha256}
print(f"Retrying {model}/{name} after hash or size mismatch", flush=True)
path.unlink()
raise RuntimeError(f"Download or integrity check failed: {model}/{name}")
def prepare(model, revision, endpoint, staging_root, workers, mirror):
published = ROOT / "models" / model
if published.is_dir():
existing = json.loads((published / "SHA256SUMS.json").read_text())
if existing["revision"] != revision:
raise FileExistsError(f"Another snapshot already published: {published}")
print(f"Snapshot already published: {published}", flush=True)
return
api = f"{endpoint}/api/models/Qwen/{model}"
metadata = json.loads(subprocess.check_output([
"curl", "-fLsS", "--retry", "3", "--retry-all-errors", "--max-time", "30",
f"{api}?blobs=true",
]))
if metadata["sha"] != revision:
metadata = json.loads(subprocess.check_output([
"curl", "-fLsS", "--retry", "3", "--retry-all-errors", "--max-time", "30",
f"{api}/revision/{revision}?blobs=true",
]))
if metadata["sha"] != revision:
raise ValueError(f"Unexpected repository revision for {model}: {metadata['sha']}")
staging = staging_root / f"{model}-{revision}"
target = Path("/cpfs01/models/Qwen") / model
files = metadata["siblings"]
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
jobs = [
pool.submit(download_file, endpoint, model, revision, item, staging, target, mirror)
for item in files
]
verified = [job.result() for job in jobs]
manifest = {"repo": f"Qwen/{model}", "revision": revision, "files": verified}
destination = published.with_name(f".{published.name}-{revision}")
destination.mkdir(exist_ok=True)
for entry in verified:
name = entry["name"]
output = destination / name
output.parent.mkdir(parents=True, exist_ok=True)
temp = output.with_name(output.name + ".tmp")
if not output.exists() or digest(output, "sha256") != entry["sha256"]:
shutil.copyfile(staging / name, temp)
if digest(temp, "sha256") != entry["sha256"]:
raise RuntimeError(f"Copied file failed verification: {temp}")
temp.chmod(0o444)
temp.replace(output)
manifest_path = destination / "SHA256SUMS.json"
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n")
manifest_path.chmod(0o444)
for directory, _, _ in os.walk(destination, topdown=False):
Path(directory).chmod(0o555)
destination.rename(published)
print(f"Published {published} at {revision}", flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", choices=MODELS, action="append")
parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--staging", type=Path, required=True)
parser.add_argument("--endpoint", default=os.environ.get("HF_ENDPOINT", "https://huggingface.co"))
parser.add_argument("--modelscope-mirror", default=None, help="ModelScope base URL for large files.")
args = parser.parse_args()
args.staging.mkdir(parents=True, exist_ok=True)
for model in args.model or MODELS:
with (args.staging / f".{model}.lock").open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
prepare(model, MODELS[model], args.endpoint.rstrip("/"), args.staging,
args.workers, args.modelscope_mirror)