File size: 12,332 Bytes
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
#!/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())