見出し画像

【MLX】Macbookで、Mistral-7B をローカル環境で実行してみた

Appleシリコンに最適化されたML用ライブラリが出たとのことで、色々試していこうと思います!これまでMacbookだと動かしにくかった色々なものが、サクッと動かせるようになっていて感動してます。

今回は Mistral-7B を、MLXを使ってローカルGUIで実行する方法についてまとめていきます。



この記事で紹介すること

  • MLXによる Mistral-7b の動かし方

  • GUIで Mistral-7b を遊ぶ方法

  • 記事へのラベル付けができるか検証


前提:動作環境

Macbook Pro、Apple M1 Maxチップ、メモリ64GBを使って検証してます。

Apple シリコンチップであれば、動作できると思いますが、メモリ不足で実行できないという場合があるかもしれません。ご了承ください。


やり方

mlx-examplesに、MLXを用いて様々なモデルを動かすためのコードが格納されています。今回はここにある Mistral-7b のコードを利用していきます。


環境構築

適当なディレクトリで以下を実行します。

git clone https://github.com/ml-explore/mlx-examples.git

続いて、Mistral-7b のコードがあるディレクトリに移動して、環境構築をしていきます。

cd mlx-examples/mistral

# .mistral という名前の仮想環境を作成
python3 -m venv .mistral

# 仮想環境をアクティベート
source .mistral/bin/activate

pip install -r requirements.txt

次に、モデルとトークナイザーをダウンロードします。

curl -O https://files.mistral-7b-v0-1.mistral.ai/mistral-7B-v0.1.tar
tar -xf mistral-7B-v0.1.tar

モデルのロードには少し時間がかかります。自分の通信環境では20分くらいだったような気がします。

モデルロードが完了したら、それをMLXで利用できる重みのフォーマットに変換します。

python convert.py

変換スクリプトは、変換された重みを同じ場所に保存されます。


実行してみる

ではお待ちかね Mistral-7b の実行です。リポジトリには、すでにスクリプトが存在しているので、そちらを実行してみます。

python mistral.py --prompt "It is a truth universally acknowledged,"  --temp 0

> [INFO] Loading model from disk.
[INFO] Starting generation...
It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.

So begins Pride and Prejudice, one of the most famous novels in the English language.

The story of the Bennet family, five unmarried daughters and their mother, is a classic tale of love and misunderstanding.

The novel was first published in 1813, and has been adapted for film and television many times.

The most recent
------

python mistral.py --prompt "どこにでも認められる真実であることとして、" --temp 0
[情報] モデルをディスクから読み込み中。
[情報] 生成を開始...
「どこにでも認められる真実である、財産を持つ独身男性は、妻を必要としているものである」というのが、英語の最も有名な小説の一つである「プライドと偏見」の始まりです。

未婚の5人の娘とその母親であるベネット家の話は、愛と誤解の古典的な物語です。

この小説は1813年に初めて出版され、何度も映画やテレビにて翻案されています。

最も最近の
------

mistral.py 実行結果の日本語訳

mistral.pyでは以下のようなコマンドが使えるようです。

$ python mistral.py --help                         
usage: mistral.py [-h] [--model_path MODEL_PATH]
                  [--prompt PROMPT]
                  [--max_tokens MAX_TOKENS] [--temp TEMP]
                  [--tokens_per_eval TOKENS_PER_EVAL]
                  [--seed SEED]

Mistral inference script

options:
  -h, --help            show this help message and exit
  --model_path MODEL_PATH
                        The path to the model weights and
                        tokenizer
  --prompt PROMPT       The message to be processed by the
                        model
  --max_tokens MAX_TOKENS, -m MAX_TOKENS
                        Maximum number of tokens to generate
  --temp TEMP           The sampling temperature.
  --tokens_per_eval TOKENS_PER_EVAL
                        The batch size of tokens to
                        generate.

$ python mistral.py --help
使用法: mistral.py [-h] [--model_path MODEL_PATH]
[--prompt PROMPT]
[--max_tokens MAX_TOKENS] [--temp TEMP]
[--tokens_per_eval TOKENS_PER_EVAL]
[--seed SEED]

