File size: 11,228 Bytes
72c7148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Assembled training pool: storage format and the only reader (CONTRACTS.md section 7).

Layout (written by ``macjev.assemble``)::

    data/master-v3/pool/<tok_tag>/<split>.ids.npy      int32, every token of every row's pieces, concatenated
    data/master-v3/pool/<tok_tag>/<split>.rows.jsonl   one JSON object per row; ``seg`` locates its pieces in ids
    data/master-v3/pool/<tok_tag>/manifest.json        sha256 + bytes of every file, counts, tokenizer identity

``load(tok_tag, split)`` returns rows with ``pieces`` exactly as ``Renderer.pieces`` produced
them (plain Python lists), so training can call ``Renderer(tok, readout).assemble(row["pieces"],
order, head_max=row["head_max"])`` with a fresh random order for choice rows.
``open_split`` gives a lazy view (token arrays memory-mapped, pieces materialised per row)
for memory-constrained consumers.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Iterator

import numpy as np

from .paths import POOL_V3

TOK_TAGS = ("qwen35", "minicpm5")
POOLED_SPLITS = ("train", "dev", "cal")
FORMAT_VERSION = "macjev-pool-v1"
ROW_FIELDS = ("id", "group_id", "source", "category", "component", "lang", "qtype", "names", "valid_idx", "soft",
              "pieces", "n_tokens", "license", "split")


class PoolError(RuntimeError):
    pass


def sha256_file(path: Path, chunk: int = 1 << 22) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while True:
            block = f.read(chunk)
            if not block:
                break
            h.update(block)
    return h.hexdigest()


def split_files(split: str) -> tuple[str, str]:
    return f"{split}.ids.npy", f"{split}.rows.jsonl"


# -- writing (used by macjev.assemble only) -------------------------------------------------
def write_split(tok_dir: Path, split: str, rows: list[dict], flat_pieces: list[np.ndarray]) -> dict:
    """``rows[i]`` is the row metadata without pieces; ``flat_pieces[i]`` its pieces as one int32 array
    laid out prefix | head | opt0 | opt1 ...; ``rows[i]['_lens']`` holds [len(prefix), len(head), len(opt0), ...]."""
    tok_dir.mkdir(parents=True, exist_ok=True)
    ids_name, rows_name = split_files(split)
    offset = 0
    with open(tok_dir / rows_name, "w", encoding="utf-8") as f:
        for row, flat in zip(rows, flat_pieces):
            lens = row.pop("_lens")
            if sum(lens) != len(flat):
                raise PoolError(f"piece lengths do not match flat ids for {row['id']}")
            seg, o = [], offset
            for n in lens:
                seg.append([o, n])
                o += n
            row["seg"] = {"prefix": seg[0], "head": seg[1], "opts": seg[2:]}
            offset = o
            f.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
    ids = np.concatenate(flat_pieces).astype(np.int32) if flat_pieces else np.zeros(0, dtype=np.int32)
    if len(ids) != offset:
        raise PoolError("flat id array length mismatch")
    np.save(tok_dir / ids_name, ids, allow_pickle=False)
    return {name: {"sha256": sha256_file(tok_dir / name), "bytes": (tok_dir / name).stat().st_size}
            for name in (ids_name, rows_name)}


# -- reading ----------------------------------------------------------------------------
def _pool_root(root: Path | str | None) -> Path:
    return Path(root) if root is not None else POOL_V3


def read_manifest(tok_tag: str, root: Path | str | None = None) -> dict:
    path = _pool_root(root) / tok_tag / "manifest.json"
    if not path.exists():
        raise PoolError(f"no pool manifest at {path}; run python -m macjev.assemble first")
    return json.loads(path.read_text())


def _check(tok_tag: str, split: str, root: Path | str | None, verify: bool) -> tuple[Path, dict]:
    if tok_tag not in TOK_TAGS:
        raise PoolError(f"unknown tok_tag {tok_tag!r}; expected one of {TOK_TAGS}")
    if split not in POOLED_SPLITS:
        raise PoolError(f"split {split!r} is not pooled (test rows are sealed and never pooled)")
    tok_dir = _pool_root(root) / tok_tag
    manifest = read_manifest(tok_tag, root)
    if manifest.get("format") != FORMAT_VERSION:
        raise PoolError(f"pool format {manifest.get('format')!r} != {FORMAT_VERSION}")
    for name in split_files(split):
        entry = manifest["files"].get(name)
        if entry is None:
            raise PoolError(f"{name} missing from manifest")
        path = tok_dir / name
        if not path.exists():
            raise PoolError(f"{path} missing")
        if verify and sha256_file(path) != entry["sha256"]:
            raise PoolError(f"sha256 mismatch for {path}; pool is corrupt or stale")
    return tok_dir, manifest


def _drop_filter(ablation: str | None, manifest: dict) -> set[str]:
    if ablation is None:
        return set()
    ablations = manifest.get("ablations", {})
    if ablation not in ablations:
        raise PoolError(f"unknown ablation {ablation!r}; known: {sorted(ablations)}")
    return set(ablations[ablation]["drop_sources"])


def _materialise(meta: dict, ids: np.ndarray) -> dict:
    seg = meta.pop("seg")
    o, n = seg["prefix"]
    prefix = ids[o:o + n].tolist()
    o, n = seg["head"]
    head = ids[o:o + n].tolist()
    opts = [ids[o:o + n].tolist() for o, n in seg["opts"]]
    meta["pieces"] = {"prefix": prefix, "head": head, "opts": opts, "names": list(meta["names"]),
                      "qtype": meta["qtype"], "template": meta.pop("template")}
    return meta


