🔠

OpenAI 言語モデルごとのエンコーディング一覧

ryohtaka2023/03/09に公開

はじめに

OpenAI の言語モデルの一覧と、各モデルが使うエンコーディングについて情報をまとめました。

[補足] Azure OpenAI Service 版とのモデル名の違いについて

一部モデル名は Azure OpenAI Service 版と少し異なりますが、本記事ではすべて本家 OpenAI 版のモデル名をベースにまとめています。両者の違いについては別の記事でまとめました。

エンコーディングについて

OpenAI 言語モデルにおけるエンコーディングとは、テキストがトークンに変換される際の (トークナイズされる際の) ルールのようなものです。モデルによって使用するエンコーディングは異なります。

確認方法

各モデルが使うエンコーディングは Python パッケージの tiktoken で確認することができます。
下記の例では ChatGPT API のモデルのひとつである gpt-3.5-turbo のエンコーディングを確認しています。

>>> import tiktoken
>>> print(tiktoken.encoding_for_model('gpt-3.5-turbo'))
<Encoding 'cl100k_base'>

参考

種類

執筆時点で OpenAI の言語モデルでは下記いずれかのエンコーディングが使われています。直近発表された GPT-4 や、ChatGPT API など GPT-3.5 シリーズの中でも後半に発表されたモデルはすべて cl100k_base を使っていることから、今後は cl100k_base が主流になると想像されます。

  • cl100k_base
  • p50k_base
  • r50k_base (gpt2)

比較

openai-cookbook のサンプルコードをユニコード文字も print できるように変更してトークナイズ結果を比較してみます。なお、一部のユニコード文字は 1 文字が複数トークンに分割されて UTF-8 でデコードできなくなってしまいますので、その部分は � で表現します。

import tiktoken

def compare_encodings(example_string: str) -> None:
    """Prints a comparison of three string encodings."""
    print(f'\nExample string: "{example_string}"')
    for encoding_name in ["cl100k_base", "p50k_base", "r50k_base"]:
        encoding = tiktoken.get_encoding(encoding_name)
        token_integers = encoding.encode(example_string)
        num_tokens = len(token_integers)
        token_bytes = [encoding.decode_single_token_bytes(token) for token in token_integers]
        token_utf8 = []
        for tb in token_bytes:
            try:
                s = tb.decode('utf-8')
            except UnicodeDecodeError:
	        # UTF-8 でデコードできないトークンは � で表現
                s = "�"
            token_utf8.append(s)
        print()
        print(f"{encoding_name}: {num_tokens} tokens")
        print(f"token integers: {token_integers}")
        print(f"token strings: {token_utf8}")

p50k_baser50k_base では、ユニコード文字は 1 文字 1 トークンもしくは 1 文字がさらに複数トークンに分割されています。下記の例では平仮名の「ち」が 2 トークンに分割されています。
一方、 cl100k_base ではユニコード文字でもある程度のフレーズを 1 トークンにまとめてくれるようです。

compare_encodings("こんにちはOpenAI")

結果

Example string: "こんにちはOpenAI"

cl100k_base: 3 tokens
token integers: [90115, 5109, 15836]
token strings: ['こんにちは', 'Open', 'AI']

p50k_base: 8 tokens
token integers: [46036, 22174, 28618, 2515, 94, 31676, 11505, 20185]
token strings: ['こ', 'ん', 'に', '�', '�', 'は', 'Open', 'AI']

r50k_base: 8 tokens
token integers: [46036, 22174, 28618, 2515, 94, 31676, 11505, 20185]
token strings: ['こ', 'ん', 'に', '�', '�', 'は', 'Open', 'AI']

p50k_baser50k_base の違いはソースコードの取り扱い方にあるようです。p50k_base ではインデントをひとまとめにするなど、トークン数がやや少なくなっています。前述の openai-cookbook でも下記のように説明されています。

p50k_base overlaps substantially with r50k_base, and for non-code applications, they will usually give the same tokens.

msg = """
def print_message_with_exclamation(message):
    str = message + '!'
    print(str)

print_message_with_exclamation('hello world')
"""

compare_encodings(msg)

結果

Example string: "
def print_message_with_exclamation(message):
    str = message + '!'
    print(str)

print_message_with_exclamation('hello world')
"

