ChatGPTが流行して、RubyでOpenAI APIを呼び出したりするときに、Tokenが気になる人もいるかも知れない。
そんなときのために、バインディングをAnkaneさんがちゃんとGemを作ってくれている。
こちらは、huggingface/tokenizers のRubyバインディングだ。
s = "In a hole in the ground there lived a hobbit."
tokenizer = Tokenizers.from_pretrained("gpt2")
ids = tokenizer.encode(s).ids
tokenizer.decode(ids)
Tokenの数を数える。
tokenizer = Tokenizers.from_pretrained('gpt2')
encoded = tokenizer.encode(prompt, add_special_tokens: true)
prompt_tokens = encoded.tokens.length
もうひとつ、blingfireというのもある。これはMicrosoftのBlingFireのバインディングだ。
s = "In a hole in the ground there lived a hobbit."
encoder = BlingFire.load_model('gpt2.bin')
decoder = BlingFire.load_model('gpt2.i2w')
ids = encoder.text_to_ids(s)
decoder.ids_to_text(ids)
GPT-2のTokenとGPT-3とは互換であるようだ。
tokenizers-ruby はRust製だ。
blingfire-ruby はWindowsでも動く。
tiktoken
最近はtiktokenというライブラリもあり、バインディングを開発する動きもいくつかある。
require 'tiktoken_ruby'
enc = Tiktoken.encoding_for_model("gpt-4")
enc.encode("hello world").length #=> 2
この記事は以上です。