class PoolSplit:
    """Lazy view: ``len(view)``, ``view.meta[i]`` (no pieces), ``view[i]`` (full row with pieces)."""

    def __init__(self, tok_tag: str, split: str, root: Path | str | None = None, verify: bool = True,
                 ablation: str | None = None):
        tok_dir, self.manifest = _check(tok_tag, split, root, verify)
        ids_name, rows_name = split_files(split)
        self.ids = np.load(tok_dir / ids_name, mmap_mode="r", allow_pickle=False)
        drop = _drop_filter(ablation, self.manifest)
        with open(tok_dir / rows_name, encoding="utf-8") as f:
            self.meta = [m for m in (json.loads(line) for line in f) if m["source"] not in drop]
        self.tok_tag, self.split = tok_tag, split

    def __len__(self) -> int:
        return len(self.meta)

    def __getitem__(self, i: int) -> dict:
        return _materialise(dict(self.meta[i]), self.ids)

    def __iter__(self) -> Iterator[dict]:
        for i in range(len(self)):
            yield self[i]


def open_split(tok_tag: str, split: str, root: Path | str | None = None, verify: bool = True,
               ablation: str | None = None) -> PoolSplit:
    return PoolSplit(tok_tag, split, root, verify, ablation)


def load(tok_tag: str, split: str, root: Path | str | None = None, verify: bool = True,
         ablation: str | None = None) -> list[dict]:
    """All rows of one pooled split for one tokenizer (sha256-verified by default).

    ``ablation`` (e.g. "heldout") removes the rows of the sources listed in quotas.json.
    Extra fields beyond CONTRACTS section 7: ``head_max`` (pass to ``assemble``), ``max_len`` (the row's category
    budget: 25,600 = ``macjev.render.CONTEXT_LIMIT`` for long_* / mac_*, else 8192; pools assembled before
    2026-09-24 lack it), ``builder``.
    """
    tok_dir, manifest = _check(tok_tag, split, root, verify)
    ids_name, rows_name = split_files(split)
    ids = np.load(tok_dir / ids_name, allow_pickle=False)
    drop = _drop_filter(ablation, manifest)
    out = []
    with open(tok_dir / rows_name, encoding="utf-8") as f:
        for line in f:
            meta = json.loads(line)
            if meta["source"] in drop:
                continue
            out.append(_materialise(meta, ids))
    return out


# ------------------------------------------------------------------------------------------------
# quotas.json helpers shared by assemble (epoch plan), data_gates and train (sampler): budgets that
# may name the single context limit, and length-split quota streams (2026-09-24, 25.6K context).
CONTEXT_LIMIT_NAME = "context_limit"


def resolve_len(value) -> int:
    """A token budget from quotas.json: an int, or "context_limit" (= ``macjev.render.CONTEXT_LIMIT``)."""
    from .render import CONTEXT_LIMIT
    n = CONTEXT_LIMIT if value == CONTEXT_LIMIT_NAME else int(value)
    if not 0 < n <= CONTEXT_LIMIT:
        raise ValueError(f"token budget {value!r} outside (0, {CONTEXT_LIMIT}] (the context limit)")
    return n


def quota_streams(quotas: dict) -> dict[str, dict]:
    """Sampling streams of ``quotas["components"]``.

    A component without ``length_split`` is one stream under its own name. A component with
    ``length_split`` (a list of ``{name, max_tokens, tokens_per_epoch, max_repeat}`` parts in increasing
    ``max_tokens`` order; the first part starts at 1 token, each next one right after the previous
    ``max_tokens``) is split by each row's rendered length into one stream per part; the parts'
    ``tokens_per_epoch`` must add up to the component's (so sums over components stay the epoch size).
    Rows keep their component name (S, exposure, pool fields); only the sampler's quota streams split."""
    out: dict[str, dict] = {}
    for comp, spec in quotas["components"].items():
        parts = spec.get("length_split")
        cats = list(spec.get("categories", []))
        if not parts:
            out[comp] = {"component": comp, "categories": cats, "min_tokens": 1, "max_tokens": None,
                         "tokens_per_epoch": float(spec["tokens_per_epoch"]),
                         "max_repeat": float(spec.get("max_repeat", 1.0))}
            continue
        lo = 1
        total = 0.0
        for part in parts:
            name = part["name"]
            if name in out or name in quotas["components"]:
                raise ValueError(f"length_split part name {name!r} clashes with another stream/component")
            hi = resolve_len(part["max_tokens"])
            if hi < lo:
                raise ValueError(f"{comp}.length_split parts must have increasing max_tokens")
            out[name] = {"component": comp, "categories": cats, "min_tokens": lo, "max_tokens": hi,
                         "tokens_per_epoch": float(part["tokens_per_epoch"]),
                         "max_repeat": float(part.get("max_repeat", spec.get("max_repeat", 1.0)))}
            total += float(part["tokens_per_epoch"])
            lo = hi + 1
        if abs(total - float(spec["tokens_per_epoch"])) > 0.5:
            raise ValueError(f"{comp}: length_split tokens_per_epoch sum {total:.0f} != component "
                             f"tokens_per_epoch {spec['tokens_per_epoch']} (no silent renormalisation)")
    return out


def stream_of(streams: dict[str, dict], component: str, n_tokens: int) -> str | None:
    """The quota stream of a row of ``component`` with ``n_tokens`` rendered tokens (None: no stream fits)."""
    if component in streams:
        return component
    for name, s in streams.items():
        if s["component"] == component and s["min_tokens"] <= n_tokens and \
                (s["max_tokens"] is None or n_tokens <= s["max_tokens"]):
            return name
    return None