cmvr-visual/inference/scripts/download_models.py

281 lines
14 KiB
Python
Raw Normal View History

"""Download pinned public checkpoints into the llmuser workspace."""
import concurrent.futures
import hashlib
import json
import os
import shutil
import subprocess
from pathlib import Path
import threading
import time
os.environ.setdefault("HF_ENDPOINT", "https://hf-mirror.com")
os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "120")
import requests
ROOT = Path("/workspace/projects/llm-services")
MODELS = Path("/workspace/models")
SPECS = [
("whisper-large-v3-turbo", "openai/whisper-large-v3-turbo", "41f01f3fe87f28c78e2fbf8b568835947dd65ed9", "plain"),
("controlnet-canny-sdxl", "diffusers/controlnet-canny-sdxl-1.0", "eb115a19a10d14909256db740ed109532ab1483c", "fp16"),
("sdxl-base", "stabilityai/stable-diffusion-xl-base-1.0", "462165984030d82259a11f4367a4eed129e94a7b", "fp16"),
("wan2.2-ti2v-5b", "Wan-AI/Wan2.2-TI2V-5B-Diffusers", "b8fff7315c768468a5333511427288870b2e9635", "plain"),
("qwen-image", "Qwen/Qwen-Image", "75e0b4be04f60ec59a75f475837eced720f823b6", "plain"),
]
lock = threading.Lock()
transfer_slots = threading.Semaphore(4)
state = {}
MODELSCOPE_REPOS = {
"Qwen/Qwen-Image": "Qwen/Qwen-Image",
"Wan-AI/Wan2.2-TI2V-5B-Diffusers": "Wan-AI/Wan2.2-TI2V-5B-Diffusers",
"stabilityai/stable-diffusion-xl-base-1.0": "stabilityai/stable-diffusion-xl-base-1.0",
"diffusers/controlnet-canny-sdxl-1.0": "AI-ModelScope/controlnet-canny-sdxl-1.0",
"openai/whisper-large-v3-turbo": "AI-ModelScope/whisper-large-v3-turbo",
}
MODELSCOPE_REVISIONS = {
"stabilityai/stable-diffusion-xl-base-1.0": "430c0c115c292c1ff9d91bb78f9b66a91fc7f77a",
}
def update(name, **values):
with lock:
state.setdefault(name, {}).update(values, updated_at=time.time())
dest = ROOT / "state/downloads.json"
temp = dest.with_suffix(".tmp")
temp.write_text(json.dumps(state, indent=2))
temp.replace(dest)
def select_files(files, variant):
chosen = []
for item in files:
name = item["rfilename"]
if name.startswith((".git", "onnx/", "openvino/", "vae_1_0/")):
continue
if name.endswith(".safetensors"):
if "/" not in name and name not in {"model.safetensors", "diffusion_pytorch_model.fp16.safetensors", "diffusion_pytorch_model.safetensors"}:
continue
if variant == "fp16" and ".fp16." not in name:
continue
if variant == "plain" and ".fp16." in name:
continue
elif not (name.endswith((".json", ".txt", ".model", ".tiktoken", ".jinja")) or name in {"LICENSE", "LICENSE.txt", "LICENSE.md", "README.md"}):
continue
chosen.append(item)
if not any(x["rfilename"].endswith(".safetensors") for x in chosen):
raise RuntimeError("Checkpoint selection contains no safetensors")
return chosen
def matches_checkpoint_file(path, item):
path = Path(path)
if not path.is_file():
return False
expected_size = item.get("size", item.get("lfs", {}).get("size", 0))
if expected_size and path.stat().st_size != expected_size:
return False
expected_lfs = item.get("lfs", {}).get("sha256")
expected_git = item.get("blobId")
if not expected_lfs and not expected_git:
return True
digest = hashlib.sha256() if expected_lfs else hashlib.sha1()
if not expected_lfs:
digest.update(b"blob " + str(path.stat().st_size).encode() + b"\0")
with path.open("rb") as source:
for chunk in iter(lambda: source.read(8 * 1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest() == (expected_lfs or expected_git)
def fetch_file(repo, item, target):
name = item["rfilename"]
path = (target / name).resolve()
if not path.is_relative_to(target.resolve()):
raise ValueError("Checkpoint path escapes its model directory")
path.parent.mkdir(parents=True, exist_ok=True)
expected = item.get("size", item.get("lfs", {}).get("size", 0))
aria_control = path.with_name(path.name + ".aria2")
if path.is_file() and not aria_control.exists() and (not expected or path.stat().st_size == expected):
if expected > 64 * 1024 * 1024 or matches_checkpoint_file(path, item):
return
temp = path.with_name(path.name + ".incomplete")
source = MODELSCOPE_REPOS[repo]
if expected <= 64 * 1024 * 1024:
revision = next(spec[2] for spec in SPECS if spec[1] == repo)
url = f"{os.environ['HF_ENDPOINT']}/{repo}/resolve/{revision}/{name}"
with requests.get(url, stream=True, timeout=(20, 120)) as response:
response.raise_for_status()
with temp.open("wb") as output:
for chunk in response.iter_content(1024 * 1024):
output.write(chunk)
if expected and temp.stat().st_size != expected:
raise RuntimeError(f"Incomplete canonical configuration: {name}")
if not matches_checkpoint_file(temp, item):
raise RuntimeError(f"Canonical configuration checksum mismatch: {name}")
temp.replace(path)
return
source_revision = MODELSCOPE_REVISIONS.get(repo, "master")
url = f"https://modelscope.cn/models/{source}/resolve/{source_revision}/{name}"
if expected > 64 * 1024 * 1024 and shutil.which("aria2c"):
previous_partial = path.with_name(path.name + ".incomplete")
if not path.exists() and previous_partial.is_file():
previous_partial.replace(path)
digest = item.get("lfs", {}).get("sha256")
args = ["aria2c", "--continue=true", "--auto-file-renaming=false", "--allow-overwrite=true",
"--file-allocation=none", "--split=8", "--max-connection-per-server=8", "--min-split-size=16M",
"--max-tries=8", "--retry-wait=5", "--connect-timeout=20", "--timeout=90",
"--summary-interval=30", "--console-log-level=warn", "--download-result=hide",
"--dir=" + str(path.parent), "--out=" + path.name]
if digest:
args.append("--checksum=sha-256=" + digest)
with transfer_slots:
result = subprocess.run(args + [url], check=False, timeout=21600)
if result.returncode == 32:
# A public replica may carry a different VAE revision. Never
# accept it just because the filename is the same.
if path.exists():
path.replace(path.with_name(path.name + ".mirror-mismatch"))
control = path.with_name(path.name + ".aria2")
if control.exists():
control.unlink()
revision = next(spec[2] for spec in SPECS if spec[1] == repo)
canonical = f"{os.environ['HF_ENDPOINT']}/{repo}/resolve/{revision}/{name}"
print("Replica checksum differs; fetching canonical file", repo, name, flush=True)
subprocess.run(args + [canonical], check=True, timeout=21600)
elif result.returncode:
raise subprocess.CalledProcessError(result.returncode, args + [url])
if expected and path.stat().st_size != expected:
raise RuntimeError(f"Incomplete file: {name}")
return
for attempt in range(4):
try:
offset = temp.stat().st_size if temp.exists() else 0
headers = {"Range": f"bytes={offset}-"} if offset else {}
with requests.get(url, headers=headers, stream=True, timeout=(20, 120)) as response:
response.raise_for_status()
append = bool(offset and response.status_code == 206)
with temp.open("ab" if append else "wb") as output:
for chunk in response.iter_content(4 * 1024 * 1024):
output.write(chunk)
if expected and temp.stat().st_size != expected:
raise RuntimeError(f"Incomplete file: {name}")
temp.replace(path)
return
except Exception:
if attempt == 3:
raise
time.sleep(3 * (attempt + 1))
def download(spec):
name, repo, revision, variant = spec
update(name, state="resolving", repo=repo, revision=revision)
for attempt in range(1, 5):
try:
cache = ROOT / "config" / "metadata" / (name + ".json")
if cache.is_file():
info = json.loads(cache.read_text())
else:
r = requests.get(f"{os.environ['HF_ENDPOINT']}/api/models/{repo}/revision/{revision}", params={"blobs": "true"}, timeout=60)
if r.status_code == 429:
raise RuntimeError("Metadata source rate-limited; supply the pinned metadata cache before retrying")
r.raise_for_status()
info = r.json()
cache.parent.mkdir(parents=True, exist_ok=True)
cache.write_text(json.dumps(info))
if info["sha"] != revision:
raise RuntimeError("Unexpected repository revision")
selected = select_files(info["siblings"], variant)
target = MODELS / name
target.mkdir(parents=True, exist_ok=True)
total = sum(x.get("size", x.get("lfs", {}).get("size", 0)) for x in selected)
update(name, state="downloading", expected_bytes=total, attempt=attempt)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
list(pool.map(lambda item: fetch_file(repo, item, target), selected))
update(name, state="verifying")
verified = []
for item in selected:
path = target / item["rfilename"]
if not path.is_file():
raise RuntimeError(f"Missing checkpoint file: {path.name}")
size = item.get("size", item.get("lfs", {}).get("size"))
if size and path.stat().st_size != size:
raise RuntimeError(f"File size mismatch: {path.name}")
expected = item.get("lfs", {}).get("sha256")
digest = None
if expected:
h = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
h.update(chunk)
digest = h.hexdigest()
if digest != expected:
path.rename(path.with_name(path.name + ".sha256-mismatch"))
raise RuntimeError(f"SHA256 mismatch: {path.name}")
elif not matches_checkpoint_file(path, item):
path.rename(path.with_name(path.name + ".sha256-mismatch"))
raise RuntimeError(f"Git object checksum mismatch: {path.name}")
verified.append({"path": item["rfilename"], "bytes": path.stat().st_size, "sha256": digest})
manifest = {"repo": repo, "revision": revision, "variant": variant,
"metadata_source": info.get("metadata_source", os.environ["HF_ENDPOINT"]),
"metadata_cache": str(cache),
"weight_source": "ModelScope replica; canonical HF mirror for small files and replica checksum mismatches",
"files": verified, "verified_at": time.time()}
marker = target / ".deployment-manifest.json"
staging = target / ".deployment-manifest.json.tmp"
staging.write_text(json.dumps(manifest, indent=2))
staging.replace(marker)
update(name, state="ready", bytes=sum(x["bytes"] for x in verified))
return
except Exception as exc:
update(name, state="retrying" if attempt < 4 else "failed", error=str(exc), attempt=attempt)
print(name, attempt, type(exc).__name__, str(exc), flush=True)
if attempt == 4 or "rate-limited" in str(exc):
raise
time.sleep(min(5 * attempt, 15))
def realesrgan():
name = "realesrgan"
target = MODELS / name
target.mkdir(parents=True, exist_ok=True)
url = "https://modelscope.cn/api/v1/models/AI-ModelScope/RealESRGAN_x4plus/repo?Revision=11797f3585f24f49d2120b6d7a2e67f61ffc542c&FilePath=RealESRGAN_x4plus.pth"
expected_sha256 = "4fa0d38905f75ac06eb49a7951b426670021be3018265fd191d2125df9d682f1"
update(name, state="downloading", url=url)
p = target / "RealESRGAN_x4plus.pth"
tmp = p.with_suffix(".incomplete")
with requests.get(url, timeout=(20, 120), stream=True) as r:
r.raise_for_status()
expected = int(r.headers.get("Content-Length", "0"))
with tmp.open("wb") as f:
for chunk in r.iter_content(1024 * 1024):
f.write(chunk)
if expected and tmp.stat().st_size != expected:
raise RuntimeError("Real-ESRGAN download incomplete")
if tmp.stat().st_size < 50_000_000:
raise RuntimeError("Real-ESRGAN checkpoint unexpectedly small")
tmp.replace(p)
digest = hashlib.sha256(p.read_bytes()).hexdigest()
if digest != expected_sha256:
raise RuntimeError("Real-ESRGAN SHA256 does not match the verified upstream checkpoint")
(target / ".deployment-manifest.json").write_text(json.dumps({"source": url, "bytes": p.stat().st_size, "sha256": digest}, indent=2))
update(name, state="ready", bytes=p.stat().st_size, sha256=digest)
if __name__ == "__main__":
ROOT.joinpath("state").mkdir(parents=True, exist_ok=True)
failures = []
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:
futures = {pool.submit(download, spec): spec[0] for spec in SPECS}
futures[pool.submit(realesrgan)] = "realesrgan"
for future in concurrent.futures.as_completed(futures):
try:
future.result()
except Exception as exc:
name = futures[future]
failures.append(name)
update(name, state="failed", error=str(exc))
if failures:
raise SystemExit("Failed downloads: " + ", ".join(failures))