284 lines
14 KiB
Python
284 lines
14 KiB
Python
|
|
"""仅下载固定官方H3 FL2VA Diffusers布局,并以官方hash逐个校验。"""
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import argparse
|
|||
|
|
import concurrent.futures
|
|||
|
|
import json
|
|||
|
|
import math
|
|||
|
|
from pathlib import Path, PurePosixPath
|
|||
|
|
import re
|
|||
|
|
import shutil
|
|||
|
|
import subprocess
|
|||
|
|
import sys
|
|||
|
|
import threading
|
|||
|
|
import time
|
|||
|
|
from urllib.parse import quote
|
|||
|
|
|
|||
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|||
|
|
from llm_services.video_profiles import H3_DIRECTORY, H3_REPO, H3_REVISION
|
|||
|
|
|
|||
|
|
PREFIXES = ('transformer/', 'text_encoder/', 'vae/', 'audio_vae/', 'scheduler/',
|
|||
|
|
'audio_scheduler/', 'processor/', 'tokenizer/')
|
|||
|
|
MIB = 1024 ** 2
|
|||
|
|
retry_sleep = time.sleep
|
|||
|
|
|
|||
|
|
|
|||
|
|
def select_files(items):
|
|||
|
|
result = []
|
|||
|
|
seen = set()
|
|||
|
|
for item in items:
|
|||
|
|
if not isinstance(item, dict) or not isinstance(item.get('rfilename'), str):
|
|||
|
|
raise ValueError('Invalid model metadata path')
|
|||
|
|
name = item['rfilename']
|
|||
|
|
path = PurePosixPath(name)
|
|||
|
|
if (not name or path.is_absolute() or '..' in path.parts or '\\' in name
|
|||
|
|
or path.as_posix() != name or any(ord(char) < 32 for char in name)):
|
|||
|
|
raise ValueError('Unsafe model metadata path')
|
|||
|
|
if name.startswith(PREFIXES) or name in {'model_index.json', 'modular_model_index.json', 'LICENSE', 'README.md'}:
|
|||
|
|
if name in seen:
|
|||
|
|
raise ValueError('Duplicate model metadata path')
|
|||
|
|
seen.add(name)
|
|||
|
|
result.append(item)
|
|||
|
|
return result
|
|||
|
|
|
|||
|
|
|
|||
|
|
def validate_metadata(info):
|
|||
|
|
if not isinstance(info, dict):
|
|||
|
|
raise ValueError('Model metadata must be an object')
|
|||
|
|
if info.get('repo', info.get('id')) != H3_REPO or info.get('revision', info.get('sha')) != H3_REVISION:
|
|||
|
|
raise ValueError('Metadata repo/revision differs from the immutable H3 profile')
|
|||
|
|
files = select_files(info.get('files', info.get('siblings', [])))
|
|||
|
|
if not files or not any(item['rfilename'].endswith('.safetensors') for item in files):
|
|||
|
|
raise ValueError('H3 metadata has no model weights')
|
|||
|
|
for item in files:
|
|||
|
|
if type(item.get('size')) is not int or item['size'] <= 0:
|
|||
|
|
raise ValueError('H3 metadata must include every file size')
|
|||
|
|
lfs = item.get('lfs') or {}
|
|||
|
|
if not isinstance(lfs, dict):
|
|||
|
|
raise ValueError('Invalid canonical checksum metadata')
|
|||
|
|
digest, length = (lfs['sha256'], 64) if lfs.get('sha256') else (item.get('blobId'), 40)
|
|||
|
|
if not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{' + str(length) + '}', digest):
|
|||
|
|
raise ValueError('H3 metadata must include every canonical checksum')
|
|||
|
|
return files
|
|||
|
|
|
|||
|
|
|
|||
|
|
def parse_args(argv=None):
|
|||
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|||
|
|
parser.add_argument('--metadata', type=Path, help='运维可提供固定revision的官方元数据缓存')
|
|||
|
|
parser.add_argument('--workers', type=int, choices=range(1, 9), default=2)
|
|||
|
|
parser.add_argument('--max-total-mib', '--total-limit', dest='max_total_mib',
|
|||
|
|
type=int, choices=range(1, 9), default=8,
|
|||
|
|
help='整个下载器的总上限MiB/s,按workers向下取整分配,默认8')
|
|||
|
|
parser.add_argument('--state', type=Path, help='进度JSON路径,默认模型目录/.download-state.json')
|
|||
|
|
parser.add_argument('--attempts', type=int, choices=range(1, 6), default=3,
|
|||
|
|
help='每个文件最多启动aria2的次数,默认3')
|
|||
|
|
return parser.parse_args(argv)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def read_limited_response(response, rate_bps, *, clock=time.monotonic, sleep=time.sleep,
|
|||
|
|
maximum=16 * MIB):
|
|||
|
|
"""只有元数据走HTTP流;读取前预留小块预算,文件全部走限速aria2。"""
|
|||
|
|
chunks, count, deadline = [], 0, clock()
|
|||
|
|
iterator = iter(response.iter_content(chunk_size=64 * 1024))
|
|||
|
|
while True:
|
|||
|
|
deadline = max(deadline, clock()) + 64 * 1024 / rate_bps
|
|||
|
|
sleep(max(0, deadline - clock()))
|
|||
|
|
try:
|
|||
|
|
chunk = next(iterator)
|
|||
|
|
except StopIteration:
|
|||
|
|
return b''.join(chunks)
|
|||
|
|
count += len(chunk)
|
|||
|
|
if count > maximum:
|
|||
|
|
raise ValueError('Model metadata response is too large')
|
|||
|
|
chunks.append(chunk)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class DownloadProgress:
|
|||
|
|
def __init__(self, target, files, workers, total_mib, per_worker_bps, state_path=None):
|
|||
|
|
self.path = Path(state_path) if state_path is not None else target / '.download-state.json'
|
|||
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
self.lock = threading.Lock()
|
|||
|
|
self.value = {'repo': H3_REPO, 'revision': H3_REVISION, 'state': 'downloading',
|
|||
|
|
'workers': workers, 'max_total_mib': total_mib,
|
|||
|
|
'per_worker_limit_bytes': per_worker_bps,
|
|||
|
|
'effective_total_limit_bytes': per_worker_bps * workers,
|
|||
|
|
'total_files': len(files), 'expected_bytes': sum(item['size'] for item in files),
|
|||
|
|
'files': {item['rfilename']: {'state': 'queued', 'expected_bytes': item['size'],
|
|||
|
|
'attempt': 0} for item in files}}
|
|||
|
|
self.update()
|
|||
|
|
|
|||
|
|
def update(self, name=None, *, state=None, **values):
|
|||
|
|
from llm_services.store import atomic_json
|
|||
|
|
with self.lock:
|
|||
|
|
if name is not None:
|
|||
|
|
self.value['files'][name].update(values, state=state, updated_at=time.time())
|
|||
|
|
elif state is not None:
|
|||
|
|
self.value['state'] = state
|
|||
|
|
entries = list(self.value['files'].values())
|
|||
|
|
self.value.update(updated_at=time.time(),
|
|||
|
|
verified_files=sum(item['state'] == 'verified' for item in entries),
|
|||
|
|
failed_files=sum(item['state'] == 'failed' for item in entries),
|
|||
|
|
verified_bytes=sum(item['expected_bytes'] for item in entries if item['state'] == 'verified'))
|
|||
|
|
atomic_json(self.path, self.value)
|
|||
|
|
if name is not None:
|
|||
|
|
label = 'VERIFIED' if state == 'verified' else state.upper()
|
|||
|
|
print(f'{label} {name} attempt={self.value["files"][name]["attempt"]}'
|
|||
|
|
+ (f' error={values["error"]}' if values.get('error') else ''), flush=True)
|
|||
|
|
else:
|
|||
|
|
print(f'PROGRESS {self.value["state"]} verified={self.value["verified_files"]}/'
|
|||
|
|
f'{self.value["total_files"]} bytes={self.value["verified_bytes"]}/'
|
|||
|
|
f'{self.value["expected_bytes"]} failed={self.value["failed_files"]}', flush=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def run_aria(command, *, timeout):
|
|||
|
|
return subprocess.run(command, check=False, timeout=timeout)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _path(target, name):
|
|||
|
|
path = target / name
|
|||
|
|
if not path.resolve().is_relative_to(target.resolve()) or path.is_symlink():
|
|||
|
|
raise ValueError('Checkpoint path escapes its model directory or is a symlink')
|
|||
|
|
for suffix in ('.aria2', '.incomplete'):
|
|||
|
|
if path.with_name(path.name + suffix).is_symlink():
|
|||
|
|
raise ValueError('Checkpoint resume/control file must not be a symlink')
|
|||
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|||
|
|
return path
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _quarantine(path):
|
|||
|
|
# 确认损坏的下载保留为旁路文件,不让后续--continue把错误字节当作可信断点。
|
|||
|
|
if path.exists():
|
|||
|
|
path.replace(path.with_name(path.name + f'.checksum-mismatch.{time.time_ns()}'))
|
|||
|
|
path.with_name(path.name + '.aria2').unlink(missing_ok=True)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _fetch(item, target, downloader, progress, *, aria_binary, rate_bps, connections, attempts):
|
|||
|
|
name = item['rfilename']
|
|||
|
|
path = _path(target, name)
|
|||
|
|
control = path.with_name(path.name + '.aria2')
|
|||
|
|
if path.is_file() and not control.exists() and path.stat().st_size == item['size']:
|
|||
|
|
progress.update(name, state='verifying')
|
|||
|
|
if downloader.matches_checkpoint_file(path, item):
|
|||
|
|
progress.update(name, state='verified')
|
|||
|
|
return name
|
|||
|
|
_quarantine(path)
|
|||
|
|
incomplete = path.with_name(path.name + '.incomplete')
|
|||
|
|
if not path.exists() and incomplete.is_file():
|
|||
|
|
incomplete.replace(path)
|
|||
|
|
encoded = quote(name, safe='/')
|
|||
|
|
canonical = (f"{downloader.os.environ['HF_ENDPOINT'].rstrip('/')}/{H3_REPO}"
|
|||
|
|
f'/resolve/{H3_REVISION}/{encoded}')
|
|||
|
|
replica = f'https://modelscope.cn/models/MiniMax/MiniMax-H3/resolve/master/{encoded}'
|
|||
|
|
for attempt in range(1, attempts + 1):
|
|||
|
|
# 权重按尝试次数轮换字节来源,每次仍强制官方hash;配置始终使用固定canonical版本。
|
|||
|
|
url = replica if attempt % 2 == 1 and name.endswith('.safetensors') else canonical
|
|||
|
|
progress.update(name, state='downloading', attempt=attempt, source=url, error=None)
|
|||
|
|
command = [aria_binary, '--continue=true', '--auto-file-renaming=false',
|
|||
|
|
'--allow-overwrite=true', '--file-allocation=none', '--check-integrity=true',
|
|||
|
|
f'--split={connections}', f'--max-connection-per-server={connections}',
|
|||
|
|
'--max-concurrent-downloads=1', f'--max-overall-download-limit={rate_bps}',
|
|||
|
|
'--min-split-size=16M', '--max-tries=1', '--retry-wait=0',
|
|||
|
|
'--connect-timeout=20', '--timeout=90', '--summary-interval=15',
|
|||
|
|
'--console-log-level=warn', '--download-result=hide',
|
|||
|
|
'--dir=' + str(path.parent), '--out=' + path.name]
|
|||
|
|
digest = (item.get('lfs') or {}).get('sha256')
|
|||
|
|
if digest:
|
|||
|
|
command.append('--checksum=sha-256=' + digest)
|
|||
|
|
try:
|
|||
|
|
result = run_aria(command + [url], timeout=max(300, math.ceil(item['size'] / rate_bps * 2) + 180))
|
|||
|
|
if result.returncode:
|
|||
|
|
if result.returncode == 32:
|
|||
|
|
_quarantine(path)
|
|||
|
|
raise RuntimeError(f'aria2 exited with code {result.returncode}')
|
|||
|
|
progress.update(name, state='verifying')
|
|||
|
|
if control.exists():
|
|||
|
|
raise RuntimeError('Unfinished aria2 control file; retaining resume state')
|
|||
|
|
if not downloader.matches_checkpoint_file(path, item):
|
|||
|
|
_quarantine(path)
|
|||
|
|
raise RuntimeError('Canonical checksum mismatch')
|
|||
|
|
progress.update(name, state='verified', error=None)
|
|||
|
|
return name
|
|||
|
|
except (OSError, RuntimeError, subprocess.SubprocessError) as exc:
|
|||
|
|
progress.update(name, state='retrying' if attempt < attempts else 'failed', error=str(exc))
|
|||
|
|
if attempt == attempts:
|
|||
|
|
raise
|
|||
|
|
retry_sleep(min(5 * attempt, 15))
|
|||
|
|
|
|||
|
|
|
|||
|
|
def download_files(files, target, downloader, *, workers=2, total_mib=8, attempts=3,
|
|||
|
|
aria_binary=None, progress_seconds=15, state_path=None):
|
|||
|
|
if (type(workers) is not int or not 1 <= workers <= 8
|
|||
|
|
or type(total_mib) is not int or not 1 <= total_mib <= 8
|
|||
|
|
or type(attempts) is not int or not 1 <= attempts <= 5):
|
|||
|
|
raise ValueError('workers/rate/attempts exceed download policy')
|
|||
|
|
# 调用入口同样校验,不能绕过CLI的固定repo、revision、路径与hash约束。
|
|||
|
|
files = validate_metadata({'repo': H3_REPO, 'revision': H3_REVISION, 'files': files})
|
|||
|
|
aria_binary = aria_binary or shutil.which('aria2c')
|
|||
|
|
if not aria_binary:
|
|||
|
|
raise RuntimeError('aria2c is required for capped resumable FL2VA downloads')
|
|||
|
|
target = Path(target)
|
|||
|
|
target.mkdir(parents=True, exist_ok=True)
|
|||
|
|
marker = target / '.deployment-manifest.json'
|
|||
|
|
marker.unlink(missing_ok=True)
|
|||
|
|
per_worker_bps = total_mib * MIB // workers
|
|||
|
|
progress = DownloadProgress(target, files, workers, total_mib, per_worker_bps, state_path)
|
|||
|
|
failed = False
|
|||
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
|||
|
|
pending = {pool.submit(_fetch, item, target, downloader, progress,
|
|||
|
|
aria_binary=aria_binary, rate_bps=per_worker_bps,
|
|||
|
|
connections=16, attempts=attempts): item['rfilename'] for item in files}
|
|||
|
|
while pending:
|
|||
|
|
done, _ = concurrent.futures.wait(pending, timeout=progress_seconds,
|
|||
|
|
return_when=concurrent.futures.FIRST_COMPLETED)
|
|||
|
|
if not done:
|
|||
|
|
progress.update()
|
|||
|
|
for future in done:
|
|||
|
|
name = pending.pop(future)
|
|||
|
|
try:
|
|||
|
|
future.result()
|
|||
|
|
except Exception as exc:
|
|||
|
|
failed = True
|
|||
|
|
progress.update(name, state='failed', error=f'{type(exc).__name__}: {exc}')
|
|||
|
|
if failed:
|
|||
|
|
progress.update(state='failed')
|
|||
|
|
return 1
|
|||
|
|
from llm_services.store import atomic_json
|
|||
|
|
atomic_json(marker, {'repo': H3_REPO, 'revision': H3_REVISION, 'files': files,
|
|||
|
|
'precision': 'official-mixed-bf16-fp32', 'verified_at': time.time()})
|
|||
|
|
progress.update(state='ready')
|
|||
|
|
print('ALL_VERIFIED', flush=True)
|
|||
|
|
return 0
|
|||
|
|
|
|||
|
|
|
|||
|
|
def main(argv=None):
|
|||
|
|
args = parse_args(argv)
|
|||
|
|
import download_models as downloader
|
|||
|
|
try:
|
|||
|
|
if args.metadata:
|
|||
|
|
info = json.loads(args.metadata.read_text(encoding='utf-8'))
|
|||
|
|
else:
|
|||
|
|
for attempt in range(1, args.attempts + 1):
|
|||
|
|
try:
|
|||
|
|
with downloader.requests.get(
|
|||
|
|
f"{downloader.os.environ['HF_ENDPOINT']}/api/models/{H3_REPO}/revision/{H3_REVISION}",
|
|||
|
|
params={'blobs': 'true'}, stream=True, headers={'Accept-Encoding': 'identity'},
|
|||
|
|
timeout=(20, 90)) as response:
|
|||
|
|
response.raise_for_status()
|
|||
|
|
info = json.loads(read_limited_response(response, args.max_total_mib * MIB))
|
|||
|
|
break
|
|||
|
|
except (downloader.requests.RequestException, OSError) as exc:
|
|||
|
|
print(f'METADATA retry={attempt}/{args.attempts} error={exc}', flush=True)
|
|||
|
|
if attempt == args.attempts:
|
|||
|
|
raise
|
|||
|
|
retry_sleep(min(5 * attempt, 15))
|
|||
|
|
return download_files(validate_metadata(info), Path(H3_DIRECTORY), downloader,
|
|||
|
|
workers=args.workers, total_mib=args.max_total_mib, attempts=args.attempts,
|
|||
|
|
state_path=args.state)
|
|||
|
|
except Exception as exc:
|
|||
|
|
print(f'DOWNLOAD_FAILED {type(exc).__name__}: {exc}', flush=True)
|
|||
|
|
return 1
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == '__main__':
|
|||
|
|
raise SystemExit(main())
|