Apple silicon用の推論ライブラリmlx-lmを試したみたのでその備忘録.
(検索すればいくらでも出てくる内容)
準備
mlxとmlx-lmのインストール
pip install mlx mlx-lm
インストールされたバージョンは以下の通り
Python 3.11.11
mlx 0.25.1
mlx_lm 0.24.0
コマンドラインからの実行
mlx_lm.generate --model mlx-community/Qwen3-8B-4bit \
--prompt "機械学習フレームワークのMLXについて教えて" \
--max-tokens 1024
Qwen3は思考テキストが長く,max-tokensが512だと出力されなかった.
以下は出力が長いので,速度だけ記しておく.なおM2 Ultraのmacstudio上で実行した.
Prompt: 20 tokens, 130.271 tokens-per-sec
Generation: 1024 tokens, 104.712 tokens-per-sec
Peak memory: 4.898 GB
/no_think
をプロンプトに追加した場合は以下の通り.
Prompt: 24 tokens, 147.129 tokens-per-sec
Generation: 1024 tokens, 104.482 tokens-per-sec
Peak memory: 4.901 GB
出力までの時間は早くなるが,生成速度自体は思考の有無によって変わらない.
次に,mlxの早さを実感するため,ollamaでも同様に実行してみる.
ollama run "qwen3:8b-q4_K_M" --verbose "機械学習フレームワークのMLXについて教えて"
total duration: 29.831782167s
load duration: 664.587959ms
prompt eval count: 20 token(s)
prompt eval duration: 295.268416ms
prompt eval rate: 67.73 tokens/s
eval count: 1909 token(s)
eval duration: 28.870143417s
eval rate: 66.12 tokens/s
プロンプト処理速度が半分,生成速度が3分の2に落ちていることから.やはりmlxは積極的に使った方が良さそう.
mlx_lmでのチャット
mlx_lm.chat --model mlx-community/Qwen3-8B-4bit
[INFO] Starting chat session with mlx-community/Qwen3-8B-4bit.
The command list:
- 'q' to exit
- 'r' to reset the chat
- 'h' to display these commands
>> こんにちは
<think>
Okay, the user said "こんにちは" which means "Hello" in Japanese. I need to respond politely. Since they're using Japanese, maybe they want a response in Japanese too. Let me check if they specified the language. The initial query was in Japanese, so it's safe to assume they prefer a Japanese response. I should greet them back in Japanese and offer assistance. Let me make sure my Japanese is correct. "こんにちは" is "Hello," so a proper response would be "こんにちは!お手伝いできますか?" which translates to "Hello! How can I assist you?" That should be good. I'll go with that.
</think>
こんにちは!お手伝いできますか?
>> おはよう /no_think
<think>
</think>
おはようございます!お手伝いできることがありましたら、どうぞよろしくお願いします!
チャットでも/no_think
を付けると,思考の過程を表示しないことがわかる.
mlx_lmサーバーの起動と「Hello World」テスト
mlx_lmサーバーの起動
mlx_lmサーバーについては公式のドキュメントを参考にした.
まず,サーバーを起動する.
mlx_lm.server --model mlx-community/Qwen3-8B-4bit --port 8082
この時,モデルによっては引数に--trust-remote-code
が必要になる.
この引数はモデルのカスタムコードの実行許可を表す設定とのこと.
モデルリポジトリにpythonスクリプトが含まれている場合はこの引数がないと実行できないそうだが,Qwen3-8B-4bit はカスタムコードがないので不要.
参考:Qwen3-8B-4bitのリポジトリ
なお --port 8082
はサーバーを起動するポート番号で,サーバーが正常に起動すると,ターミナルには以下のように準備完了メッセージが表示される.
2025-05-02 18:08:58,096 - INFO - Starting httpd at 127.0.0.1 on port 8082...
curlを使用したテスト
新しいターミナルウィンドウを開き,以下のcurlコマンドでサーバーにリクエストを送信する:
curl localhost:8082/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "Hello world/"}],
"temperature": 0.7
}'
ターミナル上にJSON形式で出力されるので,中身はよくわからないが,contentの中にHow can I assist you today?
があるのを目視確認.
とりあえず以上. GGUFをmlxバージョンに変換するコマンドもあるようだが,しばらくはhugging face上のモデルを使用するだけだと思うので,そちらは後回しにする.
Leave a Reply