TorchScript、ONNX Runtime、TensorRT推理加速,KV Cache自回归生成,FastAPI模型服务化,端侧部署全流程实践
TorchScript是PyTorch的模型序列化格式,将动态Python模型转换为静态图表示,可以在没有Python解释器的环境中运行。它是部署PyTorch模型到C++生产环境的基础。
TorchScript有两种转换方式,各有适用场景:
import torch
import torch.nn as nn
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(100, 50)
self.fc2 = nn.Linear(50, 10)
def forward(self, x):
x = torch.relu(self.fc1(x))
return self.fc2(x)
model = MyModel().eval()
# 方式1: torch.jit.script — 解析Python源码
# 优点: 支持控制流(if/for/while),准确捕获模型逻辑
# 缺点: 要求代码符合TorchScript子集规范
scripted_model = torch.jit.script(model)
# 方式2: torch.jit.trace — 用示例输入追踪执行路径
# 优点: 简单,几乎不需要修改代码
# 缺点: 丢失控制流,只记录追踪时的执行路径
example_input = torch.randn(1, 100)
traced_model = torch.jit.trace(model, example_input)
# 验证结果一致
test_input = torch.randn(5, 100)
print(f"Script差异: {(model(test_input) - scripted_model(test_input)).abs().max():.8f}")
print(f"Trace差异: {(model(test_input) - traced_model(test_input)).abs().max():.8f}")
| 特性 | torch.jit.script | torch.jit.trace |
|---|---|---|
| 控制流(if/for/while) | ✓ 支持 | ✗ 丢失 |
| 动态形状 | ✓ 支持 | ✓ 部分支持 |
| 代码修改需求 | 可能需要 | 几乎不需要 |
| 准确性 | 高(解析源码) | 依赖追踪输入 |
| 适用场景 | 有控制流的模型 | 纯计算图模型 |
# 保存 (不依赖Python类定义)
scripted_model.save("model_scripted.pt")
# 加载 (无需原始类定义)
loaded_model = torch.jit.load("model_scripted.pt")
# 在C++中加载 (libtorch)
# auto model = torch::jit::load("model_scripted.pt");
# auto output = model.forward({input}).toTensor();
# 优化模型 (融合算子)
optimized_model = torch.jit.optimize_for_inference(loaded_model)
# 限制1: 不支持所有Python特性
class ModelWithControlFlow(nn.Module):
def forward(self, x, mode):
# script支持: 控制流必须是Tensor类型相关的
if mode == "train": # ✓ script可以处理
return self.fc1(x)
else:
return self.fc2(x)
# 限制2: trace无法捕获数据依赖的控制流
class DataDependent(nn.Module):
def forward(self, x):
if x.sum() > 0: # trace会丢失这个分支!
return x * 2
else:
return x * -1
# 必须用script处理数据依赖控制流
model = DataDependent()
scripted = torch.jit.script(model) # ✓ 正确
# traced = torch.jit.trace(model, torch.randn(10)) # ✗ 危险!
ONNX Runtime是微软开发的高性能推理引擎,支持多种硬件加速器。相比PyTorch原生推理,通常有2-5倍加速。
import onnxruntime as ort
import numpy as np
import time
# 基本推理Session
session = ort.InferenceSession(
"model.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"]
)
# 查看输入输出信息
for inp in session.get_inputs():
print(f"输入: {inp.name}, 形状: {inp.shape}, 类型: {inp.type}")
for out in session.get_outputs():
print(f"输出: {out.name}, 形状: {out.shape}, 类型: {out.type}")
# 推理
input_data = np.random.randn(32, 100).astype(np.float32)
outputs = session.run(None, {"input": input_data})
print(f"输出形状: {outputs[0].shape}")
# IO Binding: 预分配输入输出缓冲区
def inference_with_iobinding(session, input_data):
binding = session.io_binding()
# 绑定输入 (直接在GPU上)
input_tensor = ort.OrtValue.ortvalue_from_numpy(
input_data, device_type="cuda", device_id=0
)
binding.bind_ortvalue_input("input", input_tensor)
# 预分配输出
output_shape = [input_data.shape[0], 10]
binding.bind_output(
"output", output_shape, input_data.dtype,
device_type="cuda", device_id=0
)
# 执行推理 (无需CPU-GPU拷贝)
session.run_with_iobinding(binding)
# 获取结果
output = binding.get_output_value(0)
return output
# 性能对比
input_data = np.random.randn(1000, 100).astype(np.float32)
# 普通推理
t0 = time.time()
for _ in range(100):
session.run(None, {"input": input_data})
time_normal = (time.time() - t0) / 100
# IO Binding推理
t0 = time.time()
for _ in range(100):
inference_with_iobinding(session, input_data)
time_binding = (time.time() - t0) / 100
print(f"普通: {time_normal*1000:.2f}ms | IO绑定: {time_binding*1000:.2f}ms")
# 高级Session配置
sess_options = ort.SessionOptions()
# 图优化级别
sess_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
# 线程控制
sess_options.intra_op_num_threads = 4 # 算子内并行
sess_options.inter_op_num_threads = 2 # 算子间并行
# 执行模式
sess_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
# 内存图案优化
sess_options.enable_mem_pattern = True
sess_options.enable_cpu_mem_arena = True
# 创建优化后的Session
session = ort.InferenceSession(
"model.onnx",
sess_options=sess_options,
providers=["CUDAExecutionProvider"],
provider_options=[{
"device_id": 0,
"arena_extend_strategy": "kSameAsRequested",
"cudnn_conv_use_max_workspace": "1",
}]
)
| 引擎 | 优势 | 硬件支持 | 易用性 | 典型加速 |
|---|---|---|---|---|
| PyTorch原生 | 无需转换 | CPU/GPU | 最简单 | 1x (基准) |
| ONNX Runtime | 跨平台优化 | CPU/GPU/NPU | 简单 | 2-3x |
| TensorRT | NVIDIA极致优化 | 仅NVIDIA GPU | 中等 | 3-5x |
| OpenVINO | Intel硬件优化 | Intel CPU/VPU | 中等 | 2-4x |
TensorRT是NVIDIA的高性能深度学习推理优化器,针对NVIDIA GPU进行极致优化,包括层融合、精度校准、kernel自动调优等。
from torch2trt import torch2trt
import torch
model = MyModel().eval().cuda()
example_input = torch.randn(1, 100).cuda()
# 转换为TensorRT引擎 (FP32)
model_trt = torch2trt(
model,
[example_input],
fp16_mode=True, # 启用FP16
max_batch_size=32, # 最大batch大小
)
# 推理 (接口与PyTorch一致)
test_input = torch.randn(16, 100).cuda()
output_trt = model_trt(test_input)
output_pytorch = model(test_input)
print(f"TRT vs PyTorch差异: {(output_trt - output_pytorch).abs().max():.6f}")
# 使用ONNX-TensorRT pipeline支持动态batch
import tensorrt as trt
# 创建Builder和Network
logger = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(logger)
network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
# 配置动态batch
profile = builder.create_optimization_profile()
profile.set_shape("input",
min=(1, 100), # 最小batch=1
opt=(16, 100), # 最优batch=16
max=(64, 100) # 最大batch=64
)
config = builder.create_builder_config()
config.add_optimization_profile(profile)
config.set_flag(trt.BuilderFlag.FP16) # FP16精度
# 构建引擎
engine = builder.build_engine(network, config)
# INT8校准需要校准数据集
class Int8Calibrator(trt.IInt8Calibrator):
def __init__(self, calibration_data, batch_size=32):
trt.IInt8Calibrator.__init__(self)
self.data = calibration_data
self.batch_size = batch_size
self.index = 0
def get_batch(self, names):
if self.index >= len(self.data):
return None
batch = self.data[self.index:self.index + self.batch_size]
self.index += self.batch_size
return [batch.ravel()]
def get_algorithm(self):
return trt.CalibrationAlgoType.ENTROPY_CALIBRATION_2
# 使用INT8校准构建引擎
calibrator = Int8Calibrator(calibration_data)
config.set_flag(trt.BuilderFlag.INT8)
config.int8_calibrator = calibrator
在大规模推理场景中,吞吐量(throughput)比单次延迟更重要。动态批处理(dynamic batching)是提升吞吐量的关键技术。
import torch
from collections import deque
import threading
import time
class DynamicBatcher:
def __init__(self, model, max_batch_size=32, max_wait_ms=10):
self.model = model
self.max_batch_size = max_batch_size
self.max_wait_ms = max_wait_ms
self.queue = deque()
self.lock = threading.Lock()
self.running = True
self.worker = threading.Thread(target=self._process)
self.worker.start()
def submit(self, input_tensor):
# 提交单个请求
result_holder = {"output": None, "done": False}
with self.lock:
self.queue.append((input_tensor, result_holder))
while not result_holder["done"]:
time.sleep(0.001)
return result_holder["output"]
def _process(self):
while self.running:
batch = []
with self.lock:
while len(batch) < self.max_batch_size and self.queue:
batch.append(self.queue.popleft())
if batch:
inputs = torch.stack([item[0] for item in batch])
with torch.no_grad():
outputs = self.model(inputs)
for i, (_, holder) in enumerate(batch):
holder["output"] = outputs[i]
holder["done"] = True
else:
time.sleep(self.max_wait_ms / 1000)
# 使用动态batcher
batcher = DynamicBatcher(model, max_batch_size=32)
result = batcher.submit(torch.randn(100))
# 变长序列的batch推理 — 不同padding策略
def batch_inference_with_padding(model, sequences):
# 策略1: pad到batch内最大长度
max_len = max(len(s) for s in sequences)
padded = torch.zeros(len(sequences), max_len, dtype=torch.long)
attention_mask = torch.zeros(len(sequences), max_len)
for i, s in enumerate(sequences):
padded[i, :len(s)] = s
attention_mask[i, :len(s)] = 1
with torch.no_grad():
outputs = model(padded, attention_mask=attention_mask)
return outputs
# 策略2: 按长度排序后分batch (减少padding)
def sorted_batch_inference(model, sequences, batch_size=32):
# 按长度排序
indexed = sorted(enumerate(sequences), key=lambda x: len(x[1]))
results = [None] * len(sequences)
# 分组推理
for i in range(0, len(indexed), batch_size):
batch = indexed[i:i+batch_size]
batch_seqs = [s for _, s in batch]
batch_indices = [idx for idx, _ in batch]
outputs = batch_inference_with_padding(model, batch_seqs)
for j, idx in enumerate(batch_indices):
results[idx] = outputs[j]
return results
| 技巧 | 原理 | 效果 | 适用场景 |
|---|---|---|---|
| 动态batching | 合并并发请求 | 3-10x吞吐 | 在线服务 |
| 长度排序分batch | 减少padding | 1.5-2x吞吐 | 变长序列 |
| FP16/INT8推理 | 降低计算精度 | 2-4x加速 | GPU推理 |
| CUDA Graph | 消除kernel启动开销 | 1.2-1.5x | 固定形状推理 |
自回归生成模型(如GPT)逐token生成输出,每步都需要重新计算之前所有token的注意力。KV Cache通过缓存已计算的Key和Value矩阵避免重复计算,是推理优化的核心技术。
# 无KV Cache: 每步重新计算所有token
def generate_without_cache(model, input_ids, max_new_tokens):
generated = input_ids
for _ in range(max_new_tokens):
# 每次处理完整序列 — O(n²) 总计算
logits = model(generated)
next_token = logits[:, -1, :].argmax(dim=-1)
generated = torch.cat([generated, next_token.unsqueeze(-1)], dim=-1)
return generated
# 有KV Cache: 只计算新token的Q,复用缓存的K/V
def generate_with_cache(model, input_ids, max_new_tokens):
# 预填充阶段: 计算prompt并缓存KV
past_key_values = None
generated = input_ids
with torch.no_grad():
outputs = model(generated, use_cache=True)
past_key_values = outputs.past_key_values
next_token = outputs.logits[:, -1, :].argmax(dim=-1)
# 逐token生成
for _ in range(max_new_tokens - 1):
# 只输入新token + cache — O(n) 每步
with torch.no_grad():
outputs = model(
next_token.unsqueeze(-1),
past_key_values=past_key_values,
use_cache=True
)
past_key_values = outputs.past_key_values
next_token = outputs.logits[:, -1, :].argmax(dim=-1)
generated = torch.cat([generated, next_token.unsqueeze(-1)], dim=-1)
return generated
# 预分配KV Cache内存 (避免动态分配开销)
def preallocate_kv_cache(model, batch_size, max_seq_len, num_layers, num_heads, head_dim):
# 计算KV Cache总内存
# 每层: 2 (K+V) * batch * heads * seq_len * head_dim * dtype_size
dtype_size = 2 # FP16
cache_size = (2 * batch_size * num_heads * max_seq_len * head_dim * dtype_size * num_layers)
cache_gb = cache_size / 1024**3
print(f"KV Cache内存: {cache_gb:.2f} GB")
# 预分配
cache = {}
for layer in range(num_layers):
cache[layer] = {
"key": torch.zeros(batch_size, num_heads, max_seq_len, head_dim, device="cuda"),
"value": torch.zeros(batch_size, num_heads, max_seq_len, head_dim, device="cuda"),
"length": 0, # 当前有效长度
}
return cache
# 示例: 7B模型, 32层, 32头, 128维
preallocate_kv_cache(None, batch_size=1, max_seq_len=2048,
num_layers=32, num_heads=32, head_dim=128)
# KV Cache内存: 1.00 GB
| 模型 | 层数 | 头数 | 头维度 | seq=2048 | seq=8192 |
|---|---|---|---|---|---|
| 7B | 32 | 32 | 128 | 1.0 GB | 4.0 GB |
| 13B | 40 | 40 | 128 | 2.5 GB | 10.0 GB |
| 70B | 80 | 64 | 128 | 10.0 GB | 40.0 GB |
对于长序列生成,KV Cache内存可能超过模型权重本身。70B模型在8K序列时KV Cache需要40GB,而4-bit量化权重仅需~35GB。这是为什么GQA(分组查询注意力)和KV Cache量化如此重要。
from fastapi import FastAPI
from pydantic import BaseModel
import torch
import uvicorn
app = FastAPI(title="模型推理服务")
# 全局加载模型 (启动时加载一次)
model = torch.jit.load("model_scripted.pt").cuda().eval()
class InferenceRequest(BaseModel):
input_data: list[list[float]]
class InferenceResponse(BaseModel):
output: list[list[float]]
latency_ms: float
import time
@app.post("/predict", response_model=InferenceResponse)
async def predict(request: InferenceRequest):
input_tensor = torch.tensor(request.input_data, dtype=torch.float32).cuda()
t0 = time.time()
with torch.inference_mode():
output = model(input_tensor)
latency = (time.time() - t0) * 1000
return InferenceResponse(
output=output.cpu().tolist(),
latency_ms=latency
)
@app.get("/health")
async def health():
return {"status": "healthy"}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
import asyncio
from fastapi import FastAPI
app = FastAPI()
# 异步批处理队列
class AsyncBatchServer:
def __init__(self, model, max_batch=16, timeout_ms=5):
self.model = model
self.max_batch = max_batch
self.timeout = timeout_ms / 1000
self.queue = asyncio.Queue()
async def infer(self, input_data):
# 创建Future用于异步等待结果
future = asyncio.get_event_loop().create_future()
await self.queue.put((input_data, future))
return await future
async def batch_worker(self):
while True:
batch = []
try:
# 等待第一个请求
item = await asyncio.wait_for(self.queue.get(), self.timeout)
batch.append(item)
# 尝试收集更多请求直到满batch或超时
while len(batch) < self.max_batch:
try:
item = await asyncio.wait_for(self.queue.get(), self.timeout)
batch.append(item)
except asyncio.TimeoutError:
break
# 批量推理
inputs = torch.stack([torch.tensor(item[0]) for item in batch]).cuda()
with torch.inference_mode():
outputs = self.model(inputs)
# 分发结果
for i, (_, future) in enumerate(batch):
future.set_result(outputs[i].cpu().tolist())
except asyncio.TimeoutError:
continue
server = AsyncBatchServer(model)
@app.on_event("startup")
async def startup():
asyncio.create_task(server.batch_worker())
@app.post("/predict")
async def predict(input_data: list[float]):
result = await server.infer(input_data)
return {"output": result}
TorchServe是PyTorch官方的模型服务框架,提供模型版本管理、批处理、多模型托管等生产级功能:
# 安装TorchServe
pip install torchserve torch-model-archiver
# 创建模型archive (.mar文件)
torch-model-archiver --model-name my_model \
--version 1.0 \
--model-file model.py \
--serialized-file model_scripted.pt \
--handler handler.py \
--export-path model_store
# 启动TorchServe
torchserve --start --model-store model_store \
--models my_model=my_model.mar \
--ncs # no config snapshot
# 推理请求
curl -X POST http://localhost:8080/predictions/my_model \
-T input.json
import torch
import time
model = torch.nn.Linear(1000, 1000).cuda().eval()
x = torch.randn(100, 1000).cuda()
# torch.no_grad: 禁用梯度计算,但仍记录一些元数据
with torch.no_grad():
t0 = time.time()
for _ in range(1000):
out = model(x)
torch.cuda.synchronize()
print(f"no_grad: {(time.time()-t0)*1000:.1f}ms")
# torch.inference_mode: 更严格,完全禁用视图追踪和版本计数
with torch.inference_mode():
t0 = time.time()
for _ in range(1000):
out = model(x)
torch.cuda.synchronize()
print(f"inference_mode: {(time.time()-t0)*1000:.1f}ms")
# inference_mode通常快5-15%,推荐用于纯推理
# CUDA Graph: 录制操作序列,一次性重放
# 适合固定形状的重复推理
model = torch.nn.Linear(1000, 1000).cuda().eval()
static_input = torch.randn(64, 1000).cuda()
static_output = torch.randn(64, 1000).cuda()
# 步骤1: 预热 (确保cudnn等选好最优kernel)
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
for _ in range(3):
static_output = model(static_input)
torch.cuda.current_stream().wait_stream(s)
# 步骤2: 录制CUDA Graph
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g):
static_output = model(static_input)
# 步骤3: 推理时只需更新输入并重放graph
def inference_with_graph(new_input):
static_input.copy_(new_input)
g.replay()
return static_output.clone()
# 性能对比
test_input = torch.randn(64, 1000).cuda()
# 普通推理
torch.cuda.synchronize()
t0 = time.time()
for _ in range(10000):
with torch.inference_mode():
out = model(test_input)
torch.cuda.synchronize()
print(f"普通: {(time.time()-t0)*1000:.1f}ms")
# CUDA Graph推理
torch.cuda.synchronize()
t0 = time.time
for _ in range(10000):
out = inference_with_graph(test_input)
torch.cuda.synchronize()
print(f"CUDA Graph: {(time.time()-t0)*1000:.1f}ms")
# 对于大模型,可以将部分层offload到CPU
def inference_with_offload(model, input_data, gpu_layers=10):
# 前gpu_layers在GPU上运行
x = input_data.cuda()
with torch.inference_mode():
for i, layer in enumerate(model.layers[:gpu_layers]):
x = layer(x)
# 移到CPU运行剩余层
x = x.cpu()
for i, layer in enumerate(model.layers[gpu_layers:]):
layer.cpu()
x = layer(x)
return x
# 导出适合移动端的ONNX模型
# 1. 量化为INT8减小体积
# 2. 简化模型图
import onnx
from onnxsim import simplify
# 加载ONNX模型
model = onnx.load("model.onnx")
# 简化模型 (常量折叠、消除冗余节点)
model_simplified, check = simplify(model)
assert check, "简化失败"
onnx.save(model_simplified, "model_mobile.onnx")
# 在移动端使用ONNX Runtime C++ API
# Android: 使用onnxruntime-android
# iOS: 使用onnxruntime-objc
# 导出精简的TorchScript模型用于移动端
import torch
model = MyModel().eval()
scripted = torch.jit.script(model)
# 优化为推理模式
optimized = torch.jit.optimize_for_inference(scripted)
# 保存 (移动端只需加载这个文件)
optimized.save("model_mobile.pt")
# Android Kotlin代码示例:
# val module = LiteModuleLoader.load("model_mobile.pt")
# val output = module.forward(IValue.from(inputTensor))
| 技巧 | 体积减少 | 精度影响 | 实现难度 |
|---|---|---|---|
| INT8量化 | ~75% | <1% | 低 |
| 结构化剪枝 | ~30-50% | ~1-2% | 中 |
| 知识蒸馏小模型 | ~80-90% | ~2-3% | 高 |
| 算子融合 | ~10% | 0 | 低 |
| 权重共享 | ~50% | ~3-5% | 高 |
| 方案 | 延迟(ms) | 吞吐(req/s) | 内存(MB) | 部署复杂度 |
|---|---|---|---|---|
| PyTorch eager | 15.2 | 65 | 500 | 最低 |
| torch.inference_mode | 12.8 | 78 | 500 | 最低 |
| TorchScript | 9.5 | 105 | 480 | 低 |
| ONNX Runtime | 6.1 | 164 | 350 | 中 |
| TensorRT FP16 | 3.2 | 312 | 280 | 高 |
| TensorRT INT8 | 2.1 | 476 | 180 | 高 |
推理优化是将训练好的模型部署到生产环境的关键环节。从TorchScript序列化到TensorRT极致加速,从KV Cache自回归优化到FastAPI服务化,每一步都对最终用户体验至关重要:
| 技术 | 核心价值 | 加速效果 | PyTorch工具 |
|---|---|---|---|
| TorchScript | 序列化+算子融合 | 1.3-1.5x | torch.jit |
| ONNX Runtime | 跨平台优化推理 | 2-3x | onnxruntime |
| TensorRT | NVIDIA极致优化 | 3-5x | torch2trt/tensorrt |
| KV Cache | 自回归生成加速 | 10-100x | use_cache=True |
| 动态Batching | 吞吐量优化 | 3-10x吞吐 | 自定义/TorchServe |
| CUDA Graph | 消除kernel开销 | 1.2-1.5x | torch.cuda.CUDAGraph |
实际部署中需要根据硬件环境、延迟要求和吞吐需求选择合适的组合。没有银弹——最适合的方案往往需要通过基准测试确定。