File size: 10,151 Bytes
aae3233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Verify delivered mega-corpus content, split isolation, attribution and native packs."""
from __future__ import annotations

import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path

import numpy as np
import pyarrow.parquet as pq
import tiktoken
from tokenizers import Tokenizer

from pack_cnc_slayer import sha256 as file_sha256
from technical_corpus_curation import assign_groups
from validate_cnc_dynaword import SCHEMA, SPLITS, validate as validate_format


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


def verify(root: Path, baseline: Path | None = None) -> dict:
    result = {"format_validation": validate_format(root)}
    manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8"))
    provenance_rows = [json.loads(line) for line in (root / "provenance/records.jsonl").read_text(encoding="utf-8").splitlines()]
    provenance = {item["id"]: item for item in provenance_rows}
    if len(provenance) != len(provenance_rows):
        raise ValueError("Duplicate provenance identity")
    metadata_rows = [json.loads(line) for line in (root / "provenance/source_metadata.jsonl").read_text(encoding="utf-8").splitlines()]
    metadata = {item["id"]: item["metadata"] for item in metadata_rows}
    if len(metadata) != len(metadata_rows):
        raise ValueError("Duplicate source metadata identity")
    policy = json.loads((root / "processing/technical_mega_curation_policy.json").read_text(encoding="utf-8"))
    all_rows, seen_ids, seen_texts, seen_groups, seen_aliases = [], set(), set(), {}, {}
    source_counts, rows_by_split = {}, {}
    cl100k = tiktoken.get_encoding("cl100k_base")
    for split, relative in {**SPLITS, "quarantine": "quarantine/records.parquet"}.items():
        table = pq.read_table(root / relative)
        if table.column_names != SCHEMA:
            raise ValueError(f"Schema mismatch: {relative}")
        rows = table.to_pylist()
        rows_by_split[split] = rows
        source_counts[split] = dict(sorted(Counter(row["source"] for row in rows).items()))
        for row in rows:
            identity, text = row["id"], row["text"]
            normalized = digest(" ".join(text.split()).casefold())
            if identity in seen_ids or normalized in seen_texts:
                raise ValueError(f"Duplicate identity/content: {identity}")
            seen_ids.add(identity)
            seen_texts.add(normalized)
            proof = provenance[identity]
            if proof["split"] != split or proof["raw_text_sha256"] != digest(text) or proof["text_sha256"] != normalized:
                raise ValueError(f"Text or split differs from provenance: {identity}")
            for field in ("source", "license", "author", "created", "token_count"):
                if proof[field] != row[field]:
                    raise ValueError(f"Attribution/content mismatch: {identity}: {field}")
            for alias in (proof["group_id"], *proof["group_aliases"]):
                if alias in seen_aliases and seen_aliases[alias] != split:
                    raise ValueError(f"Document/book alias crosses splits: {alias}")
                seen_aliases[alias] = split
            group = proof["group_id"]
            seen_groups[group] = split
            if (split == "quarantine") != bool(proof["exclusion_reasons"]):
                raise ValueError(f"Exclusion reason/split mismatch: {identity}")
            if split == "quarantine" and row["token_count"] != len(cl100k.encode_ordinary(text)):
                raise ValueError(f"Quarantine proxy token mismatch: {identity}")
            row["_aliases"] = proof["duplicate_input_identities"]
            all_rows.append(row)
        expected = manifest["quarantine"] if split == "quarantine" else manifest["splits"][split]
        if len(rows) != expected["documents"] or sum(row["token_count"] for row in rows) != expected["tokens"]:
            raise ValueError(f"Partition count mismatch: {split}")
        if source_counts[split] != expected["sources"]:
            raise ValueError(f"Source count mismatch: {split}")
        if len({provenance[row["id"]]["group_id"] for row in rows}) != expected["document_groups"]:
            raise ValueError(f"Document group count mismatch: {split}")
        if split != "quarantine":
            samples = [json.loads(line) for line in (root / f"samples/{split}.jsonl").read_text(encoding="utf-8").splitlines()]
            lookup = {row["id"]: {field: row[field] for field in SCHEMA} for row in rows}
            if len({row["id"] for row in samples}) != len(samples):
                raise ValueError(f"Duplicate sample: {split}")
            if any(lookup.get(row["id"]) != row for row in samples):
                raise ValueError(f"Sample not in its split: {split}")
            if len(source_counts[split]) <= 32 and {row["source"] for row in samples} != set(source_counts[split]):
                raise ValueError(f"Samples omit available source families: {split}")
    if seen_ids != set(provenance):
        raise ValueError("Orphan or missing provenance")
    assign_groups(all_rows, metadata, policy)
    for row in all_rows:
        proof = provenance[row["id"]]
        if row["_group_id"] != proof["group_id"] or row["_split"] != proof["split"] or row["_exclusion_reasons"] != proof["exclusion_reasons"] or row["_group_keys"] != proof["group_aliases"]:
            raise ValueError(f"Recomputed curation/group assignment differs: {row['id']}")
    conservation = manifest["conservation"]
    retained = sum(len(rows_by_split[split]) for split in SPLITS)
    if len(all_rows) != conservation["records"] or retained != manifest["documents"] or len(rows_by_split["quarantine"]) != conservation["quarantined_records"] or retained != conservation["retained_records"]:
        raise ValueError("Record conservation mismatch")
    if sum(row["token_count"] for split in SPLITS for row in rows_by_split[split]) != manifest["tokens"]:
        raise ValueError("Active corpus token total mismatch")
    if baseline:
        originals = [row for path in sorted((baseline / "data").glob("*.parquet")) for row in pq.read_table(path).to_pylist()]
        fingerprints = lambda rows: {row["id"]: tuple(row[field] for field in SCHEMA) for row in rows}
        if len(originals) != len(all_rows) or fingerprints(originals) != fingerprints(all_rows):
            raise ValueError("Original records were lost, added or modified")
    packed = json.loads((root / "slayer_v6/manifest.json").read_text(encoding="utf-8"))
    tokenizer_file = root / "slayer_v6/tokenizer.json"
    if file_sha256(tokenizer_file) != packed["tokenizer_sha256"]:
        raise ValueError("Tokenizer checksum mismatch")
    tokenizer = Tokenizer.from_file(str(tokenizer_file))
    if tokenizer.token_to_id("<|endoftext|>") != 0 or tokenizer.get_vocab_size() != packed["vocab_size"] or packed["eos_id"] != 0 or packed["version"] != manifest["version"]:
        raise ValueError("Tokenizer or pack version mismatch")
    native_counts = {}
    for split in SPLITS:
        folder = root / "slayer_v6" / split
        token_file, index_file = folder / f"{split}.bin", folder / "docs.idx"
        expected = packed["splits"][split]
        if file_sha256(token_file) != expected["bin_sha256"] or file_sha256(index_file) != expected["idx_sha256"]:
            raise ValueError(f"Pack checksum mismatch: {split}")
        tokens = np.fromfile(token_file, dtype="<u2")
        offsets = np.fromfile(index_file, dtype="<u8")
        rows = rows_by_split[split]
        if len(offsets) != len(rows) or len(rows) != expected["documents"] or len(tokens) != expected["tokens_including_eos"]:
            raise ValueError(f"Pack length mismatch: {split}")
        if len(offsets) and (offsets[0] == 0 or np.any(offsets[1:] <= offsets[:-1]) or offsets[-1] != len(tokens)):
            raise ValueError(f"Non-monotonic or incomplete document offsets: {split}")
        if len(tokens) and int(tokens.max()) >= packed["vocab_size"]:
            raise ValueError(f"Invalid vocabulary token: {split}")
        start = 0
        for row, end in zip(rows, offsets):
            end = int(end)
            if tokens[end - 1] != 0:
                raise ValueError(f"Missing EOS: {row['id']}")
            encoded = np.asarray(tokenizer.encode(row["text"]).ids, dtype="<u2")
            if not np.array_equal(encoded, tokens[start:end - 1]):
                raise ValueError(f"Packed tokens differ from exact reencoding: {row['id']}")
            start = end
        native_counts[split] = {"documents": len(rows), "tokens_including_eos": len(tokens), "exact_reencoded_documents": len(rows)}
    artifact_paths = sorted(path for path in root.rglob("*") if path.is_file() and path.name != "validation_report.json" and ".cache" not in path.parts)
    result.update({
        "version": manifest["version"], "base_hub_revision": manifest["base_hub_revision"],
        "records_accounted_for": len(all_rows), "retained_records": retained,
        "quarantined_records": len(rows_by_split["quarantine"]),
        "cross_split_group_aliases": 0, "exact_duplicate_texts": 0,
        "baseline_all_eight_columns_preserved": baseline is not None,
        "all_proxy_token_counts_verified": True,
        "native_tokenizer_sha256": packed["tokenizer_sha256"], "native_packs": native_counts,
        "sources_by_split": source_counts,
        "artifacts": {str(path.relative_to(root)).replace("\\", "/"): file_sha256(path) for path in artifact_paths},
    })
    return result


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, required=True)
    parser.add_argument("--baseline", type=Path)
    args = parser.parse_args()
    result = verify(args.root, args.baseline)
    (args.root / "provenance/validation_report.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({key: value for key, value in result.items() if key not in ("artifacts", "sources_by_split")}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()