mrfakename commited on
Commit
850106d
·
verified ·
1 Parent(s): 7ab8b49

Upload .mirror/mirror_worker.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. .mirror/mirror_worker.py +252 -0
.mirror/mirror_worker.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = ["huggingface_hub>=1.0.0", "httpx[http2]>=0.27", "modelscope-hub>=0.2.0"]
4
+ # ///
5
+ """Resumable, bounded-storage ModelScope -> HF Dataset mirror worker."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import shutil
11
+ import time
12
+ import json
13
+ import hashlib
14
+ import math
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from pathlib import Path
17
+ from urllib.parse import urlencode
18
+
19
+ import httpx
20
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
21
+ from modelscope_hub import HubApi
22
+
23
+ SOURCE_REPO = "daimonrobotics/Daimon-Infinity"
24
+ DEST_REPO = "mrfakename/Daimon-Infinity"
25
+ WORKER_INDEX = int(os.environ["WORKER_INDEX"])
26
+ WORKER_COUNT = int(os.environ["WORKER_COUNT"])
27
+ MODELSCOPE_TOKEN = os.environ["MODELSCOPE_TOKEN"]
28
+ HF_TOKEN = os.environ["HF_TOKEN"]
29
+ WORKDIR = Path("/tmp/daimon-infinity")
30
+
31
+
32
+ def retry(action, label: str, attempts: int = 6):
33
+ for attempt in range(attempts):
34
+ try:
35
+ return action()
36
+ except Exception:
37
+ if attempt == attempts - 1:
38
+ raise
39
+ time.sleep(min(180, 2 ** attempt * 5))
40
+
41
+
42
+ def commit_batch(target: HfApi, batch: list[tuple[str, Path]]) -> None:
43
+ """Upload many staged files in one Hub commit, respecting 429 cooldowns."""
44
+ operations = [
45
+ CommitOperationAdd(path_in_repo=path, path_or_fileobj=str(local))
46
+ for path, local in batch
47
+ ]
48
+ for attempt in range(8):
49
+ try:
50
+ target.create_commit(
51
+ repo_id=DEST_REPO,
52
+ repo_type="dataset",
53
+ operations=operations,
54
+ commit_message=f"Mirror batch: {len(batch)} files",
55
+ )
56
+ return
57
+ except Exception as exc:
58
+ if "429" in str(exc):
59
+ # HF reports an hour-long repository commit cooldown.
60
+ time.sleep(3700)
61
+ elif attempt == 7:
62
+ raise
63
+ else:
64
+ time.sleep(min(300, 2 ** attempt * 10))
65
+
66
+
67
+ def direct_download(path: str, target: Path, size: int, expected_sha256: str | None) -> None:
68
+ """Download a ModelScope object via direct concurrent HTTP range requests.
69
+
70
+ This intentionally bypasses ModelScope's snapshot/cache/downloader stack.
71
+ Ranges write directly into a preallocated temporary file, avoiding the
72
+ SDK's part-file merge and associated extra disk I/O.
73
+ """
74
+ query = urlencode({"Revision": "master", "FilePath": path})
75
+ url = f"https://modelscope.cn/api/v1/datasets/{SOURCE_REPO}/repo?{query}"
76
+ tmp = target.with_suffix(target.suffix + ".partial")
77
+ target.parent.mkdir(parents=True, exist_ok=True)
78
+ fd = os.open(tmp, os.O_RDWR | os.O_CREAT, 0o644)
79
+ try:
80
+ os.ftruncate(fd, size)
81
+ range_size = max(64 * 1024 * 1024, math.ceil(size / 16))
82
+ ranges = [
83
+ (start, min(size - 1, start + range_size - 1))
84
+ for start in range(0, size, range_size)
85
+ ]
86
+ timeout = httpx.Timeout(connect=30.0, read=120.0, write=120.0, pool=30.0)
87
+ limits = httpx.Limits(max_connections=20, max_keepalive_connections=16)
88
+ with httpx.Client(
89
+ # ModelScope's redirect endpoint intermittently resets HTTP/2
90
+ # multiplexed streams. A pool of independent HTTP/1.1 ranges is
91
+ # faster in practice because failed streams do not take siblings
92
+ # down with the same connection.
93
+ http2=False,
94
+ follow_redirects=True,
95
+ timeout=timeout,
96
+ limits=limits,
97
+ cookies={"m_session_id": MODELSCOPE_TOKEN},
98
+ ) as client:
99
+ def fetch(byte_range: tuple[int, int]) -> None:
100
+ start, end = byte_range
101
+ full_file_response = start == 0 and end == size - 1
102
+ for attempt in range(8):
103
+ try:
104
+ # A few tiny ModelScope objects return an empty 200 to
105
+ # a Range request. Retry their single full-file range
106
+ # without that header before treating it as a failure.
107
+ headers = (
108
+ {} if full_file_response and attempt > 0
109
+ else {"Range": f"bytes={start}-{end}"}
110
+ )
111
+ with client.stream("GET", url, headers=headers) as response:
112
+ if response.status_code != 206 and not (
113
+ response.status_code == 200 and full_file_response
114
+ ):
115
+ raise RuntimeError(f"range {start}-{end}: HTTP {response.status_code}")
116
+ offset = start
117
+ for chunk in response.iter_bytes(4 * 1024 * 1024):
118
+ os.pwrite(fd, chunk, offset)
119
+ offset += len(chunk)
120
+ if offset != end + 1:
121
+ raise RuntimeError(f"short range {start}-{end}: got {offset - start}")
122
+ return
123
+ except Exception:
124
+ if attempt == 7:
125
+ raise
126
+ time.sleep(min(60, 2 ** attempt))
127
+
128
+ with ThreadPoolExecutor(max_workers=min(16, len(ranges))) as pool:
129
+ list(pool.map(fetch, ranges))
130
+ finally:
131
+ os.close(fd)
132
+
133
+ if expected_sha256:
134
+ digest = hashlib.sha256()
135
+ with open(tmp, "rb") as handle:
136
+ for chunk in iter(lambda: handle.read(16 * 1024 * 1024), b""):
137
+ digest.update(chunk)
138
+ if digest.hexdigest() != expected_sha256:
139
+ tmp.unlink(missing_ok=True)
140
+ raise RuntimeError(f"SHA-256 mismatch for {path}")
141
+ tmp.replace(target)
142
+
143
+
144
+ def main() -> None:
145
+ WORKDIR.mkdir(parents=True, exist_ok=True)
146
+ source = HubApi(token=MODELSCOPE_TOKEN)
147
+ source.login(MODELSCOPE_TOKEN)
148
+ target = HfApi(token=HF_TOKEN)
149
+ uploaded = set(target.list_repo_files(DEST_REPO, repo_type="dataset"))
150
+ # A dedicated indexing job writes the full paginated source tree once.
151
+ # Reusing it avoids thousands of duplicate ModelScope listing requests.
152
+ manifest = hf_hub_download(
153
+ DEST_REPO, ".mirror/manifest.jsonl", repo_type="dataset", token=HF_TOKEN
154
+ )
155
+ with open(manifest, encoding="utf-8") as handle:
156
+ files = [json.loads(line) for line in handle]
157
+ selected = [
158
+ item for number, item in enumerate(files)
159
+ if number % WORKER_COUNT == WORKER_INDEX
160
+ and (item.get("Type") or item.get("type")) != "tree"
161
+ ]
162
+ # Each shard is processed in deterministic manifest order. Resume at its
163
+ # first absent path instead of walking tens of thousands of committed files
164
+ # after every hourly job restart.
165
+ shard_total = len(selected)
166
+ resume_at = next(
167
+ (
168
+ index
169
+ for index, item in enumerate(selected)
170
+ if (item.get("Path") or item.get("path") or item.get("Name")) not in uploaded
171
+ ),
172
+ len(selected),
173
+ )
174
+ print(
175
+ f"worker {WORKER_INDEX}/{WORKER_COUNT}: "
176
+ f"{resume_at}/{shard_total} complete; {shard_total - resume_at} remaining",
177
+ flush=True,
178
+ )
179
+ selected = selected[resume_at:]
180
+ pending: list[tuple[str, Path]] = []
181
+ pending_bytes = 0
182
+
183
+ def flush() -> None:
184
+ nonlocal pending, pending_bytes
185
+ if not pending:
186
+ return
187
+ commit_batch(target, pending)
188
+ for _, local_file in pending:
189
+ local_file.unlink(missing_ok=True)
190
+ pending = []
191
+ pending_bytes = 0
192
+
193
+ for number, item in enumerate(selected, start=resume_at + 1):
194
+ path = item.get("Path") or item.get("path") or item.get("Name")
195
+ if not path:
196
+ continue
197
+ if path in uploaded:
198
+ print(f"skip {number}/{shard_total} {path}", flush=True)
199
+ continue
200
+ local = WORKDIR / path
201
+ local.parent.mkdir(parents=True, exist_ok=True)
202
+ try:
203
+ file_size = int(item.get("Size") or item.get("size") or 0)
204
+ if file_size < 1_000_000:
205
+ # The ModelScope API sometimes serves an empty 200 for a
206
+ # direct ranged tiny object. The SDK path is reliable here;
207
+ # keep the custom fast path for the actual bulk data.
208
+ source.download_file(
209
+ SOURCE_REPO,
210
+ "dataset",
211
+ path,
212
+ local_dir=WORKDIR,
213
+ force=False,
214
+ expected_sha256=item.get("Sha256") or item.get("sha256"),
215
+ )
216
+ else:
217
+ direct_download(
218
+ path,
219
+ local,
220
+ file_size,
221
+ item.get("Sha256") or item.get("sha256"),
222
+ )
223
+ local_size = local.stat().st_size
224
+ # Keep Xet commit payloads small; large multi-file commits have
225
+ # timed out on the Hub. A file over 5 GB is committed by itself.
226
+ if pending and (len(pending) >= 200 or pending_bytes + local_size > 5_000_000_000):
227
+ flush()
228
+ pending.append((path, local))
229
+ pending_bytes += local_size
230
+ uploaded.add(path)
231
+ if len(pending) >= 200 or pending_bytes >= 5_000_000_000:
232
+ flush()
233
+ print(f"done {number}/{shard_total} {path}", flush=True)
234
+ finally:
235
+ # Staged files remain until their batch commit succeeds.
236
+ if path not in uploaded:
237
+ local.unlink(missing_ok=True)
238
+ # Remove any empty nested directories left by this file.
239
+ parent = local.parent
240
+ while parent != WORKDIR:
241
+ try:
242
+ parent.rmdir()
243
+ except OSError:
244
+ break
245
+ parent = parent.parent
246
+
247
+ flush()
248
+ shutil.rmtree(WORKDIR, ignore_errors=True)
249
+
250
+
251
+ if __name__ == "__main__":
252
+ main()