大模型在云端API调用有延迟和隐私风险,而直接在服务器上部署推理服务可以实现毫秒级响应。本文从模型格式转换到高并发API,给出完整的AI推理服务部署方案。
一、推理服务架构选择
| 方案 | 适用场景 | 性能 | 部署复杂度 |
|---|---|---|---|
| ONNX Runtime(CPU) | 图像分类、NLP小模型 | 中等 | 低 |
| ONNX Runtime(CUDA) | 中等规模模型,有GPU | 高 | 中等 |
| TensorRT | NVIDIA GPU,极致优化 | 极高 | 高 |
| Ollama(LLM) | 大语言模型推理 | 中等 | 低 |
| Triton Inference Server | 企业级,多模型多框架 | 极高 | 极高 |
二、模型转换为ONNX格式
<code"># pip install torch torchvision onnx onnxruntime --break-system-packages
# 将PyTorch模型转换为ONNX
import torch
import torch.onnx
# 1. 加载训练好的模型
model = YourModel()
model.load_state_dict(torch.load('model.pth', map_location='cpu'))
model.eval()
# 2. 创建示例输入(用于追踪模型形状)
dummy_input = torch.randn(1, 3, 224, 224) # 批次=1, 通道=3, 高=224, 宽=224
# 3. 导出ONNX
torch.onnx.export(
model,
dummy_input,
"model.onnx",
opset_version=17, # ONNX算子集版本
input_names=['input'],
output_names=['output'],
dynamic_axes={
'input': {0: 'batch_size'}, # batch维度动态,支持批量推理
'output': {0: 'batch_size'},
},
do_constant_folding=True, # 常量折叠优化
)
print("ONNX模型已导出")
# 4. 验证ONNX模型
import onnx
onnx_model = onnx.load("model.onnx")
onnx.checker.check_model(onnx_model)
print("ONNX模型验证通过")
三、ONNX Runtime优化配置
<code"># 高性能ONNX推理服务
import onnxruntime as ort
import numpy as np
from PIL import Image
import time
class ImageClassifier:
def __init__(self, model_path: str, use_gpu: bool = False):
# 会话配置(性能关键)
options = ort.SessionOptions()
options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
options.intra_op_num_threads = 4 # 单次推理使用的线程数
options.inter_op_num_threads = 2 # 并行推理使用的线程数
# 执行提供者(按优先级排列)
if use_gpu:
providers = [
('CUDAExecutionProvider', {
'device_id': 0,
'arena_extend_strategy': 'kNextPowerOfTwo',
'gpu_mem_limit': 2 * 1024 * 1024 * 1024, # 限制2GB GPU内存
'cudnn_conv_algo_search': 'EXHAUSTIVE', # 搜索最优卷积算法
}),
'CPUExecutionProvider', # GPU失败时降级到CPU
]
else:
providers = [
('CPUExecutionProvider', {
'arena_extend_strategy': 'kSameAsRequested',
}),
]
self.session = ort.InferenceSession(
model_path,
sess_options=options,
providers=providers,
)
# 获取输入输出信息
self.input_name = self.session.get_inputs()[0].name
self.output_name = self.session.get_outputs()[0].name
self.input_shape = self.session.get_inputs()[0].shape
print(f"模型加载成功,输入形状:{self.input_shape}")
print(f"执行提供者:{self.session.get_providers()}")
# 预热(第一次推理有编译开销)
self._warmup()
def _warmup(self, num_runs: int = 3):
dummy = np.random.randn(1, 3, 224, 224).astype(np.float32)
for _ in range(num_runs):
self.session.run([self.output_name], {self.input_name: dummy})
print("模型预热完成")
def preprocess(self, image_path: str) -> np.ndarray:
img = Image.open(image_path).convert('RGB').resize((224, 224))
arr = np.array(img, dtype=np.float32) / 255.0
# ImageNet标准化
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
arr = (arr - mean) / std
return arr.transpose(2, 0, 1)[np.newaxis, ...] # HWC → NCHW
def predict(self, image_path: str) -> dict:
start = time.time()
input_data = self.preprocess(image_path)
outputs = self.session.run([self.output_name], {self.input_name: input_data})
logits = outputs[0][0]
probs = np.exp(logits) / np.exp(logits).sum()
top5_idx = probs.argsort()[-5:][::-1]
latency = (time.time() - start) * 1000
return {
'predictions': [
{'class_id': int(i), 'confidence': float(probs[i])}
for i in top5_idx
],
'latency_ms': round(latency, 2),
}
def batch_predict(self, image_paths: list) -> list:
"""批量推理(比逐张推理快)"""
batch = np.concatenate([self.preprocess(p) for p in image_paths])
outputs = self.session.run([self.output_name], {self.input_name: batch})
return outputs[0]
# 使用
classifier = ImageClassifier("model.onnx", use_gpu=False)
result = classifier.predict("/tmp/test.jpg")
print(f"推理结果:{result['predictions'][:1]}, 延迟:{result['latency_ms']}ms")
四、模型量化(压缩模型体积和加速推理)
<code"># INT8量化(模型体积缩小4倍,速度提升2~4倍,精度损失<1%)
from onnxruntime.quantization import quantize_dynamic, QuantType
# 动态量化(不需要校准数据集,适合NLP模型)
quantize_dynamic(
model_input='model.onnx',
model_output='model_int8.onnx',
weight_type=QuantType.QInt8,
optimize_model=True,
)
# 静态量化(需要校准数据集,适合CV模型,效果更好)
from onnxruntime.quantization import quantize_static, CalibrationDataReader
class ImageCalibrationReader(CalibrationDataReader):
def __init__(self, calibration_images):
self.images = calibration_images
self.enum = iter(calibration_images)
def get_next(self):
try:
img_path = next(self.enum)
data = preprocess_image(img_path)
return {'input': data}
except StopIteration:
return None
# 用100张代表性图片做校准
calibration_reader = ImageCalibrationReader(calibration_images[:100])
quantize_static(
model_input='model.onnx',
model_output='model_int8_static.onnx',
calibration_data_reader=calibration_reader,
)
# 量化效果对比:
# FP32原始模型:100MB,延迟15ms
# INT8量化后: 25MB,延迟6ms(速度2.5倍)
# 精度损失: Top-1 Accuracy 76.1% → 75.8%(-0.3%,可接受)
五、FastAPI推理服务
<code"># api.py - 高并发推理API
from fastapi import FastAPI, UploadFile, File, HTTPException
from concurrent.futures import ThreadPoolExecutor
import asyncio
app = FastAPI(title="AI推理服务")
# 单例模式加载模型(只加载一次)
classifier = ImageClassifier("model_int8.onnx")
# 线程池(推理是CPU密集型,使用线程池避免阻塞事件循环)
executor = ThreadPoolExecutor(max_workers=4)
@app.post("/predict/image")
async def predict_image(file: UploadFile = File(...)):
if not file.content_type.startswith('image/'):
raise HTTPException(status_code=400, detail="只支持图片文件")
# 保存临时文件
tmp_path = f"/tmp/{file.filename}"
content = await file.read()
with open(tmp_path, 'wb') as f:
f.write(content)
# 在线程池中运行推理(不阻塞async事件循环)
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(executor, classifier.predict, tmp_path)
return result
@app.get("/model/info")
async def model_info():
return {
"model": "ResNet50-INT8",
"input_shape": [1, 3, 224, 224],
"providers": classifier.session.get_providers(),
}
# uvicorn api:app --host 0.0.0.0 --port 8001 --workers 2
六、性能基准
<code"># 在4核CPU VPS上的推理性能(ResNet50 ImageNet分类): # FP32 ONNX: 约15ms/张,约65 QPS(单线程) # INT8 ONNX: 约6ms/张,约165 QPS(单线程) # INT8 + 4线程批量推理:约400 QPS # 压测 wrk -t4 -c50 -d30s -s post_image.lua http://localhost:8001/predict/image # Running 30s test... 4 threads and 50 connections # Requests/sec: 312 # Latency P99: 45ms
七、总结
ONNX Runtime + INT8量化是CPU推理的黄金组合:体积缩小4倍、速度提升2~4倍、精度损失<1%。对于图像分类、目标检测、NLP分类等任务,CPU推理完全可以满足生产需求(100~500 QPS)。IDC.Net的香港VPS高主频CPU(>3GHz)对推理性能有显著帮助,4核VPS可以轻松支撑数百QPS的AI推理服务,且数据完全在本地处理,无隐私泄露风险。
