Datasets:
Download classification/imagenet-21k/tools/loader.py from UCSC-VLAA/OpenEmbed-Data: direct link, hf CLI and curl.
- Browser
- Download file 17.5 kB
-
https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/classification/imagenet-21k/tools/loader.py
- Command line
-
hf download hf://datasets/UCSC-VLAA/OpenEmbed-Data/classification/imagenet-21k/tools/loader.py
-
curl -L -o loader.py https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/classification/imagenet-21k/tools/loader.py
17.5 kB
| #!/usr/bin/env python3 | |
| """Rebuild the ImageNet-21k training shards of this package from the timm images. | |
| This folder holds every field of the 13,016,419 training records except the image bytes. Each | |
| record names its image in timm/imagenet-w21-wds at revision | |
| c08bf7ec5384ac07212a1cc1867e93fb78f5cbcc (tar file + sample key). This script fetches those | |
| images and writes the training shards back, byte for byte: | |
| * every image must have the sha256 stored in the record (``image_sha256``); | |
| * every re-serialized record must have the stored ``record_sha256``; | |
| * every finished shard must have the CRC32C and MD5 listed in ``shards.parquet``. | |
| Any mismatch stops with an error; no record is skipped or changed. | |
| Commands | |
| rebuild write shards (all, or --shards / --hosts) to --out | |
| iterate print a summary of the records that reached training (filters applied), with | |
| their images; use ``iter_training_records`` from Python for the records themselves | |
| check-tars sha256 of local timm tars against ``timm_tars.parquet`` | |
| Images come from local tars (``--timm-dir``, the files as downloaded from Hugging Face) or are | |
| streamed from Hugging Face (``--hf``; needs ``huggingface_hub`` and a login that has accepted the | |
| ImageNet terms of access on the timm/imagenet-w21-wds page). Requirements: pyarrow; crc32c or | |
| google-crc32c makes CRC32C fast (a pure-Python fallback is used otherwise, very slow). | |
| python tools/loader.py rebuild --package . --timm-dir /data/imagenet-w21-wds --out shards/ | |
| python tools/loader.py rebuild --package . --hf --out shards/ --shards part-h000-00000.tfrecord | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import io | |
| import json | |
| import os | |
| import struct | |
| import sys | |
| import tarfile | |
| from collections import defaultdict | |
| TIMM_REPO = "timm/imagenet-w21-wds" | |
| TIMM_REVISION = "c08bf7ec5384ac07212a1cc1867e93fb78f5cbcc" | |
| BYTES_FEATURES = ("query_text", "text", "neg_text", "wnid", "src", "license") | |
| # --------------------------------------------------------------------------- CRC32C | |
| try: | |
| import crc32c as _c | |
| def crc32c_update(crc: int, data) -> int: | |
| return _c.crc32c(data, crc) | |
| except ImportError: # pragma: no cover | |
| try: | |
| import google_crc32c as _g | |
| def crc32c_update(crc: int, data) -> int: | |
| return _g.extend(crc, bytes(data)) | |
| except ImportError: | |
| _T = [] | |
| for _i in range(256): | |
| _r = _i | |
| for _ in range(8): | |
| _r = (_r >> 1) ^ 0x82F63B78 if _r & 1 else _r >> 1 | |
| _T.append(_r) | |
| def crc32c_update(crc: int, data) -> int: | |
| r = crc ^ 0xFFFFFFFF | |
| for b in bytes(data): | |
| r = _T[(r ^ b) & 0xFF] ^ (r >> 8) | |
| return r ^ 0xFFFFFFFF | |
| def masked_crc32c(data) -> int: | |
| c = crc32c_update(0, data) | |
| return (((c >> 15) | (c << 17)) + 0xA282EAD8) & 0xFFFFFFFF | |
| def frame(payload: bytes) -> bytes: | |
| """One TFRecord frame: length, masked CRC of the length, payload, masked CRC of the payload.""" | |
| ln = struct.pack("<Q", len(payload)) | |
| return ln + struct.pack("<I", masked_crc32c(ln)) + payload + struct.pack("<I", masked_crc32c(payload)) | |
| # --------------------------------------------------------------------------- tf.train.Example | |
| def _varint(n: int) -> bytes: | |
| out = bytearray() | |
| while True: | |
| b = n & 0x7F | |
| n >>= 7 | |
| if n: | |
| out.append(b | 0x80) | |
| else: | |
| out.append(b) | |
| return bytes(out) | |
| def _ld(field: int, payload: bytes) -> bytes: | |
| return _varint((field << 3) | 2) + _varint(len(payload)) + payload | |
| def _bytes_feature(values: list[bytes]) -> bytes: | |
| return _ld(1, b"".join(_ld(1, v) for v in values)) # Feature.bytes_list | |
| def _float_feature(values: list[float]) -> bytes: | |
| body = _ld(1, struct.pack(f"<{len(values)}f", *values)) if values else b"" | |
| return _ld(2, body) # Feature.float_list (packed) | |
| def encode_record(row: dict, jpg: bytes) -> bytes: | |
| """Serialize one record as tf.train.Example, map entries in the stored feature order.""" | |
| entries = [] | |
| for name in row["feature_order"].split(","): | |
| if name == "jpg": | |
| feat = _bytes_feature([jpg]) | |
| elif name == "cand_jpg": | |
| feat = _bytes_feature([bytes(row["cand_jpg"])]) | |
| elif name == "teacher_scores": | |
| feat = _float_feature(list(row["teacher_scores"])) | |
| elif name in BYTES_FEATURES: | |
| feat = _bytes_feature([row[name].encode("utf-8")]) | |
| else: | |
| raise ValueError(f"unknown feature {name!r}") | |
| entries.append(_ld(1, _ld(1, name.encode("utf-8")) + _ld(2, feat))) | |
| return _ld(1, b"".join(entries)) | |
| # --------------------------------------------------------------------------- package files | |
| def _pq(): | |
| import pyarrow.dataset as ds | |
| import pyarrow.parquet as pq | |
| return ds, pq | |
| def read_table(package: str, name: str): | |
| _, pq = _pq() | |
| return pq.read_table(os.path.join(package, name)) | |
| def _dataset(package: str): | |
| ds, _ = _pq() | |
| return ds, ds.dataset(os.path.join(package, "records"), format="parquet") | |
| def shard_rows(package: str, shard: str) -> list[dict]: | |
| """All columns of one shard's records, in ordinal order.""" | |
| ds, dset = _dataset(package) | |
| rows = dset.to_table(filter=ds.field("shard") == shard).to_pylist() | |
| rows.sort(key=lambda r: r["ordinal"]) | |
| return rows | |
| def image_sources(package: str, shards: list[str]) -> dict[str, dict[str, set[str]]]: | |
| """{shard: {tar: {keys}}} from two projected columns only (cheap for many shards).""" | |
| ds, dset = _dataset(package) | |
| tbl = dset.to_table(columns=["shard", "timm_tar", "timm_key"], filter=ds.field("shard").isin(shards)) | |
| out: dict[str, dict[str, set[str]]] = defaultdict(lambda: defaultdict(set)) | |
| for s, t, k in zip(*(tbl.column(c).to_pylist() for c in ("shard", "timm_tar", "timm_key"))): | |
| out[s][t].add(k) | |
| return out | |
| class _TarCache: | |
| """Fetch each timm tar once for a group of shards; free it when no later shard needs it.""" | |
| def __init__(self, images: "TimmImages", sources: dict[str, dict[str, set[str]]], order: list[str]): | |
| self.images, self.sources = images, sources | |
| self.need: dict[str, set[str]] = defaultdict(set) | |
| self.left: dict[str, int] = defaultdict(int) | |
| for s in order: | |
| for t, keys in sources.get(s, {}).items(): | |
| self.need[t] |= keys | |
| self.left[t] += 1 | |
| self.cache: dict[str, dict[str, bytes]] = {} | |
| def images_for(self, shard: str) -> dict[tuple[str, str], bytes]: | |
| out = {} | |
| for t in sorted(self.sources.get(shard, {})): | |
| if t not in self.cache: | |
| self.cache[t] = self.images.fetch(t, self.need[t]) | |
| out.update({(t, k): v for k, v in self.cache[t].items()}) | |
| return out | |
| def done(self, shard: str) -> None: | |
| for t in self.sources.get(shard, {}): | |
| self.left[t] -= 1 | |
| if self.left[t] == 0: | |
| self.cache.pop(t, None) | |
| # --------------------------------------------------------------------------- timm images | |
| class TimmImages: | |
| """jpg bytes by (tar, key), from local tars or streamed from the pinned Hugging Face revision.""" | |
| def __init__(self, timm_dir: str | None = None, hf: bool = False): | |
| if not timm_dir and not hf: | |
| raise SystemExit("give --timm-dir or --hf") | |
| self.timm_dir, self.hf = timm_dir, hf | |
| def _open(self, tar: str): | |
| if self.timm_dir: | |
| return open(os.path.join(self.timm_dir, tar), "rb") | |
| import urllib.request | |
| from huggingface_hub import get_token | |
| url = f"https://huggingface.co/datasets/{TIMM_REPO}/resolve/{TIMM_REVISION}/{tar}" | |
| req = urllib.request.Request(url) | |
| tok = get_token() | |
| if tok: | |
| req.add_unredirected_header("Authorization", f"Bearer {tok}") | |
| return io.BufferedReader(urllib.request.urlopen(req, timeout=300), 8 << 20) | |
| def fetch(self, tar: str, keys: set[str]) -> dict[str, bytes]: | |
| """The images of the wanted keys that the tar holds (a key it lacks, or a tar that cannot be read, is | |
| reported per record by the caller).""" | |
| got: dict[str, bytes] = {} | |
| try: | |
| with self._open(tar) as f, tarfile.open(fileobj=f, mode="r|") as tf: | |
| for m in tf: | |
| if not m.isfile(): | |
| continue | |
| base, _, ext = m.name.rpartition(".") | |
| if ext == "jpg" and base in keys: | |
| got[base] = tf.extractfile(m).read() | |
| except Exception as e: # noqa: BLE001 | |
| print(f"{tar}: not read completely ({type(e).__name__}: {str(e)[:200]})", file=sys.stderr, flush=True) | |
| return got | |
| # --------------------------------------------------------------------------- rebuild | |
| def _by_host(package: str, shards: list[str]) -> list[list[str]]: | |
| meta = {r["shard"]: r for r in read_table(package, "shards.parquet").to_pylist()} | |
| groups: dict[int, list[str]] = defaultdict(list) | |
| for s in shards: | |
| if s not in meta: | |
| raise SystemExit(f"{s}: not a shard of this package") | |
| groups[meta[s]["build_host"]].append(s) | |
| return [sorted(v, key=lambda s: meta[s]["shard_index"]) for _, v in sorted(groups.items())] | |
| def rebuild(package: str, shards: list[str], images: TimmImages, out_dir: str) -> list[dict]: | |
| """Rebuild the shards. A record goes into its shard only with its image found and both sha256 equal; every other | |
| record is left out and listed in its result's "problems" (shard, ordinal, field, pointer, reason), and its shard is | |
| written as <shard>.incomplete (2026-11-12: problems no longer stop the run at the first one).""" | |
| meta = {r["shard"]: r for r in read_table(package, "shards.parquet").to_pylist()} | |
| os.makedirs(out_dir, exist_ok=True) | |
| results = [] | |
| for group in _by_host(package, shards): | |
| cache = _TarCache(images, image_sources(package, group), group) | |
| for shard in group: | |
| results.append(_rebuild_one(package, shard, meta[shard], cache, out_dir)) | |
| cache.done(shard) | |
| return results | |
| def _rebuild_one(package: str, shard: str, meta: dict, cache: "_TarCache", out_dir: str) -> dict: | |
| recs = shard_rows(package, shard) | |
| problems = [] | |
| def problem(ordinal, field, pointer, reason): | |
| problems.append({"shard": shard, "ordinal": ordinal, "field": field, "pointer": pointer, "reason": reason}) | |
| if not recs: | |
| problem(None, "records", None, "no records in this package (is its records/ file present?)") | |
| elif len(recs) != meta["records"] or [r["ordinal"] for r in recs] != list(range(len(recs))): | |
| problem(None, "records", None, f"{len(recs)} records with gaps or extras; shards.parquet says {meta['records']}") | |
| imgs = cache.images_for(shard) if recs else {} | |
| md5, crc, ok = hashlib.md5(), 0, 0 | |
| path = os.path.join(out_dir, shard) | |
| with open(path + ".partial", "wb") as f: | |
| for r in recs: | |
| ptr = {"tar": r["timm_tar"], "key": r["timm_key"]} | |
| jpg = imgs.get((r["timm_tar"], r["timm_key"])) | |
| if jpg is None: | |
| problem(r["ordinal"], "image", ptr, "not in the timm tar (or the tar could not be read)") | |
| continue | |
| if hashlib.sha256(jpg).digest() != r["image_sha256"]: | |
| problem(r["ordinal"], "image", ptr, "differs from the training image (sha256)") | |
| continue | |
| payload = encode_record(r, jpg) | |
| if hashlib.sha256(payload).digest() != r["record_sha256"]: | |
| problem(r["ordinal"], "record", ptr, "the rebuilt record differs from record_sha256") | |
| continue | |
| fr = frame(payload) | |
| f.write(fr) | |
| md5.update(fr) | |
| crc = crc32c_update(crc, fr) | |
| ok += 1 | |
| complete = not problems and crc == meta["crc32c"] and md5.hexdigest() == meta["md5"] | |
| if not problems and not complete: | |
| problem(None, "shard", None, f"shard checksum differs (crc32c {crc}, md5 {md5.hexdigest()})") | |
| final = path if complete else path + ".incomplete" | |
| os.replace(path + ".partial", final) | |
| res = {"shard": shard, "records": len(recs), "written": ok, "crc32c": crc, "md5": md5.hexdigest(), | |
| "checksums_equal": complete, "written_as": os.path.basename(final), "problems": problems} | |
| print({k: v for k, v in res.items() if k != "problems"} | {"problems": len(problems)}, flush=True) | |
| return res | |
| def iter_training_records(package: str, shards: list[str], images: TimmImages, problems: list | None = None): | |
| """Yield the records that reached training (filters applied), each with its image bytes. A record whose image is | |
| missing or differs is skipped and appended to ``problems``; without that list, the iterator raises at the end | |
| (after every good record) when any was skipped. | |
| The text is as stored by the builder. The OpenEmbed training code then applies its read-time | |
| normalisation (dataset instruction instead of the stored question template, first WordNet | |
| lemma, duplicate negatives dropped); that code is not part of this folder.""" | |
| found = problems if problems is not None else [] | |
| for group in _by_host(package, shards): | |
| cache = _TarCache(images, image_sources(package, group), group) | |
| for shard in group: | |
| imgs = cache.images_for(shard) | |
| for r in shard_rows(package, shard): | |
| if not r["reaches_training"]: | |
| continue | |
| jpg = imgs.get((r["timm_tar"], r["timm_key"])) | |
| if jpg is None or hashlib.sha256(jpg).digest() != r["image_sha256"]: | |
| found.append({"shard": shard, "ordinal": r["ordinal"], "field": "image", | |
| "pointer": {"tar": r["timm_tar"], "key": r["timm_key"]}, | |
| "reason": "not in the timm tar" if jpg is None else "differs from the training image (sha256)"}) | |
| continue | |
| yield {"shard": shard, "ordinal": r["ordinal"], "image": jpg, "question": r["query_text"], | |
| "answer": r["text"], "negatives": [t for t in r["neg_text"].split("\x1f") if t], | |
| "wnid": r["wnid"]} | |
| cache.done(shard) | |
| if found and problems is None: | |
| raise SystemExit(f"{len(found)} records skipped (image missing or different), e.g. {found[:3]}") | |
| def check_tars(package: str, timm_dir: str) -> int: | |
| bad = 0 | |
| for r in read_table(package, "timm_tars.parquet").to_pylist(): | |
| p = os.path.join(timm_dir, r["tar"]) | |
| if not os.path.exists(p): | |
| continue | |
| h = hashlib.sha256() | |
| with open(p, "rb") as f: | |
| for chunk in iter(lambda: f.read(8 << 20), b""): | |
| h.update(chunk) | |
| ok = h.hexdigest() == r["sha256"] | |
| bad += not ok | |
| print(r["tar"], "ok" if ok else "SHA256 DIFFERS", flush=True) | |
| return bad | |
| def main() -> None: | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("command", choices=["rebuild", "iterate", "check-tars"]) | |
| ap.add_argument("--package", default=".", help="this folder (records/, shards.parquet, ...)") | |
| ap.add_argument("--timm-dir", help="folder with the timm .tar files") | |
| ap.add_argument("--hf", action="store_true", help="stream the tars from Hugging Face") | |
| ap.add_argument("--out", help="output folder for rebuilt shards") | |
| ap.add_argument("--shards", default="", help="comma list of shard names") | |
| ap.add_argument("--hosts", default="", help="comma list of build hosts (0-31): all their shards") | |
| ap.add_argument("--problems", help="JSON lines, one per record that could not be rebuilt (default: " | |
| "<out>/rebuild_problems.jsonl, else ./imagenet21k_problems.jsonl)") | |
| args = ap.parse_args() | |
| if args.command == "check-tars": | |
| sys.exit(1 if check_tars(args.package, args.timm_dir) else 0) | |
| meta = read_table(args.package, "shards.parquet").to_pylist() | |
| if args.shards: | |
| shards = [s.strip() for s in args.shards.split(",") if s.strip()] | |
| elif args.hosts: | |
| hs = {int(h) for h in args.hosts.split(",")} | |
| shards = [m["shard"] for m in meta if m["build_host"] in hs] | |
| else: | |
| shards = [m["shard"] for m in meta] | |
| images = TimmImages(args.timm_dir, args.hf) | |
| probs = [] | |
| if args.command == "rebuild": | |
| if not args.out: | |
| raise SystemExit("rebuild needs --out") | |
| probs = [p for r in rebuild(args.package, shards, images, args.out) for p in r["problems"]] | |
| else: | |
| n = sum(1 for _ in iter_training_records(args.package, shards, images, probs)) | |
| print({"shards": len(shards), "records_reaching_training": n, "skipped": len(probs)}) | |
| if probs: | |
| path = args.problems or (os.path.join(args.out, "rebuild_problems.jsonl") if args.out else "imagenet21k_problems.jsonl") | |
| with open(path, "w") as fh: | |
| for p in probs: | |
| fh.write(json.dumps(p) + "\n") | |
| print(f"INCOMPLETE: {len(probs)} problems listed in {path}" + | |
| ("; their shards are written as <shard>.incomplete" if args.command == "rebuild" else ""), flush=True) | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |