Datasets:
Tools and the ImageNet-21k card for the released repository; datasets.json under the new name
787d9b7 verified Download tools/openembed_data/install_training.py from UCSC-VLAA/OpenEmbed-Data: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/tools/openembed_data/install_training.py
- Command line
-
hf download hf://datasets/UCSC-VLAA/OpenEmbed-Data/tools/openembed_data/install_training.py
-
curl -L -o install_training.py https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/tools/openembed_data/install_training.py
12.3 kB
| #!/usr/bin/env python3 | |
| """Install rebuilt shards and the training metadata so the OpenEmbed training code can read them. | |
| The training code names every object of its data under one logical root (gs://openembed-release/v1). The folder | |
| training/ of this repository holds what it reads there besides the shards: per dataset the tree card and manifest, | |
| the contamination blocklist, the read-time dedup skip list, the mined-negative side-car and the teacher store's | |
| _COMPLETE.json (training/tree/), and where each shard goes (training/shards.jsonl). This script | |
| 1. checks every rebuilt shard of the datasets asked for: bytes and CRC-32C for the datasets rebuilt exactly, the | |
| record count for those whose images are re-encoded from their source; | |
| 2. lays out a tree: the metadata at its place, each shard at the place its logical URI names, and the released | |
| teacher vectors (checked by sha256) inside the teacher store; | |
| 3. writes the tree to --to: a local folder directly, or a gs:// folder through one `gcloud storage rsync` of a local | |
| staging copy (hard links where possible). | |
| Then train with OPENEMBED_DATA=<the --to folder> (the launcher maps the logical root there) and the OPENEMBED_SKIP | |
| line it prints: the datasets left out (=<name>: that dataset only, not every name it begins), which the launcher | |
| disables and leaves out of distillation on top of a recipe's settings. Distilled datasets installed without their | |
| teacher vectors are listed apart: stage 2 needs their vectors. | |
| python tools/openembed_data/install_training.py --shards shards/ --to gs://my-bucket/openembed-data \\ | |
| [--sets all|ids,folders,categories] [--teacher teacher/] [--staging DIR] [--dry-run] | |
| --shards is the --out folder of build.py (each dataset under <folder>/). Run from the folder that holds tools/ and | |
| training/. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import shutil | |
| import struct | |
| import subprocess | |
| import sys | |
| import time | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| PACK_VERSION = "openembed_training_pack_v1" | |
| def _crc32c_backend(): | |
| try: | |
| import crc32c as _c | |
| return lambda data, value=0: _c.crc32c(data, value), "crc32c" | |
| except ImportError: | |
| pass | |
| try: | |
| import google_crc32c as _g | |
| return lambda data, value=0: _g.extend(value, data), "google-crc32c" | |
| except ImportError: | |
| pass | |
| table = [] | |
| for i in range(256): | |
| c = i | |
| for _ in range(8): | |
| c = (c >> 1) ^ 0x82F63B78 if c & 1 else c >> 1 | |
| table.append(c) | |
| def slow(data, value=0): | |
| c = value ^ 0xFFFFFFFF | |
| for b in bytes(data): | |
| c = table[(c ^ b) & 0xFF] ^ (c >> 8) | |
| return c ^ 0xFFFFFFFF | |
| return slow, "pure-python (slow)" | |
| CRC32C, CRC32C_BACKEND = _crc32c_backend() | |
| def file_crc32c(path: str) -> int: | |
| c = 0 | |
| with open(path, "rb") as fh: | |
| while True: | |
| b = fh.read(8 << 20) | |
| if not b: | |
| return c | |
| c = CRC32C(b, c) | |
| def count_records(path: str) -> int: | |
| """Records of a TFRecord file (frame lengths only); raises at a truncated file.""" | |
| n, size = 0, os.path.getsize(path) | |
| with open(path, "rb") as fh: | |
| pos = 0 | |
| while pos < size: | |
| head = fh.read(12) | |
| if len(head) < 12: | |
| raise ValueError(f"{path}: truncated frame header at byte {pos}") | |
| (length,) = struct.unpack("<Q", head[:8]) | |
| pos += 12 + length + 4 | |
| if pos > size: | |
| raise ValueError(f"{path}: truncated record at frame {n}") | |
| fh.seek(pos) | |
| n += 1 | |
| return n | |
| def sha256_file(path: str) -> str: | |
| h = hashlib.sha256() | |
| with open(path, "rb") as fh: | |
| for b in iter(lambda: fh.read(8 << 20), b""): | |
| h.update(b) | |
| return h.hexdigest() | |
| def place(src: str, dst: str): | |
| """Hard link (same file system) or copy src to dst.""" | |
| os.makedirs(os.path.dirname(dst), exist_ok=True) | |
| if os.path.exists(dst): | |
| os.remove(dst) | |
| try: | |
| os.link(src, dst) | |
| except OSError: | |
| shutil.copyfile(src, dst) | |
| def select(pack: dict, spec: str) -> list[str]: | |
| ds = pack["datasets"] | |
| if not spec or spec == "all": | |
| return sorted(ds) | |
| out, unknown = [], [] | |
| for w in (x.strip() for x in spec.split(",") if x.strip()): | |
| hit = [n for n, d in ds.items() if w in (n, d["folder"], d["folder"].split("/", 1)[1], d["folder"].split("/")[0])] | |
| if not hit: | |
| unknown.append(w) | |
| out += [n for n in sorted(hit) if n not in out] | |
| if unknown: | |
| raise SystemExit(f"unknown datasets: {unknown}") | |
| return out | |
| def check_shard(row: dict, path: str) -> str | None: | |
| """None when the rebuilt shard is what the training data needs, else the reason.""" | |
| if not os.path.exists(path): | |
| return "missing" + (" (written as .incomplete: some records could not be rebuilt)" | |
| if os.path.exists(path + ".incomplete") else "") | |
| if row["check"] == "bytes": | |
| size = os.path.getsize(path) | |
| if size != row["bytes"]: | |
| return f"{size} bytes, want {row['bytes']}" | |
| crc = file_crc32c(path) | |
| if crc != row["crc32c"]: | |
| return f"CRC-32C {crc:08x}, want {row['crc32c']:08x}" | |
| return None | |
| try: | |
| n = count_records(path) | |
| except ValueError as e: | |
| return str(e) | |
| if row["records"] is not None and n != row["records"]: | |
| return f"{n} records, want {row['records']}" | |
| return None | |
| def main(argv=None): | |
| ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| ap.add_argument("--shards", required=True, help="the --out folder of build.py") | |
| ap.add_argument("--to", required=True, help="a local folder or gs://bucket/path: your OPENEMBED_DATA") | |
| ap.add_argument("--sets", default="all") | |
| ap.add_argument("--teacher", default="teacher", help="the teacher/ folder of this repository (vectors)") | |
| ap.add_argument("--pack", default="training", help="the training/ folder of this repository") | |
| ap.add_argument("--staging", help="local staging folder for a gs:// destination (default: <shards>/../_install)") | |
| ap.add_argument("--dry-run", action="store_true", help="check only; write nothing") | |
| args = ap.parse_args(argv) | |
| pack = json.load(open(os.path.join(args.pack, "pack.json"))) | |
| if pack.get("version") != PACK_VERSION: | |
| raise SystemExit(f"{args.pack}/pack.json: version {pack.get('version')!r}, this script reads {PACK_VERSION}") | |
| bad = [rel for rel, f in pack["files"].items() | |
| if not os.path.exists(os.path.join(args.pack, "tree", rel)) | |
| or os.path.getsize(os.path.join(args.pack, "tree", rel)) != f["bytes"] | |
| or sha256_file(os.path.join(args.pack, "tree", rel)) != f["sha256"]] | |
| if bad: | |
| raise SystemExit(f"{len(bad)} files of {args.pack}/tree are missing or differ from pack.json, e.g. {bad[:3]}") | |
| rows = [json.loads(x) for x in open(os.path.join(args.pack, pack["shards"]["file"]))] | |
| by_ds: dict[str, list] = {} | |
| for r in rows: | |
| by_ds.setdefault(r["dataset_id"], []).append(r) | |
| want = select(pack, args.sets) | |
| gs = args.to.startswith("gs://") | |
| tree = None if args.dry_run else (args.staging or os.path.join(os.path.dirname(os.path.abspath(args.shards)), | |
| "_install")) if gs else args.to | |
| print(f"pack {pack['version']} ({len(pack['datasets'])} datasets, logical root {pack['logical_root']}); " | |
| f"CRC-32C via {CRC32C_BACKEND}", flush=True) | |
| t0 = time.time() | |
| ok, failed = [], {} | |
| for name in want: | |
| d = pack["datasets"][name] | |
| problems = [] | |
| for r in by_ds.get(name, []): | |
| src = os.path.join(args.shards, d["folder"], r["shard"]) | |
| why = check_shard(r, src) | |
| if why: | |
| problems.append(f"{r['shard']}: {why}") | |
| if problems: | |
| failed[name] = problems | |
| print(f" {name}: NOT installed, {len(problems)} of {len(by_ds.get(name, []))} shards: {problems[0]}" | |
| + (" ..." if len(problems) > 1 else ""), flush=True) | |
| continue | |
| ok.append(name) | |
| if tree: | |
| for r in by_ds[name]: | |
| place(os.path.join(args.shards, d["folder"], r["shard"]), | |
| os.path.join(tree, r["uri"][len(pack["logical_root"]) + 1:])) | |
| print(f" {name}: {len(by_ds[name])} shards ok", flush=True) | |
| # teacher vectors of the installed distilled datasets | |
| store_rel = pack["teacher_root"][len(pack["logical_root"]) + 1:] | |
| teacher_ok, teacher_missing = [], [] | |
| for name in ok: | |
| comp_rel = f"{store_rel}/{name}/_COMPLETE.json" | |
| if comp_rel not in pack["files"]: | |
| if (pack["datasets"][name].get("teacher") == "withheld"): | |
| teacher_missing.append(name) | |
| continue | |
| comp = json.load(open(os.path.join(args.pack, "tree", comp_rel))) | |
| rel = comp["release"] | |
| srcdir = os.path.join(args.teacher, rel["folder"]) | |
| bad = [] | |
| for fname, f in sorted(rel["files"].items()): | |
| p = os.path.join(srcdir, fname) | |
| if not os.path.exists(p) or os.path.getsize(p) != f["bytes"] or sha256_file(p) != f["sha256"]: | |
| bad.append(fname) | |
| labels = rel.get("labels") or {} | |
| lab_src = os.path.join(srcdir, "labels.npz") | |
| if comp.get("labels") and not os.path.exists(lab_src): | |
| bad.append("labels.npz") | |
| elif comp.get("labels") and labels.get("sha256") and sha256_file(lab_src) != labels["sha256"]: | |
| bad.append("labels.npz") | |
| if bad: | |
| teacher_missing.append(name) | |
| print(f" {name}: teacher vectors missing or different ({len(bad)} files, e.g. {bad[0]}); " | |
| f"left out of TEACHER_DATASETS", flush=True) | |
| continue | |
| teacher_ok.append(name) | |
| if tree: | |
| for fname in rel["files"]: | |
| place(os.path.join(srcdir, fname), os.path.join(tree, store_rel, name, fname)) | |
| if comp.get("labels"): | |
| place(lab_src, os.path.join(tree, store_rel, name, "labels.npz")) | |
| if tree: # the metadata of every dataset (small; read only when used) | |
| for rel in pack["files"]: | |
| place(os.path.join(args.pack, "tree", rel), os.path.join(tree, rel)) | |
| info = {"pack": pack["version"], "logical_root": pack["logical_root"], "installed_utc": | |
| time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "datasets": ok, "not_installed": sorted(failed), | |
| "teacher_datasets": teacher_ok, "teacher_missing": teacher_missing} | |
| with open(os.path.join(tree, "INSTALLED.json"), "w") as fh: | |
| json.dump(info, fh, indent=1) | |
| if gs: | |
| cmd = ["gcloud", "storage", "rsync", "-r", tree, args.to.rstrip("/")] | |
| print("$ " + " ".join(cmd), flush=True) | |
| subprocess.run(cmd, check=True) | |
| missing = sorted(set(pack["datasets"]) - set(ok)) | |
| # the web group is never in the pack (the web pool is released as text and image URLs, without training shards): | |
| # left out by name prefix; every other dataset by its exact name ("=mmeb/Visual7W": as a prefix it would also | |
| # disable mmeb/Visual7W-Pointing) | |
| skip = list(pack.get("not_in_pack_prefixes", ["enrich/", "gen/"])) + ["=" + m for m in missing] | |
| print(f"\n{len(ok)} of {len(want)} datasets installed ({time.time() - t0:.0f} s); teacher vectors for " | |
| f"{len(teacher_ok)}.{' (dry run: nothing written)' if args.dry_run else ''}") | |
| print("# for the training launcher (README, Training): the data, and what it should leave out") | |
| print(f"export OPENEMBED_DATA={args.to.rstrip('/')}") | |
| print(f"export OPENEMBED_SKIP={','.join(skip)}") | |
| if teacher_missing: | |
| print(f"# {len(teacher_missing)} distilled datasets were installed without their teacher vectors; stage 2 " | |
| f"distils them, so get their teacher/ folders and run this again, or add them to OPENEMBED_SKIP: " | |
| f"{','.join('=' + n for n in sorted(teacher_missing))}") | |
| return 1 if failed else 0 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |