AI・機械学習ガイド

Mac Mini M4でLLMを実行する方法 (Llama、Mistral、Phi)

Apple Siliconの統合メモリアーキテクチャは、大規模言語モデルをローカルで実行する上で、Mac Mini M4を最もコスト効率の高いプラットフォームの一つにしています。本ガイドでは、実際のベンチマークと実践的なコード例とともに、Ollama、llama.cpp、MLXを解説します。

読了時間20分 2026年3月更新 中級

1. なぜLLMにMac Mini M4なのか?

Mac Mini M4は、Apple Siliconのアーキテクチャのおかげで、大規模言語モデルの実行に独自に適しています。VRAMがモデルサイズを制限する従来のGPUサーバーとは異なり、M4の統合メモリではCPU、GPU、Neural Engineが同じメモリプールを共有できます。つまり、24GBのMac Miniは、24GBのVRAMを備えた高価なGPUを必要とするようなモデルを読み込めるのです。

🧠

統合メモリアーキテクチャ

VRAMが分離されているNVIDIA GPUとは異なり、M4の統合メモリではGPUがシステムRAM全体にアクセスできます。24GBのMac Miniは、PCI-E帯域幅のボトルネックなしに、モデル読み込み用に実質24GBの「VRAM」を持つことになります。

Neural Engine

M4の16コアNeural Engineは、最大38 TOPSのML性能を発揮します。CoreMLやMLXといったフレームワークはこれを活用し、Transformer推論に不可欠な行列演算を高速化します。

🔌

電力効率

Mac Mini M4は、典型的なLLM推論負荷でわずか5〜15Wしか消費しません。NVIDIA A100の300〜450Wと比べれば歴然です。これにより、ホスティングコストが劇的に下がり、専用の冷却も不要になります。

💰

高いコスト効率

16GBの専用Mac Mini M4が月額$85から利用でき、トークン単位のAPI料金なしで予測可能な料金体系を得られます。GPUクラウドの料金のほんの一部で、24時間365日、無制限の推論リクエストを実行できます。

重要なポイント:(トレーニングではなく)推論ワークロードにおいて、Mac Mini M4は業界で最高のドルあたり性能比を提供します。ノイジーネイバーのない専用ハードウェア、トークン単位の課金なし、そして最大120 GB/sというApple Siliconのメモリ帯域幅を手に入れられます。

2. LLMフレームワークの比較

Apple SiliconのLLMエコシステムは、3つのフレームワークが主流です。それぞれ、ユースケースに応じた明確な強みがあります。

機能 Ollama llama.cpp MLX
セットアップの容易さ 非常に簡単 普通 簡単
Metal GPUサポート 対応(自動) 対応(フラグ) 対応(ネイティブ)
APIサーバー 内蔵 内蔵 手動
モデル形式 GGUF(自動ダウンロード) GGUF SafeTensors / MLX
パフォーマンス 良好 GGUFに最適 Apple Siliconに最適
モデルライブラリ 厳選済み(ollama.com) HuggingFace GGUF HuggingFace MLX
言語 Go(CLI/API) C++(CLI/API) Python
最適な用途 迅速なデプロイ、API提供 最大限の制御、カスタムビルド Python MLパイプライン、研究

3. Ollamaでのセットアップ

Ollamaは、Mac Mini M4でLLMを始める最も簡単な方法です。単一のバイナリで、モデルのダウンロード、量子化、API提供を処理します。

ステップ1:Ollamaをインストールする

# Download and install Ollama
curl -fsSL https://ollama.com/install.sh | sh

# Verify installation
ollama --version
# ollama version 0.5.4

ステップ2:モデルをダウンロードする

# Download Llama 3 8B (4.7GB, fits 16GB RAM)
ollama pull llama3:8b

# Download Mistral 7B (4.1GB)
ollama pull mistral:7b

# Download Phi-3 Mini (2.3GB, great for constrained setups)
ollama pull phi3:mini

# Download Llama 3 70B (requires 48GB+ RAM)
ollama pull llama3:70b

# List downloaded models
ollama list
# NAME            SIZE     MODIFIED
# llama3:8b       4.7 GB   2 minutes ago
# mistral:7b      4.1 GB   5 minutes ago
# phi3:mini       2.3 GB   8 minutes ago

ステップ3:対話型チャットを実行する

# Start an interactive chat session
ollama run llama3:8b

# Example interaction:
# >>> What is the capital of France?
# The capital of France is Paris. It is the largest city in France
# and serves as the country's political, economic, and cultural center.

ステップ4:APIとして提供する

Ollamaは、ポート11434で自動的にREST APIサーバーを起動します。OpenAI互換APIを使って、あらゆるアプリケーションからクエリを送信できます。

# The Ollama server starts automatically, listening on localhost:11434

# Query using curl (OpenAI-compatible endpoint)
curl http://localhost:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "llama3:8b",
    "messages": [
      {"role": "system", "content": "You are a helpful coding assistant."},
      {"role": "user", "content": "Write a Python function to calculate fibonacci numbers."}
    ],
    "temperature": 0.7,
    "max_tokens": 500
  }'

# Native Ollama API endpoint
curl http://localhost:11434/api/generate \
  -d '{
    "model": "llama3:8b",
    "prompt": "Explain quantum computing in 3 sentences.",
    "stream": false
  }'

ステップ5:Pythonから使う

# pip install openai
from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11434/v1",
    api_key="ollama"  # Ollama doesn't require an API key
)

response = client.chat.completions.create(
    model="llama3:8b",
    messages=[
        {"role": "system", "content": "You are a senior Python developer."},
        {"role": "user", "content": "Write a FastAPI endpoint for user registration."}
    ],
    temperature=0.7,
    max_tokens=1000
)

print(response.choices[0].message.content)

ステップ6:Ollamaをバックグラウンドサービスとして実行する

# Create a launchd plist for auto-start on boot
cat <<EOF > ~/Library/LaunchAgents/com.ollama.server.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.ollama.server</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/ollama</string>
        <string>serve</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>
EOF

# Load the service
launchctl load ~/Library/LaunchAgents/com.ollama.server.plist

# Verify it's running
curl http://localhost:11434/api/tags

4. llama.cppでのセットアップ

llama.cppは、推論パラメータを最大限に制御でき、手作業で最適化されたMetalバックエンドのおかげで、Apple Siliconで最高の生パフォーマンスを発揮することがよくあります。

ステップ1:クローンしてMetalでビルドする

# Install dependencies
brew install cmake

# Clone the repository
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp

# Build with Metal GPU acceleration (Apple Silicon)
mkdir build && cd build
cmake .. -DLLAMA_METAL=ON -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Release -j$(sysctl -n hw.ncpu)

# Verify Metal support
./bin/llama-cli --help | grep metal

ステップ2:GGUFモデルをダウンロードする

# Install huggingface-cli for easy downloads
pip install huggingface_hub

# Download Llama 3 8B Q4_K_M (best quality/speed balance)
huggingface-cli download \
  TheBloke/Llama-3-8B-GGUF \
  llama-3-8b.Q4_K_M.gguf \
  --local-dir ./models

# Download Mistral 7B Q4_K_M
huggingface-cli download \
  TheBloke/Mistral-7B-Instruct-v0.2-GGUF \
  mistral-7b-instruct-v0.2.Q4_K_M.gguf \
  --local-dir ./models

# Download Phi-3 Mini Q4
huggingface-cli download \
  microsoft/Phi-3-mini-4k-instruct-gguf \
  Phi-3-mini-4k-instruct-q4.gguf \
  --local-dir ./models

ステップ3:推論を実行する

# Run Llama 3 8B with Metal GPU offloading (all layers)
./build/bin/llama-cli \
  -m ./models/llama-3-8b.Q4_K_M.gguf \
  -ngl 99 \
  -c 4096 \
  -t 8 \
  --temp 0.7 \
  -p "Explain how transformers work in machine learning:"