Mistral推論スクリプト

オプション:
-h, --help このヘルプメッセージを表示して終了します
--model_path MODEL_PATH モデルの重みとトークナイザーへのパス
--prompt PROMPT モデルに処理させるメッセージ
--max_tokens MAX_TOKENS, -m MAX_TOKENS 生成するトークンの最大数
--temp TEMP サンプリング温度。
--tokens_per_eval TOKENS_PER_EVAL 生成するトークンのバッチサイズ。
--seed SEED PRNGのシード

python mistral.py --help 実行結果の日本語訳


GUI画面上で実行してみる

今のままだと、promptを実行する際に毎回ファイル実行しないといけなくてめんどくさいですよね。そこでGUI画面を立ち上げて、プロンプトを入力できるようにしたいと思います。

今回は streamlit を使ってGUIを作成していきます。

pip install streamlit

mlx-examples/mistral/ 配下に app.py を作成し、以下のコードを記載していきます。

# mlx-examples/mistral/app.py
import streamlit as st
import mistral
import mlx.core as mx


def load_model_and_tokenizer(model_path):
    return mistral.load_model(model_path)


def main():
    st.title("Mistral-7b")

    prompt = st.text_input("Prompt", "Once upon a time, in a galaxy far, far away...")
    temp = st.number_input("Temperature", min_value=0.0, max_value=10.0, value=1.0)
    max_tokens = st.number_input("Max Tokens", min_value=1, max_value=1000, value=100)

    if st.button("Generate"):
        model_path = "mistral-7B-v0.1"
        model, tokenizer = load_model_and_tokenizer(model_path)
        prompt_encoded = mx.array(tokenizer.encode(prompt))
        tokens = []
        for token, _ in zip(
            mistral.generate(prompt_encoded, model, temp), range(max_tokens)
        ):
            tokens.append(token)
        s = tokenizer.decode([t.item() for t in tokens])
        st.text_area("Output", s, height=400)


if __name__ == "__main__":
    main()

そして、以下のコマンドでGUI画面を立ち上げます。

streamlit run app.py

Input:昔々、遥か彼方の銀河系で...

Output:私は「Urban Thoughts」というブログを共有しました。そのブログでは、文化から社会、ゲームの世界に至るまでのさまざまな主題を扱っています。もっと重要なことは、私がそれぞれの投稿に簡潔さ、熱意、そして良い意味での変わった雰囲気を持ち込もうという考えを共有したことです。重い心で皆さんにお伝えしなければならないのですが、投稿を始めて6年後の今、Urban Thoughtsは休止モードに入ることになりました。一般的な考えとしては、十分な時間があれば、2020年(ブログの10周年)にUrban Thoughtsを再開できることです。今、あなたは「まあ、書く時間があるでしょう」と言っているかもしれません。しかし、この問題は、研究、計画、そしてリクリエーション(R&R、私の時間など)に時間が必要だということです。私は「Urban Thoughts Social Club」を「復活」させたり設立したりするつもりです。読者との交流は、コミュニティを結集し、私自身の視野と読者の視野を広げるためにより重要だと感じているからです。

新しい @UrbanThoughts Twitterと潜在的な新しいInstagramページを楽しみにしてください。これらはブログが再開する前に開設される予定です。Urban Thoughtsで最も大きな変化に気付くでしょう。それは、他のトピックにも手を出すことです。以前、Urban Thoughtsは非常に多くの素材をカバーしてきました。これには限りませんが、次のようなものが含まれます。

日本語訳

ふむふむ(なるほど、わからん。)といったところでしょうか。


記事内容にラベル付けをしてもらう

あまりOSS LLMを触ったことがないので、どれくらい実用レベルなのかについて軽く検証してみたいと思います。個人的にやりたいこととして、記事内容にラベル付けをしたいなと思っており、これを Mistral-7b でできるか検証してみます。

以下の短い記事内容(GPT-4で生成)を使って試してみます。

