File size: 16,318 Bytes
2f92e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787d9b7
 
 
 
2f92e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787d9b7
2f92e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
787d9b7
 
 
2f92e95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!/usr/bin/env python3
"""One entry point for rebuilding the OpenEmbed training data from this repository.

It reads datasets.json next to this script, the index of every dataset folder: its loader, what it needs and how
large it is. For each dataset asked for, it runs that dataset's own loader with the same command its README gives,
then prints one line per dataset and writes a summary.

    python tools/openembed_data/build.py list [--sets ...] [--json]
    python tools/openembed_data/build.py fetch --sets ... [--teacher]
    python tools/openembed_data/build.py rebuild --sets ... --out shards/ [--cache cache/] [--procs N] [--no-write]
                                                 [--shards NAME,...] [--timm-dir DIR] [--fetch] [--dry-run]

--sets takes dataset ids (mmeb/GQA), folders (vqa/mmeb-gqa), a folder's last part (mmeb-gqa), categories (vqa), or
"all", separated by commas. Run it from the folder that holds tools/ and the dataset folders: the repository root,
or the folder hf download filled (see "Getting the files" in the repository README). `fetch` downloads the folders
of the datasets asked for, and tools/ (needs huggingface_hub).

Dress-ED (editing/dressed/) carries the shards the training read: for it, rebuild checks each shard against its
MANIFEST.json and links or copies it into --out.

Under --out, each dataset's shards go to <folder>/. Logs and problem lists go to _build/: <folder, / as __>.log,
.problems.jsonl and .report.json (when the loader writes one). _build/summary.json sums up the run. Each dataset ends
in one of these results:
  pass        the loader rebuilt every record and its checks hold. Exact sets: every sha256, md5 and crc32c is as
              published. Approximate sets: every record rebuilt, with the images re-encoded from the source.
  incomplete  records were left out; each one is listed in its .problems.jsonl (a source image missing or changed, ...)
  failed      the loader stopped; see its .log
  needs       a prerequisite is missing: the dataset's folder, a login, an archive to put into the cache by hand, a
              package
  not here    a folder of identifiers only (none since 2026-11-18, when DocBank became a regular folder)
The exit status is 1 unless every dataset asked for passed (a "not here" dataset does not count against it), and 2
when packages are missing.
"""
from __future__ import annotations

import argparse
import ast
import json
import os
import re
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
LOADER = {
    "rebuild_shards": ("tools", "openembed_data", "rebuild_shards.py"),
    "rebuild_edit": ("tools", "openembed_data", "rebuild_edit.py"),
    "mmeb_train": ("tools", "mmeb_train", "rebuild_shards.py"),
    "imagenet21k": ("classification", "imagenet-21k", "tools", "loader.py"),
    "shipped_shards": ("tools", "openembed_data", "copy_shards.py"),     # 2026-11-19: Dress-ED carries its shards
}
IMPORT_NAME = {"pyarrow": "pyarrow", "huggingface_hub": "huggingface_hub", "crc32c": "crc32c", "Pillow": "PIL",
               "av": "av", "numpy": "numpy"}
OPTIONAL = {"crc32c"}           # the loaders fall back to a slower CRC-32C


def load_index(path=None):
    return json.load(open(path or os.path.join(HERE, "datasets.json"), encoding="utf-8"))


def select(index, spec):
    ds = index["datasets"]
    if not spec or spec == "all":
        return list(ds)
    out, unknown = [], []
    for w in (x.strip() for x in spec.split(",") if x.strip()):
        hit = [e for e in ds if w in (e["dataset_id"], e["folder"], e["folder"].split("/", 1)[1], e["category"])]
        if not hit:
            unknown.append(w)
        out += [e for e in hit if e not in out]
    if unknown:
        raise SystemExit(f"unknown datasets: {unknown} (`build.py list` shows them all)")
    return out


def size(n):
    if n is None:
        return "?"
    for unit, f in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6)):
        if n >= f:
            return f"{n / f:,.1f} {unit}"
    return "0" if n == 0 else f"{n / 1e3:,.0f} kB"