cl100k_base: 29 tokens
token integers: [198, 755, 1194, 6598, 6753, 2769, 34084, 7483, 997, 262, 610, 284, 1984, 489, 364, 49827, 262, 1194, 4293, 696, 1374, 6598, 6753, 2769, 34084, 493, 15339, 1917, 1329]
token strings: ['\n', 'def', ' print', '_message', '_with', '_ex', 'clamation', '(message', '):\n', '   ', ' str', ' =', ' message', ' +', " '", "!'\n", '   ', ' print', '(str', ')\n\n', 'print', '_message', '_with', '_ex', 'clamation', "('", 'hello', ' world', "')\n"]

p50k_base: 42 tokens
token integers: [198, 4299, 3601, 62, 20500, 62, 4480, 62, 1069, 20931, 7, 20500, 2599, 198, 50258, 965, 796, 3275, 1343, 705, 13679, 198, 50258, 3601, 7, 2536, 8, 198, 198, 4798, 62, 20500, 62, 4480, 62, 1069, 20931, 10786, 31373, 995, 11537, 198]
token strings: ['\n', 'def', ' print', '_', 'message', '_', 'with', '_', 'ex', 'clamation', '(', 'message', '):', '\n', '   ', ' str', ' =', ' message', ' +', " '", "!'", '\n', '   ', ' print', '(', 'str', ')', '\n', '\n', 'print', '_', 'message', '_', 'with', '_', 'ex', 'clamation', "('", 'hello', ' world', "')", '\n']

r50k_base: 46 tokens
token integers: [198, 4299, 3601, 62, 20500, 62, 4480, 62, 1069, 20931, 7, 20500, 2599, 198, 220, 220, 220, 965, 796, 3275, 1343, 705, 13679, 198, 220, 220, 220, 3601, 7, 2536, 8, 198, 198, 4798, 62, 20500, 62, 4480, 62, 1069, 20931, 10786, 31373, 995, 11537, 198]
token strings: ['\n', 'def', ' print', '_', 'message', '_', 'with', '_', 'ex', 'clamation', '(', 'message', '):', '\n', ' ', ' ', ' ', ' str', ' =', ' message', ' +', " '", "!'", '\n', ' ', ' ', ' ', ' print', '(', 'str', ')', '\n', '\n', 'print', '_', 'message', '_', 'with', '_', 'ex', 'clamation', "('", 'hello', ' world', "')", '\n']

モデルごとのエンコーディング一覧

OpenAI の公式ドキュメント に記載されている表をベースにして ENCODING 列を追加しました。今後主流になりそうな cl100k_base が使われているモデルのみ拙訳を追加しました。

GPT-4

すべてのモデルで cl100k_base が使われています。ただし、執筆時点で GPT-4 API がまだ利用可能な状態ではありませんでしたので、あくまでも事前に tiktoken で確認した結果という点はご注意ください。

LATEST MODEL DESCRIPTION MAX TOKENS TRAINING DATA ENCODING
gpt-4 More capable than any GPT-3.5 model, able to do more complex tasks, and optimized for chat. Will be updated with our latest model iteration. (GPT-3.5 のどのモデルよりも高性能で、より複雑なタスクをこなし、チャットに最適化されています。 最新のモデルで更新され続けます。) 8,192 tokens Up to Sep 2021 (2021 年 9 月まで) cl100k_base
gpt-4-0314 Snapshot of gpt-4 from March 14th 2023. Unlike gpt-4, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023. (2023 年 3 月 14 日の gpt-4 のスナップショットバージョンです。このモデルは gpt-4 とは異なり、更新は行われず、2023 年 6 月 14 日までの 3 ヶ月間のみサポートされます。) 8,192 tokens Up to Sep 2021 (2021 年 9 月まで) cl100k_base
gpt-4-32k Same capabilities as the base gpt-4 mode but with 4x the context length. Will be updated with our latest model iteration. (基本 gpt-4 モデルと同じ機能ですが、コンテキスト長が 4 倍になっています。最新のモデルで更新され続けます。) 32,768 tokens Up to Sep 2021 (2021 年 9 月まで) cl100k_base
gpt-4-32k-0314 Snapshot of gpt-4-32 from March 14th 2023. Unlike gpt-4-32k, this model will not receive updates, and will only be supported for a three month period ending on June 14th 2023. (2023 年 3 月 14 日の gpt-4-32k のスナップショットバージョンです。このモデルは gpt-4-32k とは異なり、更新は行われず、2023 年 6 月 14 日までの 3 ヶ月間のみのサポートされます。) 32,768 tokens Up to Sep 2021 (2021 年 9 月まで) cl100k_base

