← 研究笔记
无需云服务运行 LLM:Ollama 实测

无需云服务运行 LLM:Ollama 实测

在禁用网络的情况下测试 Ollama 这一本地 LLM 运行时。推理成功了,但仅使用两个 CPU 核心的纯 CPU 环境无法达到实用的速度。

本文涉及的仓库

ollama/ollama

Get up and running with Kimi-K2.6, GLM-5.1, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

176.2k Go MIT License

每次通过云 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