PyTorch从入门到熟悉 · 第18/20篇

推理优化与模型部署:从研究到生产的最后一公里

TorchScript、ONNX Runtime、TensorRT推理加速,KV Cache自回归生成,FastAPI模型服务化,端侧部署全流程实践

生成日期:2026年11月6日 · 面向大模型开发 · 返回目录

TorchScript:模型序列化与优化

TorchScript是PyTorch的模型序列化格式,将动态Python模型转换为静态图表示,可以在没有Python解释器的环境中运行。它是部署PyTorch模型到C++生产环境的基础。

torch.jit.script vs torch.jit.trace

TorchScript有两种转换方式,各有适用场景:

Python
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}")

script vs trace的选择

特性torch.jit.scripttorch.jit.trace
控制流(if/for/while)✓ 支持✗ 丢失
动态形状✓ 支持✓ 部分支持
代码修改需求可能需要几乎不需要
准确性高(解析源码)依赖追踪输入
适用场景有控制流的模型纯计算图模型

保存与加载TorchScript模型

Python
# 保存 (不依赖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)

TorchScript的限制与注意事项

Python
# 限制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集成推理

ONNX Runtime是微软开发的高性能推理引擎,支持多种硬件加速器。相比PyTorch原生推理,通常有2-5倍加速。

创建推理Session

Python
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绑定:减少数据拷贝

Python
# 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")

ONNX Runtime性能优化配置

Python
# 高级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
TensorRTNVIDIA极致优化仅NVIDIA GPU中等3-5x
OpenVINOIntel硬件优化Intel CPU/VPU中等2-4x

TensorRT集成:NVIDIA极致推理加速

TensorRT是NVIDIA的高性能深度学习推理优化器,针对NVIDIA GPU进行极致优化,包括层融合、精度校准、kernel自动调优等。

使用torch2trt转换

Python
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}")

动态Batch配置

Python
# 使用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)

FP16/INT8引擎校准

Python
# 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)是提升吞吐量的关键技术。

动态Batch处理

Python
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))

Padding策略对吞吐量的影响

Python
# 变长序列的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减少padding1.5-2x吞吐变长序列
FP16/INT8推理降低计算精度2-4x加速GPU推理
CUDA Graph消除kernel启动开销1.2-1.5x固定形状推理

KV Cache推理:自回归生成加速

自回归生成模型(如GPT)逐token生成输出,每步都需要重新计算之前所有token的注意力。KV Cache通过缓存已计算的Key和Value矩阵避免重复计算,是推理优化的核心技术。

无Cache vs 有Cache的计算量

Python
# 无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内存管理

Python
# 预分配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

KV Cache内存分析

模型层数头数头维度seq=2048seq=8192
7B32321281.0 GB4.0 GB
13B40401282.5 GB10.0 GB
70B806412810.0 GB40.0 GB
⚠️ KV Cache内存瓶颈

对于长序列生成,KV Cache内存可能超过模型权重本身。70B模型在8K序列时KV Cache需要40GB,而4-bit量化权重仅需~35GB。这是为什么GQA(分组查询注意力)和KV Cache量化如此重要。

模型服务化:从模型到API

FastAPI封装推理服务

Python
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)

并发处理与批处理服务

Python
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简介

TorchServe是PyTorch官方的模型服务框架,提供模型版本管理、批处理、多模型托管等生产级功能:

Bash
# 安装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

推理优化技巧汇总

torch.inference_mode vs torch.no_grad

Python
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:消除kernel启动开销

Python
# 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")

CPU Offload策略

Python
# 对于大模型,可以将部分层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

端侧部署:移动端与边缘设备

部署流程全景

模型部署全流程 PyTorch模型 训练完成 量化/剪枝 模型压缩 格式转换 ONNX/TorchScript 推理引擎 TRT/ORT 服务化 FastAPI/TRT 端侧部署 GPU服务器 4x压缩 跨平台 3-5x加速 API服务 移动端 | 边缘设备 | WebAssembly | 嵌入式系统

ONNX移动端部署

Python
# 导出适合移动端的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

PyTorch Mobile (TorchLite)

Python
# 导出精简的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 eager15.265500最低
torch.inference_mode12.878500最低
TorchScript9.5105480低
ONNX Runtime6.1164350中
TensorRT FP163.2312280高
TensorRT INT82.1476180高

部署方案选择指南

✅ 决策建议
  1. 快速原型/开发 → PyTorch + inference_mode,零额外成本
  2. C++生产环境 → TorchScript + libtorch,无需Python依赖
  3. 跨平台/多硬件 → ONNX Runtime,一次导出到处运行
  4. NVIDIA GPU极致性能 → TensorRT FP16/INT8,最快推理
  5. 在线服务 → FastAPI + 动态batching + KV Cache
  6. 移动端/边缘 → INT8量化 + ONNX/TorchLite,最小体积

本章小结

推理优化是将训练好的模型部署到生产环境的关键环节。从TorchScript序列化到TensorRT极致加速,从KV Cache自回归优化到FastAPI服务化,每一步都对最终用户体验至关重要:

技术核心价值加速效果PyTorch工具
TorchScript序列化+算子融合1.3-1.5xtorch.jit
ONNX Runtime跨平台优化推理2-3xonnxruntime
TensorRTNVIDIA极致优化3-5xtorch2trt/tensorrt
KV Cache自回归生成加速10-100xuse_cache=True
动态Batching吞吐量优化3-10x吞吐自定义/TorchServe
CUDA Graph消除kernel开销1.2-1.5xtorch.cuda.CUDAGraph

实际部署中需要根据硬件环境、延迟要求和吞吐需求选择合适的组合。没有银弹——最适合的方案往往需要通过基准测试确定。