#!/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=" 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()