GPT-3.5

モデルによって cl100k_basep50k_base のいずれかが使われています。

LATEST MODEL DESCRIPTION MAX REQUEST TRAINING DATA ENCODING
gpt-3.5-turbo Most capable GPT-3.5 model and optimized for chat at 1/10th the cost of text-davinci-003. Will be updated with our latest model iteration. (GPT-3.5 の中で最高性能のモデルで、チャット用に最適化さています。コストは text-davinci-003 の 1/10 です。 最新のモデルで更新され続けます。) 4,096 tokens Up to Sep 2021 (2021 年 9 月まで) cl100k_base
gpt-3.5-turbo-0301 Snapshot of gpt-3.5-turbo from March 1st 2023. Unlike gpt-3.5-turbo, this model will not receive updates, and will only be supported for a three month period ending on June 1st 2023. (2023 年 3 月 1 日の gpt-3.5-turbo のスナップショットバージョンです。このモデルは gpt-3.5-turbo とは異なり、更新は行われず、2023 年 6 月 1 日までの 3 ヶ月間のみサポートされます。) 4,096 tokens Up to Sep 2021 (2021 年 9 月まで) cl100k_base
text-davinci-003 Can do any language task with better quality, longer output, and consistent instruction-following than the curie, babbage, or ada models. Also supports inserting completions within text. 4,097 tokens Up to Jun 2021 p50k_base
text-davinci-002 Similar capabilities to text-davinci-003 but trained with supervised fine-tuning instead of reinforcement learning 4,097 tokens Up to Jun 2021 p50k_base

https://platform.openai.com/docs/models/gpt-3-5

Codex

全てのモデルで p50k_base が使われてます。code-davinci-002 は GPT-3.5 と Codex 両方のドキュメントに記載がありましたので Codex 側にまとめました。

LATEST MODEL DESCRIPTION MAX REQUEST TRAINING DATA ENCODING
code-davinci-002 Most capable Codex model. Particularly good at translating natural language to code. In addition to completing code, also supports inserting completions within code. 8,001 tokens Up to Jun 2021 p50k_base
code-cushman-001 Almost as capable as Davinci Codex, but slightly faster. This speed advantage may make it preferable for real-time applications. Up to 2,048 tokens p50k_base

https://platform.openai.com/docs/models/codex

GPT-3

全てのモデルで r50k_base が使われています。

LATEST MODEL DESCRIPTION MAX REQUEST TRAINING DATA ENCODING
text-curie-001 Very capable, faster and lower cost than Davinci. 2,049 tokens Up to Oct 2019 r50k_base
text-babbage-001 Capable of straightforward tasks, very fast, and lower cost. 2,049 tokens Up to Oct 2019 r50k_base
text-ada-001 Capable of very simple tasks, usually the fastest model in the GPT-3 series, and lowest cost. 2,049 tokens Up to Oct 2019 r50k_base
davinci Most capable GPT-3 model. Can do any task the other models can do, often with higher quality. 2,049 tokens Up to Oct 2019 r50k_base
curie Very capable, but faster and lower cost than Davinci. 2,049 tokens Up to Oct 2019 r50k_base
babbage Capable of straightforward tasks, very fast, and lower cost. 2,049 tokens Up to Oct 2019 r50k_base
ada Capable of very simple tasks, usually the fastest model in the GPT-3 series, and lowest cost. 2,049 tokens Up to Oct 2019 r50k_base

https://platform.openai.com/docs/models/gpt-3

Embeddings

V2 モデル (執筆時点で text-embedding-ada-002 のみ) では cl100k_base が使われています。V1 モデル (それ以外) では r50k_base が使われています。

MODEL GENERATION TOKENIZER MAX INPUT TOKENS KNOWLEDGE CUTOFF
V2 cl100k_base 8191 Sep 2021
V1 GPT-2/GPT-3 (r50k_base) 2046 Aug 2020

https://platform.openai.com/docs/guides/embeddings/embedding-models

おわりに

以上です。🍵

Microsoft (有志)

Microsoft Azureをはじめとする最新技術情報をお届けします。Twitterアカウント @msdevjp やYouTubeチャンネル「クラウドデベロッパーちゃんねる」も運用中です。 ※このPublicationは日本マイクロソフト社員による個人の見解であり、所属する組織の公式見解ではありません。

Discussion

ログインするとコメントできます