手头只有一台没有显卡的服务器,也想跑一个能直接用 OpenAI 接口调用的本地模型,于是有了这篇记录:从装依赖到起服务,全程纯 CPU,用 llama.cpp + GGUF 量化方案。

0. 目标

在 Linux 服务器上,用 llama.cpp + CPU 启动 Qwen3.5-4B(GGUF),并提供 OpenAI 兼容 API。

1. 安装依赖

sudo apt update
sudo apt install -y git build-essential cmake python3 python3-venv python3-pip

2. 编译 llama.cpp(CPU)

mkdir -p ~/work && cd ~/work
git clone https://github.com/ggml-org/llama.cpp.git
cd llama.cpp
cmake -B build
cmake --build build -j

编译完成后,可执行文件一般在:

~/work/llama.cpp/build/bin/llama-server

3. 安装 Hugging Face 下载工具

cd ~/work
python3 -m venv .venv
source .venv/bin/activate
pip install -U huggingface_hub[cli]

4. 下载 Qwen3.5-4B 的 GGUF 模型

4.1 先查有哪些可用仓库(含 GGUF)

python - <<'PY'
from huggingface_hub import HfApi

api = HfApi()
for m in api.list_models(search="Qwen3.5 4B GGUF", limit=30):
    print(m.id)
PY

4.2 选定一个仓库后,查看文件名

python - <<'PY'
from huggingface_hub import list_repo_files

repo = "这里填上一步找到的 repo_id"
for f in list_repo_files(repo, repo_type="model"):
    if f.lower().endswith(".gguf"):
        print(f)
PY

4.3 下载一个量化版本(推荐先上 Q4_K_M)

hf download <repo_id> \
  --include "*Q4_K_M.gguf" \
  --local-dir ~/work/models/qwen35-4b
如果内存足够,也可以试 Q6_K / Q8_0,效果更好,但更慢、更占内存。

5. CPU 启动模型(OpenAI 兼容 API)

cd ~/work/llama.cpp
./build/bin/llama-server \
  -m ~/work/models/qwen35-4b/你的模型文件名-Q4_K_M.gguf \
  -c 4096 \
  -t 8 \
  --host 127.0.0.1 \
  --port 8000

参数说明(简版):

  • -m:模型文件路径
  • -c 4096:上下文长度
  • -t 8:CPU 线程数,建议设为 CPU 核数或略低
  • --host 127.0.0.1:仅本机访问,更安全

6. 测试接口是否可用

curl http://127.0.0.1:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen35-4b",
    "messages": [{"role": "user", "content": "你好,介绍一下你自己"}],
    "temperature": 0.7
  }'

返回 JSON 且带有 choices 字段,就说明服务正常。

7. 可选:对外开放 + 鉴权

如果需要从外网访问,把 --host 改成 0.0.0.0,并在防火墙里放行对应端口。

部分版本支持 --api-key,可以先确认一下:

./build/bin/llama-server --help | grep -i key

如果支持,启动时加上:

--api-key "你的密钥"

客户端请求则需要带上鉴权头:

-H "Authorization: Bearer 你的密钥"