File size: 10,801 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""R5: the ONE training-sample sequence of mix_v1 shared by every VLM arm (and proposed for VLMB's arms).

Reads the frozen DATA/data/processed/r5/mix_v1.yaml, checks each manifest's sha256 against it, keeps train-split rows
only, and writes N_ROWS = 6,000,000 rows by default (rows 0-149,999 = P_short; the leaders continue from row
150,000). Every prefix is identical whatever N_ROWS is (the process is sequential). --seed changes only the order
inside each stratum (the seeded permutations); the stratum interleave is the same for every seed.

Mix interpretation (any node of the yaml):
- a LEAF has a manifest path (key manifest / path / file / tsv) and optionally sha256 and filter {column: value(s)};
- a GROUP has children under one of: members, sources, manifests, items, children, parts, components, strata, groups;
- a node's share is under share / weight / fraction / percent / pct / proportion (percent values are / 100 when the
  top-level shares sum to about 100). Children without shares split the parent's share equally; children with shares
  that sum to about 1 are fractions of the parent; children with shares summing to the parent's share are absolute.
Order (deterministic, seed 20261121): at each position the stratum with the largest deficit share*(i+1) - count is
taken (ties by stratum order), so every prefix of the sequence holds the target shares to within one item. Inside a
stratum, items come from seeded permutations of its train rows (a new permutation when one is used up).
Fails closed: `<out>.done` is written only if every sha256 matches, every used row has split=train, every stratum is
non-empty, the realised shares in the first 150,000 rows and in all rows are within 0.001 of the targets, the file has
N_ROWS data rows, and the image file of EVERY train row used exists (missing files are listed per manifest in the
summary; a missing image would crash a training run mid-way).