# Key flags:
# -ngl 99     : Offload all layers to Metal GPU
# -c 4096     : Context window size
# -t 8        : Number of CPU threads (M4 has 10 cores)
# --temp 0.7  : Temperature for sampling

ステップ4:APIサーバーを起動する

# Start OpenAI-compatible API server
./build/bin/llama-server \
  -m ./models/llama-3-8b.Q4_K_M.gguf \
  -ngl 99 \
  -c 4096 \
  --host 0.0.0.0 \
  --port 8080 \
  --parallel 4

# Test the API
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "llama-3-8b",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

5. MLXでのセットアップ

MLXはApple独自の機械学習フレームワークで、Apple Silicon専用に設計されています。M4のGPUとNeural Engineとの最も緊密な統合を提供し、PythonベースのMLワークフローに最適です。

ステップ1:MLXをインストールする

# Create a virtual environment
python3 -m venv ~/mlx-env
source ~/mlx-env/bin/activate

# Install MLX and the LLM package
pip install mlx mlx-lm

# Verify installation
python3 -c "import mlx.core as mx; print(mx.default_device())"
# Device(gpu, 0)

ステップ2:MLXで推論を実行する

# Run Llama 3 8B using mlx-lm CLI
mlx_lm.generate \
  --model mlx-community/Meta-Llama-3-8B-Instruct-4bit \
  --prompt "Write a Python decorator for rate limiting:" \
  --max-tokens 500 \
  --temp 0.7

# Run Mistral 7B
mlx_lm.generate \
  --model mlx-community/Mistral-7B-Instruct-v0.3-4bit \
  --prompt "Explain microservices architecture:" \
  --max-tokens 500

ステップ3:Python連携

from mlx_lm import load, generate

# Load the model (downloads on first run)
model, tokenizer = load("mlx-community/Meta-Llama-3-8B-Instruct-4bit")

# Generate text
prompt = "Write a bash script to monitor disk usage and send alerts:"
response = generate(
    model,
    tokenizer,
    prompt=prompt,
    max_tokens=500,
    temp=0.7,
    top_p=0.9
)
print(response)

# Streaming generation
from mlx_lm import stream_generate

for token in stream_generate(
    model, tokenizer,
    prompt="Explain Docker networking:",
    max_tokens=300
):
    print(token, end="", flush=True)

ステップ4:MLXでシンプルなAPIを構築する

# pip install fastapi uvicorn mlx-lm
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from mlx_lm import load, stream_generate
import json

app = FastAPI()
model, tokenizer = load("mlx-community/Meta-Llama-3-8B-Instruct-4bit")

@app.post("/v1/completions")
async def completions(request: dict):
    prompt = request.get("prompt", "")
    max_tokens = request.get("max_tokens", 256)

    response = ""
    for token in stream_generate(model, tokenizer, prompt=prompt, max_tokens=max_tokens):
        response += token

    return {"choices": [{"text": response}]}

@app.post("/v1/chat/completions")
async def chat(request: dict):
    messages = request.get("messages", [])
    prompt = tokenizer.apply_chat_template(messages, tokenize=False)

    response = ""
    for token in stream_generate(model, tokenizer, prompt=prompt, max_tokens=512):
        response += token

    return {
        "choices": [{
            "message": {"role": "assistant", "content": response}
        }]
    }

# Run: uvicorn server:app --host 0.0.0.0 --port 8000

6. パフォーマンスベンチマーク

OllamaとQ4_K_M量子化を使って測定した実際のベンチマークです。すべてのテストで、512トークンのプロンプト、256トークンの生成、デフォルトのサンプリングパラメータを使用しています。

ハードウェア モデル トークン/秒 最初のトークンまでの時間 月額コスト
Mac Mini M4 16GB Llama 3 8B Q4 ~35 tok/s ~180ms $85
Mac Mini M4 16GB Mistral 7B Q4 ~38 tok/s ~160ms $85
Mac Mini M4 24GB Llama 3 13B Q4 ~22 tok/s ~320ms $95
Mac Mini M4 Pro 48GB Llama 3 70B Q4 ~12 tok/s ~850ms $179
RTX 4090 (cloud) Llama 3 8B Q4 ~120 tok/s ~50ms $500+

