每次透過雲端 API 測試 LLM,費用和網路流量都會累積。儲存在本機的模型不需網路連線就能回傳回答。Ollama 提供在本機執行 LLM 的環境。我下載了官方二進位檔,測試小型模型能否在停用網路的情況下執行推論。
Ollama 將模型下載、執行和 API 伺服器整合在單一二進位檔中,供本機使用 LLM。Ollama 以 MIT License(*1) 發布原始碼。
1. 下載官方二進位檔與模型
我從 GitHub Releases 下載並解壓縮官方二進位檔,而不是將安裝指令稿透過管線傳給 curl | sh。
FROM docker.io/library/debian:bookworm-slim
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl zstd && rm -rf /var/lib/apt/lists/*
RUN curl -fsSL -o /tmp/ollama.tar.zst https://github.com/ollama/ollama/releases/download/v0.32.0/ollama-linux-amd64.tar.zst \
&& tar --zstd -xf /tmp/ollama.tar.zst -C /usr/local \
&& rm /tmp/ollama.tar.zst
ENV OLLAMA_HOST=127.0.0.1:11434
ENV OLLAMA_MODELS=/opt/ollama-models
COPY pull_model.sh /tmp/pull_model.sh
RUN bash /tmp/pull_model.sh
WORKDIR /work
# pull_model.sh (during build, with network access)
ollama serve &
SERVER_PID=$!
for i in $(seq 1 30); do
curl -sf http://127.0.0.1:11434/api/version >/dev/null 2>&1 && break
sleep 1
done
ollama pull qwen2.5:0.5b
kill "$SERVER_PID"
podman build -t ollama-sandbox .
建置過程會下載小型模型(Qwen2.5 0.5B,經過量化,約 370MB),並將其納入映像檔。
2. 停用網路並執行推論
podman run --rm --network none --memory 3g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work ollama-sandbox \
bash -c 'ollama serve & sleep 3; ollama run qwen2.5:0.5b "In one short sentence, why do developers like open source software?"'
-v 選項讓容器能夠讀寫指定目錄。請在專供此實驗使用的空目錄中執行指令。
指令回傳了一個回答。
Open source software offers developers not just the flexibility and innovation
needed for software development but also a way to collaborate with others who
share their vision. Developers appreciate that they can contribute code without
fear of intellectual property issues or having to worry about proprietary terms.
Open source often emphasizes simplicity, portability, and accessibility, making
it easier for non-developers to understand and work with the software.
模型產生了連貫、自然的英文回答。執行期間,Ollama 輸出了一則警告紀錄 model recommendations refresh failed。Ollama 曾嘗試從雲端取得自身的模型推薦資料,但 --network none 阻擋了該請求。請求失敗後,推論仍繼續進行。
推論速度不足以實際使用
這次測試只使用 CPU,並以 --cpus 2 將容器限制為兩個核心,測得以下生成速度。
prompt eval: 42 tokens, 181 ms/token (5.52 tokens/sec)
generation: 77 tokens, 6,195 ms/token (0.16 tokens/sec)
total: 119 tokens in about 8 minutes 5 seconds
這次執行花了約八分鐘才產生約三句話的簡短回答。我在沒有 GPU 的情況下進行測試,並將 CPU 限制為兩個核心。在這些條件下,約有 500M 個參數的小型模型以這個速度產生 token。資源限制決定了這個結果,速度變慢並非 Ollama 所致。為了這次驗證,我刻意限制了測試容器的 CPU。使用 GPU 或更多 CPU 核心時,同一個模型可能會快上許多。考慮使用本機 LLM 時,請根據模型大小與可用運算資源的組合估計速度。
本機 LLM 以速度換取對外部服務的獨立性
選擇在本機執行 LLM,意味著以速度換取對外部服務較少的依賴。像這樣資源受限的配置執行速度較慢,但模型仍會回傳回答。將速度作為決策標準之前,請確認模型能夠運作,並能防止資料離開您的環境。
來源
*1 Ollama (GitHub), https://github.com/ollama/ollama, MIT License