def needs_text(e):
    n = e.get("needs") or {}
    parts = []
    if "login" in n:
        parts.append("login")
    if "archive" in n:
        parts.append(f"archive {n['archive']['file']}")
    if "builder" in n:
        parts.append("its builder")
    return ", ".join(parts) or "-"


def cmd_list(a, index):
    sets = select(index, a.sets)
    if a.json:
        print(json.dumps(sets, indent=1, ensure_ascii=False))
        return 0
    print(f"{'dataset':28} {'folder':36} {'case':17} {'records':>11} {'download':>10}  needs")
    for e in sets:
        dl = "n/a" if e["loader"] is None else size((e.get("download") or {}).get("bytes"))
        print(f"{e['dataset_id']:28} {e['folder']:36} {e['case']:17} {e['records'] or 0:>11,} {dl:>10}  {needs_text(e)}")
    known = [e["download"]["bytes"] for e in sets if (e.get("download") or {}).get("bytes") is not None]
    print(f"{len(sets)} datasets, {sum(e['records'] or 0 for e in sets):,} records; downloads known for {len(known)}: "
          f"{size(sum(known))} (counted per dataset: sets that share a source, such as M-BEIR's image archive, fetch "
          "it once into the same --cache)")
    return 0


def fetch(root, repo, sets, teacher=False):
    from huggingface_hub import snapshot_download
    pats = ["tools/*"] + [f"{e['folder']}/*" for e in sets] + ([f"teacher/{e['folder']}/*" for e in sets] if teacher else [])
    snapshot_download(repo, repo_type="dataset", allow_patterns=pats, local_dir=root)


def cmd_fetch(a, index):
    sets = select(index, a.sets)
    fetch(a.root, a.repo or index["repository"], sets, a.teacher)
    print(f"{len(sets)} dataset folders and tools/ in {a.root}")
    return 0


def check_packages(sets):
    """Missing packages the selected datasets' READMEs name (crc32c only warns), and pinned versions that differ."""
    import importlib.metadata as md
    import importlib.util
    missing, warn = {}, []
    for e in sets:
        for spec in (e.get("pip") or "").replace('"', "").split():
            name = re.split(r"[<>=!~]", spec, 1)[0]
            mod = IMPORT_NAME.get(name, name)
            if importlib.util.find_spec(mod) is None:
                (warn.append(f"{name} not installed: a slower fallback is used") if name in OPTIONAL
                 else missing.setdefault(name, spec))
                continue
            pin = re.match(r"[^=<>!~]+==(.+)$", spec)
            if pin:
                try:
                    have = md.version(name)
                except md.PackageNotFoundError:
                    continue
                if have != pin.group(1):
                    warn.append(f"{e['dataset_id']}: its README pins {spec}, {name} {have} is installed (the rebuilt "
                                f"bytes may differ and be reported as such)")
    return missing, sorted(set(warn))


def command(e, a, root, out_dir, rep, prob):
    py = sys.executable
    loader = os.path.join(root, *LOADER[e["loader"]])
    cache = os.path.abspath(a.cache)
    if e["loader"] == "rebuild_shards":
        c = [py, loader, "--root", root, "--sets", e["dataset_id"], "--cache", os.path.join(cache, "sources"),
             "--procs", str(a.procs), "--report", rep, "--problems", prob]
        return c + (["--no-write"] if a.no_write else ["--out", out_dir]) + (["--shards", a.shards] if a.shards else [])
    if e["loader"] == "rebuild_edit":
        c = [py, loader, "--set-dir", os.path.join(root, e["folder"]), "--cache", os.path.join(cache, "edit"),
             "--procs", str(a.procs), "--problems", prob]
        return c + ([] if a.no_write else ["--out", out_dir]) + (["--shards", a.shards] if a.shards else [])
    if e["loader"] == "mmeb_train":
        c = [py, loader, "--root", root, "--sets", e["dataset_id"], "--zips", os.path.join(cache, "mmeb_train_zips"),
             "--procs", str(a.procs), "--report", rep, "--problems", prob]
        return c + (["--no-write"] if a.no_write else ["--out", out_dir])
    if e["loader"] == "imagenet21k":
        c = [py, loader, "iterate" if a.no_write else "rebuild", "--package", os.path.join(root, e["folder"])]
        c += ["--timm-dir", os.path.abspath(a.timm_dir)] if a.timm_dir else ["--hf"]
        c += ([] if a.no_write else ["--out", out_dir]) + ["--problems", prob]
        return c + (["--shards", a.shards] if a.shards else [])
    if e["loader"] == "shipped_shards":
        c = [py, loader, "--set-dir", os.path.join(root, e["folder"]), "--problems", prob]
        return c + ([] if a.no_write else ["--out", out_dir]) + (["--shards", a.shards] if a.shards else [])
    raise ValueError(e["loader"])


