#!/usr/bin/env python3 """Load and evaluate the non-Hugging-Face tokenizer JSONs in this dataset. The adapters deliberately do not pretend that missing configuration is known. ``load_custom_tokenizer`` returns a usable byte-level BPE core, plus a fidelity classification describing whether its intended pre-tokenization is reproducible from the artifact alone. """ from __future__ import annotations import json from dataclasses import dataclass from pathlib import Path from typing import Callable try: import regex except ImportError: # pragma: no cover - surfaced only for regex tokenizers regex = None GPT2_PATTERN = r"(?i:'s|'t|'re|'ve|'m|'ll|'d)| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+" def bytes_to_unicode() -> dict[int, str]: """The reversible byte alphabet used by GPT-2/minBPE-style artifacts.""" visible = list(range(ord("!"), ord("~") + 1)) visible += list(range(ord("¡"), ord("¬") + 1)) visible += list(range(ord("®"), ord("ÿ") + 1)) chars = visible[:] extra = 0 for byte in range(256): if byte not in visible: visible.append(byte) chars.append(256 + extra) extra += 1 return dict(zip(visible, map(chr, chars))) @dataclass class AdaptedTokenizer: source_format: str fidelity: str fidelity_note: str vocab_size: int merge_count: int merge_ranks: dict[tuple[int, int], int] token_bytes: dict[int, bytes] pretokenizer: Callable[[str], list[str]] | None = None def _encode_bytes(self, data: bytes) -> list[int]: ids = list(data) while len(ids) >= 2: candidate = min( ((self.merge_ranks[pair], pair) for pair in zip(ids, ids[1:]) if pair in self.merge_ranks), default=None, ) if candidate is None: break new_id, pair = candidate out: list[int] = [] i = 0 while i < len(ids): if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair: out.append(new_id) i += 2 else: out.append(ids[i]) i += 1 ids = out return ids def encode(self, text: str) -> list[int]: chunks = self.pretokenizer(text) if self.pretokenizer else [text] return [token for chunk in chunks for token in self._encode_bytes(chunk.encode("utf-8"))] def decode(self, ids: list[int]) -> str: return b"".join(self.token_bytes[token] for token in ids).decode("utf-8") def _regex_split(pattern: str) -> Callable[[str], list[str]]: if regex is None: raise RuntimeError("The 'regex' package is required by this tokenizer") compiled = regex.compile(pattern) return lambda text: compiled.findall(text) def _from_symbol_bpe(document: dict, path: Path) -> AdaptedTokenizer: model = document["model"] vocab: dict[str, int] = model["vocab"] byte_for_symbol = {symbol: byte for byte, symbol in bytes_to_unicode().items()} token_bytes: dict[int, bytes] = {} for symbol, token_id in vocab.items(): token_bytes[token_id] = bytes(byte_for_symbol[c] for c in symbol) ranks = {} for line in model["merges"]: left, right = line.split(" ") ranks[(vocab[left], vocab[right])] = vocab[left + right] meta = document.get("meta", {}) variant = str(meta.get("variant", "")) if "naive" in path.name: pretok, fidelity, note = None, "exact", "Artifact specifies no pre-tokenization." elif "slayer-v2" in path.name: # README specifies cl100k + full digit runs, but the exact cl100k # expression is not serialized. This is enough to inspect the BPE core, # not enough to claim benchmark parity. pretok, fidelity, note = None, "core_only", "Exact cl100k pre-tokenizer is absent from JSON; BPE core is lossless but intended boundaries are not reproducible from the artifact alone." elif isinstance(meta.get("regex_pretok"), str): pretok, fidelity, note = _regex_split(meta["regex_pretok"]), "exact", "Exact pre-tokenizer regex is serialized in artifact metadata." elif variant == "fast": pretok, fidelity, note = _regex_split(GPT2_PATTERN), "documented", "README identifies GPT-2 pre-tokenization, but the exact expression is not serialized." else: pretok, fidelity, note = None, "core_only", "Pre-tokenization is not fully specified." return AdaptedTokenizer("symbol_bpe", fidelity, note, len(vocab), len(ranks), ranks, token_bytes, pretok) def _from_integer_bpe(document: dict) -> AdaptedTokenizer: merges = document.get("merges") or document.get("reguly_merge") vocab = document["vocab"] ranks = {(int(left), int(right)): int(new) for left, right, new in merges} # Merge triples are the authoritative lossless representation. Some early # Kasia artifacts rendered invalid standalone UTF-8 bytes as U+FFFD in # ``vocab``; reconstructing recursively avoids inheriting that display loss. token_bytes = {token_id: bytes([token_id]) for token_id in range(256)} for left, right, new in merges: token_bytes[int(new)] = token_bytes[int(left)] + token_bytes[int(right)] pattern = document.get("pretokenizer_regex") if pattern: pretok, fidelity, note = _regex_split(pattern), "exact", "Pre-tokenizer regex is serialized in the artifact." else: pretok, fidelity, note = None, "exact", "Artifact defines raw-stream byte BPE without pre-tokenization." return AdaptedTokenizer("integer_bpe", fidelity, note, len(vocab), len(ranks), ranks, token_bytes, pretok) def _from_vocab_export(document: dict) -> AdaptedTokenizer: inverse = {symbol: byte for byte, symbol in bytes_to_unicode().items()} vocab: dict[str, int] = document["token_to_id"] token_bytes = {token_id: bytes(inverse[c] for c in symbol) for symbol, token_id in vocab.items()} ranks = {(int(left), int(right)): int(new) for left, right, new in document["merges"]} return AdaptedTokenizer( "vocab_export", "core_only", "Vocabulary and merge ranks are complete, but the intended Polish regex pre-tokenizer is documented only in the write-up, not serialized in JSON.", len(vocab), len(ranks), ranks, token_bytes, None, ) def load_custom_tokenizer(path: str | Path) -> AdaptedTokenizer: path = Path(path) document = json.loads(path.read_text(encoding="utf-8")) return load_custom_tokenizer_document(document, path) def load_custom_tokenizer_document(document: dict, source_path: str | Path) -> AdaptedTokenizer: """Load an artifact already parsed from JSON, retaining its source filename hints.""" path = Path(source_path) if isinstance(document.get("model"), dict) and isinstance(document["model"].get("merges"), list): return _from_symbol_bpe(document, path) if "token_to_id" in document and "merges" in document: return _from_vocab_export(document) if ("merges" in document or "reguly_merge" in document) and "vocab" in document: return _from_integer_bpe(document) raise ValueError(f"Unsupported custom tokenizer schema: {path}")