Daimon-Infinity / mirror_worker.py
mrfakename's picture
Retry empty tiny ranged responses without Range header
7ab8b49 verified
Raw
History Blame Contribute Delete
9.23 kB
# /// script
# requires-python = ">=3.10"
# dependencies = ["huggingface_hub>=1.0.0", "httpx[http2]>=0.27"]
# ///
"""Resumable, bounded-storage ModelScope -> HF Dataset mirror worker."""
from __future__ import annotations
import os
import shutil
import time
import json
import hashlib
import math
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import urlencode
import httpx
from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
SOURCE_REPO = "daimonrobotics/Daimon-Infinity"
DEST_REPO = "mrfakename/Daimon-Infinity"
WORKER_INDEX = int(os.environ["WORKER_INDEX"])
WORKER_COUNT = int(os.environ["WORKER_COUNT"])
MODELSCOPE_TOKEN = os.environ["MODELSCOPE_TOKEN"]
HF_TOKEN = os.environ["HF_TOKEN"]
WORKDIR = Path("/tmp/daimon-infinity")
def retry(action, label: str, attempts: int = 6):
for attempt in range(attempts):
try:
return action()
except Exception:
if attempt == attempts - 1:
raise
time.sleep(min(180, 2 ** attempt * 5))
def commit_batch(target: HfApi, batch: list[tuple[str, Path]]) -> None:
"""Upload many staged files in one Hub commit, respecting 429 cooldowns."""
operations = [
CommitOperationAdd(path_in_repo=path, path_or_fileobj=str(local))
for path, local in batch
]
for attempt in range(8):
try:
target.create_commit(
repo_id=DEST_REPO,
repo_type="dataset",
operations=operations,
commit_message=f"Mirror batch: {len(batch)} files",
)
return
except Exception as exc:
if "429" in str(exc):
# HF reports an hour-long repository commit cooldown.
time.sleep(3700)
elif attempt == 7:
raise
else:
time.sleep(min(300, 2 ** attempt * 10))
def direct_download(path: str, target: Path, size: int, expected_sha256: str | None) -> None:
"""Download a ModelScope object via direct concurrent HTTP range requests.
This intentionally bypasses ModelScope's snapshot/cache/downloader stack.
Ranges write directly into a preallocated temporary file, avoiding the
SDK's part-file merge and associated extra disk I/O.
"""
query = urlencode({"Revision": "master", "FilePath": path})
url = f"https://modelscope.cn/api/v1/datasets/{SOURCE_REPO}/repo?{query}"
tmp = target.with_suffix(target.suffix + ".partial")
target.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(tmp, os.O_RDWR | os.O_CREAT, 0o644)
try:
os.ftruncate(fd, size)
range_size = max(64 * 1024 * 1024, math.ceil(size / 16))
ranges = [
(start, min(size - 1, start + range_size - 1))
for start in range(0, size, range_size)
]
timeout = httpx.Timeout(connect=30.0, read=120.0, write=120.0, pool=30.0)
limits = httpx.Limits(max_connections=20, max_keepalive_connections=16)
with httpx.Client(
# ModelScope's redirect endpoint intermittently resets HTTP/2
# multiplexed streams. A pool of independent HTTP/1.1 ranges is
# faster in practice because failed streams do not take siblings
# down with the same connection.
http2=False,
follow_redirects=True,
timeout=timeout,
limits=limits,
cookies={"m_session_id": MODELSCOPE_TOKEN},
) as client:
def fetch(byte_range: tuple[int, int]) -> None:
start, end = byte_range
full_file_response = start == 0 and end == size - 1
for attempt in range(8):
try:
# A few tiny ModelScope objects return an empty 200 to
# a Range request. Retry their single full-file range
# without that header before treating it as a failure.
headers = (
{} if full_file_response and attempt > 0
else {"Range": f"bytes={start}-{end}"}
)
with client.stream("GET", url, headers=headers) as response:
if response.status_code != 206 and not (
response.status_code == 200 and full_file_response
):
raise RuntimeError(f"range {start}-{end}: HTTP {response.status_code}")
offset = start
for chunk in response.iter_bytes(4 * 1024 * 1024):
os.pwrite(fd, chunk, offset)
offset += len(chunk)
if offset != end + 1:
raise RuntimeError(f"short range {start}-{end}: got {offset - start}")
return
except Exception:
if attempt == 7:
raise
time.sleep(min(60, 2 ** attempt))
with ThreadPoolExecutor(max_workers=min(16, len(ranges))) as pool:
list(pool.map(fetch, ranges))
finally:
os.close(fd)
if expected_sha256:
digest = hashlib.sha256()
with open(tmp, "rb") as handle:
for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""):
digest.update(chunk)
if digest.hexdigest() != expected_sha256:
tmp.unlink(missing_ok=True)
raise RuntimeError(f"SHA-256 mismatch for {path}")
tmp.replace(target)
def main() -> None:
WORKDIR.mkdir(parents=True, exist_ok=True)
target = HfApi(token=HF_TOKEN)
uploaded = set(target.list_repo_files(DEST_REPO, repo_type="dataset"))
# A dedicated indexing job writes the full paginated source tree once.
# Reusing it avoids thousands of duplicate ModelScope listing requests.
manifest = hf_hub_download(
DEST_REPO, ".mirror/manifest.jsonl", repo_type="dataset", token=HF_TOKEN
)
with open(manifest, encoding="utf-8") as handle:
files = [json.loads(line) for line in handle]
selected = [
item for number, item in enumerate(files)
if number % WORKER_COUNT == WORKER_INDEX
and (item.get("Type") or item.get("type")) != "tree"
]
# Each shard is processed in deterministic manifest order. Resume at its
# first absent path instead of walking tens of thousands of committed files
# after every hourly job restart.
shard_total = len(selected)
resume_at = next(
(
index
for index, item in enumerate(selected)
if (item.get("Path") or item.get("path") or item.get("Name")) not in uploaded
),
len(selected),
)
print(
f"worker {WORKER_INDEX}/{WORKER_COUNT}: "
f"{resume_at}/{shard_total} complete; {shard_total - resume_at} remaining",
flush=True,
)
selected = selected[resume_at:]
pending: list[tuple[str, Path]] = []
pending_bytes = 0
def flush() -> None:
nonlocal pending, pending_bytes
if not pending:
return
commit_batch(target, pending)
for _, local_file in pending:
local_file.unlink(missing_ok=True)
pending = []
pending_bytes = 0
for number, item in enumerate(selected, start=resume_at + 1):
path = item.get("Path") or item.get("path") or item.get("Name")
if not path:
continue
if path in uploaded:
print(f"skip {number}/{shard_total} {path}", flush=True)
continue
local = WORKDIR / path
local.parent.mkdir(parents=True, exist_ok=True)
try:
direct_download(
path,
local,
int(item.get("Size") or item.get("size") or 0),
item.get("Sha256") or item.get("sha256"),
)
local_size = local.stat().st_size
# Keep Xet commit payloads small; large multi-file commits have
# timed out on the Hub. A file over 5 GB is committed by itself.
if pending and (len(pending) >= 200 or pending_bytes + local_size > 5_000_000_000):
flush()
pending.append((path, local))
pending_bytes += local_size
uploaded.add(path)
if len(pending) >= 200 or pending_bytes >= 5_000_000_000:
flush()
print(f"done {number}/{shard_total} {path}", flush=True)
finally:
# Staged files remain until their batch commit succeeds.
if path not in uploaded:
local.unlink(missing_ok=True)
# Remove any empty nested directories left by this file.
parent = local.parent
while parent != WORKDIR:
try:
parent.rmdir()
except OSError:
break
parent = parent.parent
flush()
shutil.rmtree(WORKDIR, ignore_errors=True)
if __name__ == "__main__":
main()