usage: build_sequence.py MIX_YAML OUT_TSV [--rows 2000000] [--seed 20261121]
"""
import hashlib
import json
import os
import random
import sys
import unicodedata

import yaml

args = [a for a in sys.argv[1:] if not a.startswith("--")]
opts = dict(zip(sys.argv[1:][::1], sys.argv[2:]))
mix_path, out = args[0], args[1]
N_ROWS = int(opts.get("--rows", 6000000))
SEED = int(opts.get("--seed", 20261121))
P_SHORT = min(150000, N_ROWS)
SHARE_KEYS = ("share", "weight", "fraction", "percent", "pct", "proportion")
CHILD_KEYS = ("members", "sources", "manifests", "items", "children", "parts", "components", "strata", "groups")
PATH_KEYS = ("manifest", "path", "file", "tsv")


def sha256(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def get_share(node):
    for k in SHARE_KEYS:
        if isinstance(node, dict) and k in node and node[k] is not None:
            return float(node[k]), k
    return None, None


def children_of(node):
    if isinstance(node, list):
        return node
    if isinstance(node, dict):
        for k in CHILD_KEYS:
            v = node.get(k)
            if isinstance(v, list):
                return v
            if isinstance(v, dict):
                return [dict(c, name=c.get("name", n)) if isinstance(c, dict) else {"name": n, "manifest": c} for n, c in v.items()]
    return None


def path_of(node):
    if isinstance(node, str):
        return node
    if isinstance(node, dict):
        for k in PATH_KEYS:
            if isinstance(node.get(k), str):
                return node[k]
    return None


leaves = []


def walk(node, share, name, inherited_filter):
    p = path_of(node)
    flt = dict(inherited_filter)
    if isinstance(node, dict) and isinstance(node.get("filter"), dict):
        flt.update(node["filter"])
    if p is not None and children_of(node) is None:
        leaves.append({"name": name, "manifest": p, "sha256": node.get("sha256") if isinstance(node, dict) else None,
                       "share": share, "filter": flt})
        return
    ch = children_of(node)
    if ch is None:
        raise SystemExit(f"cannot read mix node {name!r}: no manifest path and no children ({str(node)[:200]})")
    shares = [get_share(c)[0] for c in ch]
    if all(s is None for s in shares):
        sub = [share / len(ch)] * len(ch)
    elif any(s is None for s in shares):
        raise SystemExit(f"mix node {name!r}: some children have shares and some do not")
    else:
        tot = sum(shares)
        if abs(tot - share) < 1e-6 * max(1, share) or abs(tot - share * 100) < 1e-4:
            sub = [s * share / tot for s in shares]  # absolute shares (or percents of the whole)
        elif abs(tot - 1.0) < 1e-6 or abs(tot - 100.0) < 1e-4:
            sub = [share * s / tot for s in shares]
        else:
            raise SystemExit(f"mix node {name!r}: child shares sum to {tot}, neither 1/100 nor the parent's {share}")
    for i, (c, s) in enumerate(zip(ch, sub)):
        nm = (c.get("name") if isinstance(c, dict) else None) or os.path.splitext(os.path.basename(path_of(c) or str(i)))[0]
        walk(c, s, f"{name}/{nm}" if name else nm, flt)


doc = yaml.safe_load(open(mix_path, encoding="utf-8"))
root = doc.get("mix", doc) if isinstance(doc, dict) else doc
walk(root, 1.0, "", {})
tot = sum(l["share"] for l in leaves)
if abs(tot - 1.0) > 1e-6:
    if abs(tot - 100.0) < 1e-3:
        for l in leaves:
            l["share"] /= 100.0
    else:
        raise SystemExit(f"leaf shares sum to {tot}")
leaves = [l for l in leaves if l["share"] > 0]
problems = []
items = []
for l in leaves:
    p = l["manifest"]
    if not os.path.isabs(p):
        p = os.path.join(os.path.dirname(os.path.abspath(mix_path)), p)
        l["manifest"] = p
    if not os.path.exists(p):
        problems.append(f"missing manifest {p}")
        items.append([])
        continue
    got = sha256(p)
    l["sha256_found"] = got
    if l.get("sha256") and l["sha256"] != got:
        problems.append(f"sha256 mismatch {p}: yaml {l['sha256']} file {got}")
    if not l.get("sha256"):
        problems.append(f"no sha256 in the yaml for {p}")
    rows = []
    with open(p, encoding="utf-8", newline="") as f:
        hdr = f.readline().rstrip("\n").split("\t")
        ix = {h: i for i, h in enumerate(hdr)}
        for need in ("id", "image", "text", "split"):
            if need not in ix:
                problems.append(f"{p}: column {need} missing")
        if problems and problems[-1].startswith(p):
            items.append([])
            continue
        for line in f:
            q = line.rstrip("\n").split("\t")
            if len(q) < len(hdr):
                q += [""] * (len(hdr) - len(q))
            r = {h: q[i] for h, i in ix.items()}
            if r["split"] != "train":
                continue
            ok = True
            for k, v in l["filter"].items():
                vals = v if isinstance(v, list) else [v]
                if str(r.get(k)) not in [str(x) for x in vals]:
                    ok = False
                    break
            if ok:
                rows.append((r["id"], r["image"], unicodedata.normalize("NFC", r["text"]), r.get("unit", ""),
                             r.get("kind", ""), r.get("lang", ""), r.get("source", "")))
    if not rows:
        problems.append(f"stratum {l['name']} has no train rows after the filter {l['filter']}")
    l["train_rows"] = len(rows)
    items.append(rows)
if problems:
    print("FAIL (no sequence written):", *problems, sep="\n  ", flush=True)
    sys.exit(2)

S = len(leaves)
shares = [l["share"] for l in leaves]
rng = random.Random(SEED)
perms = []
for k in range(S):
    idx = list(range(len(items[k])))
    rng.shuffle(idx)
    perms.append([idx, 0, 1])  # permutation, position, pass number
counts = [0] * S
tmp = out + ".tmp"
os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
h = hashlib.sha256()
first_counts = None
with open(tmp, "w", encoding="utf-8") as f:
    hdr = "row\tid\timage\ttext\tunit\tkind\tlang\tsource\tstratum\n"
    f.write(hdr)
    h.update(hdr.encode())
    for i in range(N_ROWS):
        k = max(range(S), key=lambda j: (shares[j] * (i + 1) - counts[j], -j))
        counts[k] += 1
        pm = perms[k]
        if pm[1] >= len(pm[0]):
            rng.shuffle(pm[0])
            pm[1] = 0
            pm[2] += 1
        r = items[k][pm[0][pm[1]]]
        pm[1] += 1
        line = f"{i}\t{r[0]}\t{r[1]}\t{r[2]}\t{r[3]}\t{r[4]}\t{r[5]}\t{r[6]}\t{leaves[k]['name']}\n"
        f.write(line)
        h.update(line.encode())
        if i + 1 == P_SHORT:
            first_counts = list(counts)
bad = []
for k in range(S):
    for n_, c_ in ((P_SHORT, first_counts), (N_ROWS, counts)):
        if abs(c_[k] / n_ - shares[k]) > 0.001:
            bad.append(f"{leaves[k]['name']}: realised {c_[k] / n_:.5f} vs target {shares[k]:.5f} in the first {n_}")
missing_by_manifest = {}
checked = set()
for k in range(S):
    man = leaves[k]["manifest"]
    for r in items[k]:
        if r[1] in checked:
            continue
        checked.add(r[1])
        if not os.path.exists(r[1]):
            m = missing_by_manifest.setdefault(man, {"n": 0, "examples": []})
            m["n"] += 1
            if len(m["examples"]) < 5:
                m["examples"].append([r[0], r[1]])
if missing_by_manifest:
    bad.append("image files missing (every train row checked): " + json.dumps(
        {os.path.basename(k): v["n"] for k, v in missing_by_manifest.items()}))
summary = {
    "mix_yaml": os.path.abspath(mix_path), "mix_yaml_sha256": sha256(mix_path), "seed": SEED, "rows": N_ROWS,
    "p_short_rows": P_SHORT, "order": "largest-deficit interleave; seeded permutations inside each stratum",
    "strata": [{"name": l["name"], "manifest": l["manifest"], "sha256": l["sha256_found"], "filter": l["filter"],
                "target_share": l["share"], "train_rows": l["train_rows"], "rows_in_first_150000": first_counts[k],
                "rows_in_all": counts[k], "passes_in_first_150000": round(first_counts[k] / max(l["train_rows"], 1), 3),
                "passes_in_all": round(counts[k] / max(l["train_rows"], 1), 3)} for k, l in enumerate(leaves)],
    "output_sha256": h.hexdigest(), "problems": bad, "images_checked": len(checked),
    "missing_images": missing_by_manifest,
}
json.dump(summary, open(out + ".summary.json", "w"), indent=1, ensure_ascii=False)
if bad:
    print("FAIL (sequence not marked done):", *bad, sep="\n  ", flush=True)
    sys.exit(3)
os.replace(tmp, out)
with open(out + ".done", "w") as f:
    f.write(json.dumps({"sha256": h.hexdigest(), "rows": N_ROWS, "seed": SEED}) + "\n")
print("OK", out, h.hexdigest(), json.dumps([(s["name"], s["target_share"], s["rows_in_first_150000"], s["passes_in_all"]) for s in summary["strata"]], ensure_ascii=False))