File size: 9,231 Bytes
0c8d13f
 
745d432
0c8d13f
 
 
 
 
 
 
 
ee9224b
745d432
 
 
0c8d13f
745d432
0c8d13f
745d432
a17dd5e
0c8d13f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a17dd5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
745d432
c247c74
5e918b3
745d432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c247c74
 
 
 
 
745d432
 
 
 
 
 
 
7ab8b49
745d432
 
7ab8b49
 
 
 
 
 
 
745d432
bcdf7c0
 
 
745d432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e918b3
 
0c8d13f
 
 
 
ee9224b
 
 
 
 
 
 
0c8d13f
 
d658581
 
0c8d13f
4b5f8e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a17dd5e
 
 
 
 
 
 
 
 
 
 
 
0c8d13f
4b5f8e4
d658581
 
 
0c8d13f
4b5f8e4
0c8d13f
 
 
 
745d432
 
 
 
 
0c8d13f
3804f66
 
 
 
 
a17dd5e
3804f66
0c8d13f
3804f66
a17dd5e
4b5f8e4
0c8d13f
a17dd5e
 
 
0c8d13f
 
 
 
 
 
 
 
 
a17dd5e
0c8d13f
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# /// 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()