随着开源大模型的快速发展,在本地与服务端高效部署 AI 大模型已成为开发者的必备技能。本文将围绕本地推理、API 服务化以及容器化封装三个核心维度,分享一套生产级的落地方案。
一、整体架构概览
整个部署流程通常涵盖从开发调试到团队协作,最终交付生产环境。技术选型上,我们主要关注模型加载方式(如 llama.cpp、vLLM)、服务框架(FastAPI)以及容器编排(Docker)。性能调优与监控运维则是保障稳定性的关键。
二、模型选型与技术栈
| 维度 | 推荐方案 | 适用场景 |
|---|---|---|
| 本地推理 | llama.cpp / Ollama | 个人开发、低资源环境 |
| GPU 推理 | vLLM / TGI | 高并发、低延迟 |
| API 框架 | FastAPI | 轻量、高性能 |
| 容器化 | Docker + NVIDIA Container Toolkit | 标准化部署 |
| 编排 | docker-compose / K8s | 多服务协同 |
三、方案一:本地运行大模型
3.1 环境准备
首先创建独立的虚拟环境,避免依赖冲突。Linux/macOS 下使用 source llm-env/bin/activate,Windows 则用 llm-env\Scripts\activate。
# 安装核心依赖
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124
pip install transformers accelerate sentencepiece
3.2 使用 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", : prompt}]
input_ids = tokenizer.apply_chat_template(messages, return_tensors=).to(model.device)
torch.no_grad():
outputs = model.generate(
input_ids,
max_new_tokens=max_new_tokens,
temperature=,
top_p=,
do_sample=,
)
response = tokenizer.decode(outputs[][input_ids.shape[-]:], skip_special_tokens=)
response
__name__ == :
result = chat()
(result)


