File size: 29,675 Bytes
d2a1a41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
"""Bounded offline preparation of the initial real text/chat/Python corpus.



SQLite spools documents and deduplication keys instead of retaining a corpus in

RAM. No downloads, archive extraction, GPU calls, or optimizer steps occur here.

"""
from __future__ import annotations

from collections import Counter
from copy import deepcopy
import hashlib
import json
import os
from pathlib import Path
import shutil
import sqlite3
import time
from urllib.parse import urlsplit, urlunsplit

import numpy as np
import pyarrow.parquet as pq
import yaml

from .adapters import normalize
from .curated import canonical, digest, verify_record
from .preprocessing import sha256_file
from ..tokenizers.text import TextTokenizer
from ..tokenizers.universal import UniversalVocab


def atomic_json(path: Path, value: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False), encoding="utf-8")
    for attempt in range(8):
        try:
            os.replace(tmp, path)
            return
        except PermissionError:
            if attempt == 7:
                raise
            time.sleep(0.01 * 2**attempt)


def normalized_hash(text: str) -> str:
    return hashlib.sha256(" ".join(text.split()).encode("utf-8")).hexdigest()


def document_group(url: str, text: str) -> str:
    """Group HTTP/HTTPS aliases and fragments of the same document together."""
    if not url:
        return normalized_hash(text)
    p = urlsplit(url)
    return urlunsplit(("https", p.netloc.lower(), p.path.rstrip("/"), p.query, ""))


def parquet_rows(path: Path):
    for batch in pq.ParquetFile(path).iter_batches(batch_size=128):
        yield from batch.to_pylist()


def pinned_source_sha(path: Path, root: Path, dataset: str, revision: str, ledger: dict) -> str:
    """Starter downloads retain pinned LFS hashes in HF's local metadata file."""
    rel = path.relative_to(root).as_posix()
    if rel in ledger:
        expected = ledger[rel]["sha256"]
    else:
        relative = path.relative_to(root / dataset)
        metadata = root / dataset / ".cache/huggingface/download" / (str(relative) + ".metadata")
        lines = metadata.read_text(encoding="utf-8").splitlines()
        if len(lines) < 2 or lines[0] != revision:
            raise ValueError(f"missing or mismatched pinned acquisition metadata: {rel}")
        expected = lines[1]
    if len(expected) != 64 or any(c not in "0123456789abcdef" for c in expected):
        raise ValueError(f"source has no pinned SHA256: {rel}")
    return expected


