Kat / tokenizer.py
FirestormFMD's picture
Upload 23 files
ac5c307 verified
Raw History Blame Contribute Delete
3.31 kB
"""Train a byte-level BPE tokenizer on data/train.txt and encode both splits.
Outputs:
tokenizer.json the trained tokenizer
data/train.bin flat uint16 token stream
data/val.bin
Training then just slices random windows out of the .bin files — no
per-step tokenization, which matters on CPU.
"""
import sys
import numpy as np
from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from config import DATA_DIR, ROOT, SPECIALS, USER, ModelConfig
TOKENIZER_PATH = ROOT / "tokenizer.json"
def train_tokenizer(vocab_size: int) -> Tokenizer:
tok = Tokenizer(BPE(unk_token=None))
# Byte-level: every input is representable, so no <unk> is ever needed.
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
tok.decoder = decoders.ByteLevel()
tok.post_processor = processors.ByteLevel(trim_offsets=False)
trainer = BpeTrainer(
vocab_size=vocab_size,
# Listed here so they occupy the first, lowest ids; add_special_tokens
# below is what actually keeps them atomic at encode time.
special_tokens=SPECIALS,
initial_alphabet=pre_tokenizers.ByteLevel.alphabet(),
show_progress=False,
)
# Train on train.txt only — letting the tokenizer see val.txt would leak.
tok.train([str(DATA_DIR / "train.txt")], trainer)
tok.add_special_tokens(SPECIALS)
return tok
def encode_split(tok: Tokenizer, name: str) -> np.ndarray:
lines = (DATA_DIR / f"{name}.txt").read_text(encoding="utf-8").splitlines()
# Encode per dialogue so BPE merges never straddle a dialogue boundary,
# then concatenate: each line already ends in <|eos|>, so the stream stays
# unambiguous without the newline.
ids = [i for enc in tok.encode_batch(lines) for i in enc.ids]
arr = np.array(ids, dtype=np.uint16)
arr.tofile(DATA_DIR / f"{name}.bin")
return arr
def main() -> None:
cfg = ModelConfig()
assert cfg.vocab_size < 2**16, "uint16 storage requires vocab < 65536"
tok = train_tokenizer(cfg.vocab_size)
tok.save(str(TOKENIZER_PATH))
print(f"tokenizer: {tok.get_vocab_size()} tokens -> {TOKENIZER_PATH.name}")
print("special ids:", {s: tok.token_to_id(s) for s in SPECIALS})
for name in ("train", "val"):
arr = encode_split(tok, name)
chars = len((DATA_DIR / f"{name}.txt").read_text(encoding="utf-8"))
print(
f"{name:5s} {len(arr):9,} tokens "
f"({chars / len(arr):.2f} chars/token) -> data/{name}.bin"
)
# Round-trip check: encoding then decoding must preserve the text, and the
# speaker tags must survive as single tokens. skip_special_tokens=False is
# required here -- the default drops the speaker tags from the output.
sample = (DATA_DIR / "train.txt").read_text(encoding="utf-8").splitlines()[0]
enc = tok.encode(sample)
decoded = tok.decode(enc.ids, skip_special_tokens=False)
assert decoded == sample, f"round-trip failed:\n{sample[:120]}\n{decoded[:120]}"
assert enc.tokens[0] == USER, "speaker tag was split by the pre-tokenizer"
print("\nround-trip identical: True")
print("first 12 tokens:", enc.tokens[:12])
if __name__ == "__main__":
sys.exit(main())