Upload mgpt2 tokenizer
Browse files- README.md +22 -0
- added_tokens.json +3 -0
- evaluation.json +129 -0
- special_tokens_map.json +3 -0
- tokenizer.model +3 -0
- tokenizer.vocab +0 -0
- tokenizer/__init__.py +15 -0
- tokenizer/base.py +158 -0
- tokenizer/basic.py +52 -0
- tokenizer/gpt4.py +105 -0
- tokenizer/hf_tokenizer.py +89 -0
- tokenizer/patterns.py +13 -0
- tokenizer/regex_tokenizer.py +246 -0
- tokenizer_config.json +22 -0
README.md
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ace-1/mgpt2-tokenizer
|
| 2 |
+
|
| 3 |
+
Custom mgpt2 tokenizer (pure-Python) exported for Hugging Face `trust_remote_code=True`.
|
| 4 |
+
|
| 5 |
+
## Usage
|
| 6 |
+
|
| 7 |
+
```python
|
| 8 |
+
from transformers import AutoTokenizer
|
| 9 |
+
|
| 10 |
+
tok = AutoTokenizer.from_pretrained('ace-1/mgpt2-tokenizer', trust_remote_code=True)
|
| 11 |
+
print(tok.encode('hello world'))
|
| 12 |
+
```
|
| 13 |
+
|
| 14 |
+
## Contents
|
| 15 |
+
- Trained tokenizer artifact: `mgpt2_dev.model` (native `.model` format)
|
| 16 |
+
- Python implementation under `tokenizer/` (loaded via `trust_remote_code`)
|
| 17 |
+
|
| 18 |
+
## Evaluation
|
| 19 |
+
|
| 20 |
+
Evaluated on `heldout_eval.txt` with `--limit 10000`.
|
| 21 |
+
See `evaluation.json` for metrics (bytes/token, p95 tokens/line, and bucket breakdown).
|
| 22 |
+
|
added_tokens.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"<|endoftext|>": 7995
|
| 3 |
+
}
|
evaluation.json
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"text": "tokenizer/artifacts/heldout_eval.txt",
|
| 3 |
+
"limit": 10000,
|
| 4 |
+
"overall": [
|
| 5 |
+
{
|
| 6 |
+
"name": "tiktoken_cl100k_base",
|
| 7 |
+
"total_chars": 43290048,
|
| 8 |
+
"total_bytes": 43442607,
|
| 9 |
+
"total_tokens": 11515953,
|
| 10 |
+
"tokens_per_1k_chars": 266.0184853571888,
|
| 11 |
+
"tokens_per_1k_bytes": 265.0842984630273,
|
| 12 |
+
"bytes_per_token": 3.772384882084878,
|
| 13 |
+
"chars_per_token": 3.759137259417436,
|
| 14 |
+
"p50_tokens_per_line": 604,
|
| 15 |
+
"p95_tokens_per_line": 3719,
|
| 16 |
+
"p95_tokens_per_1k_bytes_per_line": 394.09722222222223
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"name": "mgpt2_GPT4Tokenizer_reference",
|
| 20 |
+
"total_chars": 43290048,
|
| 21 |
+
"total_bytes": 43442607,
|
| 22 |
+
"total_tokens": 11515953,
|
| 23 |
+
"tokens_per_1k_chars": 266.0184853571888,
|
| 24 |
+
"tokens_per_1k_bytes": 265.0842984630273,
|
| 25 |
+
"bytes_per_token": 3.772384882084878,
|
| 26 |
+
"chars_per_token": 3.759137259417436,
|
| 27 |
+
"p50_tokens_per_line": 604,
|
| 28 |
+
"p95_tokens_per_line": 3719,
|
| 29 |
+
"p95_tokens_per_1k_bytes_per_line": 394.09722222222223
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"name": "mgpt2_RegexTokenizer_candidate (tokenizer/artifacts/mgpt2_dev.model)",
|
| 33 |
+
"total_chars": 43290048,
|
| 34 |
+
"total_bytes": 43442607,
|
| 35 |
+
"total_tokens": 11749984,
|
| 36 |
+
"tokens_per_1k_chars": 271.4246008690034,
|
| 37 |
+
"tokens_per_1k_bytes": 270.47142912026436,
|
| 38 |
+
"bytes_per_token": 3.697248183486888,
|
| 39 |
+
"chars_per_token": 3.68426442112602,
|
| 40 |
+
"p50_tokens_per_line": 658,
|
| 41 |
+
"p95_tokens_per_line": 3543,
|
| 42 |
+
"p95_tokens_per_1k_bytes_per_line": 334.74443399184696
|
| 43 |
+
}
|
| 44 |
+
],
|
| 45 |
+
"by_bucket": {
|
| 46 |
+
"latin": [
|
| 47 |
+
{
|
| 48 |
+
"name": "tiktoken_cl100k_base",
|
| 49 |
+
"total_chars": 42393232,
|
| 50 |
+
"total_bytes": 42542626,
|
| 51 |
+
"total_tokens": 11183977,
|
| 52 |
+
"tokens_per_1k_chars": 263.81515332447407,
|
| 53 |
+
"tokens_per_1k_bytes": 262.88873188034984,
|
| 54 |
+
"bytes_per_token": 3.8038906911199835,
|
| 55 |
+
"chars_per_token": 3.790532831031394,
|
| 56 |
+
"p50_tokens_per_line": 601,
|
| 57 |
+
"p95_tokens_per_line": 3613,
|
| 58 |
+
"p95_tokens_per_1k_bytes_per_line": 394.2307692307692
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"name": "mgpt2_GPT4Tokenizer_reference",
|
| 62 |
+
"total_chars": 42393232,
|
| 63 |
+
"total_bytes": 42542626,
|
| 64 |
+
"total_tokens": 11183977,
|
| 65 |
+
"tokens_per_1k_chars": 263.81515332447407,
|
| 66 |
+
"tokens_per_1k_bytes": 262.88873188034984,
|
| 67 |
+
"bytes_per_token": 3.8038906911199835,
|
| 68 |
+
"chars_per_token": 3.790532831031394,
|
| 69 |
+
"p50_tokens_per_line": 601,
|
| 70 |
+
"p95_tokens_per_line": 3613,
|
| 71 |
+
"p95_tokens_per_1k_bytes_per_line": 394.2307692307692
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"name": "mgpt2_RegexTokenizer_candidate (tokenizer/artifacts/mgpt2_dev.model)",
|
| 75 |
+
"total_chars": 42393232,
|
| 76 |
+
"total_bytes": 42542626,
|
| 77 |
+
"total_tokens": 11499062,
|
| 78 |
+
"tokens_per_1k_chars": 271.2475897096027,
|
| 79 |
+
"tokens_per_1k_bytes": 270.2950682922112,
|
| 80 |
+
"bytes_per_token": 3.6996605462254224,
|
| 81 |
+
"chars_per_token": 3.686668703934286,
|
| 82 |
+
"p50_tokens_per_line": 654,
|
| 83 |
+
"p95_tokens_per_line": 3472,
|
| 84 |
+
"p95_tokens_per_1k_bytes_per_line": 334.74443399184696
|
| 85 |
+
}
|
| 86 |
+
],
|
| 87 |
+
"mixed": [
|
| 88 |
+
{
|
| 89 |
+
"name": "tiktoken_cl100k_base",
|
| 90 |
+
"total_chars": 896816,
|
| 91 |
+
"total_bytes": 899981,
|
| 92 |
+
"total_tokens": 331976,
|
| 93 |
+
"tokens_per_1k_chars": 370.17180781788016,
|
| 94 |
+
"tokens_per_1k_bytes": 368.8700094779779,
|
| 95 |
+
"bytes_per_token": 2.710982119189339,
|
| 96 |
+
"chars_per_token": 2.701448297467287,
|
| 97 |
+
"p50_tokens_per_line": 1688,
|
| 98 |
+
"p95_tokens_per_line": 13746,
|
| 99 |
+
"p95_tokens_per_1k_bytes_per_line": 390.70425858204555
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"name": "mgpt2_GPT4Tokenizer_reference",
|
| 103 |
+
"total_chars": 896816,
|
| 104 |
+
"total_bytes": 899981,
|
| 105 |
+
"total_tokens": 331976,
|
| 106 |
+
"tokens_per_1k_chars": 370.17180781788016,
|
| 107 |
+
"tokens_per_1k_bytes": 368.8700094779779,
|
| 108 |
+
"bytes_per_token": 2.710982119189339,
|
| 109 |
+
"chars_per_token": 2.701448297467287,
|
| 110 |
+
"p50_tokens_per_line": 1688,
|
| 111 |
+
"p95_tokens_per_line": 13746,
|
| 112 |
+
"p95_tokens_per_1k_bytes_per_line": 390.70425858204555
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"name": "mgpt2_RegexTokenizer_candidate (tokenizer/artifacts/mgpt2_dev.model)",
|
| 116 |
+
"total_chars": 896816,
|
| 117 |
+
"total_bytes": 899981,
|
| 118 |
+
"total_tokens": 250922,
|
| 119 |
+
"tokens_per_1k_chars": 279.7920643699488,
|
| 120 |
+
"tokens_per_1k_bytes": 278.8081081711725,
|
| 121 |
+
"bytes_per_token": 3.5866962641777125,
|
| 122 |
+
"chars_per_token": 3.574082782697412,
|
| 123 |
+
"p50_tokens_per_line": 1316,
|
| 124 |
+
"p95_tokens_per_line": 9925,
|
| 125 |
+
"p95_tokens_per_1k_bytes_per_line": 333.2627791300667
|
| 126 |
+
}
|
| 127 |
+
]
|
| 128 |
+
}
|
| 129 |
+
}
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"eos_token": "<|endoftext|>"
|
| 3 |
+
}
|
tokenizer.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:31d08b39fa5466b3913866a8dc1a26fa2f86578b814bab25ac978641609a6a40
|
| 3 |
+
size 65352
|
tokenizer.vocab
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .base import Tokenizer
|
| 2 |
+
from .basic import BasicTokenizer
|
| 3 |
+
from .regex_tokenizer import RegexTokenizer
|
| 4 |
+
from .gpt4 import GPT4Tokenizer
|
| 5 |
+
from .patterns import GPT4_SPLIT_PATTERN, INDIC_SPLIT_PATTERN
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"Tokenizer",
|
| 9 |
+
"BasicTokenizer",
|
| 10 |
+
"RegexTokenizer",
|
| 11 |
+
"GPT4Tokenizer",
|
| 12 |
+
"GPT4_SPLIT_PATTERN",
|
| 13 |
+
"INDIC_SPLIT_PATTERN",
|
| 14 |
+
]
|
| 15 |
+
|
tokenizer/base.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A minimal implementation of Byte-Pair Encoding (BPE) tokenization.
|
| 3 |
+
|
| 4 |
+
BPE is a subword tokenization algorithm that iteratively merges the most frequent pairs of bytes or characters
|
| 5 |
+
to build a vocabulary of subword tokens. This implementation is inspired by Andrej Karpathy's minbpe
|
| 6 |
+
(https://github.com/karpathy/minbpe).
|
| 7 |
+
"""
|
| 8 |
+
import unicodedata
|
| 9 |
+
|
| 10 |
+
def get_stats(ids, freq):
|
| 11 |
+
for pair in zip(ids[:-1], ids[1:]):
|
| 12 |
+
freq[pair] = freq.get(pair, 0) + 1
|
| 13 |
+
|
| 14 |
+
def merge(ids, pair, idx):
|
| 15 |
+
newids = []
|
| 16 |
+
i = 0
|
| 17 |
+
while i < len(ids):
|
| 18 |
+
if i < len(ids) - 1 and ids[i] == pair[0] and ids[i+1] == pair[1]:
|
| 19 |
+
newids.append(idx)
|
| 20 |
+
i += 2
|
| 21 |
+
else:
|
| 22 |
+
newids.append(ids[i])
|
| 23 |
+
i += 1
|
| 24 |
+
return newids
|
| 25 |
+
|
| 26 |
+
def visualise_tokens(token_values: list[bytes]) -> None:
|
| 27 |
+
background = [f"\u001b[48;5;{i}m" for i in [167, 179, 185, 77, 80, 68, 134]]
|
| 28 |
+
# If token boundaries do not occur at unicode character boundaries, it's unclear how best to
|
| 29 |
+
# visualise the token. Here, we'll just use the unicode replacement character to represent some
|
| 30 |
+
# fraction of a character.
|
| 31 |
+
unicode_token_values = [x.decode("utf-8", errors="replace") for x in token_values]
|
| 32 |
+
|
| 33 |
+
running_length = 0
|
| 34 |
+
last_color = None
|
| 35 |
+
for token in unicode_token_values:
|
| 36 |
+
color = background[running_length % len(background)]
|
| 37 |
+
if color == last_color:
|
| 38 |
+
color = background[(running_length + 1) % len(background)]
|
| 39 |
+
assert color != last_color
|
| 40 |
+
last_color = color
|
| 41 |
+
running_length += len(token)
|
| 42 |
+
print(color + token, end="")
|
| 43 |
+
print("\u001b[0m")
|
| 44 |
+
|
| 45 |
+
# first two helper functions...
|
| 46 |
+
def replace_control_characters(s: str) -> str:
|
| 47 |
+
# we don't want to print control characters
|
| 48 |
+
# which distort the output (e.g. \n or much worse)
|
| 49 |
+
# https://stackoverflow.com/questions/4324790/removing-control-characters-from-a-string-in-python/19016117#19016117
|
| 50 |
+
# http://www.unicode.org/reports/tr44/#GC_Values_Table
|
| 51 |
+
chars = []
|
| 52 |
+
for ch in s:
|
| 53 |
+
if unicodedata.category(ch)[0] != "C":
|
| 54 |
+
chars.append(ch) # this character is ok
|
| 55 |
+
else:
|
| 56 |
+
chars.append(f"\\u{ord(ch):04x}") # escape
|
| 57 |
+
return "".join(chars)
|
| 58 |
+
|
| 59 |
+
def render_token(t: bytes) -> str:
|
| 60 |
+
# pretty print a token, escaping control characters
|
| 61 |
+
s = t.decode('utf-8', errors='replace')
|
| 62 |
+
s = replace_control_characters(s)
|
| 63 |
+
return s
|
| 64 |
+
|
| 65 |
+
#--------------------------------------------------------------------------------------------------
|
| 66 |
+
class Tokenizer:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self.merges = {} # (int, int) -> int
|
| 69 |
+
self.pattern = "" # str
|
| 70 |
+
self.special_tokens = {} # str -> int e.g {'<|endoftext|>': 100257}
|
| 71 |
+
self.inverse_special_tokens = {} # int -> str
|
| 72 |
+
self.vocab = self._build_vocab() # int -> bytes
|
| 73 |
+
|
| 74 |
+
def _build_vocab(self):
|
| 75 |
+
vocab = {idx: bytes([idx]) for idx in range(256)}
|
| 76 |
+
for (p0, p1), idx in self.merges.items():
|
| 77 |
+
vocab[idx] = vocab[p0] + vocab[p1]
|
| 78 |
+
return vocab
|
| 79 |
+
|
| 80 |
+
def train(self, text, vocab_size, verbose=False):
|
| 81 |
+
raise NotImplementedError
|
| 82 |
+
|
| 83 |
+
def decode(self, ids) -> str:
|
| 84 |
+
raise NotImplementedError
|
| 85 |
+
|
| 86 |
+
def encode(self, text, verbose=False) -> list[int]:
|
| 87 |
+
raise NotImplementedError
|
| 88 |
+
|
| 89 |
+
def save(self, file_prefix):
|
| 90 |
+
"""
|
| 91 |
+
Saves two files: file_prefix.vocab and file_prefix.model
|
| 92 |
+
This is inspired (but not equivalent to!) sentencepiece's model saving:
|
| 93 |
+
- model file is the critical one, intended for load()
|
| 94 |
+
- vocab file is just a pretty printed version for human inspection only
|
| 95 |
+
"""
|
| 96 |
+
# write the model: to be used in load() later
|
| 97 |
+
model_file = file_prefix + ".model"
|
| 98 |
+
with open(model_file, 'w') as f:
|
| 99 |
+
# write the version, pattern and merges, that's all that's needed
|
| 100 |
+
f.write("minbpe v1\n")
|
| 101 |
+
f.write(f"{self.pattern}\n")
|
| 102 |
+
# write the special tokens, first the number of them, then each one
|
| 103 |
+
f.write(f"{len(self.special_tokens)}\n")
|
| 104 |
+
for special, idx in self.special_tokens.items():
|
| 105 |
+
f.write(f"{special} {idx}\n")
|
| 106 |
+
# the merges dict
|
| 107 |
+
for idx1, idx2 in self.merges:
|
| 108 |
+
f.write(f"{idx1} {idx2}\n")
|
| 109 |
+
# write the vocab: for the human to look at
|
| 110 |
+
vocab_file = file_prefix + ".vocab"
|
| 111 |
+
inverted_merges = {idx: pair for pair, idx in self.merges.items()}
|
| 112 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
| 113 |
+
for idx, token in self.vocab.items():
|
| 114 |
+
# note: many tokens may be partial utf-8 sequences
|
| 115 |
+
# and cannot be decoded into valid strings. Here we're using
|
| 116 |
+
# errors='replace' to replace them with the replacement char �.
|
| 117 |
+
# this also means that we couldn't possibly use .vocab in load()
|
| 118 |
+
# because decoding in this way is a lossy operation!
|
| 119 |
+
s = render_token(token)
|
| 120 |
+
# find the children of this token, if any
|
| 121 |
+
if idx in inverted_merges:
|
| 122 |
+
# if this token has children, render it nicely as a merge
|
| 123 |
+
idx0, idx1 = inverted_merges[idx]
|
| 124 |
+
s0 = render_token(self.vocab[idx0])
|
| 125 |
+
s1 = render_token(self.vocab[idx1])
|
| 126 |
+
f.write(f"[{s0}][{s1}] -> [{s}] {idx}\n")
|
| 127 |
+
else:
|
| 128 |
+
# otherwise this is leaf token, just print it
|
| 129 |
+
# (this should just be the first 256 tokens, the bytes)
|
| 130 |
+
f.write(f"[{s}] {idx}\n")
|
| 131 |
+
|
| 132 |
+
def load(self, model_file):
|
| 133 |
+
"""Inverse of save() but only for the model file"""
|
| 134 |
+
assert model_file.endswith(".model")
|
| 135 |
+
# read the model file
|
| 136 |
+
merges = {}
|
| 137 |
+
special_tokens = {}
|
| 138 |
+
idx = 256
|
| 139 |
+
with open(model_file, 'r', encoding="utf-8") as f:
|
| 140 |
+
# read the version
|
| 141 |
+
version = f.readline().strip()
|
| 142 |
+
assert version == "minbpe v1"
|
| 143 |
+
# read the pattern
|
| 144 |
+
self.pattern = f.readline().strip()
|
| 145 |
+
# read the special tokens
|
| 146 |
+
num_special = int(f.readline().strip())
|
| 147 |
+
for _ in range(num_special):
|
| 148 |
+
special, special_idx = f.readline().strip().split()
|
| 149 |
+
special_tokens[special] = int(special_idx)
|
| 150 |
+
# read the merges
|
| 151 |
+
for line in f:
|
| 152 |
+
idx1, idx2 = map(int, line.split())
|
| 153 |
+
merges[(idx1, idx2)] = idx
|
| 154 |
+
idx += 1
|
| 155 |
+
self.merges = merges
|
| 156 |
+
self.special_tokens = special_tokens
|
| 157 |
+
self.inverse_special_tokens = {v: k for k, v in special_tokens.items()}
|
| 158 |
+
self.vocab = self._build_vocab()
|
tokenizer/basic.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
from .base import Tokenizer, get_stats, merge, visualise_tokens
|
| 3 |
+
except ImportError: # allow running as a script from inside `tokenizer/`
|
| 4 |
+
from base import Tokenizer, get_stats, merge, visualise_tokens
|
| 5 |
+
|
| 6 |
+
class BasicTokenizer(Tokenizer):
|
| 7 |
+
def __init__(self):
|
| 8 |
+
super().__init__()
|
| 9 |
+
|
| 10 |
+
def train(self, text, vocab_size, verbose=False):
|
| 11 |
+
# 'ids' is a list of integers, each representing a byte from the UTF-8 encoded string
|
| 12 |
+
ids = list(text.encode("utf-8")) # list[int]
|
| 13 |
+
if verbose:
|
| 14 |
+
print(f"len(text) = {len(text)}")
|
| 15 |
+
print(f"len(tokens) = {len(ids)}")
|
| 16 |
+
|
| 17 |
+
num_merges = vocab_size - 256
|
| 18 |
+
|
| 19 |
+
merges = {}
|
| 20 |
+
vocab = {idx: bytes([idx]) for idx in range(256)}
|
| 21 |
+
for i in range(num_merges):
|
| 22 |
+
stats = {}
|
| 23 |
+
get_stats(ids, stats)
|
| 24 |
+
pair = max(stats, key=stats.get) # (int, int)
|
| 25 |
+
idx = 256 + i
|
| 26 |
+
ids = merge(ids, pair, idx)
|
| 27 |
+
merges[pair] = idx
|
| 28 |
+
vocab[idx] = vocab[pair[0]] + vocab[pair[1]]
|
| 29 |
+
if verbose and i % 100 == 0:
|
| 30 |
+
print(f"merge {i+1}/{num_merges}: {pair} -> {idx} ({vocab[idx]}) had {stats[pair]} occurrences")
|
| 31 |
+
|
| 32 |
+
self.vocab = vocab
|
| 33 |
+
self.merges = merges
|
| 34 |
+
|
| 35 |
+
def decode(self, ids) -> str:
|
| 36 |
+
text = b"".join([self.vocab[id] for id in ids])
|
| 37 |
+
text = text.decode(encoding="utf-8", errors="replace")
|
| 38 |
+
return text
|
| 39 |
+
|
| 40 |
+
def encode(self, text, verbose=False) -> list[int]:
|
| 41 |
+
tokens = list(text.encode("utf-8"))
|
| 42 |
+
while len(tokens) >= 2:
|
| 43 |
+
if verbose:
|
| 44 |
+
visualise_tokens([self.vocab[token] for token in tokens])
|
| 45 |
+
stats = {}
|
| 46 |
+
get_stats(tokens, stats)
|
| 47 |
+
pair = min(stats, key=lambda p: self.merges.get(p, float("inf")))
|
| 48 |
+
if not pair in self.merges:
|
| 49 |
+
break
|
| 50 |
+
idx = self.merges[pair]
|
| 51 |
+
tokens = merge(tokens, pair, idx)
|
| 52 |
+
return tokens
|
tokenizer/gpt4.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
from .regex_tokenizer import RegexTokenizer
|
| 3 |
+
from .base import visualise_tokens, get_stats, merge
|
| 4 |
+
from .patterns import GPT4_SPLIT_PATTERN
|
| 5 |
+
except ImportError: # allow running as a script from inside `tokenizer/`
|
| 6 |
+
from regex_tokenizer import RegexTokenizer
|
| 7 |
+
from base import visualise_tokens, get_stats, merge
|
| 8 |
+
from patterns import GPT4_SPLIT_PATTERN
|
| 9 |
+
from typing import Optional
|
| 10 |
+
import regex as re
|
| 11 |
+
import tiktoken
|
| 12 |
+
GPT4_SPECIAL_TOKENS = {
|
| 13 |
+
'<|endoftext|>': 100257,
|
| 14 |
+
'<|fim_prefix|>': 100258,
|
| 15 |
+
'<|fim_middle|>': 100259,
|
| 16 |
+
'<|fim_suffix|>': 100260,
|
| 17 |
+
'<|endofprompt|>': 100276
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
def bpe(mergeable_ranks: dict[bytes, int], token: bytes, max_rank: Optional[int] = None) -> list[bytes]:
|
| 21 |
+
parts = [bytes([b]) for b in token]
|
| 22 |
+
while True:
|
| 23 |
+
min_idx = None
|
| 24 |
+
min_rank = None
|
| 25 |
+
for i, pair in enumerate(zip(parts[:-1], parts[1:])):
|
| 26 |
+
rank = mergeable_ranks.get(pair[0] + pair[1])
|
| 27 |
+
if rank is not None and (min_rank is None or rank < min_rank):
|
| 28 |
+
min_idx = i
|
| 29 |
+
min_rank = rank
|
| 30 |
+
if min_rank is None or (max_rank is not None and min_rank >= max_rank):
|
| 31 |
+
break
|
| 32 |
+
assert min_idx is not None
|
| 33 |
+
parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2:]
|
| 34 |
+
return parts
|
| 35 |
+
|
| 36 |
+
def recover_merges(mergeable_ranks: dict[bytes, int]) -> dict[bytes, tuple[bytes, bytes]]:
|
| 37 |
+
merges = {}
|
| 38 |
+
for token, rank in mergeable_ranks.items():
|
| 39 |
+
if len(token) == 1:
|
| 40 |
+
continue
|
| 41 |
+
pair = tuple(bpe(mergeable_ranks, token, max_rank=rank))
|
| 42 |
+
assert len(pair) == 2
|
| 43 |
+
ix0 = mergeable_ranks[pair[0]]
|
| 44 |
+
ix1 = mergeable_ranks[pair[1]]
|
| 45 |
+
merges[(ix0, ix1)] = rank
|
| 46 |
+
return merges
|
| 47 |
+
|
| 48 |
+
class GPT4Tokenizer(RegexTokenizer):
|
| 49 |
+
def __init__(self):
|
| 50 |
+
super().__init__(GPT4_SPLIT_PATTERN)
|
| 51 |
+
enc = tiktoken.get_encoding("cl100k_base")
|
| 52 |
+
mergeable_ranks = enc._mergeable_ranks
|
| 53 |
+
self.merges = recover_merges(mergeable_ranks)
|
| 54 |
+
vocab = {idx: bytes([idx]) for idx in range(256)}
|
| 55 |
+
for pair, idx in self.merges.items():
|
| 56 |
+
vocab[idx] = vocab[pair[0]] + vocab[pair[1]]
|
| 57 |
+
self.vocab = vocab
|
| 58 |
+
# for some reason, the tokens corresponding to individual bytes
|
| 59 |
+
# are permuted in a different order. This is completely non-sensical
|
| 60 |
+
# and probably historical, but therefore we have to deal with it here
|
| 61 |
+
self.byte_shuffle = {idx: mergeable_ranks[bytes([idx])] for idx in range(256)}
|
| 62 |
+
self.inverse_byte_shuffle = {v: k for k, v in self.byte_shuffle.items()}
|
| 63 |
+
self.register_special_tokens(GPT4_SPECIAL_TOKENS)
|
| 64 |
+
|
| 65 |
+
def train(self, text: str, vocab_size: int = 50_257, verbose: bool = False):
|
| 66 |
+
raise NotImplementedError
|
| 67 |
+
|
| 68 |
+
def _encode_chunk(self, chunk_bytes: bytes, verbose: bool = False) -> list[int]:
|
| 69 |
+
chunk_bytes = bytes(self.byte_shuffle[b] for b in chunk_bytes)
|
| 70 |
+
ids = list(chunk_bytes)
|
| 71 |
+
while len(ids) >= 2:
|
| 72 |
+
if verbose:
|
| 73 |
+
decodable_ids = [] # each id can be multiple bytes i.e. any utf-8 character
|
| 74 |
+
for id in ids:
|
| 75 |
+
char = self.vocab[id] # id can be > 256 after merging
|
| 76 |
+
decodable_ids.append(bytes(self.inverse_byte_shuffle[b] for b in char))
|
| 77 |
+
visualise_tokens(decodable_ids)
|
| 78 |
+
stats = {}
|
| 79 |
+
get_stats(ids, stats)
|
| 80 |
+
pair = min(stats, key=lambda p: self.merges.get(p, float("inf")))
|
| 81 |
+
if not pair in self.merges:
|
| 82 |
+
break
|
| 83 |
+
idx = self.merges[pair]
|
| 84 |
+
ids = merge(ids, pair, idx)
|
| 85 |
+
return ids
|
| 86 |
+
|
| 87 |
+
def decode(self, ids) -> str:
|
| 88 |
+
part_bytes = []
|
| 89 |
+
for id in ids:
|
| 90 |
+
if id in self.vocab:
|
| 91 |
+
char = self.vocab[id] # id can be > 256 after merging
|
| 92 |
+
part_bytes.extend(self.inverse_byte_shuffle[b] for b in char)
|
| 93 |
+
elif id in self.inverse_special_tokens:
|
| 94 |
+
part_bytes.extend(self.inverse_special_tokens[id].encode("utf-8"))
|
| 95 |
+
else:
|
| 96 |
+
raise ValueError(f"id={id} not in vocab or special_tokens")
|
| 97 |
+
text_bytes = bytes(part_bytes)
|
| 98 |
+
text = text_bytes.decode(encoding="utf-8", errors="replace")
|
| 99 |
+
return text
|
| 100 |
+
|
| 101 |
+
def save(self, path: str):
|
| 102 |
+
raise NotImplementedError("GPT4Tokenizer not meant to be saved")
|
| 103 |
+
|
| 104 |
+
def load(self, path: str):
|
| 105 |
+
raise NotImplementedError("GPT4Tokenizer not meant to be loaded")
|
tokenizer/hf_tokenizer.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from typing import Any, Optional
|
| 5 |
+
|
| 6 |
+
from transformers import PreTrainedTokenizer
|
| 7 |
+
|
| 8 |
+
from tokenizer.regex_tokenizer import RegexTokenizer
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class MGPT2Tokenizer(PreTrainedTokenizer):
|
| 12 |
+
"""
|
| 13 |
+
Hugging Face-compatible (slow) tokenizer wrapper around `RegexTokenizer`.
|
| 14 |
+
|
| 15 |
+
This is intended for publishing alongside the model using `trust_remote_code=True`.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
model_input_names = ["input_ids", "attention_mask"]
|
| 19 |
+
|
| 20 |
+
def __init__(self, model_file: str, **kwargs: Any):
|
| 21 |
+
if not model_file.endswith(".model"):
|
| 22 |
+
raise ValueError(f"model_file must end with .model, got: {model_file}")
|
| 23 |
+
|
| 24 |
+
self._tok = RegexTokenizer()
|
| 25 |
+
self._tok.load(model_file)
|
| 26 |
+
|
| 27 |
+
# Bind common special tokens if present in the trained tokenizer.
|
| 28 |
+
special = self._tok.special_tokens
|
| 29 |
+
kwargs.setdefault("eos_token", "<|endoftext|>" if "<|endoftext|>" in special else None)
|
| 30 |
+
kwargs.setdefault("unk_token", None)
|
| 31 |
+
kwargs.setdefault("pad_token", None)
|
| 32 |
+
kwargs.setdefault("bos_token", None)
|
| 33 |
+
|
| 34 |
+
super().__init__(**kwargs)
|
| 35 |
+
|
| 36 |
+
self.model_file = model_file
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def vocab_size(self) -> int:
|
| 40 |
+
# vocab is sparse only if merges are incomplete; generally size is max_id+1
|
| 41 |
+
return max(self._tok.vocab.keys()) + 1
|
| 42 |
+
|
| 43 |
+
def get_vocab(self) -> dict[str, int]:
|
| 44 |
+
# Provide a stable token-string mapping for HF internals.
|
| 45 |
+
inv_special = self._tok.inverse_special_tokens
|
| 46 |
+
vocab: dict[str, int] = {}
|
| 47 |
+
for i in range(self.vocab_size):
|
| 48 |
+
if i in inv_special:
|
| 49 |
+
vocab[inv_special[i]] = i
|
| 50 |
+
else:
|
| 51 |
+
vocab[f"<|bytebpe_{i}|>"] = i
|
| 52 |
+
return vocab
|
| 53 |
+
|
| 54 |
+
def _tokenize(self, text: str, **kwargs: Any) -> list[str]:
|
| 55 |
+
ids = self._tok.encode(text, allowed_special="all")
|
| 56 |
+
inv_special = self._tok.inverse_special_tokens
|
| 57 |
+
out: list[str] = []
|
| 58 |
+
for i in ids:
|
| 59 |
+
out.append(inv_special.get(i, f"<|bytebpe_{i}|>"))
|
| 60 |
+
return out
|
| 61 |
+
|
| 62 |
+
def _convert_token_to_id(self, token: str) -> int:
|
| 63 |
+
if token in self._tok.special_tokens:
|
| 64 |
+
return self._tok.special_tokens[token]
|
| 65 |
+
if token.startswith("<|bytebpe_") and token.endswith("|>"):
|
| 66 |
+
inner = token[len("<|bytebpe_") : -len("|>")]
|
| 67 |
+
return int(inner)
|
| 68 |
+
raise KeyError(f"Unknown token string: {token!r}")
|
| 69 |
+
|
| 70 |
+
def _convert_id_to_token(self, index: int) -> str:
|
| 71 |
+
return self._tok.inverse_special_tokens.get(index, f"<|bytebpe_{index}|>")
|
| 72 |
+
|
| 73 |
+
def convert_tokens_to_string(self, tokens: list[str]) -> str:
|
| 74 |
+
ids = [self._convert_token_to_id(t) for t in tokens]
|
| 75 |
+
return self._tok.decode(ids)
|
| 76 |
+
|
| 77 |
+
def build_inputs_with_special_tokens(self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None) -> list[int]:
|
| 78 |
+
if token_ids_1 is not None:
|
| 79 |
+
raise ValueError("This tokenizer does not support pair inputs.")
|
| 80 |
+
return token_ids_0
|
| 81 |
+
|
| 82 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
|
| 83 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 84 |
+
prefix = filename_prefix or "tokenizer"
|
| 85 |
+
out_prefix = os.path.join(save_directory, prefix)
|
| 86 |
+
# Save in the native `.model`/`.vocab` format (human + machine readable for this repo).
|
| 87 |
+
self._tok.save(out_prefix)
|
| 88 |
+
return (out_prefix + ".model",)
|
| 89 |
+
|
tokenizer/patterns.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Regex patterns used by tokenizers in this package.
|
| 3 |
+
|
| 4 |
+
Keep patterns centralized so experiments + training scripts + notebooks
|
| 5 |
+
stay in sync.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
# Default GPT-4-ish split pattern (as used in `RegexTokenizer` and `GPT4Tokenizer`)
|
| 9 |
+
GPT4_SPLIT_PATTERN = r"""'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]++[\r\n]*|\s*[\r\n]|\s+(?!\S)|\s+"""
|
| 10 |
+
|
| 11 |
+
# Indic-focused experimental pattern (Hindi Devanagari + Kannada ranges and punctuation)
|
| 12 |
+
INDIC_SPLIT_PATTERN = r"""(?i) 's|'t|'re|'ve|'m|'ll|'d| ?\b[\p{L}\u0900-\u0963|\u0966-\u097F]+\b| ?\b[\p{L}\u0C80-\u0C9E|\u0CA0-\u0CFF]+\b| ?[\p{N}]+| ?[.,!?;:'\"-]| ?[\u0964-\u0965]| ?[\u0C9E-\u0C9F]| ?[^\s\p{L}\p{N}\u0900-\u097F\u0C80-\u0CFF]+| \s+(?!\S)| \s+"""
|
| 13 |
+
|
tokenizer/regex_tokenizer.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
from .base import get_stats, merge, visualise_tokens
|
| 3 |
+
from .basic import BasicTokenizer
|
| 4 |
+
from .patterns import GPT4_SPLIT_PATTERN
|
| 5 |
+
except ImportError: # allow running as a script from inside `tokenizer/`
|
| 6 |
+
from base import get_stats, merge, visualise_tokens
|
| 7 |
+
from basic import BasicTokenizer
|
| 8 |
+
from patterns import GPT4_SPLIT_PATTERN
|
| 9 |
+
from collections import Counter, defaultdict
|
| 10 |
+
import heapq
|
| 11 |
+
import regex as re
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
import time
|
| 14 |
+
|
| 15 |
+
class RegexTokenizer(BasicTokenizer):
|
| 16 |
+
def __init__(self, regex: str = GPT4_SPLIT_PATTERN):
|
| 17 |
+
super().__init__()
|
| 18 |
+
self.pattern = regex
|
| 19 |
+
self.regex = re.compile(self.pattern)
|
| 20 |
+
|
| 21 |
+
def register_special_tokens(self, special_tokens: dict[str, int]):
|
| 22 |
+
self.special_tokens = special_tokens
|
| 23 |
+
self.inverse_special_tokens = {v: k for k, v in special_tokens.items()}
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def _merge_word(word: tuple[int, ...], pair: tuple[int, int], new_id: int) -> tuple[int, ...]:
|
| 27 |
+
"""Merge all non-overlapping occurrences of `pair` in `word`."""
|
| 28 |
+
out: list[int] = []
|
| 29 |
+
i = 0
|
| 30 |
+
while i < len(word):
|
| 31 |
+
if i < len(word) - 1 and word[i] == pair[0] and word[i + 1] == pair[1]:
|
| 32 |
+
out.append(new_id)
|
| 33 |
+
i += 2
|
| 34 |
+
else:
|
| 35 |
+
out.append(word[i])
|
| 36 |
+
i += 1
|
| 37 |
+
return tuple(out)
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _pair_occurrences(word: tuple[int, ...]) -> dict[tuple[int, int], int]:
|
| 41 |
+
"""Return unweighted pair -> count for a single word/chunk."""
|
| 42 |
+
if len(word) < 2:
|
| 43 |
+
return {}
|
| 44 |
+
counts: dict[tuple[int, int], int] = {}
|
| 45 |
+
a = word[0]
|
| 46 |
+
for b in word[1:]:
|
| 47 |
+
p = (a, b)
|
| 48 |
+
counts[p] = counts.get(p, 0) + 1
|
| 49 |
+
a = b
|
| 50 |
+
return counts
|
| 51 |
+
|
| 52 |
+
def train(
|
| 53 |
+
self,
|
| 54 |
+
text: str,
|
| 55 |
+
vocab_size: int = 50_257,
|
| 56 |
+
verbose: bool = False,
|
| 57 |
+
*,
|
| 58 |
+
min_chunk_freq: int = 1,
|
| 59 |
+
max_chunks: int | None = None,
|
| 60 |
+
):
|
| 61 |
+
assert vocab_size >= 256, "Vocab size must be at least 256"
|
| 62 |
+
num_merges = vocab_size - 256
|
| 63 |
+
|
| 64 |
+
# Count chunk frequencies without storing a giant list of chunks.
|
| 65 |
+
# Each unique chunk becomes a "word" in classic BPE training.
|
| 66 |
+
chunk_counts: Counter[bytes] = Counter()
|
| 67 |
+
for m in self.regex.finditer(text):
|
| 68 |
+
s = m.group(0)
|
| 69 |
+
if s:
|
| 70 |
+
chunk_counts[s.encode("utf-8")] += 1
|
| 71 |
+
|
| 72 |
+
# Heuristic speed knobs: ignore rare chunks and/or cap unique chunk types.
|
| 73 |
+
# This massively reduces training state on web-scale corpora and keeps code simple.
|
| 74 |
+
if min_chunk_freq > 1:
|
| 75 |
+
chunk_counts = Counter({b: f for b, f in chunk_counts.items() if f >= min_chunk_freq})
|
| 76 |
+
if max_chunks is not None and len(chunk_counts) > max_chunks:
|
| 77 |
+
chunk_counts = Counter(dict(chunk_counts.most_common(max_chunks)))
|
| 78 |
+
|
| 79 |
+
# words: tuple(symbol_ids) -> frequency
|
| 80 |
+
words: dict[tuple[int, ...], int] = {}
|
| 81 |
+
for b, freq in chunk_counts.items():
|
| 82 |
+
words[tuple(b)] = freq
|
| 83 |
+
|
| 84 |
+
# Global pair stats and a reverse index pair -> set(words containing it)
|
| 85 |
+
pair_counts: dict[tuple[int, int], int] = defaultdict(int)
|
| 86 |
+
pair_to_words: dict[tuple[int, int], set[tuple[int, ...]]] = defaultdict(set)
|
| 87 |
+
for w, freq in words.items():
|
| 88 |
+
local = self._pair_occurrences(w)
|
| 89 |
+
for p, occ in local.items():
|
| 90 |
+
pair_counts[p] += freq * occ
|
| 91 |
+
pair_to_words[p].add(w)
|
| 92 |
+
|
| 93 |
+
# Max-heap for fast "most frequent pair" selection (lazy updates).
|
| 94 |
+
heap: list[tuple[int, tuple[int, int]]] = [(-c, p) for p, c in pair_counts.items()]
|
| 95 |
+
heapq.heapify(heap)
|
| 96 |
+
|
| 97 |
+
merges = {}
|
| 98 |
+
vocab = {idx: bytes([idx]) for idx in range(256)}
|
| 99 |
+
|
| 100 |
+
def bump_pair(p: tuple[int, int], delta: int) -> None:
|
| 101 |
+
if delta == 0:
|
| 102 |
+
return
|
| 103 |
+
new = pair_counts.get(p, 0) + delta
|
| 104 |
+
if new <= 0:
|
| 105 |
+
pair_counts.pop(p, None)
|
| 106 |
+
pair_to_words.pop(p, None)
|
| 107 |
+
return
|
| 108 |
+
pair_counts[p] = new
|
| 109 |
+
heapq.heappush(heap, (-new, p))
|
| 110 |
+
|
| 111 |
+
for i in tqdm(range(num_merges), desc="Training tokenizer"):
|
| 112 |
+
start_time = time.time()
|
| 113 |
+
|
| 114 |
+
# Pop stale heap entries until the top matches current counts.
|
| 115 |
+
while heap:
|
| 116 |
+
negc, p = heap[0]
|
| 117 |
+
c = pair_counts.get(p, 0)
|
| 118 |
+
if c > 0 and -negc == c:
|
| 119 |
+
break
|
| 120 |
+
heapq.heappop(heap)
|
| 121 |
+
if not heap:
|
| 122 |
+
break
|
| 123 |
+
|
| 124 |
+
pair = heap[0][1]
|
| 125 |
+
count = pair_counts.get(pair, 0)
|
| 126 |
+
if count <= 0:
|
| 127 |
+
break
|
| 128 |
+
|
| 129 |
+
idx = 256 + i
|
| 130 |
+
merges[pair] = idx
|
| 131 |
+
vocab[idx] = vocab[pair[0]] + vocab[pair[1]]
|
| 132 |
+
|
| 133 |
+
affected = list(pair_to_words.get(pair, ()))
|
| 134 |
+
if not affected:
|
| 135 |
+
pair_counts.pop(pair, None)
|
| 136 |
+
pair_to_words.pop(pair, None)
|
| 137 |
+
continue
|
| 138 |
+
|
| 139 |
+
# Apply merge to all words that contain the best pair.
|
| 140 |
+
for w in affected:
|
| 141 |
+
freq = words.get(w)
|
| 142 |
+
if not freq:
|
| 143 |
+
continue
|
| 144 |
+
|
| 145 |
+
new_w = self._merge_word(w, pair, idx)
|
| 146 |
+
if new_w == w:
|
| 147 |
+
continue
|
| 148 |
+
|
| 149 |
+
# Remove old word contributions
|
| 150 |
+
old_local = self._pair_occurrences(w)
|
| 151 |
+
for p, occ in old_local.items():
|
| 152 |
+
bump_pair(p, -freq * occ)
|
| 153 |
+
s = pair_to_words.get(p)
|
| 154 |
+
if s is not None:
|
| 155 |
+
s.discard(w)
|
| 156 |
+
if not s:
|
| 157 |
+
pair_to_words.pop(p, None)
|
| 158 |
+
|
| 159 |
+
# Update words dict (merge words that collapse to the same new tuple)
|
| 160 |
+
del words[w]
|
| 161 |
+
words[new_w] = words.get(new_w, 0) + freq
|
| 162 |
+
|
| 163 |
+
# Add new word contributions
|
| 164 |
+
new_local = self._pair_occurrences(new_w)
|
| 165 |
+
for p, occ in new_local.items():
|
| 166 |
+
bump_pair(p, freq * occ)
|
| 167 |
+
pair_to_words[p].add(new_w)
|
| 168 |
+
|
| 169 |
+
# This pair should be fully merged away.
|
| 170 |
+
pair_counts.pop(pair, None)
|
| 171 |
+
pair_to_words.pop(pair, None)
|
| 172 |
+
|
| 173 |
+
if verbose and i % 10 == 0:
|
| 174 |
+
time_taken = time.time() - start_time
|
| 175 |
+
tqdm.write(
|
| 176 |
+
f"merge {i+1}/{num_merges}: {pair} -> {idx} ({vocab[idx]}) "
|
| 177 |
+
f"had {count} occurrences (took {time_taken:.2f}s)"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
self.merges = merges
|
| 181 |
+
self.vocab = vocab
|
| 182 |
+
|
| 183 |
+
def decode(self, ids) -> str:
|
| 184 |
+
part_bytes = []
|
| 185 |
+
for id in ids:
|
| 186 |
+
if id in self.vocab:
|
| 187 |
+
part_bytes.append(self.vocab[id]) # id can be > 256 after merging
|
| 188 |
+
elif id in getattr(self, "inverse_special_tokens", {}):
|
| 189 |
+
part_bytes.append(self.inverse_special_tokens[id].encode("utf-8"))
|
| 190 |
+
else:
|
| 191 |
+
raise ValueError(f"id={id} not in vocab or special_tokens")
|
| 192 |
+
text_bytes = b"".join(part_bytes)
|
| 193 |
+
text = text_bytes.decode(encoding="utf-8", errors="replace")
|
| 194 |
+
return text
|
| 195 |
+
|
| 196 |
+
def _encode_chunk(self, chunk_bytes: bytes, verbose=False) -> list[int]:
|
| 197 |
+
tokens = list(chunk_bytes)
|
| 198 |
+
while len(tokens) >= 2:
|
| 199 |
+
if verbose:
|
| 200 |
+
visualise_tokens([self.vocab[token] for token in tokens]) # token can be > 256 after merging
|
| 201 |
+
stats = {}
|
| 202 |
+
get_stats(tokens, stats)
|
| 203 |
+
pair = min(stats, key=lambda p: self.merges.get(p, float("inf")))
|
| 204 |
+
if not pair in self.merges:
|
| 205 |
+
break
|
| 206 |
+
idx = self.merges[pair]
|
| 207 |
+
tokens = merge(tokens, pair, idx)
|
| 208 |
+
return tokens
|
| 209 |
+
|
| 210 |
+
def encode_ordinary(self, text, verbose=False) -> list[int]:
|
| 211 |
+
chunk_texts = re.findall(self.regex, text)
|
| 212 |
+
ids_list = []
|
| 213 |
+
for i, text in enumerate(chunk_texts):
|
| 214 |
+
if verbose:
|
| 215 |
+
print()
|
| 216 |
+
print(f"encoding chunk {i+1}/{len(chunk_texts)}: {text}")
|
| 217 |
+
chunk_bytes = text.encode("utf-8") # raw bytes
|
| 218 |
+
ids = self._encode_chunk(chunk_bytes, verbose)
|
| 219 |
+
ids_list.extend(ids)
|
| 220 |
+
return ids_list
|
| 221 |
+
|
| 222 |
+
def encode(self, text, verbose=False, allowed_special="none") -> list[int]:
|
| 223 |
+
special = {}
|
| 224 |
+
if allowed_special == "all":
|
| 225 |
+
special = self.special_tokens
|
| 226 |
+
elif allowed_special == "none":
|
| 227 |
+
special = {}
|
| 228 |
+
elif allowed_special == "none_raise":
|
| 229 |
+
special = {}
|
| 230 |
+
assert all(token not in text for token in self.special_tokens), "Text contains special tokens that are not allowed"
|
| 231 |
+
elif isinstance(allowed_special, set):
|
| 232 |
+
special = {k: v for k, v in self.special_tokens.items() if k in allowed_special}
|
| 233 |
+
else:
|
| 234 |
+
raise ValueError(f"allowed_special={allowed_special} not understood.")
|
| 235 |
+
if not special:
|
| 236 |
+
return self.encode_ordinary(text, verbose)
|
| 237 |
+
special_pattern = "(" + "|".join(re.escape(token) for token in special) + ")"
|
| 238 |
+
parts = re.split(special_pattern, text)
|
| 239 |
+
ids = []
|
| 240 |
+
for part in parts:
|
| 241 |
+
if part in special:
|
| 242 |
+
ids.append(special[part])
|
| 243 |
+
else:
|
| 244 |
+
ids.extend(self.encode_ordinary(part, verbose))
|
| 245 |
+
return ids
|
| 246 |
+
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"7995": {
|
| 4 |
+
"content": "<|endoftext|>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
}
|
| 11 |
+
},
|
| 12 |
+
"bos_token": null,
|
| 13 |
+
"clean_up_tokenization_spaces": true,
|
| 14 |
+
"eos_token": "<|endoftext|>",
|
| 15 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 16 |
+
"pad_token": null,
|
| 17 |
+
"tokenizer_class": "MGPT2Tokenizer",
|
| 18 |
+
"unk_token": null,
|
| 19 |
+
"auto_map": {
|
| 20 |
+
"AutoTokenizer": "tokenizer.hf_tokenizer.MGPT2Tokenizer"
|
| 21 |
+
}
|
| 22 |
+
}
|