注:NVIDIA GPUの方が生のスループットは高いものの、Mac Mini M4はそのわずかなコストで、対話型ユースケースに十分優れたトークン/秒を実現します。35 tok/sあれば、チャットアプリケーションでは応答が瞬時に感じられます。真の利点はコストです。無制限で月額$85なのに対し、トークン従量課金のAPIは容易に月額$500を超えることがあります。

7. どのモデルがどの構成に適しているか?

鍵となる要素は統合メモリです。Q4量子化では、モデルは10億パラメータあたりおよそ0.5〜0.6 GBを使用し、これに加えてコンテキストとOS用のオーバーヘッドが必要です。

メモリ モデルサイズの範囲 モデルの例 月額料金
16 GB 7B - 13B (Q4) Llama 3 8B, Mistral 7B, Phi-3 Mini, Gemma 7B $85
24 GB 13B - 34B (Q4) Llama 3 13B, CodeLlama 34B, Yi 34B $95
48 GB 34B - 70B (Q4) Llama 3 70B, Mixtral 8x7B, DeepSeek 67B $179
64 GB+ 70B+ (Q4/Q6) Llama 3 70B Q6, Mixtral 8x22B, Command-R+ $249+
# Quick formula to estimate memory requirements:
# Memory needed = (Parameters in B * Bits per weight / 8) + context overhead
#
# Example: Llama 3 70B at Q4 quantization
# = (70 * 4 / 8) GB = 35 GB model weights
# + ~4 GB context/overhead
# = ~39 GB total → fits in 48GB Mac Mini M4 Pro
#
# Check current memory usage while running a model:
ollama ps
# NAME          SIZE     PROCESSOR    UNTIL
# llama3:8b     5.1 GB   100% GPU     4 minutes from now

8. ユースケース

プライベートAIアシスタント

すべてのデータをサーバー上に保持する、ChatGPTのようなアシスタントを実行できます。データがインフラの外に出ることはありません。機密文書、顧客データ、独自コードの取り扱いに最適です。

推奨:16GBでLlama 3 8B

RAGパイプライン

ドキュメントを検索して回答を生成する、検索拡張生成(RAG)システムを構築できます。埋め込みにはChromaDBやQdrantを、生成にはOllamaを使います。

推奨:16GBでMistral 7B

コード生成

CodeLlamaやDeepSeek Coderのような専用コーディングモデルを、自動補完、コードレビュー、自動リファクタリングに使えます。Continue.dev経由でVS CodeやJetBrainsと連携できます。

推奨:48GBでCodeLlama 34B

コンテンツ生成

マーケティングコピー、ブログ記事、製品説明、メールテンプレートを大規模に生成できます。トークン単位のAPI料金がかさむことなく、夜間にバッチジョブを実行できます。

推奨:48GBでLlama 3 70B

9. パフォーマンスのヒント

適切な量子化を選ぶ

量子化レベルは、速度と品質の両方に劇的に影響します。Q4_K_Mは、ほとんどのユースケースで最良のバランスを提供します。

# Quantization levels (from fastest to best quality):
# Q2_K  - Fastest, lowest quality, smallest size
# Q3_K  - Fast, acceptable quality
# Q4_K_M - Best balance of speed and quality (RECOMMENDED)
# Q5_K_M - Slower, better quality
# Q6_K  - Slow, near-original quality
# Q8_0  - Slowest, best quality, largest size
# F16   - Full precision, requires 2x memory

# Example: Download Q4_K_M for best balance
ollama pull llama3:8b-instruct-q4_K_M

Metal GPUオフロードを最大化する

最大限のパフォーマンスを得るために、モデルのすべてのレイヤーがGPUで実行されるようにします。CPUへの部分的なオフロードは、スループットを大幅に低下させます。

