"""The byte-level BPE tokenizer shared by the released PAT and FA checkpoints.""" import hashlib import json from pathlib import Path from tokenizers import Tokenizer as BPETokenizer TOKENIZER_SHA256 = "67df57fd93740b7feb7462529fffb9edc0c7c9a30724489472385980b5bdd0b5" VOCAB_SIZE = 50304 EOD_ID, PAD_ID, BOS_ID, EOC_ID = 50256, 50257, 50258, 50259 class Tokenizer: """Encode text without adding tokens; the model handles document boundaries. IDs 0–50255 encode text. ID 50256 ends a document, 50257 pads batches, 50258 starts a document, and 50259 marks a chunk boundary. IDs 50260–50303 only align the vocabulary size and must never be generated. """ vocab_size = VOCAB_SIZE eod_token_id = EOD_ID pad_token_id = PAD_ID bos_token_id = BOS_ID eoc_token_id = EOC_ID def __init__(self, path: str | Path | None = None): self.path = Path(path) if path else Path(__file__).parent / "assets" / "tokenizer.json" payload = self.path.read_bytes() if hashlib.sha256(payload).hexdigest() != TOKENIZER_SHA256: raise ValueError("Tokenizer does not match the released checkpoint vocabulary.") self._tokenizer = BPETokenizer.from_str(payload.decode("utf-8")) # Literal marker text remains ordinary text. Packing supplies framing # IDs explicitly; added-token matching must not insert those IDs here. ordinary = json.loads(payload) ordinary["added_tokens"] = [] self._content = BPETokenizer.from_str(json.dumps(ordinary)) def encode(self, text: str) -> list[int]: """Encode a raw prompt or document, without implicit truncation or BOS.""" return self._content.encode(text, add_special_tokens=False).ids def decode(self, ids: list[int]) -> str: """Decode generated text, omitting document and packing markers.""" return self._tokenizer.decode(ids, skip_special_tokens=True)