def prerequisite(e, a, root):
    """None, or what is missing before this dataset's loader can run."""
    n = e.get("needs") or {}
    if e["loader"] is None:
        return "not here", n.get("builder", "identifiers only")
    if not os.path.isdir(os.path.join(root, e["folder"])):
        return "needs", f"its folder {e['folder']}/ (build.py fetch --sets {e['dataset_id']}, or --fetch)"
    if "archive" in n:
        x = n["archive"]
        if not os.path.exists(os.path.join(os.path.abspath(a.cache), "sources", x["file"])):
            return "needs", (f"{x['file']} ({size(x.get('bytes'))}, sha256 {x.get('sha256')}) in "
                             f"{os.path.join(os.path.abspath(a.cache), 'sources')}/ (from {x.get('url')})")
    if "login" in n and not a.timm_dir:
        try:
            from huggingface_hub import get_token
            tok = get_token()
        except ImportError:
            tok = None
        if not tok:
            return "needs", n["login"]
    return None


def outcome(e, rc, rep, prob, log):
    """The result line of one dataset from the loader's exit status, report, problem list and output."""
    problems = sum(1 for _ in open(prob)) if os.path.exists(prob) else 0
    info = {"exit_status": rc, "problems": problems}
    if os.path.exists(rep):
        r = json.load(open(rep)).get("sets", {}).get(e["dataset_id"], {})
        info.update({k: r[k] for k in ("records", "record_ok", "shards", "shards_ok", "error") if k in r})
    text = open(log, errors="replace").read()
    for line in text.splitlines():                    # rebuild_edit: one JSON summary line
        if line.startswith('{"set"'):
            s = json.loads(line)
            info.update({"records_written": s.get("records"), "skipped": s.get("skipped")})
        elif line.startswith("{'shard'"):              # the ImageNet-21k loader: one dict per shard
            s = ast.literal_eval(line)
            info["records_written"] = info.get("records_written", 0) + s.get("written", 0)
    if rc == 0:
        return "pass", info
    if info.get("error"):
        return "needs", info
    if problems:
        return "incomplete", info
    return "failed", info


