victus-tiny-v0.4 / tokenizer.py
Yo272727's picture
Upload 9 files
fdddde2 verified
Raw History Blame Contribute Delete
1.13 kB
"""Small deterministic word/punctuation tokenizer for the Victus Tiny experiment."""
from __future__ import annotations
import re
_PATTERN = re.compile(r"\n|[^\W_]+(?:['’][^\W_]+)?|\d+(?:\.\d+)?|[^\w\s]", re.UNICODE)
def tokenize(text: str) -> list[str]:
return ["<nl>" if token == "\n" else token.lower() for token in _PATTERN.findall(text)]
def encode(text: str, vocab: dict[str, int]) -> list[int]:
return [vocab.get(token, 0) for token in tokenize(text)]
def decode(tokens: list[str]) -> str:
output = ""
no_space_before = {",", ".", ";", ":", "!", "?", "%", ")", "]", "}", "'s", "'re", "'ve", "n't"}
no_space_after = {"(", "[", "{"}
for token in tokens:
if token == "<nl>":
output = output.rstrip() + "\n"
elif token in no_space_before:
output = output.rstrip() + token
elif output.endswith(tuple(no_space_after)):
output += token
elif token == "#" and output.endswith("#"):
output += token
else:
output += ("" if not output or output.endswith((" ", "\n")) else " ") + token
return output