How to count tokens with tiktoken
#tiktoken の使い方
https://github.com/openai/openai-cookbook/blob/297c53430cad2d05ba763ab9dca64309cb5091e9/examples/How_to_count_tokens_with_tiktoken.ipynb
モデル名からencodingを取得できる
Encodings specify how text is converted into tokens. Different models use different encodings.
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
tiktoken.encoding_for_model
encoding.encodeメソッドでテキストをトークンIDに変換できる
code:python
>> encoding.encode("tiktoken is great!") # 6トークン
83, 1609, 5963, 374, 2294, 0
>> encoding.encode("お誕生日おめでとう") # 9トークン (33334は「お」)
33334, 45918, 243, 21990, 9080, 33334, 62004, 16556, 78699
encodeメソッドの返り値(リスト)の長さから、何トークン分かが(ChatGPTのAPIに送らなくても)分かる
encoding.decodeメソッドでトークンIDから戻せる
Warning: although .decode() can be applied to single tokens, beware that it can be lossy for tokens that aren't on utf-8 boundaries.
「単一のトークンにdecodeを適用できるけれども、utf-8 boundariesにないトークンは失いうることに注意」
encoding.decode_single_token_bytesでトークンIDからbytesに戻せる
code:python
>> encoding.decode_single_token_bytes(token_id) for token_id in encoding.encode("tiktoken is great!") # ascii文字はbytesも見やすい
b't', b'ik', b'token', b' is', b' great', b'!'
>> encoding.decode_single_token_bytes(token_id) for token_id in encoding.encode("お誕生日おめでとう")
b'\xe3\x81\x8a', b'\xe8\xaa', b'\x95', b'\xe7\x94\x9f', b'\xe6\x97\xa5', b'\xe3\x81\x8a', b'\xe3\x82\x81', b'\xe3\x81\xa7', b'\xe3\x81\xa8\xe3\x81\x86'
>> "お誕生日おめでとう".encode() # 全体のbytesと比較するアイデア
b'\xe3\x81\x8a\xe8\xaa\x95\xe7\x94\x9f\xe6\x97\xa5\xe3\x81\x8a\xe3\x82\x81\xe3\x81\xa7\xe3\x81\xa8\xe3\x81\x86'
>> b'\xe3\x81\x8a'.decode()
'お'
>> b'\xe8\xaa'.decode() # 「誕」は2トークンに分かれている!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: unexpected end of data
>> b'\xe8\xaa\x95'.decode()
'誕'
>> b'\xe3\x81\xa8\xe3\x81\x86'.decode() # 「とう」で1トークン
'とう'
以下、TODO
encodingを比較する例
API呼び出しのレスポンスに含まれるトークンの数と一致することを確認する例
トークンのID列(encode)
👉Getting Dense Word Embeddings(PyTorchのチュートリアル「Word Embeddings: Encoding Lexical Semantics」)