File size: 11,234 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
"""Offline normalized records -> validated, deduplicated, tokenized v2 caches.



No network access, model updates, tool execution or implicit license assumptions.

Records retain dataset, revision, group, split, attribution, asset checksums and

packet inputs/outputs. Paired generation/understanding rows share one split key.

"""
from __future__ import annotations

from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path

import numpy as np

from ..tokenizers.multimodal import Sample
from ..tokenizers.universal import UniversalVocab
from .preprocessing import sha256_file


def canonical(value) -> str:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False)


def digest(value) -> str:
    return hashlib.sha256(canonical(value).encode()).hexdigest()


def validate_calls(tools: list[dict], calls: list[dict]) -> None:
    """Validate tool names and arguments with full JSON Schema; never execute tools."""
    from jsonschema import Draft202012Validator
    names = {}
    for tool in tools:
        f = tool.get("function", tool)
        name = f["name"]
        if name in names:
            raise ValueError(f"duplicate tool name: {name}")
        schema = f["parameters"]
        Draft202012Validator.check_schema(schema)
        names[name] = Draft202012Validator(schema)
    for call in calls:
        if call["name"] not in names:
            raise ValueError(f"unknown tool: {call['name']}")
        if not isinstance(call["arguments"], dict):
            raise ValueError("tool arguments must be a JSON object")
        names[call["name"]].validate(call["arguments"])


def verify_record(r: dict, catalog: dict):
    for key in ("id", "dataset", "revision", "group", "license", "attribution", "source_url", "task", "inputs", "outputs"):
        if key not in r or r[key] in (None, "", []):
            # Text pretraining legitimately has no input conditioning.
            if key == "inputs" and r.get(key) == []:
                continue
            raise ValueError(f"missing provenance/content field: {key}")
    ds = catalog["datasets"].get(r["dataset"])
    if ds is None or ds["role"] != "core":
        raise ValueError("dataset is unknown or disabled/reserve")
    if r["task"] not in ds["tasks"]:
        raise ValueError("task not registered for dataset")
    if r["dataset"] == "mbpp":
        expected = {"train": "train", "validation": "val", "test": "test"}
        if r.get("source_split") not in expected or r.get("split") != expected[r["source_split"]]:
            raise ValueError("MBPP official splits must be retained; held-out solutions cannot be relabeled train")
    if r["revision"] != ds.get("revision", ds.get("release")):
        raise ValueError("record revision differs from the pinned catalog")
    if ds.get("caption_revision") and r.get("caption_revision") != ds["caption_revision"]:
        raise ValueError("record must pin its caption source revision as well as its asset source")
    allowed = catalog["policy"]["allowed_asset_licenses"]
    licenses = r["license"] if isinstance(r["license"], list) else [r["license"]]
    for lic in licenses:
        if lic not in allowed:
            raise ValueError(f"unapproved or ambiguous license: {lic}")
    declared = ds.get("license")
    if declared and declared not in licenses and not (declared == "CC-BY" and any(x.startswith("CC-BY-") for x in licenses)):
        raise ValueError("record license differs from pinned dataset terms")
    media = [s for s in r["inputs"] + r["outputs"] if s["type"] in ("image", "video", "audio", "mesh")]
    if media:
        for asset in r.get("assets", []):
            for key in ("sha256", "license", "attribution", "source_url", "rights_evidence"):
                if not asset.get(key):
                    raise ValueError(f"media asset missing {key}")
            if asset["license"] not in allowed:
                raise ValueError("unapproved media asset license")
            if len(asset["sha256"]) != 64 or any(c not in "0123456789abcdef" for c in asset["sha256"]):
                raise ValueError("invalid asset checksum")
        if not r.get("assets"):
            raise ValueError("media record needs asset rights evidence and checksums")
    if r["task"] == "tools":
        tools = next(s["value"] for s in r["inputs"] if s["type"] == "tools")
        calls = next(s["value"] for s in r["outputs"] if s["type"] == "calls")
        validate_calls(tools, calls)
    inputs = {s["type"] for s in r["inputs"]}
    outputs = {s["type"] for s in r["outputs"]}
    expected = {"t2i": ("text", "image"), "i2t": ("image", "text"), "t2v": ("text", "video"),
                "v2t": ("video", "text"), "vcont": ("video", "video"), "t2a": ("text", "audio"),
                "a2t": ("audio", "text"), "t2m": ("text", "mesh"), "m2t": ("mesh", "text"),
                "chat_text": ("text", "text"), "coding": ("text", "text"), "tools": ("tools", "calls")}
    if r["task"] in expected:
        a, b = expected[r["task"]]
        if a not in inputs or b not in outputs: raise ValueError("packet types do not match the registered task")
    if r["task"] == "text" and outputs != {"text"}: raise ValueError("text task needs text targets")