def cmd_rebuild(a, index):
    sets = select(index, a.sets)
    root = os.path.abspath(a.root)
    if a.shards and len(sets) != 1:
        raise SystemExit("--shards names shards of one dataset: give exactly one in --sets")
    if a.shards and not (sets[0].get("shards_option") or sets[0].get("loader") == "rebuild_shards"):   # 2026-11-18
        raise SystemExit(f"{sets[0]['dataset_id']}: its loader rebuilds whole datasets only (no --shards)")
    if a.fetch:
        todo = [e for e in sets if e["loader"] and not os.path.isdir(os.path.join(root, e["folder"]))]
        if todo:
            fetch(root, a.repo or index["repository"], todo)
    runnable = [e for e in sets if e["loader"]]
    missing, warn = check_packages(runnable)
    for w in warn:
        print(f"note: {w}", flush=True)
    if missing:
        print("missing packages: pip install " + " ".join(sorted(missing.values())), flush=True)
        return 2
    out, bdir = os.path.abspath(a.out), os.path.join(os.path.abspath(a.out), "_build")
    os.makedirs(bdir, exist_ok=True)
    results = []
    for e in sets:
        base = os.path.join(bdir, e["folder"].replace("/", "__"))
        rep, prob, log = base + ".report.json", base + ".problems.jsonl", base + ".log"
        pre = prerequisite(e, a, root)
        if pre:
            res = {"dataset_id": e["dataset_id"], "folder": e["folder"], "result": pre[0], "why": pre[1]}
        else:
            cmd = command(e, a, root, os.path.join(out, e["folder"]), rep, prob)
            if a.dry_run:
                print(" ".join(cmd), flush=True)
                continue
            for p in (rep, prob):
                if os.path.exists(p):
                    os.remove(p)
            t0 = time.time()
            what = f"shards {a.shards}" if a.shards else f"{e['records']:,} records"
            print(f"{time.strftime('%H:%M:%S')} {e['dataset_id']}: {e['case']}, {what} ...", flush=True)
            with open(log, "w") as fh:
                rc = subprocess.run(cmd, cwd=root, stdout=fh, stderr=subprocess.STDOUT).returncode
            result, info = outcome(e, rc, rep, prob, log)
            res = {"dataset_id": e["dataset_id"], "folder": e["folder"], "result": result, "seconds": round(time.time() - t0),
                   "case": e["case"], **info, "log": os.path.relpath(log, out),
                   "problem_list": os.path.relpath(prob, out) if info["problems"] else None}
        results.append(res)
        print(f"  {res['dataset_id']}: {res['result']}" + (f" ({res['why']})" if res.get("why") else
              f" in {res['seconds']}s" + (f", {res['problems']} problems in {res['problem_list']}" if res.get("problem_list")
                                          else "")), flush=True)
    if a.dry_run:
        return 0
    bad = [r for r in results if r["result"] not in ("pass", "not here")]
    summary = {"finished": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "out": out, "no_write": a.no_write,
               "counts": {k: sum(r["result"] == k for r in results) for k in ("pass", "incomplete", "failed", "needs", "not here")},
               "datasets": results}
    json.dump(summary, open(os.path.join(bdir, "summary.json"), "w"), indent=1)
    print(f"{len(results)} datasets: " + ", ".join(f"{v} {k}" for k, v in summary["counts"].items() if v) +
          f"; summary in {os.path.join(bdir, 'summary.json')}", flush=True)
    return 1 if bad else 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--root", default=os.path.abspath(os.path.join(HERE, "..", "..")),
                    help="the folder that holds tools/ and the dataset folders (default: two levels above this script)")
    ap.add_argument("--index", default=None, help="the index to read (default: datasets.json next to this script)")
    sub = ap.add_subparsers(dest="cmd", required=True)
    p = sub.add_parser("list")
    p.add_argument("--sets", default="all")
    p.add_argument("--json", action="store_true")
    p = sub.add_parser("fetch")
    p.add_argument("--sets", required=True)
    p.add_argument("--teacher", action="store_true", help="also the datasets' teacher embeddings (teacher/<folder>/)")
    p.add_argument("--repo", default=None)
    p = sub.add_parser("rebuild")
    p.add_argument("--sets", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--cache", default="cache", help="downloads of the original sources (and archives put in by hand, "
                                                    "under <cache>/sources/)")
    p.add_argument("--procs", type=int, default=os.cpu_count() or 4)
    p.add_argument("--no-write", action="store_true", help="rebuild and check without writing shards")
    p.add_argument("--shards", default="", help="only these shards (one dataset whose loader takes --shards)")
    p.add_argument("--timm-dir", default=None, help="ImageNet-21k: local timm tars instead of streaming them")
    p.add_argument("--fetch", action="store_true", help="download the dataset folders that are not here yet")
    p.add_argument("--repo", default=None)
    p.add_argument("--dry-run", action="store_true", help="print the loader commands and stop")
    a = ap.parse_args(argv)
    index = load_index(a.index)
    return {"list": cmd_list, "fetch": cmd_fetch, "rebuild": cmd_rebuild}[a.cmd](a, index)


if __name__ == "__main__":
    sys.exit(main())