在 AI 中台架構中,「地端模型」是保障敏感資料不外流的核心防線。當系統判定問題包含內部專案程式碼、架構機密或未公開 API 規格時,必須強制將請求導向企業內部的推論伺服器。
今天將實戰部署地端推論環境,評估 Ollama 與 vLLM 兩種推論框架,並透過基準測試(Benchmarking)驗證推論延遲與資源消耗。
| 評估維度 | Ollama | vLLM |
|---|---|---|
| 核心優勢 | 輕量、開箱即用、支援 CPU/GPU 混合推論 | 高吞吐量、PagedAttention 技術、原生連續批次處理(Continuous Batching) |
| API 相容性 | 原生相容 OpenAI API 規範 | 原生相容 OpenAI API 規範 |
| 適用場景 | 本機開發、邊緣節點、低併發驗證 | 企業級高併發推論集群、生產環境伺服器 |
| 部署門檻 | 極低(單一二進位檔 / Docker) | 中等(需配置 CUDA 環境與顯存參數) |
使用 Docker 啟動 Ollama 容器,並拉取針對程式碼優化的模型(以 qwen2.5-coder:7b 為例):
# 啟動 Ollama 容器(啟用 GPU 支援)
docker run -d --gpus=all -v ollama_data:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
# 下載開發輔助專用模型
docker exec -it ollama ollama pull qwen2.5-coder:7b
驗證 API 端點相容性:
curl http://localhost:11434/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "qwen2.5-coder:7b",
"messages": [
{"role": "user", "content": "請用 Python 寫一個二元搜尋演算法並加上型別標註"}
],
"temperature": 0.2
}'
vLLM 具備 PagedAttention 記憶體管理機制,能大幅提升多連線併發時的吞吐量(Throughput)。
建立 docker-compose.vllm.yml 配置檔:
version: '3.8'
services:
vllm:
image: vllm/vllm-openai:latest
container_name: vllm_server
runtime: nvidia
environment:
- HUGGING_FACE_HUB_TOKEN=${HF_TOKEN}
ports:
- "8000:8000"
volumes:
- ~/.cache/huggingface:/root/.cache/huggingface
ipc: host
command: >
--model Qwen/Qwen2.5-Coder-7B-Instruct
--gpu-memory-utilization 0.90
--max-model-len 4096
--port 8000
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: all
capabilities: [gpu]
啟動服務:
docker compose -f docker-compose.vllm.yml up -d
在中台架構中,必須量化評估模型的兩大核心指標:
撰寫 Python 測試腳本 benchmark_local.py 進行量測:
import time
from openai import OpenAI
# 指向地端推論節點 (Ollama: 11434 / vLLM: 8000)
client = OpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama" # 地端服務填入任意非空字串即可
)
prompt = "請詳細解釋什麼是 RESTful API 的冪等性 (Idempotence),並舉例說明 GET、POST、PUT、DELETE 的差異。"
start_time = time.time()
first_token_time = None
token_count = 0
response = client.chat.completions.create(
model="qwen2.5-coder:7b",
messages=[{"role": "user", "content": prompt}],
stream=True,
temperature=0.1
)
print("--- 生成回覆開始 ---")
for chunk in response:
if chunk.choices and chunk.choices[0].delta.content:
if first_token_time is None:
first_token_time = time.time()
content = chunk.choices[0].delta.content
print(content, end="", flush=True)
token_count += 1
print("\n--- 生成回覆結束 ---")
end_time = time.time()
ttft = (first_token_time - start_time) if first_token_time else 0
total_time = end_time - start_time
tps = token_count / (total_time - ttft) if (total_time - ttft) > 0 else 0
print(f"\n[效能統計數據]")
print(f"首字延遲 (TTFT): {ttft:.3f} 秒")
print(f"總耗時: {total_time:.3f} 秒")
print(f"生成 Token 總數: {token_count}")
print(f"每秒生成速率 (TPS): {tps:.2f} tokens/s")
顯存佔用分配(GPU Memory Utilization):
Context Window 長度設定:
KV Cache 量化:
完成地端推論基建後,明天 Day 04 將進入多雲端模型介面抽象化,統一封裝 OpenAI、Claude 與 Gemini 的 Client 介面,並實作跨 Provider 的自動容錯降級(Fallback)機制。