"""Encode ordinary text and explicitly decode registered control IDs.""" from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from types import MappingProxyType from .pairs import merge_pair from .pretokenization import split_chunks @dataclass(frozen=True) class Tokenizer: """A fixed byte vocabulary, ordered BPE merges, and separate control IDs. vocabulary contains ordinary byte tokens only. vocab_size also includes controls and is the size required by a model's embedding/output matrices. """ vocabulary: Mapping[int, bytes] merges: Sequence[tuple[tuple[int, int], int]] control_token_ids: Mapping[str, int] def __post_init__(self): """Validate and take immutable snapshots of the supplied state.""" vocabulary = dict(self.vocabulary) merges = tuple((tuple(pair), new_id) for pair, new_id in self.merges) controls = dict(self.control_token_ids) if (any(type(i) is not int for i in vocabulary) or set(vocabulary) != set(range(len(vocabulary)))): raise ValueError("Vocabulary IDs must be contiguous integers starting at zero.") if any(vocabulary.get(i) != bytes([i]) for i in range(256)): raise ValueError("Vocabulary must include all 256 base bytes.") if any(not isinstance(value, bytes) for value in vocabulary.values()): raise ValueError("Ordinary vocabulary entries must be bytes.") if len(vocabulary) != 256 + len(merges): raise ValueError("Vocabulary size must match the merge rules.") # Every merge can reference only tokens established by earlier rules. seen_pairs = set() for expected_id, (pair, new_id) in enumerate(merges, start=256): if (len(pair) != 2 or any(type(i) is not int for i in (*pair, new_id)) or new_id != expected_id or any(not 0 <= i < new_id for i in pair) or pair in seen_pairs): raise ValueError("Invalid merge order or token IDs.") if vocabulary[new_id] != vocabulary[pair[0]] + vocabulary[pair[1]]: raise ValueError("Vocabulary bytes do not match merge rules.") seen_pairs.add(pair) if any(not isinstance(text, str) or not text for text in controls): raise ValueError("Control-token spellings must be non-empty strings.") if (any(type(i) is not int for i in controls.values()) or set(controls.values()) != set(range( len(vocabulary), len(vocabulary) + len(controls) ))): raise ValueError("Control IDs must be unique and follow the byte vocabulary.") object.__setattr__(self, "vocabulary", MappingProxyType(vocabulary)) object.__setattr__(self, "merges", merges) object.__setattr__(self, "control_token_ids", MappingProxyType(controls)) object.__setattr__(self, "_control_text", MappingProxyType( {token_id: text for text, token_id in controls.items()} )) @property def vocab_size(self) -> int: """Return the actual vocabulary size, including control tokens.""" return len(self.vocabulary) + len(self.control_token_ids) def encode(self, text: str) -> list[int]: """Encode ordinary text; control-token spellings have no special meaning.""" result = [] for chunk in split_chunks(text): tokens = list(chunk) for pair, new_id in self.merges: tokens = merge_pair(tokens, pair, new_id) result.extend(tokens) return result def decode(self, token_ids: Iterable[int], *, skip_control_tokens: bool = False) -> str: """Join bytes before UTF-8 decoding; invalid generated bytes become U+FFFD. Control IDs display their registered spellings unless skipped. Display text cannot distinguish a control ID from its ordinary-text spelling. """ pieces = [] for token_id in token_ids: if token_id in self._control_text: if not skip_control_tokens: pieces.append(self._control_text[token_id].encode("utf-8")) else: pieces.append(self.vocabulary[token_id]) return b"".join(pieces).decode("utf-8", errors="replace") def save(self, path: str | Path) -> None: """Save this fixed tokenizer as a versioned JSON artifact.""" from .storage import save_tokenizer save_tokenizer(self, path) @classmethod def load(cls, path: str | Path) -> "Tokenizer": """Load a tokenizer without adding or changing vocabulary entries.""" from .storage import load_tokenizer return load_tokenizer(path)