def compile_manifest(manifest: str | Path, out: str | Path, vocab: UniversalVocab, tok, catalog: dict,

                     context: int = 1024, max_disk_bytes: int = 20_000_000_000) -> dict:
    """Stream into uint16 token files and per-row indices; reject overlong samples without truncation.



    Existing output directories are refused. Failure preserves an INCOMPLETE marker;

    a loader refuses that directory. Provenance is saved separately from compact indices.

    """
    manifest, out = Path(manifest), Path(out)
    if out.exists():
        raise FileExistsError(f"refusing to overwrite cache {out}; use a new versioned directory")
    if tok.vocab_size != vocab.text_size or vocab.size > 65536:
        raise ValueError("tokenizer size/vocabulary mismatch for uint16 cache")
    out.mkdir(parents=True)
    (out / "INCOMPLETE").write_text("preparation in progress")
    counts, offsets = Counter(), defaultdict(int)
    groups, assets, seen, seen_split = {}, {}, set(), {}
    report = {"training_started": False, "records": 0, "target_tokens": 0}
    handles = {}
    try:
        for split in ("train", "val", "test"):
            handles[split] = ((out / f"{split}.bin").open("wb"), (out / f"{split}.index.jsonl").open("w", encoding="utf-8"))
        with manifest.open(encoding="utf-8") as src, (out / "provenance.jsonl").open("w", encoding="utf-8") as prov:
            for lineno, line in enumerate(src, 1):
                if not line.strip(): continue
                try:
                    r = json.loads(line)
                    verify_record(r, catalog)
                    group = r["dataset"] + ":" + str(r["group"])
                    # Explicit official splits win. Otherwise hash source groups, never windows/captions.
                    split = r.get("split") or ("val" if int(digest(group)[:8], 16) % 100 < 2 else "train")
                    if split not in handles: raise ValueError("split must be train, val or test")
                    if group in groups and groups[group] != split: raise ValueError("source group leaks across splits")
                    groups[group] = split
                    for a in r.get("assets", []):
                        h = a["sha256"]
                        if h in assets and assets[h] != split: raise ValueError("asset content leaks across splits")
                        assets[h] = split
                    key = digest([r["task"], r["inputs"], r["outputs"]])
                    if key in seen:
                        if seen_split[key] != split: raise ValueError("duplicate example leaks across splits")
                        counts["duplicates_skipped"] += 1
                        continue
                    seen.add(key)
                    seen_split[key] = split
                    sample = vocab.build(r["task"], r["inputs"], r["outputs"], tok.encode, context)
                    if (sum(offsets.values()) + len(sample.tokens)) * 2 > max_disk_bytes:
                        raise ValueError("prepared token disk budget exceeded")
                    sample.tokens.astype("<u2").tofile(handles[split][0])
                    idx = {"offset": offsets[split], "length": len(sample.tokens), "target_start": sample.target_start,
                           "task": r["task"], "id": r["id"], "dataset": r["dataset"], "group": r["group"]}
                    handles[split][1].write(canonical(idx) + "\n")
                    prov.write(canonical({k: r[k] for k in r if k not in ("inputs", "outputs")}) + "\n")
                    offsets[split] += len(sample.tokens)
                    counts[split + "/" + r["task"]] += 1
                    report["records"] += 1
                    report["target_tokens"] += len(sample.tokens) - sample.target_start
                except Exception as e:
                    raise ValueError(f"{manifest}:{lineno}: {e}") from e
    finally:
        for pair in handles.values():
            for f in pair: f.close()
    tok.save(out / "text_tokenizer.json")
    (out / "vocab_v2.json").write_text(json.dumps(vocab.to_dict(), indent=2))
    (out / "catalog.json").write_text(json.dumps(catalog, indent=2))
    report |= {"counts": dict(counts), "manifest_sha256": sha256_file(manifest), "catalog_sha256": digest(catalog),
               "token_bytes": sum(offsets.values()) * 2, "context": context, "tokenizer_sha256": sha256_file(out / "text_tokenizer.json")}
    (out / "stats.json").write_text(json.dumps(report, indent=2))
    (out / "INCOMPLETE").unlink()
    return report


class UniversalSources:
    """Same sample/available interface as TaskSources; consumed by existing MixtureLoader."""
    def __init__(self, cache: str | Path, split: str, vocab: UniversalVocab, seq_len: int = 1024):
        cache = Path(cache)
        if (cache / "INCOMPLETE").exists(): raise ValueError("incomplete v2 cache")
        if json.loads((cache / "vocab_v2.json").read_text()) != vocab.to_dict(): raise ValueError("v2 vocabulary mismatch")
        self.vocab, self.seq_len, self.rows = vocab, seq_len, defaultdict(list)
        path = cache / f"{split}.bin"
        self.tokens = np.memmap(path, dtype="<u2", mode="r") if path.stat().st_size else np.array([], dtype=np.uint16)
        for line in (cache / f"{split}.index.jsonl").read_text().splitlines():
            r = json.loads(line)
            if r["length"] - 1 > seq_len: raise ValueError("cached sample exceeds requested context")
            self.rows[r["task"]].append(r)

    def available(self): return list(self.rows)

    def sample(self, task: str, rng: np.random.Generator) -> Sample:
        rows = self.rows[task]
        r = rows[int(rng.integers(len(rows)))]
        return Sample(np.array(self.tokens[r["offset"]:r["offset"] + r["length"]], dtype=np.int32), r["target_start"])