File size: 8,872 Bytes
643267a | 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 | """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="<u4")
self.offsets = np.load(self.path / "offsets.npy", mmap_mode="r", allow_pickle=False)
self.lexical_lengths = np.load(
self.path / "lexical_lengths.npy", mmap_mode="r", allow_pickle=False
)
if self.offsets.dtype != np.dtype("<i8") or self.offsets.ndim != 1:
raise ValueError("Piece offsets must be a one-dimensional int64 array")
if (self.offsets.size != self.lexical_lengths.size + 1
or self.offsets[0] != 0 or self.offsets[-1] != len(self.tokens)
or np.any(np.diff(self.offsets) <= 0)):
raise ValueError("Invalid document-piece offsets")
if self.lexical_lengths.ndim != 1 or self.lexical_lengths.dtype != np.dtype("<i8"):
raise ValueError("Lexical lengths must be a one-dimensional int64 array")
self.routed_lengths = np.diff(self.offsets)
if np.any(self.lexical_lengths <= 0):
raise ValueError("Each document piece must have at least one lexical token")
endings = self.routed_lengths - self.lexical_lengths
if np.any((endings != 0) & (endings != 1)):
raise ValueError("Only a terminal EOD may extend a lexical piece")
if np.any(self.lexical_lengths > 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
|