llama.cpp-youtu-moe / download_weights.py
gatilin's picture
Upload folder using huggingface_hub
7e0a8c6 verified
Raw History Blame Contribute Delete
7.81 kB
#!/usr/bin/env python3
"""Youtu-LLM-A7B-Base 权重下载器:镜像优先 + 多连接分段 + 断点续传。
用法:
python download_weights.py # 镜像优先,失败回落官方
python download_weights.py --endpoint https://hf-mirror.com
python download_weights.py --conns 16 # 每文件并发连接数
说明:
- 每个文件按 32 MiB 分块并发下载,已完成的块记录在 <file>.parts.json,
进程中断后再次运行会跳过已完成块。
- hf-mirror 若只是 308 重定向到官方 CDN,脚本会跟随重定向,速度取决于 CDN。
- 下载完成后按官方文件清单校验字节数;不校验 sha256(仓库未提供 LFS sha)。
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import requests
REPO = "tencent/Youtu-LLM-A7B-Base"
REVISION = "6b0d02b2912c2975806db5a4922a1e091fa2f5d3"
CHUNK = 32 * 1024 * 1024
ROOT = Path(__file__).resolve().parent
OUT = ROOT / "models" / "Youtu-LLM-A7B-Base"
_print_lock = threading.Lock()
def log(msg: str) -> None:
with _print_lock:
print(msg, flush=True)
def list_files(session: requests.Session, endpoint: str) -> dict[str, int]:
"""返回 {文件名: 字节数}。"""
url = f"{endpoint}/api/models/{REPO}?blobs=true"
r = session.get(url, timeout=60)
r.raise_for_status()
data = r.json()
if data.get("sha") != REVISION:
log(f"[warn] 远端 revision={data.get('sha')} 与锁定值不同,仍按锁定 revision 下载")
return {s["rfilename"]: s.get("size", 0) for s in data.get("siblings", [])}
def resolve_url(endpoint: str, filename: str) -> str:
return f"{endpoint}/{REPO}/resolve/{REVISION}/{filename}"
def probe(session: requests.Session, endpoint: str) -> bool:
try:
r = session.head(resolve_url(endpoint, "config.json"), allow_redirects=True, timeout=30)
return r.status_code == 200
except Exception as exc: # noqa: BLE001
log(f"[probe] {endpoint} 不可用: {type(exc).__name__}")
return False
def download_file(session_factory, endpoint: str, filename: str, size: int, conns: int) -> None:
dest = OUT / filename
dest.parent.mkdir(parents=True, exist_ok=True)
if dest.exists() and dest.stat().st_size == size:
log(f"[skip] {filename} 已完成")
return
url = resolve_url(endpoint, filename)
part_path = dest.with_suffix(dest.suffix + ".part")
state_path = dest.with_suffix(dest.suffix + ".parts.json")
# 预分配
if not part_path.exists() or part_path.stat().st_size != size:
with open(part_path, "wb") as f:
f.truncate(size)
done: set[int] = set()
if state_path.exists():
try:
done = set(json.loads(state_path.read_text())["done"])
except Exception: # noqa: BLE001
done = set()
chunks = [(i, i * CHUNK, min(size, (i + 1) * CHUNK) - 1) for i in range((size + CHUNK - 1) // CHUNK)]
todo = [c for c in chunks if c[0] not in done]
if not todo:
if part_path.stat().st_size != size:
raise RuntimeError(f"{filename} 分块记录齐全但文件大小不符")
os.replace(part_path, dest)
state_path.unlink(missing_ok=True)
log(f"[done] {filename}")
return
lock = threading.Lock()
written = [0]
started = time.time()
def fetch(chunk: tuple[int, int, int]) -> None:
idx, start, end = chunk
pos = start # 块内断点,网络中断后从上次字节继续
attempt = 0
while True:
try:
s = session_factory()
r = s.get(url, headers={"Range": f"bytes={pos}-{end}"}, stream=True, timeout=120)
if r.status_code not in (200, 206):
raise RuntimeError(f"HTTP {r.status_code}")
if r.status_code == 200 and pos != start:
raise RuntimeError("服务器忽略 Range 请求")
with open(part_path, "r+b") as f:
f.seek(pos)
for block in r.iter_content(1024 * 1024):
if block:
f.write(block)
pos += len(block)
s.close()
if pos <= end:
raise RuntimeError(f"提前结束 {pos}/{end}")
with lock:
done.add(idx)
written[0] += end - start + 1
return
except Exception: # noqa: BLE001
attempt += 1
time.sleep(min(2 ** min(attempt, 5), 30))
with ThreadPoolExecutor(max_workers=conns) as pool:
futures = [pool.submit(fetch, c) for c in todo]
last = 0.0
for fut in as_completed(futures):
fut.result()
now = time.time()
if now - last > 20:
last = now
speed = written[0] / max(now - started, 1e-6)
pct = 100 * (sum(c[2] - c[1] + 1 for c in chunks if c[0] in done)) / size
log(f"[{filename}] {pct:5.1f}% {speed / 2**20:.2f} MiB/s")
state_path.write_text(json.dumps({"done": sorted(done)}))
state_path.write_text(json.dumps({"done": sorted(done)}))
if part_path.stat().st_size != size:
raise RuntimeError(f"{filename} 完成后大小 {part_path.stat().st_size} != 期望 {size}")
os.replace(part_path, dest)
state_path.unlink(missing_ok=True)
log(f"[done] {filename}")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--endpoint", default="https://hf-mirror.com")
ap.add_argument("--fallback", default="https://huggingface.co")
ap.add_argument("--conns", type=int, default=8)
ap.add_argument("--only", default="", help="只下载匹配的子串,如 model-00001")
args = ap.parse_args()
session = requests.Session()
endpoint = args.endpoint
try:
files = list_files(session, endpoint)
except Exception as exc: # noqa: BLE001
log(f"[warn] 镜像元数据失败({type(exc).__name__}),回落 {args.fallback}")
endpoint = args.fallback
files = list_files(session, endpoint)
if not probe(session, endpoint):
log(f"[warn] {endpoint} 探测失败,改用 {args.fallback}")
endpoint = args.fallback
if not probe(session, endpoint):
log("两个端点都不可用")
return 1
targets = {k: v for k, v in files.items() if v > 0 and args.only in k}
total = sum(targets.values())
log(f"端点 {endpoint};文件 {len(targets)} 个,共 {total / 2**30:.1f} GiB;并发 {args.conns}")
def factory() -> requests.Session:
s = requests.Session()
s.headers.update({"User-Agent": "youtu-gguf-downloader/1.0"})
return s
started = time.time()
# 先续传已有 .part 的分片,再按文件名顺序补剩余分片
order = sorted(targets.items(), key=lambda kv: (not (OUT / (kv[0] + ".part")).exists(), kv[0]))
for name, size in order:
while True:
try:
download_file(factory, endpoint, name, size, args.conns)
break
except Exception as exc: # noqa: BLE001
log(f"[retry] {name}: {type(exc).__name__} {exc},10s 后继续")
time.sleep(10)
have = sum((OUT / n).stat().st_size for n in targets if (OUT / n).exists())
elapsed = time.time() - started
log(f"完成 {have / 2**30:.1f}/{total / 2**30:.1f} GiB,用时 {elapsed / 60:.1f} 分钟")
return 0 if have == total else 2
if __name__ == "__main__":
sys.exit(main())