蓝色天空网mbsky.com · 知识 · 实践 · 创造PyTorch · 本地阅读预览
教程 / AI / 智能开发 / PyTorch

PyTorch 模型部署

核对 TorchScript trace/script 控制流差异、model.eval() 导出前切换、torch.export、动态与静态量化及离线图像推理服务流程。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

模型部署目标与导出格式概览

模型部署是将训练完成的神经网络接入 Web、移动端或嵌入式生产环境的过程,核心目标是降低推理延迟、提高并发吞吐并稳定管理计算资源。

典型部署流程涵盖模型导出、图优化与量化、推理运行时集成及上线监控。PyTorch 常见导出路线包括 TorchScript、ONNX、Torch-TensorRT 以及 PyTorch 2.x 现代图捕获接口 torch.export.export,下表对比主要格式定位。

TorchScript 追踪、脚本化与 torch.export

TorchScript 提供 torch.jit.trace 与 torch.jit.script 两种转换方式。两者关键边界在于控制流:本站实测对含 if x.sum() > 0 分支的网络用正数样本 trace 后,再传入负数样本会产生 1.02368 的错误偏差(分支被写死);改用 torch.jit.script 保存并重新 torch.jit.load 载入后,正负输入最大误差均为 0.0。导出前务必调用 model.eval():本站含 BatchNorm 与 Dropout 的网络在 train 模式下同输入两次前向相差 0.96337,切换 eval() 后重复误差降为 0.0。此外 PyTorch 2.10 原生 torch.export.export 也可在固定形状下完整捕获图并保持 0.0 最大误差。

本地与云端部署方案及推理处理流程

脱离 Python 解释器进行 C++ 本地部署可使用 LibTorch 加载 .pt TorchScript 模型;跨框架或跨硬件推理常先导出 ONNX 再交给 ONNX Runtime 执行。注意当前纯 PyTorch CPU 教学环境未安装 C++ 工具链及 onnx/onnxruntime 依赖,对应编译与推理流程保留为外部部署边界。

云端服务既可选用支持多版本管理与批处理的专用服务框架(如 TorchServe),也可用 FastAPI/Uvicorn 封装轻量化 REST API。在推理接口内部,标准数据链是接收图像字节流 → Pillow 解码为 RGB → 与训练一致的 transforms 预处理并增加 batch 维 → 在 model.eval() 与 torch.inference_mode() 下前向计算并返回 JSON。本站离线实测 158 字节合成 PNG 经该处理链稳定返回形状 [1, 3, 32, 32] 与类别索引 3。

量化加速与上线运维要点

量化通过将 FP32 权重/激活转为低比特整型以缩减体积并加速推理。重要 API 迁移:旧版 torch.quantization.* 已弃用,PyTorch 2.10 应使用 torch.ao.quantization.*。本站实测对三层全连接网络做 INT8 动态量化(quantize_dynamic),序列化文件体积由 331,135 字节压缩至 86,705 字节(仅原体积 26.2%),输出最大绝对误差 0.01568;对带 QuantStub/DeQuantStub 的网络用 x86 qconfig 校准后执行静态量化(prepare → 校准前向 → convert),算子替换为量化线性层,输出最大绝对误差 0.01506。NVIDIA GPU 上还可结合 Torch-TensorRT 做 FP16/INT8 引擎编译(待 GPU 环境验证)。

生产运维常见实践:使用 Docker 或锁定环境依赖文件解决版本兼容问题;接入 Prometheus 等指标系统监控 P99 延迟、QPS 与内存水位;通过版本化模型目录或服务框架的模型管理接口配合灰度发布实现热更新。

PyTorch 常见模型导出格式对比

格式特点适用场景
TorchScriptPyTorch 原生序列化格式,支持 trace 与 scriptPyTorch / LibTorch 生态内部署
ONNX开放交换标准,支持多框架与多运行时跨框架部署与 ONNX Runtime 推理(需另装 onnx)
Torch-TensorRT针对 NVIDIA GPU 的底层算子融合与低精度加速高吞吐 NVIDIA GPU 生产推理

运行 TorchScript、torch.export、动态/静态量化与离线推理流实验

