Download quasar/tokenizers/text.py from AtlasAI-org/Quasar: direct link, hf CLI and curl.
- Browser
- Download file 1.78 kB
-
https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/tokenizers/text.py
- Command line
-
hf download hf://AtlasAI-org/Quasar/quasar/tokenizers/text.py
-
curl -L -o text.py https://huggingface.co/AtlasAI-org/Quasar/resolve/main/quasar/tokenizers/text.py
1.78 kB
| """Byte-level BPE text tokenizer (trained locally with HF `tokenizers`). | |
| Byte-level means every UTF-8 string is encodable (no UNK). The tokenizer has no special | |
| tokens of its own: structural tokens live in the unified vocabulary (multimodal.py), above the | |
| text range, so text ids are exactly [0, vocab_size). | |
| """ | |
| from __future__ import annotations | |
| from pathlib import Path | |
| from typing import Iterable | |
| from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers | |
| class TextTokenizer: | |
| def __init__(self, tok: Tokenizer): | |
| self.tok = tok | |
| def train(cls, texts: Iterable[str], vocab_size: int = 8192) -> "TextTokenizer": | |
| tok = Tokenizer(models.BPE()) | |
| tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) | |
| tok.decoder = decoders.ByteLevel() | |
| trainer = trainers.BpeTrainer(vocab_size=vocab_size, initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), show_progress=False) | |
| tok.train_from_iterator(texts, trainer) | |
| return cls(tok) | |
| def vocab_size(self) -> int: | |
| return self.tok.get_vocab_size() | |
| def encode(self, text: str) -> list[int]: | |
| return self.tok.encode(text).ids | |
| def encode_batch(self, texts: list[str]) -> list[list[int]]: | |
| return [e.ids for e in self.tok.encode_batch(texts)] | |
| def decode(self, ids: Iterable[int]) -> str: | |
| return self.tok.decode([i for i in ids if 0 <= i < self.vocab_size]) | |
| def save(self, path: str | Path) -> None: | |
| Path(path).parent.mkdir(parents=True, exist_ok=True) | |
| self.tok.save(str(path)) | |
| def load(cls, path: str | Path) -> "TextTokenizer": | |
| return cls(Tokenizer.from_file(str(path))) | |