🤖

商用利用可能かつ軽量なLLM、phi-2をMacbook Pro (M1 Pro)で動かす

2024/01/08に公開

phi-2ってなに?

自然言語モデルには “スケーリング則” と呼ばれる法則が存在します。スケーリング則は、以下の3つの変数が大きくなればなるほど、パフォーマンスが良くなるというシンプルなルールです。

  • パラメーター数
  • データセットのサイズ
  • トレーニングに使用される計算量

スケーリング則に従えばお金を投入すればするほど良いモデルを作ることができるため、MicrosoftやGoogleなどのビッグテックはその資金を数兆円という規模で投資してきました。GPT、Gemini、LLaMaといったLLMはこのスケーリング則の産物と言えます。

投資が進み、モデルが大規模になればなるほどそれを動かすことのできるコンピュータのスペック要求が高くなってしてしまい、限られた設備でなければ運用できないレベルに達しました。2023年の初頭ごろから、大規模言語モデルを軽量化することを目指す研究が見られるようになりました。

phiシリーズの第一弾であるphi-1は “Textbooks Are All You Need” という論文とともに発表されました。"Textbooks" は品質の高い学習データセットを意味し、少ないパラメーター数と少ない学習量であっても、学習データの品質さえ高ければパフォーマンスの高いLLMを作ることができる!ということを主張した論文です。
https://arxiv.org/abs/2306.11644

phi-1, phi-1.5は1.3Bパラーメータというコンパクトなサイズでありながら高いパフォーマンスであったため大きな注目を集めました。しかし発表当初のライセンスは商用利用不可であり、業務に導入する際の選択肢には含まれませんでした。また2023年12月13日に発表されたphi-2は、前バージョンの1.3Bから2.7Bにサイズアップしているものの、依然として一般的なラップトップPCでも動作する程度にコンパクトさをとどめています。

そして2024年1月6日、突如phi-2のライセンスがMITライセンスに変更され、商用利用が可能となったことが知られるとX上で大きな反響を呼びました。

phi-2をMacbook Proで動かす

弊Macbook Pro スペック
Chip Apple M1 Pro
Memory 32GB
macOS Sonoma 14.1.2

M1などのApple SiliconでLLMを動かす技術としてMLXがあります。MLXはNumPyやPyTorchのような機械学習のためのフレームワークで、モデルを学習したり実行したりすることができます。
https://github.com/ml-explore/mlx

セットアップ

HuggingFaceのModel Summaryのガイドを参考にしながらセットアップをしていきます。
https://huggingface.co/mlx-community/phi-2

git clone https://github.com/ml-explore/mlx-examples.git
cd mlx-examples
pip install mlx transformers huggingface_hub hf_transfer
export HF_HUB_ENABLE_HF_TRANSFER=1
huggingface-cli download --local-dir-use-symlinks False --local-dir llms/phi2 mlx-community/phi-2

実行

python llms/phi2/phi2.py --prompt "Who are you?"

🚧 書かれた通りに実行するとエラーが出た

python llms/phi2/phi2.py --prompt "Who are you?"                           
---
Traceback (most recent call last):
  File "/Users/k3ntar0/Workspace/mlx-examples/llms/phi2/phi2.py", line 207, in <module>
    model, tokenizer = load_model(args.model_path)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/k3ntar0/Workspace/mlx-examples/llms/phi2/phi2.py", line 162, in load_model
    with open(model_path / "config.json", "r") as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'mlx_model/config.json

✅ 動くコード

python llms/phi2/phi2.py --model-path llms/phi2 --prompt "Who are you?"

性能は?

コードを書かせてみる

プロンプト
Write a sample code using the reduce method of Array in JavaScript.

Write a sample code using the reduce method of Array in JavaScript.

A:

You can use the reduce method of Array.

var arr = [1, 2, 3, 4, 5];
var sum = arr.reduce(function(a, b) {
  return a + b;
}, 0);
console.log(sum);

A:

You can use the reduce method of Array.

var arr = [1, 2, 3, 4, 5];

constではなくvarで宣言していたりアロー関数じゃなかったりするので、もしかしたら結構古い学習データを使ってそうだな〜と思いました。

少し調べてみると、まずphi-2はphi-1, phi-1.5と同じデータセットを使っています。
更にphi-1のドキュメントを見る限りではJavaScript等の知識は gpt-3.5-turbo-0301 を蒸留したデータセットから得ていそうなので、これが正しければモデルが学習している情報は総じて古いはずです。

推論能力は?

ChatGPTに作ってもらった問題