python · 阅读源码
"""Independent PyTorch 2.10 CPU observations for model export, quantization, and inference handlers."""
import io
import json
import platform
import tempfile
from pathlib import Path

import numpy as np
import PIL
from PIL import Image
import torch
import torch.nn as nn
import torchvision
from torchvision import transforms


class BranchingNet(nn.Module):
    """Module with data-dependent control flow to contrast trace vs script."""

    def __init__(self):
        super().__init__()
        self.fc_pos = nn.Linear(4, 2)
        self.fc_neg = nn.Linear(4, 2)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if float(x.sum().item()) >= 0.0:
            return self.fc_pos(x)
        return self.fc_neg(x)


class DropoutEvalNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(8, 16)
        self.drop = nn.Dropout(p=0.5)
        self.fc2 = nn.Linear(16, 4)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.fc2(self.drop(torch.relu(self.fc1(x))))


class QuantizableMLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.quant = torch.ao.quantization.QuantStub()
        self.fc1 = nn.Linear(16, 32)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(32, 4)
        self.dequant = torch.ao.quantization.DeQuantStub()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.quant(x)
        x = self.relu(self.fc1(x))
        x = self.fc2(x)
        return self.dequant(x)


class TinyImageNetClassifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(3, 8, kernel_size=3, padding=1),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d(1),
            nn.Flatten(),
            nn.Linear(8, 4),
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.net(x)