def text_windows(text: str, tok: TextTokenizer, limit: int):
    """Segment at Unicode character/whitespace boundaries; never cut byte tokens."""
    remaining = text.strip()
    while remaining:
        encoded = tok.tok.encode(remaining)
        if len(encoded.ids) <= limit:
            yield remaining
            return
        cut = encoded.offsets[limit - 1][1]
        # Prefer a nearby complete word while retaining at least ~75% capacity.
        lower = encoded.offsets[max(0, limit * 3 // 4 - 1)][1]
        boundary = max(remaining.rfind(" ", lower, cut), remaining.rfind("\n", lower, cut))
        if boundary > lower:
            cut = boundary
        while cut > 0 and len(tok.encode(remaining[:cut])) > limit:
            cut -= 1
        if cut <= 0:
            raise ValueError("cannot segment text within context")
        yield remaining[:cut].strip()
        remaining = remaining[cut:].strip()


def text_sample(record: dict, tok: TextTokenizer, vocab: UniversalVocab, context: int):
    """Exact UniversalVocab text packet layout, validated in bulk with NumPy."""
    s = vocab.special
    ids = [s("bos"), s("task:" + record["task"]), s("input")]
    for segment in record["inputs"]:
        ids.extend([s("text"), *tok.encode(segment["text"]), s("/text")])
    ids.append(s("output"))
    target = len(ids)
    for segment in record["outputs"]:
        ids.extend([s("text"), *tok.encode(segment["text"]), s("/text")])
    ids.append(s("eos"))
    tokens = np.array(ids, dtype="<u2")
    validate_text_sample(tokens, target, record["task"], vocab, context)
    return tokens, target


def validate_text_sample(tokens: np.ndarray, target: int, task: str, v: UniversalVocab, context: int) -> None:
    """Strict text-only subset of the universal grammar; reserved IDs are rejected."""
    s = v.special
    if task not in ("text", "chat_text", "coding") or not 7 <= len(tokens) <= context + 1:
        raise ValueError("invalid task or context length")
    if tokens[:3].tolist() != [s("bos"), s("task:" + task), s("input")] or tokens[-1] != s("eos"):
        raise ValueError("invalid sequence boundary")
    if not 4 <= target < len(tokens) or tokens[target - 1] != s("output"):
        raise ValueError("invalid supervision boundary")
    for start, end, required in ((3, target - 1, task != "text"), (target, len(tokens) - 1, True)):
        count = 0
        while start < end:
            if tokens[start] != s("text"):
                raise ValueError("invalid text packet start")
            closes = np.flatnonzero(tokens[start + 1:end] >= v.text_size)
            if not len(closes):
                raise ValueError("unterminated text packet")
            close = start + 1 + int(closes[0])
            if tokens[close] != s("/text"):
                raise ValueError("non-text token in text packet")
            start, count = close + 1, count + 1
        if required and count == 0:
            raise ValueError("empty packet side")


class TextPreparation:
    def __init__(self, config: dict, status_path: Path | None = None):
        self.cfg, self.status_path = config, status_path
        self.work, self.out = Path(config["work"]), Path(config["output"])
        if self.work.exists() or self.out.exists():
            raise FileExistsError("preserve existing preparation/cache; inspect it before selecting a new work directory")
        self.guard()
        self.work.mkdir(parents=True)
        self.catalog = yaml.safe_load(Path(config["catalog"]).read_text(encoding="utf-8"))
        self.catalog = deepcopy(self.catalog)
        self.counts, self.source_files = Counter(), []
        self.started = time.time()
        self.db = sqlite3.connect(self.work / "records.sqlite")
        self.db.executescript("""

          PRAGMA journal_mode=WAL;

          PRAGMA cache_size=-32768;

          CREATE TABLE records (id INTEGER PRIMARY KEY, dataset TEXT, split TEXT, payload TEXT);

          CREATE TABLE groups (dataset TEXT, name TEXT, split TEXT, PRIMARY KEY(dataset,name));

          CREATE TABLE contents (hash TEXT PRIMARY KEY, split TEXT);

        """)

    def guard(self):
        anchor = self.work if self.work.exists() else self.work.parent
        if shutil.disk_usage(anchor).free < self.cfg["reserve_gib"] * 2**30:
            raise RuntimeError("25 GiB free-space reserve reached")
        if self.work.exists():
            used = sum(p.stat().st_size for p in self.work.rglob("*") if p.is_file())
            if self.out.exists():
                used += sum(p.stat().st_size for p in self.out.rglob("*") if p.is_file())
            if used > self.cfg["max_work_gib"] * 2**30:
                raise RuntimeError("bounded preparation disk budget reached")

    def progress(self, phase: str, **fields):
        self.guard()
        record = {"phase": phase, "pid": os.getpid(), "updated": time.time(), "elapsed_s": time.time() - self.started,
                  "training_started": False, "counts": dict(self.counts), **fields}
        atomic_json(self.work / "progress.json", record)
        if self.status_path:
            state = json.loads(self.status_path.read_text(encoding="utf-8")) if self.status_path.exists() else {}
            state.update(state="preparing_data", updated=time.time(),
                         message="CPU data preparation: " + phase, preprocessing_elapsed_s=record["elapsed_s"])
            atomic_json(self.status_path, state)
        print(json.dumps({k: v for k, v in record.items() if k != "counts"}), flush=True)

    def source(self, path: Path, expected: str | None = None) -> str:
        sha = sha256_file(path)
        if expected and sha != expected:
            raise ValueError(f"source checksum mismatch: {path}")
        self.source_files.append({"path": str(path), "bytes": path.stat().st_size, "sha256": sha})
        return sha

    def provenance(self, ds: str, ident: str, split: str, path: Path, sha: str, source_split: str, **extra):
        d = self.catalog["datasets"][ds]
        return {"id": ds + ":" + ident, "revision": d.get("revision", d.get("release")), "license": d["license"],
                "attribution": d.get("attribution", d.get("repo_id", ds)) + "; see pinned dataset card and retained source metadata",
                "source_url": d["source"], "source_file": str(path), "source_sha256": sha,
                "source_split": source_split, "split": split, **extra}

    def add(self, record: dict) -> bool:
        verify_record(record, self.catalog)
        if any(not segment.get("text", "").strip() for segment in record["inputs"] + record["outputs"]):
            self.counts["empty_text_excluded"] += 1
            return False
        key = normalized_hash("\n".join(x["text"] for x in record["inputs"] + record["outputs"]))
        old = self.db.execute("SELECT split FROM contents WHERE hash=?", (key,)).fetchone()
        group = (record["dataset"], str(record["group"]))
        prior = self.db.execute("SELECT split FROM groups WHERE dataset=? AND name=?", group).fetchone()
        if old or (prior and prior[0] != record["split"]):
            self.counts["cross_split_duplicates_excluded" if (old and old[0] != record["split"]) or
                        (prior and prior[0] != record["split"]) else "duplicates_excluded"] += 1
            return False
        self.db.execute("INSERT INTO contents VALUES (?,?)", (key, record["split"]))
        self.db.execute("INSERT OR IGNORE INTO groups VALUES (?,?,?)", (*group, record["split"]))
        record["document_content_sha256"] = key
        self.db.execute("INSERT INTO records(dataset,split,payload) VALUES (?,?,?)",
                        (record["dataset"], record["split"], canonical(record)))
        self.counts[f"documents/{record['split']}/{record['dataset']}"] += 1
        return True

    def acquired_sources(self):
        root = Path(self.cfg["acquired"])
        ledger = {}
        for line in (root / "files.jsonl").open(encoding="utf-8"):
            r = json.loads(line)
            ledger[r["path"]] = r
        for ds in ("mbpp", "smoltalk", "fineweb_edu"):
            for path in sorted((root / ds).rglob("*.parquet")):
                expected = pinned_source_sha(path, root, ds, self.catalog["datasets"][ds]["revision"], ledger)
                self.source(path, expected)
        hashes = {r["path"]: r["sha256"] for r in self.source_files}
        # Held-out MBPP precedes train so duplicate solutions cannot contaminate it.
        for split, source_split in (("test", "test"), ("val", "validation"), ("train", "train")):
            p = next((root / "mbpp/full").glob(source_split + "-*.parquet"))
            for row in parquet_rows(p):
                prov = self.provenance("mbpp", str(row["task_id"]), split, p, hashes[str(p)], source_split)
                try:
                    self.add(normalize("mbpp", row, prov)[0])
                except SyntaxError:
                    self.counts["mbpp_syntax_rejected/" + split] += 1
        self.db.commit()
        for source_split, split, capkey in (("test", "val", "smoltalk_val_per_subset"),
                                          ("train", "train", "smoltalk_train_per_subset")):
            for subset in self.catalog["datasets"]["smoltalk"]["subsets"]:
                accepted = 0
                for p in sorted((root / "smoltalk/data" / subset).glob(source_split + "-*.parquet")):
                    for i, row in enumerate(parquet_rows(p)):
                        prov = self.provenance("smoltalk", f"{subset}/{p.name}/{i}", split, p, hashes[str(p)], source_split,
                                               component=subset)
                        try:
                            accepted += self.add(normalize("smoltalk", row, prov)[0])
                        except (ValueError, KeyError, TypeError):
                            self.counts["smoltalk_invalid"] += 1
                        if accepted >= self.cfg[capkey]:
                            break
                    if accepted >= self.cfg[capkey]:
                        break
                self.db.commit()
                self.progress("source_selection", component=subset, split=split, accepted=accepted)
        # FineWeb source budget is publisher-token based; actual BPE budget is applied later.
        source_tokens = 0
        for p in sorted((root / "fineweb_edu").rglob("*.parquet")):
            for i, row in enumerate(parquet_rows(p)):
                if row.get("language") != "en" or float(row["score"]) < self.cfg["fineweb_min_score"]:
                    self.counts["fineweb_quality_rejected"] += 1
                    continue
                text = row["text"].strip()
                if not text or len(text) > 500000:
                    self.counts["fineweb_size_rejected"] += 1
                    continue
                group = document_group(row.get("url", ""), text)
                split = "val" if int(digest(group)[:8], 16) % 100 < 2 else "train"
                prov = self.provenance("fineweb_edu", str(row["id"]), split, p, hashes[str(p)], "sample-10BT",
                                       original_url=row.get("url"), crawl_dump=row.get("dump"), warc_file=row.get("file_path"),
                                       educational_score=row["score"])
                record = normalize("fineweb_edu", row, prov)[0]
                record["group"] = group
                if self.add(record):
                    source_tokens += int(row["token_count"])
                if i % 2000 == 0:
                    self.db.commit()
                    self.progress("source_selection", component="fineweb_edu", publisher_tokens=source_tokens)
                if source_tokens >= self.cfg["fineweb_source_tokens"]:
                    break
            if source_tokens >= self.cfg["fineweb_source_tokens"]:
                break
        self.db.commit()

    def legacy_sources(self):
        raw, cache = Path(self.cfg["legacy_raw"]), Path(self.cfg["legacy_cache"])
        stats = json.loads((cache / "stats.json").read_text())
        for ds in ("tinystories", "dolly"):
            p = raw / ds / "provenance.json"
            src = json.loads(p.read_text())
            self.source(p)
            self.catalog["datasets"][ds] = {"role": "core", "repo_id": src["repo_id"], "revision": src["revision"],
                "license": src["license"], "source": src["url"], "tasks": ["text" if ds == "tinystories" else "chat_text"],
                "attribution": src["repo_id"], "notes": src["notes"], "retained_builtin": True}
            if src["license"] not in self.catalog["policy"]["allowed_asset_licenses"]:
                self.catalog["policy"]["allowed_asset_licenses"].append(src["license"])
            for filename in src["files"]:
                self.source(raw / ds / filename, src["sha256"][Path(filename).name])
        for split, source_split in (("val", "validation"), ("train", "train")):
            p = next((raw / "tinystories/data").glob(source_split + "-*.parquet"))
            sha = next(r["sha256"] for r in self.source_files if r["path"] == str(p))
            for i, row in enumerate(parquet_rows(p)):
                if i >= stats["text"][split]["documents"]:
                    break
                text = row["text"].strip()
                self.add({**self.provenance("tinystories", f"{source_split}/{i}", split, p, sha, source_split),
                          "dataset": "tinystories", "task": "text", "group": normalized_hash(text),
                          "inputs": [], "outputs": [{"type": "text", "text": text}]})
        # Preserve the actual historical Dolly split and pairs, not a new random split.
        for split in ("val", "train"):
            p = cache / f"chat_{split}.json"
            sha = self.source(p)
            for i, row in enumerate(json.loads(p.read_text())):
                self.add({**self.provenance("dolly", f"legacy-{split}/{i}", split, p, sha, "legacy-" + split),
                          "dataset": "dolly", "task": "chat_text", "group": normalized_hash(row["user"]),
                          "inputs": [{"type": "text", "text": row["user"]}],
                          "outputs": [{"type": "text", "text": row["assistant"]}]})
        self.db.commit()

    def fit_tokenizer(self):
        fitted = Counter()
        def corpus():
            for ds, cap in self.cfg["tokenizer_characters"].items():
                for (payload,) in self.db.execute("SELECT payload FROM records WHERE dataset=? AND split='train' ORDER BY id", (ds,)):
                    r = json.loads(payload)
                    for segment in r["inputs"] + r["outputs"]:
                        text = segment["text"][:cap - fitted[ds]]
                        if text:
                            fitted[ds] += len(text)
                            yield text
                    if fitted[ds] >= cap:
                        break
        self.progress("fit_training_only_bpe")
        tok = TextTokenizer.train(corpus(), self.cfg["text_vocab_size"])
        if tok.vocab_size != self.cfg["text_vocab_size"]:
            raise ValueError("BPE did not reach the exact shared vocabulary size")
        tok.save(self.work / "text_tokenizer.json")
        atomic_json(self.work / "tokenizer_fit.json", {"split": "train", "characters_by_dataset": dict(fitted),
                                                      "sha256": sha256_file(self.work / "text_tokenizer.json")})
        return tok

    def compile(self, tok: TextTokenizer):
        v, context = UniversalVocab(), self.cfg["context"]
        if tok.vocab_size != v.text_size:
            raise ValueError("text vocabulary mismatch")
        self.out.mkdir()
        (self.out / "INCOMPLETE").write_text("awaiting complete validation")
        handles, offsets, seen = {}, Counter(), {}
        manifest_hash = hashlib.sha256()
        targets, lengths, sources = Counter(), Counter(), Counter()
        fineweb_train_tokens, total = 0, 0
        for split in ("train", "val", "test"):
            handles[split] = ((self.out / f"{split}.bin").open("wb"), (self.out / f"{split}.index.jsonl").open("w", encoding="utf-8"))
        try:
            with (self.out / "provenance.jsonl").open("w", encoding="utf-8") as provenance:
                for row_id, payload in self.db.execute("SELECT id,payload FROM records ORDER BY id"):
                    manifest_hash.update((payload + "\n").encode("utf-8"))
                    r = json.loads(payload)
                    chunks = text_windows(r["outputs"][0]["text"], tok, context - 6) if r["task"] == "text" else [r["outputs"][0]["text"]]
                    for chunk_id, chunk in enumerate(chunks):
                        candidate = r | {"outputs": [{"type": "text", "text": chunk}]}
                        try:
                            tokens, target = text_sample(candidate, tok, v, context)
                        except ValueError as exc:
                            if r["task"] == "text" or "context length" not in str(exc):
                                raise
                            self.counts[f"over_context_rejected/{r['split']}/{r['dataset']}"] += 1
                            continue
                        if r["dataset"] == "fineweb_edu" and r["split"] == "train":
                            if fineweb_train_tokens + len(tokens) - target > self.cfg["fineweb_train_tokens"]:
                                self.counts["fineweb_bpe_budget_excluded"] += 1
                                continue
                        content_key = normalized_hash("\n".join(x["text"] for x in candidate["inputs"] + candidate["outputs"]))
                        if content_key in seen:
                            self.counts["window_duplicates_excluded"] += 1
                            continue
                        seen[content_key] = r["split"]
                        split, task = r["split"], r["task"]
                        ident = r["id"] + f"/window-{chunk_id}"
                        idx = {"offset": offsets[split], "length": len(tokens), "target_start": target,
                               "task": task, "id": ident, "dataset": r["dataset"], "group": r["group"], "split": split,
                               "document_content_sha256": r["document_content_sha256"], "content_sha256": content_key,
                               "tokens_sha256": hashlib.sha256(tokens.tobytes()).hexdigest()}
                        tokens.tofile(handles[split][0]); handles[split][1].write(canonical(idx) + "\n")
                        prov = {k: val for k, val in r.items() if k not in ("inputs", "outputs")}
                        prov.update(id=ident, window=chunk_id, token_offset=offsets[split], token_length=len(tokens),
                                    tokens_sha256=idx["tokens_sha256"], content_sha256=content_key)
                        provenance.write(canonical(prov) + "\n")
                        offsets[split] += len(tokens)
                        self.counts[f"samples/{split}/{task}"] += 1
                        targets[f"{split}/{task}"] += len(tokens) - target
                        sources[f"{split}/{r['dataset']}"] += 1
                        lengths[str(min(context, max(128, 1 << (len(tokens) - 2).bit_length())))] += 1
                        if r["dataset"] == "fineweb_edu" and split == "train":
                            fineweb_train_tokens += len(tokens) - target
                        total += 1
                    if row_id % 1000 == 0:
                        self.progress("encode_cache", documents=row_id, samples=total, fineweb_train_targets=fineweb_train_tokens)
        finally:
            for pair in handles.values():
                for f in pair:
                    f.close()
        tok.save(self.out / "text_tokenizer.json")
        atomic_json(self.out / "vocab_v2.json", v.to_dict())
        atomic_json(self.out / "catalog.json", self.catalog)
        report = {"training_started": False, "records": total, "context": context, "counts": dict(self.counts),
                  "target_tokens_by_task": dict(targets), "samples_by_dataset": dict(sources), "bucket_lengths": dict(lengths),
                  "input_tokens_by_split": dict(offsets), "token_bytes": sum(offsets.values()) * 2,
                  "sources": self.catalog["datasets"], "source_files": self.source_files,
                  "tokenizer_fit": json.loads((self.work / "tokenizer_fit.json").read_text()),
                  "user_data_included": False, "media_included": False,
                  "limitations": ["exact whitespace-normalized dedup only; near-duplicate/template overlap is unmeasured",
                                  "over-context chat/coding examples are rejected, never truncated",
                                  "FineWeb page rights remain governed by underlying sources; crawl URLs retained"],
                  "elapsed_preparation_s": time.time() - self.started}
        report["normalized_manifest_sha256"] = manifest_hash.hexdigest()
        atomic_json(self.out / "stats.json", report)
        self.progress("validate_cache", samples=total)
        validation = validate_cache(self.out)
        atomic_json(self.out / "validation.json", validation)
        checksums = {p.name: sha256_file(p) for p in self.out.iterdir() if p.is_file() and p.name != "INCOMPLETE"}
        atomic_json(self.out / "checksums.json", checksums)
        (self.out / "INCOMPLETE").unlink()
        self.progress("complete", samples=total, validation_passed=True)
        return report

    def run(self):
        try:
            self.progress("verify_sources")
            self.legacy_sources()
            self.acquired_sources()
            return self.compile(self.fit_tokenizer())
        finally:
            self.db.close()


def validate_cache(cache: Path, require_tasks: bool = True, expected_vocab: UniversalVocab | None = None) -> dict:
    cache = Path(cache)
    v = UniversalVocab(**json.loads((cache / "vocab_v2.json").read_text()))
    if v.to_dict() != (expected_vocab or UniversalVocab()).to_dict():
        raise ValueError("not the exact expected UniversalVocab")
    tok = TextTokenizer.load(cache / "text_tokenizer.json")
    if tok.vocab_size != v.text_size:
        raise ValueError("tokenizer vocabulary mismatch")
    stats = json.loads((cache / "stats.json").read_text())
    groups, contents, documents, identities = {}, {}, {}, {}
    counts, total = Counter(), 0
    for split in ("train", "val", "test"):
        p = cache / f"{split}.bin"
        if p.stat().st_size % 2:
            raise ValueError("misaligned uint16 stream")
        tokens = np.memmap(p, dtype="<u2", mode="r") if p.stat().st_size else np.array([], dtype="<u2")
        offset = 0
        with (cache / f"{split}.index.jsonl").open(encoding="utf-8") as index:
            for line in index:
                r = json.loads(line)
                if r["offset"] != offset or offset + r["length"] > len(tokens) or r["split"] != split:
                    raise ValueError("invalid index offset/length/split")
                sample = tokens[offset:offset + r["length"]]
                if r["task"] in ("text", "chat_text", "coding"):
                    validate_text_sample(sample, r["target_start"], r["task"], v, stats["context"])
                else:
                    if len(sample)-1 > stats["context"] or not 0 < r["target_start"] < len(sample):
                        raise ValueError("invalid multimodal context or target boundary")
                    if int(sample[r["target_start"]-1]) != v.special("output"):
                        raise ValueError("multimodal targets must start after the output marker")
                    v.validate(sample.tolist())
                if hashlib.sha256(sample.tobytes()).hexdigest() != r["tokens_sha256"]:
                    raise ValueError("sample token checksum mismatch")
                for key, store in ((r["dataset"] + ":" + r["group"], groups),
                                   (r["content_sha256"], contents), (r["document_content_sha256"], documents)):
                    if key in store and store[key] != split:
                        raise ValueError("train/heldout content or source-group leakage")
                    store[key] = split
                if r["id"] in identities:
                    raise ValueError("duplicate sample identity")
                identities[r["id"]] = (split, r["tokens_sha256"], r["dataset"], r["group"])
                offset += r["length"]; counts[split + "/" + r["task"]] += 1; total += 1
        if offset != len(tokens):
            raise ValueError("unindexed trailing tokens")
    catalog = json.loads((cache / "catalog.json").read_text())
    checked = set()
    with (cache / "provenance.jsonl").open(encoding="utf-8") as f:
        for line in f:
            r = json.loads(line)
            key = r["id"]
            if key in checked or identities.get(key) != (r["split"], r["tokens_sha256"], r["dataset"], r["group"]):
                raise ValueError("provenance/index mismatch")
            ds = catalog["datasets"][r["dataset"]]
            if r["revision"] != ds.get("revision", ds.get("release")) or r["license"] != ds["license"]:
                raise ValueError("provenance identity/license mismatch")
            if not all(r.get(k) for k in ("attribution", "source_url", "source_file", "source_sha256")):
                raise ValueError("missing source provenance")
            if r["dataset"] == "mbpp" and {"train":"train","validation":"val","test":"test"}.get(r["source_split"]) != r["split"]:
                raise ValueError("MBPP heldout partition changed")
            checked.add(key)
    if len(checked) != total or total != stats["records"]:
        raise ValueError("provenance/statistics count mismatch")
    if require_tasks:
        for split in ("train", "val"):
            for task in ("text", "chat_text", "coding"):
                if not counts[split + "/" + task]:
                    raise ValueError("missing required task coverage")
    checksums = cache / "checksums.json"
    if checksums.exists():
        for name, sha in json.loads(checksums.read_text()).items():
            if Path(name).name != name or sha256_file(cache / name) != sha:
                raise ValueError("cache file checksum mismatch: " + name)
    return {"passed": True, "records": total, "counts": dict(counts), "source_groups": len(groups),
            "content_leakage": 0, "context": stats["context"], "vocab_size": v.size,
            "validated_at": time.time(), "training_started": False}