3
0

More than 1 year has passed since last update.

RubyでTokenizersを使う

Last updated at Posted at 2023-03-02

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

この記事は以上です。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0