"""Document pieces and the deterministic token-budget batching rule. Each piece contains lexical token IDs and, only at a document's actual end, one EOD. BOS and abstraction slots are added by the model, never stored here. """ from __future__ import annotations import hashlib import heapq import itertools import json import math import random from pathlib import Path import numpy as np import torch EOD = 50256 def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: while block := stream.read(8 * 1024 * 1024): digest.update(block) return digest.hexdigest() class PieceDataset: """Read a prepared corpus without loading its token array into RAM. Hash verification occurs once when opening the dataset. The resulting fingerprint is saved with training state and checked on every resume. """ def __init__(self, path: str | Path): self.path = Path(path) manifest_path = self.path / "manifest.json" self.fingerprint = file_sha256(manifest_path) self.manifest = json.loads(manifest_path.read_text()) if self.manifest.get("format") != "pat-document-pieces-1": raise ValueError("Unsupported dataset format; use python -m pat.prepare") expected = {"tokens.bin", "offsets.npy", "lexical_lengths.npy"} if set(self.manifest["files"]) != expected: raise ValueError("Dataset manifest must identify the three required arrays") for filename, digest in self.manifest["files"].items(): if file_sha256(self.path / filename) != digest: raise ValueError(f"Dataset file checksum mismatch: {filename}") self.tokens = np.memmap(self.path / "tokens.bin", mode="r", dtype=" int(self.manifest["context_length"])): raise ValueError("Piece exceeds the declared context length") def __len__(self) -> int: return len(self.lexical_lengths) def __getitem__(self, index: int) -> torch.Tensor: start, end = int(self.offsets[index]), int(self.offsets[index + 1]) values = np.array(self.tokens[start:end], dtype=np.int64) final = int(self.routed_lengths[index] - self.lexical_lengths[index]) == 1 lexical = values[:-1] if final else values if np.any(lexical >= EOD) or (final and values[-1] != EOD): raise ValueError(f"Invalid lexical IDs or document boundary at piece {index}") return torch.from_numpy(values) def _bucket_order(routed_lengths, lexical_lengths, budget, seed, epoch): """Shared fixed-width buckets and seeded within-bucket piece ordering.""" routed = np.asarray(routed_lengths, dtype=np.int64) lexical = np.asarray(lexical_lengths, dtype=np.int64) if routed.ndim != 1 or lexical.shape != routed.shape: raise ValueError("Lengths must be equally sized one-dimensional arrays") if budget <= 0 or epoch < 0 or np.any(lexical <= 0): raise ValueError("Budgets and lengths must be positive, epoch nonnegative") if np.any(routed < lexical): raise ValueError("Routed lengths cannot be smaller than lexical lengths") count = math.ceil(int(lexical.sum()) / budget) order = list(range(len(lexical))) random.Random(seed + epoch).shuffle(order) order.sort(key=lambda index: -((int(routed[index]) - 1) // 20)) return routed, lexical, count, order def training_batches( routed_lengths: np.ndarray, lexical_lengths: np.ndarray, *, budget: int, seed: int, epoch: int, quantum: int = 1, ) -> list[list[int]]: """Preallocate bins, place longest buckets first, then shuffle bins. This reproduces the paper's Python Fisher–Yates shuffles and worst-fit tie breaking. A bin's budget counts lexical tokens. Pieces that do not fit the preallocated capacity are dropped for this epoch. The last incomplete distributed accumulation window is dropped without wrapping. """ if quantum <= 0: raise ValueError("The distributed optimizer window must be positive") _, lexical, count, order = _bucket_order( routed_lengths, lexical_lengths, budget, seed, epoch ) slots = list(range(count)) random.Random(f"{seed}:{epoch}:prealloc-slot-order").shuffle(slots) heap = [(-budget, ordinal, slot) for ordinal, slot in enumerate(slots)] heapq.heapify(heap) bins: list[list[int]] = [[] for _ in slots] ordinal = count for index in order: length = int(lexical[index]) if length > budget or not heap: continue negative_remaining, _, slot = heapq.heappop(heap) remaining = -negative_remaining if remaining >= length: bins[slot].append(index) remaining -= length if remaining > 0: heapq.heappush(heap, (-remaining, ordinal, slot)) ordinal += 1 emitted = [slot for slot, batch in enumerate(bins) if batch] random.Random(f"{seed}:{epoch}:final-batch-order").shuffle(emitted) emitted = emitted[: len(emitted) // quantum * quantum] return [bins[slot] for slot in emitted] def validation_batches(dataset: PieceDataset, budget: int, *, seed: int = 42) -> list[list[int]]: """Preserve the paper's complete-coverage, fixed validation batch plan. Length buckets retain seeded piece order. Preallocated slots are visited cyclically, with no slot/final shuffle. Capacity too small for the current bucket is reconsidered in the next bucket. Overflow receives extra bins, so every validation piece appears exactly once, including oversized ones. """ routed, lexical, count, order = _bucket_order( dataset.routed_lengths, dataset.lexical_lengths, budget, seed, 0 ) bins: list[list[int]] = [[] for _ in range(count)] used = [0] * count active = list(range(count)) cursor = 0 overflow: list[list[int]] = [] overflow_used = 0 for _, bucket in itertools.groupby(order, key=lambda index: (int(routed[index]) - 1) // 20): group = list(bucket) minimum = min(int(lexical[index]) for index in group) deferred = [] for index in group: length = int(lexical[index]) attempts, candidates = 0, len(active) placed = False while active and attempts < candidates: cursor %= len(active) slot = active[cursor] if budget - used[slot] < minimum: deferred.append(active.pop(cursor)) if not active or cursor >= len(active): cursor = 0 continue if used[slot] + length <= budget: bins[slot].append(index) used[slot] += length if used[slot] == budget: active.pop(cursor) if not active or cursor >= len(active): cursor = 0 else: cursor = (cursor + 1) % len(active) placed = True break attempts += 1 cursor = (cursor + 1) % len(active) if not placed: if not overflow or length > budget or overflow_used + length > budget: overflow.append([]) overflow_used = 0 overflow[-1].append(index) overflow_used += length active.extend(deferred) cursor = cursor % len(active) if active else 0 return [batch for batch in bins if batch] + overflow