pear15-stage3-checkpoints / pear15 /scratch_data.py
coderofpears's picture
publish portable stage runner + frozen sources
4e15292 verified
Raw History Blame Contribute Delete
27.5 kB
"""Offline BPE data preparation and resumable packed windows for scratch135.
Wire format (all shard bytes are uint16 little-endian, never byte-vocab IDs)::
{"format": "pear15-bpe-v1",
"tokenizer": {"name": "...", "revision": "...", "vocab_size": 49152,
"eos_token_id": 2},
"files": [{"path": "train-00000.bin", "split": "train", "tokens": 100,
"bytes": 200, "sha256": "<64 lowercase hex digits>"}]}
``files`` order is the stream order within each split; no sorting or shuffling.
Optional preparation metadata includes document split provenance and a separately
checksummed ``document_index`` (not a token shard). Readers require no NumPy,
torch, or transformers. A notebook embedding this module's preparation helpers
must also embed pear15/data.py; the reader itself has no pear15 imports.
``PackedTokenReader.get_batch(B, T)`` returns (x, y, B*T), with already-shifted
targets. Compute cross entropy on logits vs y directly: do NOT pass y to a
model loss that shifts labels again. All B*T positions are targets, including
row ends. One lookahead token is read but not counted as an input exposure.
The next microbatch reuses that lookahead as its first input. Count is raw input
ID exposure (including EOS and later epochs), not unique tokens or read I/O.
Train cursors are {epoch, offset_tokens}, addressing a periodic N-token stream.
Advancing N input positions increments epoch; offsets are normalized to [0,N).
The last->first target is allowed at a cycling epoch boundary. A single batch
requires B*T+1 <= N, so short corpora cannot be inflated by repetition. Validation
does not cycle, and evaluation_batches always opens a fresh independent reader.
Datasets must remain immutable after verification/opening.
"""
from __future__ import annotations
import argparse
from array import array
from bisect import bisect_right
from collections import Counter
import hashlib
import itertools
import json
import mmap
import os
from pathlib import Path
import re
import shutil
import sqlite3
import stat
import sys
FORMAT = "pear15-bpe-v1"
VOCAB_SIZE = 49_152
CHUNK_BYTES = 1024 * 1024
MAX_MANIFEST_BYTES = 16 * 1024 * 1024
MAX_FILES = 20_000
def _canonical(value):
return json.dumps(value, sort_keys=True, ensure_ascii=False,
separators=(",", ":"), allow_nan=False)
def _integer(value, name, minimum=0):
if type(value) is not int or value < minimum:
raise ValueError(f"{name} must be an integer >= {minimum}")
return value
def _chunk_size(value):
_integer(value, "chunk_bytes", 2)
if value > CHUNK_BYTES or value % 2:
raise ValueError("chunk_bytes must be even and <= 1048576")
return value
def _tokenizer_identity(value):
if not isinstance(value, dict):
raise ValueError("missing tokenizer identity")
for key in ("name", "revision"):
if not isinstance(value.get(key), str) or not value[key].strip():
raise ValueError(f"tokenizer {key} must be explicit and nonempty")
if type(value.get("vocab_size")) is not int or value["vocab_size"] != VOCAB_SIZE:
raise ValueError("scratch135 requires tokenizer vocab_size 49152")
eos = _integer(value.get("eos_token_id"), "eos_token_id")
if eos >= VOCAB_SIZE:
raise ValueError("eos_token_id outside vocabulary")
return dict(value)
def _is_link(path):
if path.is_symlink():
return True
# Windows junctions/reparse points can redirect directories without being
# reported as symlinks. Treat them the same way for dataset containment.
try:
attributes = getattr(path.lstat(), "st_file_attributes", 0)
except FileNotFoundError:
return False
return bool(attributes & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400))
def _safe_root(dataset_dir):
root = Path(dataset_dir).absolute()
for part in (root, *root.parents):
if _is_link(part):
raise ValueError("unsafe symlink in dataset path")
if not root.is_dir():
raise ValueError("dataset directory does not exist")
return root
def _safe_path(root, name):
# Portable paths: reject Windows drives/ADS, backslashes and traversal even
# on POSIX. Nested relative paths are fine; every component is checked.
if (not isinstance(name, str) or not name or "\\" in name or ":" in name
or "\x00" in name or any(p in {"", ".", ".."} for p in name.split("/"))):
raise ValueError("unsafe manifest path")
path = root
for component in name.split("/"):
if (component.endswith((".", " "))
or any(ord(c) < 32 or c in '<>"|?*' for c in component)
or re.fullmatch(r"(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?", component, re.I)):
raise ValueError("unsafe manifest path")
path = path / component
if _is_link(path):
raise ValueError("unsafe symlink in manifest path")
return path
def _open_regular(root, name):
path = _safe_path(root, name)
# O_NOFOLLOW adds protection on platforms that support it. fstat also
# rejects directories/devices; lstat before open avoids blocking on FIFOs.
if not stat.S_ISREG(path.stat().st_mode):
raise ValueError("manifest member must be a regular file")
fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0)
| getattr(os, "O_NOFOLLOW", 0))
try:
if not stat.S_ISREG(os.fstat(fd).st_mode):
raise ValueError("manifest member must be a regular file")
return os.fdopen(fd, "rb")
except BaseException:
os.close(fd)
raise
def _unique_json(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("duplicate JSON key")
result[key] = value
return result
def _reject_constant(value):
raise ValueError(f"nonfinite JSON constant: {value}")
def _load_manifest(root):
with _open_regular(root, "manifest.json") as stream:
raw = stream.read(MAX_MANIFEST_BYTES + 1)
if len(raw) > MAX_MANIFEST_BYTES:
raise ValueError("manifest exceeds size bound")
try:
manifest = json.loads(raw, object_pairs_hook=_unique_json, parse_constant=_reject_constant)
except (ValueError, UnicodeError) as exc:
raise ValueError("invalid manifest JSON") from exc
if not isinstance(manifest, dict) or manifest.get("format") != FORMAT:
raise ValueError("unsupported dataset format; expected pear15-bpe-v1")
_tokenizer_identity(manifest.get("tokenizer"))
files = manifest.get("files")
if not isinstance(files, list) or not files or len(files) > MAX_FILES:
raise ValueError("manifest requires 1..20000 token shards")
return manifest
def _entry(entry, *, shard):
if not isinstance(entry, dict):
raise ValueError("invalid manifest member")
_integer(entry.get("bytes"), "bytes")
if not isinstance(entry.get("sha256"), str) or not re.fullmatch(r"[0-9a-f]{64}", entry["sha256"]):
raise ValueError("invalid sha256")
if shard:
_integer(entry.get("tokens"), "tokens", 1)
if entry.get("split") not in ("train", "validation"):
raise ValueError("shard split must be train or validation")
if entry["bytes"] != 2 * entry["tokens"]:
raise ValueError("invalid uint16 shard size")
def _ids(raw):
values = array("H")
values.frombytes(raw)
if sys.byteorder != "little":
values.byteswap()
return values
def _verify_member(root, entry, *, shard, chunk_bytes):
_entry(entry, shard=shard)
digest = hashlib.sha256()
with _open_regular(root, entry.get("path")) as stream:
if os.fstat(stream.fileno()).st_size != entry["bytes"]:
raise ValueError(f"size mismatch: {entry['path']}")
for block in iter(lambda: stream.read(chunk_bytes), b""):
digest.update(block)
if shard and (len(block) % 2 or any(t >= VOCAB_SIZE for t in _ids(block))):
raise ValueError(f"token ID outside 0..49151 or malformed uint16: {entry['path']}")
if digest.hexdigest() != entry["sha256"]:
raise ValueError(f"sha256 checksum mismatch: {entry['path']}")
def verify_dataset(dataset_dir, *, chunk_bytes=CHUNK_BYTES):
"""Stream SHA-256 and ID-range validation for every shard, including holdout.
No corpus-sized read or token list. Optional document_index is verified too.
Hashes detect corruption, not authenticity. Paths/symlinks are rejected before
reading members. All handles are closed even when verification fails.
"""
_chunk_size(chunk_bytes)
root = _safe_root(dataset_dir)
manifest = _load_manifest(root)
members = [(e, True) for e in manifest["files"]]
if "document_index" in manifest:
members.append((manifest["document_index"], False))
paths = {"manifest.json".casefold()}
for entry, shard in members:
_entry(entry, shard=shard)
name = entry.get("path")
_safe_path(root, name)
if name.casefold() in paths:
raise ValueError("duplicate manifest path")
paths.add(name.casefold())
for entry, shard in members:
_verify_member(root, entry, shard=shard, chunk_bytes=chunk_bytes)
return manifest
def manifest_fingerprint(manifest):
"""SHA-256 of canonical complete manifest, including tokenizer, order/hashes.
Insignificant JSON whitespace/object-key order does not change identity.
Extra metadata and document ledger hashes DO affect identity. Verify the
dataset first; this function alone does not read or authenticate any files.
"""
return hashlib.sha256(_canonical(manifest).encode("utf-8")).hexdigest()
class PackedTokenReader:
"""One open mmap at a time, bounded decoding, deterministic manifest order.
Save fingerprint and split alongside state_dict in a training checkpoint;
load_state_dict accepts those as optional strict compatibility checks. A
batch allocation is O(B*T), verification/decoding chunks <= chunk_bytes.
Train cycles by default; validation never cycles. Use as a context manager.
"""
def __init__(self, dataset_dir, *, split="train", cycle=None,
chunk_bytes=CHUNK_BYTES):
self._handle = self._map = None
self._mapped_index = None
self._closed = False
self.chunk_bytes = _chunk_size(chunk_bytes)
if split not in {"train", "validation"}:
raise ValueError("split must be train or validation")
if cycle is None:
cycle = split == "train"
if type(cycle) is not bool or (split == "validation" and cycle):
raise ValueError("validation cannot cycle; cycle must be boolean")
self.split, self.cycle = split, cycle
self.root = _safe_root(dataset_dir)
self.manifest = verify_dataset(self.root, chunk_bytes=chunk_bytes)
self.fingerprint = manifest_fingerprint(self.manifest)
self.files = [e for e in self.manifest["files"] if e["split"] == split]
self._ends = list(itertools.accumulate(e["tokens"] for e in self.files))
self.total_tokens = self._ends[-1] if self._ends else 0
if self.total_tokens < 2:
raise ValueError(f"{split} requires at least context+1 tokens (minimum 2)")
self.epoch = self.offset_tokens = 0
def _check_open(self):
if self._closed:
raise ValueError("reader is closed")
def _unmap(self):
if self._map is not None:
self._map.close()
self._map = None
if self._handle is not None:
self._handle.close()
self._handle = None
self._mapped_index = None
def _mapping(self, index):
if self._mapped_index != index:
self._unmap()
self._handle = _open_regular(self.root, self.files[index]["path"])
try:
if os.fstat(self._handle.fileno()).st_size != self.files[index]["bytes"]:
raise ValueError("shard size changed after verification")
self._map = mmap.mmap(self._handle.fileno(), 0, access=mmap.ACCESS_READ)
self._mapped_index = index
except BaseException:
self._unmap()
raise
return self._map
def _read_tokens(self, offset, count):
result = []
while count:
index = bisect_right(self._ends, offset)
start = self._ends[index - 1] if index else 0
take = min(count, self._ends[index] - offset, self.chunk_bytes // 2)
mapping = self._mapping(index)
begin = 2 * (offset - start)
values = _ids(mapping[begin:begin + 2 * take])
if any(t >= VOCAB_SIZE for t in values):
raise ValueError("token ID changed outside vocabulary")
result.extend(values)
count -= take
offset = (offset + take) % self.total_tokens
return result
def get_batch(self, batch_size, sequence_length):
"""Return rectangular list[int] x/y and exact B*T input/target count.
Read B*T+1, advance only B*T, overlapping one token across calls. Every
row has its own next-token labels; there is no loss/drop at row ends.
Failed reads close handles and leave the cursor unchanged.
"""
self._check_open()
count = (_integer(batch_size, "batch_size", 1)
* _integer(sequence_length, "sequence_length", 1))
if count + 1 > self.total_tokens:
raise ValueError("corpus needs batch_size*sequence_length+1 tokens; no silent repetition")
if not self.cycle and self.offset_tokens + count + 1 > self.total_tokens:
raise StopIteration("not enough remaining validation/noncycling targets")
try:
tokens = self._read_tokens(self.offset_tokens, count + 1)
except BaseException:
self.close()
raise
x = [tokens[i:i + sequence_length] for i in range(0, count, sequence_length)]
y = [tokens[i + 1:i + sequence_length + 1] for i in range(0, count, sequence_length)]
epochs, offset = divmod(self.offset_tokens + count, self.total_tokens)
self.epoch += epochs
self.offset_tokens = offset
return x, y, count
def state_dict(self):
self._check_open()
return {"epoch": self.epoch, "offset_tokens": self.offset_tokens}
def load_state_dict(self, state, *, fingerprint=None, split=None):
"""Restore the exact next input position; offset==N normalizes to (e+1,0).
Store/check reader.fingerprint and reader.split in the outer checkpoint
to reject a different dataset/tokenizer or accidental train/eval resume.
Noncycling readers must have epoch zero and offset <= N-1.
"""
self._check_open()
if fingerprint is not None and fingerprint != self.fingerprint:
raise ValueError("dataset/tokenizer fingerprint mismatch")
if split is not None and split != self.split:
raise ValueError("cursor split mismatch")
if not isinstance(state, dict) or set(state) != {"epoch", "offset_tokens"}:
raise ValueError("cursor requires epoch and offset_tokens")
epoch = _integer(state["epoch"], "epoch")
offset = _integer(state["offset_tokens"], "offset_tokens")
if offset > self.total_tokens:
raise ValueError("offset_tokens outside available tokens")
if not self.cycle and (epoch != 0 or offset >= self.total_tokens):
raise ValueError("noncycling cursor outside available targets")
epoch += offset // self.total_tokens
self.epoch, self.offset_tokens = epoch, offset % self.total_tokens
def close(self):
self._unmap()
self._closed = True
def __enter__(self):
self._check_open()
return self
def __exit__(self, *exc):
self.close()
def evaluation_batches(dataset_dir, batch_size, sequence_length, *, eval_targets,
chunk_bytes=CHUNK_BYTES):
"""Fresh validation prefix, capped at min(eval_targets, N-1) actual labels.
No cycling, no training cursor access. The final batch can have fewer rows
or a shorter sequence to honor the cap exactly. Closing the generator also
closes its reader; exhaust it or use contextlib.closing on an early exit.
"""
_integer(batch_size, "batch_size", 1)
_integer(sequence_length, "sequence_length", 1)
_integer(eval_targets, "eval_targets", 1)
with PackedTokenReader(dataset_dir, split="validation", chunk_bytes=chunk_bytes) as reader:
remaining = min(eval_targets, reader.total_tokens - 1)
while remaining:
length = min(sequence_length, remaining)
rows = min(batch_size, remaining // length)
batch = reader.get_batch(rows, length)
remaining -= batch[2]
yield batch
class _ShardWriter:
def __init__(self, root, split, limit, max_shards):
self.root, self.split, self.limit, self.max_shards = root, split, limit, max_shards
self.handle = None
self.files = []
def write(self, tokens):
offset = 0
while offset < len(tokens):
if self.handle is None:
if len(self.files) >= self.max_shards:
raise ValueError("max_shards exceeded")
name = f"{self.split}-{len(self.files):05d}.bin"
self.handle = (self.root / name).open("xb")
self.files.append({"path": name, "split": self.split, "tokens": 0})
take = min(len(tokens) - offset, self.limit - self.files[-1]["tokens"], CHUNK_BYTES // 2)
block = array("H", tokens[offset:offset + take])
if sys.byteorder != "little":
block.byteswap()
self.handle.write(block.tobytes())
offset += take
self.files[-1]["tokens"] += take
if self.files[-1]["tokens"] == self.limit:
self.close()
def close(self):
if self.handle is not None:
self.handle.close()
self.handle = None
def prepare_records(records, tokenizer, output_dir, tokenizer_identity, *,
heldout_fraction=0.05, seed="pear15-v1", shard_tokens=1_000_000,
max_docs=100_000, max_tokens=100_000_000, max_bytes=200_000_000,
min_chars=20, max_chars=1_000_000, max_shards=10_000):
"""Encode caller-selected local/HF-exported records; no fetching or downloads.
Uses data.validate_record and data.split_for_hash BEFORE BPE encoding, exact
SQLite dedup (2 MiB cache), and a checksummed document ledger. encode is
called with add_special_tokens=False; exactly one EOS is appended per doc.
Identity must describe the already-loaded 49152-entry tokenizer, including
added tokens. Local tokenizer loading/network permission belongs to caller.
max_docs caps records examined (including rejected/duplicates), max_tokens
caps emitted IDs including EOS, max_bytes caps binary shard bytes (2/ID).
Entire documents only: stop before a document exceeds either output cap.
Input iteration is lazy; one validated document is encoded at a time, bounded
by max_chars. Shards contain <=1M IDs. Ledger records content digest, split,
provenance, and per-split start/tokens. Existing output is always refused;
failures remove staging files and publish no dataset.
"""
from . import data
identity = _tokenizer_identity(tokenizer_identity)
try:
size = len(tokenizer)
except TypeError:
size = getattr(tokenizer, "vocab_size", None)
if size != VOCAB_SIZE or getattr(tokenizer, "eos_token_id", None) != identity["eos_token_id"]:
raise ValueError("loaded tokenizer does not match vocab_size/eos_token_id identity")
for name, value in (("shard_tokens", shard_tokens), ("max_docs", max_docs),
("max_tokens", max_tokens), ("max_bytes", max_bytes),
("min_chars", min_chars), ("max_chars", max_chars),
("max_shards", max_shards)):
_integer(value, name, 1)
if shard_tokens > 1_000_000 or max_shards > MAX_FILES // 2 or max_chars < min_chars:
raise ValueError("invalid shard/record bounds")
data.split_for_hash("0" * 64, heldout_fraction, seed)
target, stage = data._staging_directory(output_dir)
writers = {s: _ShardWriter(stage, s, shard_tokens, max_shards) for s in ("train", "validation")}
stats = {s: {"documents": 0, "tokens": 0, "utf8_bytes": 0} for s in writers}
rejected = Counter()
records_read = duplicates = total_tokens = 0
db = None
stopped = "max_docs_or_input_end"
try:
db = sqlite3.connect(stage / "dedup.sqlite")
db.execute("PRAGMA cache_size=-2048")
db.execute("CREATE TABLE seen (hash TEXT PRIMARY KEY)")
with (stage / "documents.jsonl").open("x", encoding="utf-8", newline="\n") as ledger:
for record in itertools.islice(records, max_docs):
records_read += 1
try:
text, digest, provenance = data.validate_record(record, min_chars=min_chars, max_chars=max_chars)
except data.RecordError as exc:
rejected[str(exc)] += 1
continue
if db.execute("INSERT OR IGNORE INTO seen VALUES (?)", (digest,)).rowcount == 0:
duplicates += 1
continue
split = "validation" if data.split_for_hash(digest, heldout_fraction, seed) == "heldout" else "train"
tokens = tokenizer.encode(text, add_special_tokens=False)
if not isinstance(tokens, (list, tuple)) or any(type(t) is not int or not 0 <= t < VOCAB_SIZE for t in tokens):
raise ValueError("tokenizer returned invalid IDs outside 0..49151")
tokens = list(tokens)
tokens.append(identity["eos_token_id"])
if total_tokens + len(tokens) > max_tokens or 2 * (total_tokens + len(tokens)) > max_bytes:
stopped = "max_tokens_or_max_bytes"
break
start = stats[split]["tokens"]
writers[split].write(tokens)
stats[split]["documents"] += 1
stats[split]["tokens"] += len(tokens)
stats[split]["utf8_bytes"] += len(text.encode("utf-8"))
total_tokens += len(tokens)
ledger.write(_canonical({"sha256": digest, "split": split, "offset_tokens": start,
"tokens": len(tokens), **provenance}) + "\n")
if not total_tokens:
raise ValueError("no accepted documents fit output budgets")
db.close()
db = None
(stage / "dedup.sqlite").unlink()
files = []
for writer in writers.values():
writer.close()
files.extend(writer.files)
index = {"path": "documents.jsonl"}
for entry in [*files, index]:
path = stage / entry["path"]
entry.update(bytes=path.stat().st_size, sha256=data.sha256_file(path))
manifest = {"format": FORMAT, "tokenizer": identity, "files": files,
"document_index": index,
"split": {"algorithm": "sha256(seed:content_sha256)", "seed": seed,
"heldout_fraction": heldout_fraction},
"stats": stats, "records_read": records_read, "duplicates": duplicates,
"rejected": dict(sorted(rejected.items())), "stopped": stopped,
"limits": {"max_docs": max_docs, "max_tokens": max_tokens, "max_bytes": max_bytes,
"min_chars": min_chars, "max_chars": max_chars,
"shard_tokens": shard_tokens, "max_shards_per_split": max_shards}}
(stage / "manifest.json").write_text(_canonical(manifest) + "\n", encoding="utf-8")
if (stage / "manifest.json").stat().st_size > MAX_MANIFEST_BYTES:
raise ValueError("manifest exceeds size bound")
data._publish(stage, target)
return manifest
finally:
if db is not None:
db.close()
for writer in writers.values():
writer.close()
if stage.exists():
shutil.rmtree(stage)
def prepare_jsonl(input_path, output_dir, tokenizer, tokenizer_identity, *,
max_record_bytes=4_000_000, **options):
"""Bounded local JSONL adapter for prepare_records, same provenance schema."""
from .data import iter_jsonl
_integer(max_record_bytes, "max_record_bytes", 1)
records = iter_jsonl(input_path, max_record_bytes=max_record_bytes)
try:
return prepare_records((r for _, r in records), tokenizer, output_dir,
tokenizer_identity, **options)
finally:
records.close()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
verify = commands.add_parser("verify")
verify.add_argument("dataset_dir")
prep = commands.add_parser("prepare")
prep.add_argument("input_path")
prep.add_argument("output_dir")
prep.add_argument("--tokenizer", required=True, help="local tokenizer directory, or explicitly selected HF name")
prep.add_argument("--revision", required=True, help="explicit tokenizer revision/identity")
prep.add_argument("--allow-download", action="store_true", help="opt in to AutoTokenizer network access")
prep.add_argument("--heldout-fraction", type=float, default=0.05)
prep.add_argument("--seed", default="pear15-v1")
prep.add_argument("--shard-tokens", type=int, default=1_000_000)
prep.add_argument("--max-docs", type=int, default=100_000)
prep.add_argument("--max-tokens", type=int, default=100_000_000)
prep.add_argument("--max-bytes", type=int, default=200_000_000)
prep.add_argument("--max-record-bytes", type=int, default=4_000_000)
args = parser.parse_args(argv)
if args.command == "verify":
manifest = verify_dataset(args.dataset_dir)
else:
# Optional dependency is imported only for this explicit CLI command.
from transformers import AutoTokenizer
options = vars(args).copy()
for name in ("command", "tokenizer", "revision", "allow_download"):
options.pop(name)
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer, revision=args.revision,
local_files_only=not args.allow_download,
trust_remote_code=False)
identity = {"name": args.tokenizer, "revision": args.revision,
"vocab_size": VOCAB_SIZE, "eos_token_id": tokenizer.eos_token_id}
manifest = prepare_jsonl(tokenizer=tokenizer, tokenizer_identity=identity, **options)
print(json.dumps({"format": manifest["format"], "fingerprint": manifest_fingerprint(manifest),
"tokens": {s: sum(e["tokens"] for e in manifest["files"] if e["split"] == s)
for s in ("train", "validation")}}, sort_keys=True))
if __name__ == "__main__":
main()