File size: 8,226 Bytes
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
"""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")