要在本地跑大模型,或者对外提供 API,最后打包成镜像交付,整个流程里踩的坑不算少。这里记一下我用到的三种方式,从单机调试到容器化部署都覆盖到了,可以当成一份可落地的参考。
整体看,部署流程分三步:先在本地把模型跑通,再封装成 HTTP 接口,最后用 Docker 打包成标准服务。技术栈上,本地推理用 llama.cpp 或 Ollama 很省资源;GPU 推理首选 vLLM;API 框架 FastAPI 足够轻量;容器化用 Docker + NVIDIA Container Toolkit。性能优化和监控运维是后面的保底工作。
本地运行大模型
环境准备
建议开一个独立虚拟环境,免得依赖打架:
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124
pip install transformers accelerate sentencepiece
激活环境的话,Linux/macOS 用 source llm-env/bin/activate,Windows 用 llm-env\\Scripts\\activate。
用 transformers 快速加载
如果想快速验证,直接用 transformers 拉一个量化模型。以 Qwen 为例,device_map=\"auto\" 会自动分配显存。
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model_id = \"Qwen/Qwen2.5-72B-Instruct-GPTQ-Int4\"
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id,
device_map=\"auto\",
torch_dtype=torch.float16,
trust_remote_code=True,
)
def chat(prompt: str, max_new_tokens: int = 512) -> str:
messages = [{\"role\": \"user\", \"content\": prompt}]
input_ids = tokenizer.apply_chat_template(messages, return_tensors=\"pt\").to(model.device)
with torch.no_grad():
outputs = model.generate(
input_ids,
max_new_tokens=max_new_tokens,
temperature=0.7,
top_p=0.9,
do_sample=True,
)
response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
return response
if __name__ == \"__main__\":
result = chat(\"用 Python 写一个快速排序算法,并解释其时间复杂度。\")
print(result)
用 llama.cpp 榨干 CPU/GPU
资源吃紧或者需要跨平台时,llama.cpp 更好用。编译的时候记得开 CUDA。
CMAKE_ARGS=\"-DGGML_CUDA=on\" pip install llama-cpp-python
huggingface-cli download \\
Qwen/Qwen2.5-7B-Instruct-GGUF \\
qwen2.5-7b-instruct-q4_k_m.gguf \\
--localdir ./models
from llama_cpp import Llama
llm = Llama(
model_path=\"./models/qwen2.5-7b-instruct-q4_k_m.gguf\",
n_ctx=4096,
n_gpu_layers=-1, # 全部卸载到 GPU
verbose=False,
)
response = llm.create_chat_completion(
messages=[{\"role\": \"user\", \"content\": \"解释 Transformer 的自注意力机制\"}],
temperature=0.7,
max_tokens=1024,
)
print(response[\"choices\"][0][\"message\"][\"content\"])


