見出し画像

NPUを使える日に備えてONNX Runtime拡張ライブラリでローカルLLMのPhi-3の動かし方

ASUS Vivobook s15を買いましたが、pythonでLLMを動かすときにNPUをどうやって使用させるのかがわかりませんでした。

Microsoftが提供するONNX Runtimeの拡張ライブラリであるonnxruntime-genaiを使えば出来るみたいとのことですが、Arm64は開発中とのことでした。


https://github.com/microsoft/onnxruntime-genai


今回は、いつかArm64版のONNX Runtimeの拡張ライブラリが出るであろうことに備えて、非ArmPCで、ONNX Runtimeの拡張ライブラリでphi-3-miniを動かしてみます。



最初に、ONNX Runtime用のPhi-3-miniのLLMをダウンロードします。

huggingface-cli download microsoft/Phi-3-mini-4k-instruct-onnx --include cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4/* --local-dir .

次に、numpyとonnxruntime-genaiをインストールします。

pip install numpy
pip install --pre onnxruntime-genai

次に、githubからonnxruntime-genaiのプロジェクトを持ってきます。

git clone https://github.com/microsoft/onnxruntime-genai.git

次に、onnxruntime-genaiフォルダ内に、test.pyというファイルを作成して、次のコードを記載します。

import onnxruntime_genai as og

model = og.Model('cpu_and_mobile/cpu-int4-rtn-block-32-acc-level-4')
tokenizer = og.Tokenizer(model)
tokenizer_stream = tokenizer.create_stream()
 
# Set the max length to something sensible by default,
# since otherwise it will be set to the entire context length
search_options = {}
search_options['max_length'] = 2048

chat_template = '<|user|>\n{input} <|end|>\n<|assistant|>'

text = input("Input: ")
if not text:
   print("Error, input cannot be empty")
   exit

prompt = f'{chat_template.format(input=text)}'

input_tokens = tokenizer.encode(prompt)

params = og.GeneratorParams(model)
params.set_search_options(**search_options)
params.input_ids = input_tokens
generator = og.Generator(model, params)

print("Output: ", end='', flush=True)

try:
   while not generator.is_done():
     generator.compute_logits()
     generator.generate_next_token()

     new_token = generator.get_next_tokens()[0]
     print(tokenizer_stream.decode(new_token), end='', flush=True)
except KeyboardInterrupt:
    print("  --control+c pressed, aborting generation--")

print()
del generator

最後に、実行です。


python test.py

Inputが表示されますので、今回はHello! We are happy!と入力してみました。

Input: Hello! We are happy!
Output:  Hello! We are delighted to hear that! How can we assist you today?

ちなみに、日本語も対応可能です。


Input: 何か面白いネタは無いですか?
Output:  面白いネタとは、個人の好みや文化によって異なりますが、一般的には以
下のようなテーマが考えられます。

1. 科学技術の進歩、特にAIやロボティクスの進展に関する話題。
2. 日常生活で起こる予期せぬ出来事やユーモア。
3. ファンタジーやファンファーレーティングの世界観。
4. 歴史的な出来事や人物に関するエピソード。
5. 現実のエピックな事件やニュース。
6. 冒険や旅行に関するエピソード。
7. 絵画や音楽、芸術についての考察。
8. ファンタジーやファンファーレーティングのキャラクターやストーリー。
9. 日常生活の小さなエピソードやユーモア。
10. 科学的な発見や理論に関する話題。

これらは単なる例であり、あなたの好みや興味に合わせてネタを選ぶことが重要です。



この記事が気に入ったらサポートをしてみませんか?