Download classification/imagenet-21k/tools/tests/test_loader.py from UCSC-VLAA/OpenEmbed-Data: direct link, hf CLI and curl.
- Browser
- Download file 8.23 kB
-
https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/classification/imagenet-21k/tools/tests/test_loader.py
- Command line
-
hf download hf://datasets/UCSC-VLAA/OpenEmbed-Data/classification/imagenet-21k/tools/tests/test_loader.py
-
curl -L -o test_loader.py https://huggingface.co/datasets/UCSC-VLAA/OpenEmbed-Data/resolve/main/classification/imagenet-21k/tools/tests/test_loader.py
8.23 kB
| """Offline tests of tools/loader.py (no network, no ImageNet data). | |
| 1. The record encoder reproduces a golden serialization. The golden bytes come from the encoder | |
| that re-created all 13,016,419 training records of this package byte for byte from their | |
| stored fields, so this pins the published loader to it. | |
| 2. End to end: a synthetic package (records parquet, shards.parquet, timm_tars.parquet) and a | |
| fake timm tar; ``rebuild`` writes the shard and checks every hash; the output equals the | |
| reference bytes; a corrupted image is refused; ``iter_training_records`` leaves out records | |
| that did not reach training. | |
| python tools/tests/test_loader.py | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import io | |
| import json | |
| import os | |
| import sys | |
| import tarfile | |
| import tempfile | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| sys.path.insert(0, os.path.join(HERE, "..")) | |
| import loader as L # noqa: E402 | |
| ORDER = "query_text,cand_jpg,neg_text,jpg,license,wnid,text,teacher_scores,src" | |
| GOLDEN_FRAME = bytes.fromhex( | |
| "0a01000000000000a8532f640a87020a2c0a0a71756572795f74657874121e0a1c0a1a576861742069732074686973206120" | |
| "70696374757265206f663f0a100a0863616e645f6a706712040a020a000a130a086e65675f7465787412070a050a03611f62" | |
| "0a170a036a706712100a0e0a0cffd84a50454744415441ffd90a100a076c6963656e736512050a030a014c0a150a04776e69" | |
| "64120d0a0b0a096e30303030303030310a110a047465787412090a070a057468696e670a3a0a0e746561636865725f73636f" | |
| "726573122812260a24000080bf000080bf000080bf000080bf000080bf000080bf000080bf000080bf000080bf0a1f0a0373" | |
| "726312180a160a14636c6173736966792f696d6167656e657432316b3bdb01b8") | |
| def _row(o, key, jpg, *, question="What is this a picture of?", answer="thing", negs="a\x1fb", | |
| wnid="n00000001", reaches=True): | |
| r = {"shard": "part-h000-00000.tfrecord", "ordinal": o, "build_host": 0, | |
| "timm_tar": "imagenet_w21-train-0000.tar", "timm_key": key, "timm_sample_index": o, | |
| "image_sha256": hashlib.sha256(jpg).digest(), "image_len": len(jpg), "image_hash_multi_key": False, | |
| "feature_order": ORDER, "query_text": question, "text": answer, "neg_text": negs, "wnid": wnid, | |
| "src": "classify/imagenet21k", "license": "L", "cand_jpg": b"", "teacher_scores": [-1.0] * 9, | |
| "record_len": 0, "record_crc32c_masked": 0, "frame_offset": 0, "record_content_hash": 0, | |
| "training_input_sha256": b"\0" * 32, "dedup_skip": not reaches, "contamination_block": False, | |
| "reaches_training": reaches} | |
| payload = L.encode_record(r, jpg) | |
| r["record_sha256"] = hashlib.sha256(payload).digest() | |
| r["record_len"] = len(payload) | |
| return r, L.frame(payload) | |
| def test_golden_encoding(): | |
| r, fr = _row(0, "k0", b"\xff\xd8JPEGDATA\xff\xd9") | |
| assert fr == GOLDEN_FRAME, "encoder differs from the golden serialization" | |
| def _package(tmp, images): | |
| import pyarrow as pa | |
| import pyarrow.parquet as pq | |
| rows, frames = [], [] | |
| for o, (key, jpg) in enumerate(images): | |
| r, fr = _row(o, key, jpg, reaches=(o != 1)) | |
| rows.append(r) | |
| frames.append(fr) | |
| shard_bytes = b"".join(frames) | |
| os.makedirs(os.path.join(tmp, "pkg", "records")) | |
| cols = {k: [r[k] for r in rows] for k in rows[0]} | |
| schema = pa.schema([ | |
| ("shard", pa.string()), ("ordinal", pa.int32()), ("build_host", pa.int16()), ("timm_tar", pa.string()), | |
| ("timm_key", pa.string()), ("timm_sample_index", pa.int32()), ("image_sha256", pa.binary(32)), | |
| ("image_len", pa.int32()), ("image_hash_multi_key", pa.bool_()), ("feature_order", pa.string()), | |
| ("query_text", pa.string()), ("text", pa.string()), ("neg_text", pa.string()), ("wnid", pa.string()), | |
| ("src", pa.string()), ("license", pa.string()), ("cand_jpg", pa.binary()), | |
| ("teacher_scores", pa.list_(pa.float32())), ("record_len", pa.int32()), | |
| ("record_crc32c_masked", pa.uint32()), ("frame_offset", pa.int64()), ("record_content_hash", pa.int64()), | |
| ("training_input_sha256", pa.binary(32)), ("dedup_skip", pa.bool_()), ("contamination_block", pa.bool_()), | |
| ("reaches_training", pa.bool_()), ("record_sha256", pa.binary(32))]) | |
| pq.write_table(pa.table(cols, schema=schema), os.path.join(tmp, "pkg", "records", "part-00000.parquet")) | |
| pq.write_table(pa.table({ | |
| "shard": ["part-h000-00000.tfrecord"], "build_host": [0], "shard_index": [0], "records": [len(rows)], | |
| "records_reaching_training": [len(rows) - 1], "size_bytes": [len(shard_bytes)], | |
| "crc32c": pa.array([L.crc32c_update(0, shard_bytes)], pa.uint32()), | |
| "md5": [hashlib.md5(shard_bytes).hexdigest()]}), os.path.join(tmp, "pkg", "shards.parquet")) | |
| tar_path = os.path.join(tmp, "timm", "imagenet_w21-train-0000.tar") | |
| os.makedirs(os.path.dirname(tar_path)) | |
| with tarfile.open(tar_path, "w") as tf: | |
| for key, jpg in images: | |
| for ext, data in (("cls", b"0"), ("jpg", jpg), ("json", json.dumps({"class_name": "n00000001"}).encode())): | |
| ti = tarfile.TarInfo(f"{key}.{ext}") | |
| ti.size = len(data) | |
| tf.addfile(ti, io.BytesIO(data)) | |
| pq.write_table(pa.table({"tar": ["imagenet_w21-train-0000.tar"], "revision": [L.TIMM_REVISION], | |
| "sha256": [hashlib.sha256(open(tar_path, "rb").read()).hexdigest()], | |
| "size_bytes": [os.path.getsize(tar_path)], "samples": [len(images)]}), | |
| os.path.join(tmp, "pkg", "timm_tars.parquet")) | |
| return shard_bytes, tar_path | |
| def test_end_to_end(): | |
| images = [("n00000001_1", b"\xff\xd8one\xff\xd9"), ("n00000001_2", b"\xff\xd8two\xff\xd9"), | |
| ("n00000001_3", b"\xff\xd8three\xff\xd9")] | |
| with tempfile.TemporaryDirectory() as tmp: | |
| shard_bytes, tar_path = _package(tmp, images) | |
| pkg, out = os.path.join(tmp, "pkg"), os.path.join(tmp, "out") | |
| imgs = L.TimmImages(timm_dir=os.path.dirname(tar_path)) | |
| res = L.rebuild(pkg, ["part-h000-00000.tfrecord"], imgs, out) | |
| assert res[0]["checksums_equal"] | |
| assert open(os.path.join(out, "part-h000-00000.tfrecord"), "rb").read() == shard_bytes | |
| assert L.check_tars(pkg, os.path.dirname(tar_path)) == 0 | |
| got = list(L.iter_training_records(pkg, ["part-h000-00000.tfrecord"], imgs)) | |
| assert [g["ordinal"] for g in got] == [0, 2] and got[1]["image"] == images[2][1] | |
| assert got[0]["negatives"] == ["a", "b"] | |
| # a corrupted image and a missing one: both records left out and listed, the shard written as .incomplete | |
| # (2026-11-12: the loader no longer stops at the first problem) | |
| with tarfile.open(tar_path, "w") as tf: | |
| for key, jpg in images: | |
| if key == "n00000001_3": | |
| continue | |
| data = jpg if key != "n00000001_2" else jpg + b"x" | |
| for ext, d in (("jpg", data), ("json", b"{}")): | |
| ti = tarfile.TarInfo(f"{key}.{ext}") | |
| ti.size = len(d) | |
| tf.addfile(ti, io.BytesIO(d)) | |
| out2 = os.path.join(tmp, "out2") | |
| res = L.rebuild(pkg, ["part-h000-00000.tfrecord"], imgs, out2) | |
| assert not res[0]["checksums_equal"] and res[0]["written_as"] == "part-h000-00000.tfrecord.incomplete" | |
| assert not os.path.exists(os.path.join(out2, "part-h000-00000.tfrecord")) | |
| assert sorted((p["ordinal"], p["field"]) for p in res[0]["problems"]) == [(1, "image"), (2, "image")] | |
| first = shard_bytes[:len(L.frame(L.encode_record(_row(0, images[0][0], images[0][1])[0], images[0][1])))] | |
| assert open(os.path.join(out2, "part-h000-00000.tfrecord.incomplete"), "rb").read() == first | |
| probs = [] | |
| got = list(L.iter_training_records(pkg, ["part-h000-00000.tfrecord"], imgs, probs)) | |
| assert [g["ordinal"] for g in got] == [0] and [p["ordinal"] for p in probs] == [2] | |
| try: | |
| list(L.iter_training_records(pkg, ["part-h000-00000.tfrecord"], imgs)) | |
| except SystemExit as e: | |
| assert "1 records skipped" in str(e) | |
| else: | |
| raise AssertionError("a missing image went unreported") | |
| if __name__ == "__main__": | |
| test_golden_encoding() | |
| test_end_to_end() | |
| print("ok") | |