LLM [3] トークナイザー
- 01LLM [1] データ、ハードウェア、モデルの選択
- 02LLM [2] データの準備
- 03LLM [3] トークナイザー
3. トークナイザー
さて、テキストは手に入った。だがニューラルネットワークが扱うのは数値だ。つまり各単語に番号を割り当てる必要がある。英単語の辞書を用意し、各単語に番号を振れば、トークナイザーはほぼ完成する。残るのは、句読点、数字、冠詞、造語、単語の一部にどの番号を割り当てるかを決めることだ。要するにトークンとは単語の ID である。そして単語は辞書にある単語とは限らない。文字、記号、数字を含むモデル名ということもある。
単語をトークン化するために BPE(Byte-pair encoding)が考案された。初期のバージョンでは、語彙にない単語に <|unk|> トークンを使っていた。しかし現代の BPE には <|unk|> は不要だ。文字と記号のどんな組み合わせでもエンコードできる。そのために単語を単語の一部に分割する。最小単位は 1 バイトだ。だからどんな造語でもトークンに分解できる。
これから使う tiktoken の基本トークナイザーにある特殊トークンは <|endoftext|> だけだ。とはいえ、独自のトークンはいつでも追加できる。モデルに特定の動作、たとえばプログラムの関数呼び出しを学習させる場合には意味がある。そのとき生成結果にそのトークンが現れることは LLM が関数を呼び出そうとしていることを意味し、生成の中にそのトークンを見つけたら、私たちがその関数を呼び出せばよい。
最も単純なトークナイザーの例を示す。これは実際には使わない。原理を理解するためだけのものだ。やっていることは次のとおり:
- 入力テキストを単語に分け、単語を文字に分ける。後で使う tiktoken ライブラリも同じことをするが、単語を文字ではなく UTF-8 のバイトに分ける。だから
<|unk|>が要らない:どんなテキストも 256 通りのバイトでできている。 - 隣り合うトークンのペアが、学習で覚えたマージの中にあれば、それを繰り返し結合する。この簡略版は単語を左から右へたどり、最初に見つかったペアを結合する。本物の BPE(と tiktoken)は、最も早く学習されたペア、つまりランクが最も高いペアから適用する。そのため下の出力では、最も頻出する単語の一つであるにもかかわらず
" and"が" a"、"n"、"d"に分かれている。 - 結合できるペアがなくなるまで結合を続ける。
- 結果はトークン ID のリストだ。
この記事のコード:gpt/tokenizer
from collections import Counter, deque
from functools import lru_cache
import yaml
class BPETokenizerSimple:
def __init__(self):
# Maps token_id to token_str (e.g., {11246: "some"})
self.vocab = {}
# Maps token_str to token_id (e.g., {"some": 11246})
self.inverse_vocab = {}
# Dictionary of BPE merges: {(token_id1, token_id2): merged_token_id}
self.bpe_merges = {}
def train(self, text, vocab_size, allowed_special={"<|endoftext|>"}):
"""
Train the BPE tokenizer from scratch.
Args:
text (str): The training text.
vocab_size (int): The desired vocabulary size.
allowed_special (set): A set of special tokens to include.
"""
# Preprocess: Replace spaces with 'Ġ'
# Note that Ġ is a particularity of the GPT-2 BPE implementation
# E.g., "Hello world" might be tokenized as ["Hello", "Ġworld"]
# (GPT-4 BPE would tokenize it as ["Hello", " world"])
processed_text = []
for i, char in enumerate(text):
if char == " " and i != 0:
processed_text.append("Ġ")
if char != " ":
processed_text.append(char)
processed_text = "".join(processed_text)
# Initialize vocab with unique characters, including 'Ġ' if present
# Start with the first 256 ASCII characters
unique_chars = [chr(i) for i in range(256)]
# Extend unique_chars with characters from processed_text that are not already included
unique_chars.extend(char for char in sorted(set(processed_text)) if char not in unique_chars)
# Optionally, ensure 'Ġ' is included if it is relevant to your text processing
if 'Ġ' not in unique_chars:
unique_chars.append('Ġ')
# Now create the vocab and inverse vocab dictionaries
self.vocab = {i: char for i, char in enumerate(unique_chars)}
self.inverse_vocab = {char: i for i, char in self.vocab.items()}
# Add allowed special tokens
if allowed_special:
for token in allowed_special:
if token not in self.inverse_vocab:
new_id = len(self.vocab)
self.vocab[new_id] = token
self.inverse_vocab[token] = new_id
# Tokenize the processed_text into token IDs
token_ids = [self.inverse_vocab[char] for char in processed_text]
# BPE steps 1-3: Repeatedly find and replace frequent pairs
for new_id in range(len(self.vocab), vocab_size):
pair_id = self.find_freq_pair(token_ids, mode="most")
if pair_id is None: # No more pairs to merge. Stopping training.
break
token_ids = self.replace_pair(token_ids, pair_id, new_id)
self.bpe_merges[pair_id] = new_id
# Build the vocabulary with merged tokens
for (p0, p1), new_id in self.bpe_merges.items():
merged_token = self.vocab[p0] + self.vocab[p1]
self.vocab[new_id] = merged_token
self.inverse_vocab[merged_token] = new_id
def encode(self, text):
"""
Encode the input text into a list of token IDs.
Args:
text (str): The text to encode.
Returns:
List[int]: The list of token IDs.
"""
tokens = []
# Split text into tokens, keeping newlines intact
words = text.replace("\n", " \n ").split() # Ensure '\n' is treated as a separate token
for i, word in enumerate(words):
if i > 0 and not word.startswith("\n"):
tokens.append("Ġ" + word) # Add 'Ġ' to words that follow a space or newline
else:
tokens.append(word) # Handle first word or standalone '\n'
token_ids = []
for token in tokens:
if token in self.inverse_vocab:
# token is contained in the vocabulary as is
token_id = self.inverse_vocab[token]
token_ids.append(token_id)
else:
# Attempt to handle subword tokenization via BPE
sub_token_ids = self.tokenize_with_bpe(token)
token_ids.extend(sub_token_ids)
return token_ids
def tokenize_with_bpe(self, token):
"""
Tokenize a single token using BPE merges.
Args:
token (str): The token to tokenize.
Returns:
List[int]: The list of token IDs after applying BPE.
"""
# Tokenize the token into individual characters (as initial token IDs)
token_ids = [self.inverse_vocab.get(char, None) for char in token]
if None in token_ids:
missing_chars = [char for char, tid in zip(token, token_ids) if tid is None]
raise ValueError(f"Characters not found in vocab: {missing_chars}")
can_merge = True
while can_merge and len(token_ids) > 1:
can_merge = False
new_tokens = []
i = 0
while i < len(token_ids) - 1:
pair = (token_ids[i], token_ids[i + 1])
if pair in self.bpe_merges:
merged_token_id = self.bpe_merges[pair]
new_tokens.append(merged_token_id)
i += 2 # Skip the next token as it's merged
can_merge = True
else:
new_tokens.append(token_ids[i])
i += 1
if i < len(token_ids):
new_tokens.append(token_ids[i])
token_ids = new_tokens
return token_ids
def decode(self, token_ids):
"""
Decode a list of token IDs back into a string.
Args:
token_ids (List[int]): The list of token IDs to decode.
Returns:
str: The decoded string.
"""
decoded_string = ""
for token_id in token_ids:
if token_id not in self.vocab:
raise ValueError(f"Token ID {token_id} not found in vocab.")
token = self.vocab[token_id]
if token.startswith("Ġ"):
# Replace 'Ġ' with a space
decoded_string += " " + token[1:]
else:
decoded_string += token
return decoded_string
@lru_cache(maxsize=None)
def get_special_token_id(self, token):
return self.inverse_vocab.get(token, None)
@staticmethod
def find_freq_pair(token_ids, mode="most"):
pairs = Counter(zip(token_ids, token_ids[1:]))
if mode == "most":
return max(pairs.items(), key=lambda x: x[1])[0]
elif mode == "least":
return min(pairs.items(), key=lambda x: x[1])[0]
else:
raise ValueError("Invalid mode. Choose 'most' or 'least'.")
@staticmethod
def replace_pair(token_ids, pair_id, new_id):
dq = deque(token_ids)
replaced = []
while dq:
current = dq.popleft()
if dq and (current, dq[0]) == pair_id:
replaced.append(new_id)
# Remove the 2nd token of the pair, 1st was already removed
dq.popleft()
else:
replaced.append(current)
return replaced
トークナイザーの学習とは、要するに最適なペアを探すことだ。学習後、bpe_merges にそのペアが入っている。
def main():
with open("config.yaml") as f:
cfg = yaml.safe_load(f)["tokenizer"]
with open(cfg["sample_file"], encoding="utf-8") as f:
text = f.read(cfg["sample_chars"]) # first N characters, not the whole 500 MB
tokenizer = BPETokenizerSimple()
tokenizer.train(text, vocab_size=1000, allowed_special={"<|endoftext|>"})
print(len(tokenizer.vocab))
print(len(tokenizer.bpe_merges))
input_text = "Jack embraced beauty through art and life."
token_ids = tokenizer.encode(input_text)
print("token_ids:", token_ids)
print("Number of characters:", len(input_text))
print("Number of token IDs:", len(token_ids))
for token_id in token_ids:
print(f"{token_id} -> {tokenizer.decode([token_id])}")
print(tokenizer.decode(tokenizer.encode("This is some text.")))
if __name__=='__main__':
main()
出力:
$ python tokenizer/bpe_simple.py
1000
718
token_ids: [74, 468, 107, 256, 364, 791, 468, 333, 315, 351, 441, 121, 291, 360, 117, 334, 309, 114, 116, 309, 110, 100, 256, 356, 448, 46]
Number of characters: 42
Number of token IDs: 26
74 -> J
468 -> ac
107 -> k
256 ->
364 -> em
791 -> br
468 -> ac
333 -> ed
315 -> b
351 -> ea
441 -> ut
121 -> y
291 -> th
360 -> ro
117 -> u
334 -> gh
309 -> a
114 -> r
116 -> t
309 -> a
110 -> n
100 -> d
256 ->
356 -> li
448 -> fe
46 -> .
This is some text.
トークン 256 は単独のスペース(Ġ)だ。"Ġembraced" という単語は語彙にないので文字に分解され、Ġ は次の断片と結合されなかった。そのためスペースが独立したトークンとして残った。
出来合いの tiktoken ライブラリを使い、テキストをトークンに変換し、また元に戻す様子を見てみよう。
import tiktoken
import yaml
def main():
tokenizer = tiktoken.get_encoding("gpt2")
text = "Jack embraced beauty through art and life."
integers = tokenizer.encode(text)
print("integers:", integers)
print([tokenizer.decode([i]) for i in integers])
decoded = tokenizer.decode(integers)
print("decoded:", decoded)
# Special tokens: the same string can be encoded in two different ways.
text = "end of book<|endoftext|>next book"
# 1. Default: tiktoken refuses to encode text that contains a special token.
try:
tokenizer.encode(text)
except ValueError as e:
print("default: ValueError:", str(e).splitlines()[0])
# 2. Allowed: "<|endoftext|>" becomes ONE special token, id 50256.
ids = tokenizer.encode(text, allowed_special={"<|endoftext|>"})
print("allowed:", [tokenizer.decode([i]) for i in ids], ids)
# 3. Treated as plain text: the same characters become ordinary pieces.
ids = tokenizer.encode(text, disallowed_special=())
print("as text:", [tokenizer.decode([i]) for i in ids], ids)
with open("config.yaml") as f:
cfg = yaml.safe_load(f)["tokenizer"]
with open(cfg["sample_file"], encoding="utf-8") as f:
text = f.read(10_000_000)
ids = tokenizer.encode(text, allowed_special={"<|endoftext|>"})
print(f"{len(text) / len(ids):.2f} chars per token")
if __name__=="__main__":
main()
出力:
$ python tokenizer/tiktoken_sample.py
integers: [14295, 18079, 8737, 832, 1242, 290, 1204, 13]
['Jack', ' embraced', ' beauty', ' through', ' art', ' and', ' life', '.']
decoded: Jack embraced beauty through art and life.
default: ValueError: Encountered text corresponding to disallowed special token '<|endoftext|>'.
allowed: ['end', ' of', ' book', '<|endoftext|>', 'next', ' book'] [437, 286, 1492, 50256, 19545, 1492]
as text: ['end', ' of', ' book', '<', '|', 'end', 'of', 'text', '|', '>', 'next', ' book'] [437, 286, 1492, 27, 91, 437, 1659, 5239, 91, 29, 19545, 1492]
3.40 chars per token
文字列 <|endoftext|> のエンコード方法は 2 通りある。allowed_special を指定すると、ID 50256 の特殊トークン 1 個になる。モデルが本の終わりを知るのはまさにこれによってだ。disallowed_special=() を指定すると、ただの 13 文字として扱われ、通常のトークン <、|、end、of、text、|、> に分割される。デフォルトでは tiktoken はどちらかを推測せず、例外を投げる。これは安全策だ:ユーザーがプロンプトに <|endoftext|> と書いても、制御トークンになってはならない。本の区切りは自分たちで挿入したものなので、明示的に許可する。
まとめ:
- 単純な BPE:語彙 1000、20 万文字での学習に約 14 秒、例文は 26 トークン。
- tiktoken gpt2:語彙 50257、同じ例文は 8 トークン。
- 私たちの本では 1 トークンあたり約 3.4 文字:14.3 GB ≈ 42 億トークン。
次のパート、埋め込み(エンベディング)へ進む。