使用 llama.cpp 在本地 CPU/GPU 高效運行大型語言模型,支援 GGUF 格式和量化優化
專案簡介
llama.cpp 是一個純 C/C++ 實作的 LLM 推理引擎,無需 GPU 即可高效運行大型語言模型。支援多種硬體加速,是本地 LLM 部署的首選方案。
GitHub Stars: 94K+
主要功能
- 純 C/C++ - 無 Python 依賴
- CPU 優化 - AVX、AVX2、AVX512 加速
- GPU 支援 - CUDA、Metal、Vulkan
- 量化支援 - 2-8 bit 量化減少記憶體
- GGUF 格式 - 高效模型格式
安裝
從原始碼編譯
1
2
3
4
5
6
7
8
9
10
11
| git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp
# CPU 版本
make
# CUDA 版本
make GGML_CUDA=1
# Metal 版本(macOS)
make GGML_METAL=1
|
使用 CMake
1
2
3
| mkdir build && cd build
cmake .. -DGGML_CUDA=ON
cmake --build . --config Release
|
下載模型
從 HuggingFace 下載
1
2
3
4
5
| # 安裝 huggingface-cli
pip install huggingface-hub
# 下載 GGUF 模型
huggingface-cli download TheBloke/Llama-2-7B-GGUF llama-2-7b.Q4_K_M.gguf
|
常用量化版本
| 量化等級 | 大小 | 品質 | 速度 |
|---|
| Q2_K | 最小 | 較低 | 最快 |
| Q4_K_M | 中等 | 良好 | 快 |
| Q5_K_M | 較大 | 優秀 | 中等 |
| Q8_0 | 大 | 接近原始 | 較慢 |
基本使用
命令列推理
1
2
3
4
5
| # 互動模式
./llama-cli -m llama-2-7b.Q4_K_M.gguf -p "Hello, how are you?" -n 128
# 對話模式
./llama-cli -m llama-2-7b.Q4_K_M.gguf --chat-template llama2 -cnv
|
參數說明
1
2
3
4
5
6
| -m, --model # 模型檔案路徑
-p, --prompt # 輸入提示詞
-n, --predict # 生成 token 數量
-c, --ctx-size # 上下文大小
-t, --threads # CPU 執行緒數
-ngl, --gpu-layers # GPU 層數
|
Server 模式
啟動 API Server
1
| ./llama-server -m llama-2-7b.Q4_K_M.gguf --host 0.0.0.0 --port 8080
|
OpenAI 相容 API
1
2
3
4
5
6
7
8
| curl http://localhost:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "llama-2-7b",
"messages": [
{"role": "user", "content": "什麼是 Kubernetes?"}
]
}'
|
Python 整合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| from openai import OpenAI
client = OpenAI(
base_url="http://localhost:8080/v1",
api_key="not-needed"
)
response = client.chat.completions.create(
model="llama-2-7b",
messages=[
{"role": "user", "content": "解釋什麼是容器化"}
]
)
print(response.choices[0].message.content)
|
GPU 加速
CUDA 設定
1
2
3
4
5
| # 將所有層載入 GPU
./llama-cli -m model.gguf -ngl 99
# 部分層載入 GPU(記憶體不足時)
./llama-cli -m model.gguf -ngl 20
|
記憶體需求
| 模型大小 | Q4_K_M | Q8_0 |
|---|
| 7B | ~4 GB | ~7 GB |
| 13B | ~8 GB | ~14 GB |
| 70B | ~40 GB | ~70 GB |
效能優化
CPU 優化
1
2
3
4
5
| # 設定執行緒數
./llama-cli -m model.gguf -t 8
# 啟用 mmap
./llama-cli -m model.gguf --mmap
|
Batch 處理
1
2
| # 增加 batch size
./llama-server -m model.gguf -b 512 --parallel 4
|
模型轉換
轉換為 GGUF
1
2
3
4
5
| # 從 HuggingFace 格式轉換
python convert_hf_to_gguf.py ./model_dir --outtype f16
# 量化
./llama-quantize model-f16.gguf model-q4_k_m.gguf Q4_K_M
|
Docker 部署
1
2
3
4
5
| docker run -p 8080:8080 \
-v /path/to/models:/models \
ghcr.io/ggerganov/llama.cpp:server \
-m /models/llama-2-7b.Q4_K_M.gguf \
--host 0.0.0.0 --port 8080
|
相關連結
延伸閱讀