File size: 15,241 Bytes
6661fea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Pack independently approved v6 document streams into the ten slots of clean Base 1.10.

Differences from pack_110_base.py: roles code and logic; per-component task epochs ("epochs", 1-4);
base pools may carry "base_weight" (share of each slot's base fill within its language) and
"max_unique_positions" (capacity cap); the specialist unique budget comes from the manifest
("task_unique_cap") instead of a fixed fraction of the token cap.
"""
import argparse
from collections import Counter
from hashlib import sha256
import heapq
import json
from pathlib import Path
import tempfile

import numpy as np

import start_110c as launch


ROLES = {"reading", "tools", "math", "code", "logic", "base"}
MAX_EPOCHS = 4
LANGS = ("EN", "PL")


class Pool:
    def __init__(self, root, row):
        self.role, self.lang = row["role"], row["language"]
        self.name = row["name"]
        if self.role not in ROLES or self.lang not in LANGS or not self.name:
            raise ValueError("invalid component name, role or language")
        self.reason = row.get("reason")
        if not isinstance(self.reason, str) or not self.reason.strip():
            raise ValueError(f"missing selection reason: {self.name}")
        tokens, index = root / row["bin"], root / row["index"]
        self.pin = row["bin_sha256"]
        launch.require_hash(tokens, self.pin)
        launch.require_hash(index, row["index_sha256"])
        if tokens.stat().st_size % 2 or index.stat().st_size % 8:
            raise ValueError(f"unaligned binary or index: {self.name}")
        self.ends = np.memmap(index, dtype="<u8", mode="r")
        self.tokens = np.memmap(tokens, dtype="<u2", mode="r")
        self.total = int(self.ends[-1])
        if not 0 < self.ends[0] <= self.total == self.tokens.size or np.any(self.ends[1:] <= self.ends[:-1]):
            raise ValueError(f"invalid document ends: {self.name}")
        for start in range(0, self.ends.size, 65536):
            if np.any(self.tokens[self.ends[start:start + 65536] - 1] != 0):
                raise ValueError(f"document does not end with EOT=0: {self.name}")
        self.cursor = 0
        self.limit = len(self.ends)
        if "max_unique_positions" in row:
            budget = row["max_unique_positions"]
            if type(budget) is not int or budget < 1:
                raise ValueError(f"invalid unique budget: {self.name}")
            self.limit = int(np.searchsorted(self.ends, np.uint64(min(budget, self.total)), side="right"))
        self.epochs = row.get("epochs")
        self.weight = row.get("base_weight")
        if self.role == "base":
            if self.epochs is not None:
                raise ValueError(f"base pools are read once: {self.name}")
            if self.weight is not None and (type(self.weight) is not int or self.weight < 1):
                raise ValueError(f"invalid base weight: {self.name}")
        else:
            if self.weight is not None:
                raise ValueError(f"base_weight is only for base pools: {self.name}")
            if self.epochs is not None and (type(self.epochs) is not int or not 1 <= self.epochs <= MAX_EPOCHS):
                raise ValueError(f"epochs must be 1-{MAX_EPOCHS}: {self.name}")

    def offset(self, row):
        return int(self.ends[row - 1]) if row else 0

    @property
    def remaining(self):
        return self.offset(self.limit) - self.offset(self.cursor)

    def take(self, minimum):
        start = self.cursor
        if minimum:
            until = self.offset(start) + minimum
            self.cursor = min(self.limit, int(np.searchsorted(self.ends, np.uint64(until))) + 1)
        return start, self.cursor


def task_cut(src, target, per_epoch):
    if not target:
        return 0
    epoch, remainder = divmod(target, per_epoch)
    local = int(np.searchsorted(src.ends[:src.limit], np.uint64(remainder))) + 1 if remainder else 0
    return epoch * src.limit + local


def plan(pools, task_epochs=1, max_tool_share_bp=None, task_unique_cap=None):
    minimum = (launch.SLOT_STEPS * launch.BATCH + 1) * launch.BLOCK
    en = minimum * 7 // 10
    target = {"EN": en, "PL": minimum - en}
    if type(task_epochs) is not int or task_epochs not in (1, 2):
        raise ValueError("task_epochs must be 1 or 2")
    specialists = [src for src in pools if src.role != "base"]
    for src in specialists:
        if src.epochs is None:
            src.epochs = task_epochs
    if (max_tool_share_bp is not None or any(src.epochs > 1 for src in specialists)) and (
        type(max_tool_share_bp) is not int or not 1 <= max_tool_share_bp <= 10000
    ):
        raise ValueError("an explicit max_tool_share_bp is required for repeated task epochs")
    specialist_tokens = sum(src.offset(src.limit) for src in specialists)
    if task_unique_cap is None:
        unique_cap = launch.FIRST_TRAIN_TOKEN_CAP // (5 * task_epochs)
    elif type(task_unique_cap) is int and 0 < task_unique_cap < launch.FIRST_TRAIN_TOKEN_CAP:
        unique_cap = task_unique_cap
    else:
        raise ValueError("invalid task_unique_cap")
    if specialist_tokens > unique_cap:
        for src in specialists:
            quota = src.offset(src.limit) * unique_cap // specialist_tokens
            src.limit = int(np.searchsorted(src.ends[:src.limit], np.uint64(quota), side="right"))
    unique_tasks = sum(src.offset(src.limit) for src in specialists)
    unique_tools = sum(src.offset(src.limit) for src in specialists if src.role == "tools")
    if max_tool_share_bp is not None and unique_tools * 10000 > unique_tasks * max_tool_share_bp:
        raise ValueError("selected sources exceed the tool share cap; lower their unique budgets")
    present_roles = {src.role for src in pools}
    slots = []
    for step in range(1, launch.SLOTS + 1):
        spans, counts = [], Counter()

        def add(src, lo, hi, epoch):
            if lo < hi:
                spans.append((src, lo, hi, epoch))
                counts[src.lang] += src.offset(hi) - src.offset(lo)

        for src in specialists:
            per_epoch = src.offset(src.limit)
            if not per_epoch:
                continue
            total = per_epoch * src.epochs
            lo = task_cut(src, total * (step - 1) // launch.SLOTS, per_epoch)
            hi = task_cut(src, total * step // launch.SLOTS, per_epoch)
            while lo < hi:
                epoch, start = divmod(lo, src.limit)
                end = min(src.limit, start + hi - lo)
                add(src, start, end, epoch + 1)
                lo += end - start
        for language in LANGS:
            need = target[language] - counts[language]
            plain = [src for src in pools if src.role == "base" and src.lang == language]
            capacity = sum(src.remaining for src in plain)
            if not 0 <= need <= capacity:
                raise ValueError(f"slot {step}: {language} needs {need} base tokens, has {capacity}")
            # Weighted fill keeping whole documents; a pool without base_weight weighs what it has left.
            weights = [(src, src.weight if src.weight is not None else src.remaining) for src in plain if src.remaining]
            left = sum(w for _, w in weights)
            for src, w in weights:
                if need and left:
                    want = min(src.remaining, (need * w + left - 1) // left)
                    add(src, *src.take(want), 1)
                    need = max(0, target[language] - counts[language])
                left -= w
            if need:
                for src in plain:
                    if need and src.remaining:
                        add(src, *src.take(need), 1)
                        need = max(0, target[language] - counts[language])
            if need:
                raise ValueError(f"slot {step}: {language} base fill short by {need}")
        if {src.role for src, _, _, _ in spans} != present_roles:
            raise ValueError(f"slot {step} does not contain every role present in the inputs")
        if not any(src.role == "reading" and src.lang == "PL" for src, _, _, _ in spans):
            raise ValueError(f"slot {step} lacks Polish reading; EN reading supplements it")
        slots.append(spans)
    for src in specialists:
        src.cursor = src.limit
    return slots


def interleave(spans):
    # Merge document-aligned runs by relative progress through each source span.
    # Even a small specialist block is spread through the slot, not appended.
    pending = []

    def schedule(i, lo):
        src, begin, end, _ = spans[i]
        first, last = src.offset(begin), src.offset(end)
        goal = src.offset(lo) + max(1, (last - first) // 4096)
        hi = min(end, int(np.searchsorted(src.ends, np.uint64(goal))) + 1)
        heapq.heappush(pending, ((src.offset(hi) - first) / (last - first), i, lo, hi))

    for i, (_, start, _, _) in enumerate(spans):
        schedule(i, start)
    while pending:
        _, i, lo, hi = heapq.heappop(pending)
        src, _, end, _ = spans[i]
        yield memoryview(src.tokens[src.offset(lo):src.offset(hi)]).cast("B")
        if hi < end:
            schedule(i, hi)


def assemble(manifest, receipt_sha, output):
    launch.require_hash(manifest, receipt_sha)
    if output.exists():
        raise FileExistsError(output)
    spec = json.loads(manifest.read_bytes())
    if spec["tokenizer_sha256"] != launch.TOK_SHA:
        raise ValueError("approved inputs do not use the pinned v6 tokenizer")
    root = manifest.parent
    validation = (root / spec["validation"]["path"]).read_bytes()
    val_sha = sha256(validation).hexdigest()
    if val_sha != spec["validation"]["sha256"] or len(validation) % 2 or len(validation) < 2 * (launch.BLOCK + 2):
        raise ValueError("validation pin or geometry does not match")
    pools = [Pool(root, row) for row in spec["components"]]
    if len({p.name for p in pools}) != len(pools) or len({p.pin for p in pools}) != len(pools) or val_sha in {p.pin for p in pools}:
        raise ValueError("duplicate component name or train/validation bytes")
    epochs, tool_cap = spec.get("task_epochs", 1), spec.get("max_tool_share_bp")
    slots = plan(pools, epochs, tool_cap, spec.get("task_unique_cap"))
    planned_tokens = sum(src.offset(hi) - src.offset(lo) for spans in slots for src, lo, hi, _ in spans)
    if planned_tokens > launch.FIRST_TRAIN_TOKEN_CAP:
        raise ValueError("whole-document slot boundaries exceed the token cap")
    queue = {"steps_per_shard": launch.SLOT_STEPS, "shards": {}, "rotations": []}
    report = {"approved_inputs_sha256": receipt_sha, "task_epochs": epochs, "max_tool_share_bp": tool_cap,
              "task_unique_cap": spec.get("task_unique_cap"), "slots": {}}
    by_component, by_language, by_role = Counter(), Counter(), Counter()
    train_hash, pos = sha256(), 0
    with tempfile.TemporaryDirectory(dir=output.parent) as tmp:
        stage = Path(tmp) / "packed"
        stage.mkdir()
        with (stage / "train.bin").open("wb") as train:
            for i, spans in enumerate(slots, 1):
                name, lo, slot_hash = f"slot{i:02d}", pos, sha256()
                for buf in interleave(spans):
                    train.write(buf)
                    train_hash.update(buf)
                    slot_hash.update(buf)
                    pos += buf.nbytes // 2
                queue["shards"][name] = {"lo": lo, "hi": pos, "sha256": slot_hash.hexdigest()}
                queue["rotations"].append([name])
                report["slots"][name] = per_slot = {}
                for p, a, b, epoch in spans:
                    tokens = p.offset(b) - p.offset(a)
                    entry = per_slot.setdefault(p.name, {"role": p.role, "language": p.lang, "ranges": [], "tokens": 0})
                    entry["ranges"].append({"epoch": epoch, "documents": [a, b]})
                    entry["tokens"] += tokens
                    by_component[p.name] += tokens
                    by_language[p.lang] += tokens
                    by_role[p.role] += tokens
        launch.validate_queue(queue, pos)
        def share(tokens):
            return {"tokens": tokens, "percent": 100 * tokens / pos}

        if by_component.total() != pos:
            raise ValueError("component totals do not match train.bin")
        for p in pools:
            if by_component[p.name] != p.offset(p.cursor) * (1 if p.role == "base" else p.epochs):
                raise ValueError(f"exposure accounting disagrees with selected documents: {p.name}")
        report["composition"] = {
            "basis": "positions in train.bin including EOT and slot buffer, not sampled training targets",
            "tokens": pos,
            "task_unique_positions": sum(p.offset(p.cursor) for p in pools if p.role != "base"),
            "task_exposure_positions": pos - by_role["base"],
            "by_component": {
                p.name: {**share(by_component[p.name]), "unique_positions": p.offset(p.cursor),
                         "role": p.role, "language": p.lang, "reason": p.reason,
                         "epochs": 1 if p.role == "base" else p.epochs, "base_weight": p.weight}
                for p in pools if by_component[p.name]
            },
            "by_language": {k: share(v) for k, v in sorted(by_language.items())},
            "by_role": {k: share(v) for k, v in sorted(by_role.items())},
        }
        (stage / "val.bin").write_bytes(validation)
        queue_bytes = (json.dumps(queue, indent=2) + "\n").encode("ascii")
        (stage / "queue.json").write_bytes(queue_bytes)
        sums = f"{train_hash.hexdigest()}  train.bin\n{val_sha}  val.bin\n{sha256(queue_bytes).hexdigest()}  queue.json\n".encode("ascii")
        (stage / "SHA256SUMS").write_bytes(sums)
        # Task repetitions in this tranche use only the selected prefix; defer each unused tail once.
        deferred = {"approved_inputs_sha256": receipt_sha, "first_train_sha256": train_hash.hexdigest(),
                    "components": [{**row, "documents": [p.cursor, len(p.ends)],
                                    "token_range": [p.offset(p.cursor), p.total]}
                                   for row, p in zip(spec["components"], pools, strict=True)
                                   if p.cursor < len(p.ends)]}
        deferred_bytes = (json.dumps(deferred, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
        (stage / "deferred.json").write_bytes(deferred_bytes)
        report["deferred_sha256"] = sha256(deferred_bytes).hexdigest()
        (stage / "assembly.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
        stage.rename(output)
    print(f"PACKED tokens={pos} SHA256SUMS={sha256(sums).hexdigest()} — awaiting final data acceptance", flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("approved_inputs", type=Path)
    parser.add_argument("approved_inputs_sha256")
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    try:
        assemble(args.approved_inputs, args.approved_inputs_sha256, args.output)
    except (OSError, ValueError, KeyError, TypeError) as exc:
        parser.exit(2, f"STOP: {exc}\n")


if __name__ == "__main__":
    main()