# llama.cpp: offload all layers to GPU
./llama-cli -m model.gguf -ngl 99

# Check GPU utilization
sudo powermetrics --samplers gpu_power -n 1 -i 1000

# Monitor memory pressure
memory_pressure
# System-wide memory free percentage: 45%

バッチサイズとコンテキストを最適化する

コンテキストウィンドウのサイズを小さくするとメモリが解放され、スループットが向上することがあります。アプリケーションが実際に必要とする分だけコンテキストを使いましょう。

# Default context is often 4096 or 8192 tokens
# Reduce if you don't need long context:
ollama run llama3:8b --num-ctx 2048

# For llama.cpp, set context and batch size:
./llama-server -m model.gguf -ngl 99 \
  -c 2048 \      # Context window
  -b 512 \       # Batch size for prompt processing
  --parallel 2   # Concurrent request slots

モデルをメモリ上でホットに保つ

ディスクからのモデル読み込みには数秒かかります。頻繁に使うモデルはメモリに常駐させておき、即座に応答できるようにしましょう。

# Ollama: set keep-alive to keep model in memory indefinitely
curl http://localhost:11434/api/generate -d '{
  "model": "llama3:8b",
  "keep_alive": -1
}'

# Or set environment variable for default behavior
export OLLAMA_KEEP_ALIVE=-1

# Check which models are loaded
ollama ps

10. よくある質問

Mac Mini M4でChatGPTレベルのモデルを実行できますか?

はい。Llama 3 8BやMistral 7Bのようなモデルは、多くのタスクでGPT-3.5に匹敵する品質を発揮します。GPT-4レベルの品質には70Bモデルが必要で、これには48GB以上の統合メモリ(Mac Mini M4 Pro)が求められます。コーディング支援、ドキュメントのQ&A、コンテンツ生成には、非常に優れた体験です。

35トークン/秒は、リアルタイムチャットに十分な速さですか?

もちろんです。人間の平均的な読書速度は毎秒約4〜5語で、これはおよそ毎秒5〜7トークンに相当します。35 tok/sなら、モデルは人間が読めるより5〜7倍速くテキストを生成します。チャットアプリケーションでは、これは完全に瞬時と感じられます。

Mac Mini M4は何人の同時ユーザーに対応できますか?

7Bモデルの場合、1台のMac Mini M4は、許容できるレイテンシで2〜4件の同時リクエストに対応できます。さらに高い同時実行数が必要な場合は、ロードバランサーの背後に複数のMac Miniを配置できます。Ollamaとllama.cppのサーバーは、どちらも同時リクエストのキューイングに対応しています。

Mac Mini M4でモデルをファインチューニングできますか?

はい、ただし制限があります。MLXやHugging Face PEFTライブラリを使えば、16GBのデバイスでLoRA/QLoRAにより7Bモデルをファインチューニングできます。より大きなモデルのフルファインチューニングには、より多くのメモリが必要です。70B以上のモデルを本番用にファインチューニングする場合は、GPUサーバーの方が現実的です。

Ollama、llama.cpp、MLXのどのフレームワークを選ぶべきですか?

最速のセットアップと簡単なAPI提供が欲しいならOllamaを選びましょう。推論パラメータの最大限の制御と、GGUFモデルの最高のパフォーマンスが欲しいならllama.cppを。Python MLパイプラインを構築し、ネイティブなApple Silicon最適化が欲しいならMLXを選びましょう。多くのユーザーはOllamaから始め、ニーズが拡大するにつれてllama.cppやMLXへ移行します。

関連ガイド

Apple SiliconでLLMの実行を始めましょう

専用Mac Mini M4サーバーを手に入れ、Llama、Mistral、Phiを無制限の推論で実行しましょう。月額$85から。

さらに詳しい情報をお探しですか?

ステップバイステップのセットアップ手順、設定リファレンス、トラブルシューティングについては、完全なドキュメントをご覧ください。

ドキュメントを開く →