File size: 2,459 Bytes
7e2301f | 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 | """Tokenizers. All expose the same interface:
tok.encode(text) -> list[int] # control tokens like <laugh> map to single ids
tok.vocab_size, tok.pad_id, tok.id(token_str)
ByteTokenizer: UTF-8 bytes + control tokens. Language-agnostic, used for tests and Photon-S fallback.
HFTokenizer: wraps a pretrained LLM tokenizer (Qwen3) with the control tokens added.
CTC targets always use bytes (`ctc_targets`), independent of the backbone tokenizer.
"""
from __future__ import annotations
from .tags import SPECIAL_TOKENS, split_specials, strip_tags
CTC_BLANK = 0 # CTC vocab: 0 = blank, 1..256 = byte value + 1
CTC_VOCAB = 257
def ctc_targets(text: str) -> list[int]:
return [b + 1 for b in strip_tags(text).encode("utf-8")]
class ByteTokenizer:
def __init__(self):
self.specials = {t: 256 + i for i, t in enumerate(SPECIAL_TOKENS)}
self.vocab_size = 256 + len(SPECIAL_TOKENS)
self.pad_id = self.specials["<pad>"]
def id(self, token: str) -> int:
return self.specials[token]
def encode(self, text: str) -> list[int]:
ids: list[int] = []
for chunk, special in split_specials(text):
ids.extend([self.specials[chunk]] if special else chunk.encode("utf-8"))
return ids
def decode(self, ids: list[int]) -> str:
inv = {v: k for k, v in self.specials.items()}
out, buf = [], bytearray()
for i in ids:
if i < 256:
buf.append(i)
else:
out.append(buf.decode("utf-8", errors="replace"))
buf = bytearray()
out.append(inv.get(i, ""))
out.append(buf.decode("utf-8", errors="replace"))
return "".join(out)
class HFTokenizer:
def __init__(self, name: str):
from transformers import AutoTokenizer
self.tok = AutoTokenizer.from_pretrained(name)
self.tok.add_special_tokens({"additional_special_tokens": SPECIAL_TOKENS})
self.vocab_size = len(self.tok)
self.pad_id = self.tok.convert_tokens_to_ids("<pad>")
def id(self, token: str) -> int:
return self.tok.convert_tokens_to_ids(token)
def encode(self, text: str) -> list[int]:
return self.tok.encode(text, add_special_tokens=False)
def decode(self, ids: list[int]) -> str:
return self.tok.decode(ids)
def build_tokenizer(name: str):
return ByteTokenizer() if name == "bytes" else HFTokenizer(name)
|