def run_cases():
    torch.manual_seed(2026)
    cases = []

    # 1. torch.jit.trace vs torch.jit.script on data-dependent control flow
    branch_model = BranchingNet().eval()
    pos_x = torch.tensor([[1.0, 2.0, 0.5, 0.5]])
    neg_x = torch.tensor([[-1.0, -2.0, -0.5, -0.5]])
    with torch.inference_mode():
        eager_pos = branch_model(pos_x)
        eager_neg = branch_model(neg_x)
        traced = torch.jit.trace(branch_model, pos_x)
        scripted = torch.jit.script(branch_model)
        with tempfile.TemporaryDirectory() as tmp:
            t_path = Path(tmp) / "traced.pt"
            s_path = Path(tmp) / "scripted.pt"
            traced.save(str(t_path))
            scripted.save(str(s_path))
            re_traced = torch.jit.load(str(t_path))
            re_scripted = torch.jit.load(str(s_path))
            traced_neg_err = float((re_traced(neg_x) - eager_neg).abs().max().item())
            scripted_pos_err = float((re_scripted(pos_x) - eager_pos).abs().max().item())
            scripted_neg_err = float((re_scripted(neg_x) - eager_neg).abs().max().item())
    c1_ok = traced_neg_err > 1e-2 and scripted_pos_err < 1e-6 and scripted_neg_err < 1e-6
    cases.append(dict(
        name="trace_vs_script_control_flow",
        inputs=dict(pos_sum=4.0, neg_sum=-4.0),
        prerequisites="带条件分支的 BranchingNet,在 eval 模式下分别追踪与脚本化保存重载",
        action="证明 torch.jit.trace 会固化示例输入分支导致反分支偏差,而 torch.jit.script 完整保留双分支。",
        expected=dict(trace_misses_other_branch=True, script_matches_both=True),
        actual=dict(trace_misses_other_branch=traced_neg_err > 1e-2, script_matches_both=scripted_pos_err < 1e-6 and scripted_neg_err < 1e-6),
        measurements=dict(traced_neg_max_err=round(traced_neg_err, 5), scripted_neg_max_err=round(scripted_neg_err, 8)),
        passed=c1_ok,
    ))

    # 2. model.eval() requirement before export
    torch.manual_seed(12)
    drop_net = DropoutEvalNet()
    sample = torch.randn(4, 8)
    drop_net.train()
    train_a, train_b = drop_net(sample), drop_net(sample)
    train_diff = float((train_a - train_b).abs().max().item())
    drop_net.eval()
    with torch.inference_mode():
        eval_traced = torch.jit.trace(drop_net, sample)
        eval_diff = float((eval_traced(sample) - eval_traced(sample)).abs().max().item())
    c2_ok = train_diff > 1e-3 and eval_diff == 0.0
    cases.append(dict(
        name="eval_mode_before_export",
        inputs=dict(dropout_p=0.5, sample_shape=[4, 8]),
        prerequisites="含 Dropout(0.5) 的网络,对比 train() 与 eval() 导出行为",
        action="验证未切 eval() 时两次前向结果随机波动,切换 eval() 后追踪导出完全确定。",
        expected=dict(train_nondeterministic=True, eval_export_deterministic=True),
        actual=dict(train_nondeterministic=train_diff > 1e-3, eval_export_deterministic=eval_diff == 0.0),
        measurements=dict(train_repeat_diff=round(train_diff, 5), eval_repeat_diff=eval_diff),
        passed=c2_ok,
    ))

    # 3. PyTorch 2.x torch.export.export modern export path
    img_net = TinyImageNetClassifier().eval()
    img_in = torch.randn(1, 3, 32, 32)
    with torch.inference_mode():
        eager_img_out = img_net(img_in)
        ep = torch.export.export(img_net, (img_in,))
        exp_img_out = ep.module()(img_in)
        exp_err = float((eager_img_out - exp_img_out).abs().max().item())
    c3_ok = exp_err < 1e-5 and list(exp_img_out.shape) == [1, 4]
    cases.append(dict(
        name="torch_export_program",
        inputs=dict(input_shape=[1, 3, 32, 32]),
        prerequisites="PyTorch 2.10 torch.export.export(model, (example_input,))",
        action="将轻量卷积网络导出为 ExportedProgram 并核对输出与 Eager 一致。",
        expected=dict(output_shape=[1, 4], matches_eager=True),
        actual=dict(output_shape=list(exp_img_out.shape), matches_eager=exp_err < 1e-5),
        measurements=dict(max_abs_err=round(exp_err, 8)),
        passed=c3_ok,
    ))

    # 4. Dynamic quantization (torch.ao.quantization.quantize_dynamic) on Linear layers
    torch.manual_seed(30)
    big_mlp = nn.Sequential(nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, 64)).eval()
    q_input = torch.randn(8, 256)
    with torch.inference_mode():
        fp32_out = big_mlp(q_input)
        q_dyn = torch.ao.quantization.quantize_dynamic(big_mlp, {nn.Linear}, dtype=torch.qint8)
        dyn_out = q_dyn(q_input)
        dyn_err = float((fp32_out - dyn_out).abs().max().item())
    with tempfile.TemporaryDirectory() as tmp:
        p_fp = Path(tmp) / "fp32.pt"
        p_q = Path(tmp) / "qint8.pt"
        torch.save(big_mlp.state_dict(), p_fp)
        torch.save(q_dyn.state_dict(), p_q)
        fp_bytes = p_fp.stat().st_size
        q_bytes = p_q.stat().st_size
    c4_ok = q_bytes < fp_bytes * 0.45 and dyn_err < 0.08
    cases.append(dict(
        name="dynamic_quantization_linear",
        inputs=dict(layers="Linear(256,256)+Linear(256,64)", dtype="qint8"),
        prerequisites="torch.ao.quantization.quantize_dynamic 量化全连接层权重",
        action="验证动态量化后状态字典体积明显缩小且推理输出与 FP32 近似。",
        expected=dict(size_reduced_over_55pct=True, output_close=True),
        actual=dict(size_reduced_over_55pct=q_bytes < fp_bytes * 0.45, output_close=dyn_err < 0.08),
        measurements=dict(fp32_bytes=fp_bytes, qint8_bytes=q_bytes, size_ratio=round(q_bytes / fp_bytes, 3), max_abs_err=round(dyn_err, 5)),
        passed=c4_ok,
    ))

    # 5. Static post-training quantization with QuantStub/DeQuantStub + calibration
    torch.manual_seed(40)
    stat_net = QuantizableMLP().eval()
    calib_x = torch.randn(32, 16)
    with torch.inference_mode():
        fp_stat_out = stat_net(calib_x[:4])
        stat_net.qconfig = torch.ao.quantization.get_default_qconfig("x86")
        prepared = torch.ao.quantization.prepare(stat_net, inplace=False)
        prepared(calib_x)  # calibration pass
        converted = torch.ao.quantization.convert(prepared, inplace=False)
        q_stat_out = converted(calib_x[:4])
        stat_err = float((fp_stat_out - q_stat_out).abs().max().item())
    has_qlinear = any("quantized" in type(m).__module__ and type(m).__name__ == "Linear" for m in converted.modules())
    c5_ok = has_qlinear and stat_err < 0.15 and list(q_stat_out.shape) == [4, 4]
    cases.append(dict(
        name="static_quantization_calibrated",
        inputs=dict(qconfig="x86", calib_batch=32),
        prerequisites="含 QuantStub/DeQuantStub 的网络经 prepare -> 校准前向 -> convert",
        action="验证静态量化替换为量化算子且校准后输出保持近似。",
        expected=dict(has_quantized_linear=True, out_shape=[4, 4], output_close=True),
        actual=dict(has_quantized_linear=has_qlinear, out_shape=list(q_stat_out.shape), output_close=stat_err < 0.15),
        measurements=dict(max_abs_err=round(stat_err, 5)),
        passed=c5_ok,
    ))

    # 6. Offline inference service preprocessing & JSON response handler
    pil_img = Image.fromarray(np.full((48, 48, 3), 180, dtype=np.uint8), mode="RGB")
    buf = io.BytesIO()
    pil_img.save(buf, format="PNG")
    raw_bytes = buf.getvalue()
    preprocess = transforms.Compose([transforms.Resize((32, 32)), transforms.ToTensor()])
    with torch.inference_mode():
        decoded = Image.open(io.BytesIO(raw_bytes)).convert("RGB")
        tensor_in = preprocess(decoded).unsqueeze(0)
        logits = img_net(tensor_in)
        pred_idx = int(logits.argmax(dim=1).item())
        resp = {"prediction": pred_idx, "input_shape": list(tensor_in.shape)}
        serialized = json.dumps(resp)
    c6_ok = isinstance(pred_idx, int) and 0 <= pred_idx < 4 and json.loads(serialized)["input_shape"] == [1, 3, 32, 32]
    cases.append(dict(
        name="image_bytes_inference_handler",
        inputs=dict(image_format="PNG", raw_bytes=len(raw_bytes)),
        prerequisites="离线验证 Web API 推理核心流程(PNG 字节流 -> PIL -> Tensor -> inference_mode -> JSON)",
        action="核对推理请求处理函数可将图像字节解码预处理并返回可序列化预测结果。",
        expected=dict(valid_class_index=True, json_roundtrip_shape=[1, 3, 32, 32]),
        actual=dict(valid_class_index=0 <= pred_idx < 4, json_roundtrip_shape=json.loads(serialized)["input_shape"]),
        measurements=dict(prediction=pred_idx, png_bytes=len(raw_bytes)),
        passed=c6_ok,
    ))

    print(json.dumps(dict(
        version=platform.python_version(),
        torch=torch.__version__,
        torchvision=torchvision.__version__,
        pillow=PIL.__version__,
        system=platform.system(),
        cases=cases,
    ), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
预期结果 · 待实际运行核验
  • 核对 trace 冻结控制流与 script 保留分支差异、eval 模式确定性、torch.export 零误差、动态量化体积降至 26.2%、静态量化校准及 PNG 字节推理处理链。
运行 TorchScript、torch.export、动态/静态量化与离线推理流实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

当前源码 SHA256:8d4ba00014d92ba01b5d2e4af5f86b81a87fe13e0bc102fceff6387fc4691e58

下载本站示例源码

本地运行

解压后按 README 选择对应构建并运行脚本。

下载PyTorch 模型部署实验

所需环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

ZIP SHA256:373a4a8f8af56e70c26f6a62cedc6c081f3c8517d6248ba84d4fa3426c78db47

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么含条件分支的网络用 torch.jit.trace 导出会产生错误预测,如何避免?

展开参考解答

torch.jit.trace 只记录示例输入实际走过的单条算子轨迹,会固化控制流分支;应改用 torch.jit.script 解析 Python 控制流,且导出前务必先调用 model.eval()。

规范与官方依据