Question Model Answer
1. If a train travels 500 miles in 5 hours, what is its average speed in miles per hour? 100 mph
2. Describe the significance of the Turing Test in Artificial Intelligence. It measures a machine's ability to exhibit intelligent behavior equivalent to, or indistinguishable from, that of a human.
3. Calculate the area of a circle with a radius of 10 cm. 314.16 cm² (π * radius²)
4. How does the principle of supply and demand affect market prices? Prices are determined by the interaction of supply and demand; as demand increases and/or supply decreases, prices go up.
5. What is photosynthesis and why is it essential for life on Earth? It is the process by which green plants and some other organisms use sunlight to synthesize nutrients from carbon dioxide and water. Photosynthesis in plants generally involves the green pigment chlorophyll and generates oxygen as a by-product. It is essential as it is the base of the food chain and oxygen production.
6. Solve: If 3x - 2 = 13, what is the value of x? x = 5
7. Explain the impact of global warming on polar ice caps. Global warming leads to melting of polar ice caps, which contributes to rising sea levels and the loss of habitat for animals adapted to this cold environment.
8. If you invest $1,000 at an annual interest rate of 5% compounded annually, how much will you have after 10 years? $1,628.89
9. What is the theory of evolution and who proposed it? The theory of evolution by natural selection was proposed by Charles Darwin. It explains the diversity of life as the result of gradual changes in populations over generations.
10. A rectangle has a length of 20 cm and a width of 10 cm. What is its perimeter? 60 cm (2*(length + width))

結果

ChatGPTにお願いして正誤判定してもらいました。
複利の計算だけ間違えてしまいましたが、それ以外はちゃんと正解しているので思ったより使えそうじゃ無いでしょうか?
ただしContext Windowが比較的小さく 2048 tokens までしか扱えないため、少し長い問題の場合生成が途切れてしまうことがあります。

Question Model Answer Your Answer Evaluation
1. If a train travels 500 miles in 5 hours, what is its average speed in miles per hour? 100 mph 100 mph Correct
2. Describe the significance of the Turing Test in Artificial Intelligence. It measures a machine's ability to exhibit intelligent behavior equivalent to, or indistinguishable from, that of a human. The Turing Test is a test of a machine's ability to exhibit intelligent behavior equivalent to, or indistinguishable from, that of a human. It is considered a significant milestone in the field of Artificial Intelligence (AI) as it provides a way to measure and compare the intelligence of machines to that of humans... Correct
3. Calculate the area of a circle with a radius of 10 cm. 314.16 cm² (π * radius²) 314.16 cm² Correct
4. How does the principle of supply and demand affect market prices? Prices are determined by the interaction of supply and demand; as demand increases and/or supply decreases, prices go up. The principle of supply and demand is a fundamental concept in economics that explains how market prices are determined. It states that the price of a good or service is influenced by the interaction of its supply and demand... Correct
5. What is photosynthesis and why is it essential for life on Earth? Photosynthesis is the process by which green plants and some other organisms use sunlight to synthesize nutrients from carbon dioxide and water. It is essential as it is the base of the food chain and oxygen production. Photosynthesis is the process by which plants, algae, and some bacteria use light energy to convert water and carbon dioxide into organic molecules, such as glucose and oxygen. It provides the primary source of energy and organic matter for most living organisms... Correct
6. Solve: If 3x - 2 = 13, what is the value of x? x = 5 x = 5 Correct
7. Explain the impact of global warming on polar ice caps. Global warming leads to melting of polar ice caps, which contributes to rising sea levels and the loss of habitat for animals adapted to this cold environment. Global warming is causing the polar ice caps to melt at an alarming rate. This is primarily due to the increase in greenhouse gases in the atmosphere, which trap heat and cause the Earth's temperature to rise. As a result, the ice caps are melting... Correct
8. If you invest $1,000 at an annual interest rate of 5% compounded annually, how much will you have after 10 years? $1,628.89 $16,386.17 Incorrect
9. What is the theory of evolution and who proposed it? The theory of evolution by natural selection was proposed by Charles Darwin. It explains the diversity of life as the result of gradual changes in populations over generations. The theory of evolution is a scientific explanation for the diversity of life on Earth, which proposes that all living organisms share a common ancestor and have changed over time through the process of natural selection... Correct
10. A rectangle has a length of 20 cm and a width of 10 cm. What is its perimeter? 60 cm (2*(length + width)) 60 cm Correct

英語以外も使える?

phi-2に日本語とフランス語で質問しましたが何も返答が無く無視されたので、英語以外の処理能力は無いようです。

業務で使える?

  • 業務で使うにはプロンプトチューニングが必須だが、最大2,048トークンしか扱えないので、Context Windowにチューニングするほどの余裕が無く、まだちょっと厳しそう。
  • 英語以外扱えないのもの厳しい。
  • 軽量さで言えばオンプレでの動作も問題なさそう!
  • 速度的には十分スピードが出ているし推論も割と賢いと感じるので、phi-3に期待!

宣伝

僕がCTOを務める株式会社DynagonではLLMを使った事業を作りたいエンジニア・デザイナー・BizDev募集中です!
Xにてお気軽にDMください!
https://x.com/k3ntar0

Discussion