The 21st century has transformed education through technology. Digital tools have reshaped classrooms, introducing interactive and engaging teaching methods. Interactive whiteboards and digital projectors have replaced traditional tools, enhancing learning experiences. Educational technology enables personalized learning, with apps and online platforms offering customized learning paths. Students learn at their own pace, accommodating diverse learning styles.

The internet provides access to a wealth of resources like e-books and videos, democratizing education and allowing global collaboration. This technological integration prepares students for a future dominated by technology, enhancing digital literacy and readiness for future careers.

However, challenges like the digital divide pose threats to educational equality. Overuse of technology can also impact attention spans. Despite these challenges, the positive impact of technology on education is clear. It has made learning more interactive, personalized, and accessible. Effective and equitable use of technology remains crucial for the future of education.

日本語訳
21世紀は、技術を通じて教育を変革してきました。デジタルツールが教室を再形成し、インタラクティブで魅力的な教授方法を導入しています。インタラクティブなホワイトボードやデジタルプロジェクターが伝統的なツールに取って代わり、学習体験を向上させています。教育技術は、アプリやオンラインプラットフォームを通じてパーソナライズされた学習を可能にし、学生が自分のペースで、さまざまな学習スタイルに対応しながら学べるようにしています。

インターネットは、電子書籍やビデオなどの豊富なリソースへのアクセスを提供し、教育を民主化し、世界的な協力を可能にしています。この技術統合は、技術に支配された未来に向けて学生を準備し、デジタルリテラシーを高め、将来のキャリアに備えます。

しかし、デジタルデバイドのような課題は教育の平等に対する脅威をもたらします。技術の過剰使用は注意力にも影響を与える可能性があります。これらの課題にもかかわらず、教育に対する技術の肯定的な影響は明らかです。それは学習をよりインタラクティブで、パーソナライズされ、アクセスしやすいものにしています。教育の将来に向けて、技術の効果的かつ公平な使用が重要です。

GPT-4で生成

これを使って以下のプロンプトを投げてみます。

You are a professional in labeling articles. Please assign only one label to the given article.

## Example Article 1
Climate change is an urgent issue facing the world today. Rising temperatures, melting ice caps, and unpredictable weather patterns are having a profound impact on the environment. Efforts to reduce carbon emissions and promote sustainable practices are vital to mitigate these effects. The global community must work together to address this crisis and protect our planet for future generations.

Label: Environmental Issues

## Example Article 2
The art of baking has evolved significantly over the years. From traditional breads and pastries to elaborate cakes and desserts, the culinary world has seen a wide variety of baking styles. Innovations in baking technology and ingredients have also contributed to this evolution, allowing bakers to experiment with new flavors and textures. Baking is not only a culinary skill but also a form of creative expression.

Label: Culinary Arts

## Article Content
The 21st century has transformed education through technology. Digital tools have reshaped classrooms, introducing interactive and engaging teaching methods. Interactive whiteboards and digital projectors have replaced traditional tools, enhancing learning experiences. Educational technology enables personalized learning, with apps and online platforms offering customized learning paths. Students learn at their own pace, accommodating diverse learning styles. The internet provides access to a wealth of resources like e-books and videos, democratizing education and allowing global collaboration. This technological integration prepares students for a future dominated by technology, enhancing digital literacy and readiness for future careers. However, challenges like the digital divide pose threats to educational equality. Overuse of technology can also impact attention spans. Despite these challenges, the positive impact of technology on education is clear. It has made learning more interactive, personalized, and accessible. Effective and equitable use of technology remains crucial for the future of education.

Label:

プロンプト

21st Century Education Coding has become

出力結果

惜しいような、、といった感じでしょうか。そもそも max_tokens 分だけ出力し続けるため、stop_tokensみたいなものを設定する必要があるかもしれません。ここら辺は追加で色々と検証してみます。


おわりに

Mistral-7b についてMLXで動かせるようになりました。結構簡単に動かせるようになったと思います。次回はこれをLoRAチューニングする方法について検証していきます。


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