蓝色天空.知识 · 实践 · 创造
我的收藏
PyTorch 教程目录 39章
PyTorch / LEARN BY DOING

PyTorch TorchScript/ONNX 导出

核对修正版 SimpleCNN 追踪导出、trace 与 script 动态控制流差异、离线 ResNet18(weights=None)、freeze/optimize_for_inference、动态 INT8 量化与移动端 .ptl。

学完这一章,你能够

  • 核对修正版 SimpleCNN 追踪导出、trace 与 script 动态控制流差异、离线 ResNet18(weights=None)、freeze/optimize_for_inference、动态 INT8 量化与移动端 .ptl。

模型导出概述与 TorchScript 追踪/脚本化对比

模型导出是将训练完成的 PyTorch 模型转换为可脱离 Python 或跨框架运行的序列化表示,服务于服务器高并发、边缘与移动端推理。TorchScript 是 PyTorch 原生静态图序列化格式,支持 Python 子集语法并可在 C++ LibTorch 虚拟机独立执行,提供追踪(Tracing)与脚本化(Scripting)两条路径。

追踪(torch.jit.trace)通过喂入示例输入记录实际执行轨迹,速度快但会固化 if/for 控制流且易受动态尺寸限制;脚本化(torch.jit.script)直接解析 Python AST 源码保留动态控制流与循环(注意直接传 torch.jit.script(model) 即可,无需无效的 example_inputs 位置参数)。本站实测并修正两处来源错误:(1)64×64 图像经两次 2×2 MaxPool2d 后特征图为 16×16(128×16×16=32,768),来源 SimpleNet 误写 128×8×8 会直接报 RuntimeError,修正后 trace 保存为 4,359,903 字节 .pt 并重载输出最大误差 0.0;(2)对 if x.sum() > 0: return x * 2 else: return x * 3 用 [1.0] 追踪后再输入 [-1.0],trace 走固化的 *2 分支输出 -2.0(修正来源注释误写的 2),而 script 走 else 分支精确输出 -3.0,带 for 循环的脚本模型误差亦为 0.0。

ONNX 开放导出格式与 ResNet18 离线验证

ONNX(Open Neural Network eXchange)是跨框架、跨硬件的开放交换标准,支持通过 ONNX Runtime 在 CPU、GPU 与边缘端推理,导出时可配合 opset_version 与 dynamic_axes 指定可变批量维。实例化标准视觉模型时注意 API 迁移:torchvision 旧参数 pretrained=True 已弃用,在线应传 weights=ResNet18_Weights.DEFAULT,离线校验可传 weights=None。本站离线实例化 models.resnet18(weights=None).eval() 并完成 TorchScript 追踪,输出 [1, 1000] 与 Eager 最大误差为 0.0。

推理图优化、动态量化、移动端导出与排障清单

导出模型后务必先做数值一致性校验再做图优化与量化:(1)在 eval() 下依次执行 torch.jit.freeze 与 torch.jit.optimize_for_inference 可折叠 Conv+BN 等算子,本站实测折叠前后输出最大差值为 0.0;(2)对全连接网络使用现代接口 torch.ao.quantization.quantize_dynamic(..., {nn.Linear}, dtype=torch.qint8) 动态量化,权重序列化体积由 271,473 字节缩减至 72,905 字节(仅原体积 26.9%),输出最大误差 0.0056。

面向移动端部署,TorchScript 支持通过 _save_for_lite_interpreter 导出轻量级 .ptl 文件(本站实测产出 17,828 字节有效 .ptl;PyTorch 2.x 生态中更前沿的移动端方案正向 ExecuTorch 演进)。面向跨框架 ONNX Runtime 与 iOS Core ML(coremltools)的导出与推理需安装外部包,本站如实探测当前纯 PyTorch CPU 环境 onnx/onnxruntime/coremltools 均未安装,保留为独立部署环境待核验项。下表汇总导出排障与格式对比。

模型导出常见问题排查

问题原因解决方案
导出失败算子不受目标格式支持或输入维度错配核对前向维度、提高 ONNX opset_version 或替换算子
输出不一致含动态控制流误用 trace 或导出前漏切 eval()先调 eval(),有控制流改用 torch.jit.script
ONNX Runtime 错误目标运行时版本不支持特定 opset 或算子检查 ONNX 算子支持表并匹配 opset_version

TorchScript 与 ONNX 导出格式对比

格式优点缺点适用场景
TorchScript (.pt)PyTorch 原生内置、支持 trace/script 与 freeze 优化绑定 PyTorch/LibTorch 生态,跨框架能力弱PyTorch 服务器 C++ 部署与移动端 .ptl
ONNX (.onnx)开放标准、跨框架与多硬件运行时生态丰富部分动态控制流或自定义算子需改写多框架互通、ONNX Runtime 与 TensorRT/CoreML 转换

运行 SimpleCNN 维度修正追踪、trace/script 对比、ResNet18、图优化与量化导出实验

含完整源码 · 212 行
展开查看收起
python
"""Independent PyTorch 2.10 CPU model export lab (TorchScript trace/script, ResNet18 offline, freeze/optimize, dynamic quantization, mobile lite)."""
import importlib.util
import json
import platform
import tempfile
from pathlib import Path

import PIL
import torch
import torch.nn as nn
import torchvision
from torchvision import models


class SimpleCNN(nn.Module):
    """Fixed flatten dimension for 64x64 input: two 2x2 pools -> 16x16 (128*16*16=32768)."""

    def __init__(self, fc_in: int = 128 * 16 * 16):
        super().__init__()
        self.conv1 = nn.Conv2d(3, 32, 3, padding=1)
        self.conv2 = nn.Conv2d(32, 128, 3, padding=1)
        self.pool = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(fc_in, 32)
        self.fc2 = nn.Linear(32, 10)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.pool(torch.relu(self.conv1(x)))
        x = self.pool(torch.relu(self.conv2(x)))
        x = x.flatten(1)
        x = torch.relu(self.fc1(x))
        return self.fc2(x)


class ControlFlowNet(nn.Module):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if x.sum() > 0:
            return x * 2.0
        return x * 3.0


class LoopScriptNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.lin = nn.Linear(8, 8)

    def forward(self, x: torch.Tensor, steps: int = 2) -> torch.Tensor:
        out = x
        for _ in range(steps):
            out = torch.tanh(self.lin(out))
        return out


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

    # 1. Prove source SimpleNet 128*8*8 bug on 64x64 input, fix to 128*16*16, trace + save/load roundtrip
    x64 = torch.randn(1, 3, 64, 64)
    buggy_failed = False
    try:
        SimpleCNN(fc_in=128 * 8 * 8).eval()(x64)
    except RuntimeError:
        buggy_failed = True

    fixed = SimpleCNN(fc_in=128 * 16 * 16).eval()
    with torch.inference_mode():
        eager_out = fixed(x64)
    traced = torch.jit.trace(fixed, x64)
    with tempfile.TemporaryDirectory() as tmp:
        pt_path = Path(tmp) / "simple_cnn_traced.pt"
        traced.save(str(pt_path))
        reloaded = torch.jit.load(str(pt_path))
        with torch.inference_mode():
            ts_out = reloaded(x64)
        file_bytes = pt_path.stat().st_size
    max_diff = float((eager_out - ts_out).abs().max().item())
    c1_ok = buggy_failed and list(ts_out.shape) == [1, 10] and max_diff < 1e-6 and file_bytes > 0
    cases.append(dict(
        name="fix_simplenet_flatten_and_trace",
        inputs=dict(input_shape=[1, 3, 64, 64], buggy_fc_in=8192, fixed_fc_in=32768),
        prerequisites="两次 MaxPool2d(2) 将 64×64 降至 16×16(128×16×16=32768),修正来源 128×8×8 维度错误并完成 trace 存读",
        action="核对 128×8×8 报错、修正后 trace 导出与重载输出误差 <1e-6。",
        expected=dict(buggy_8x8_raises=True, out_shape=[1, 10], trace_reload_exact=True),
        actual=dict(buggy_8x8_raises=buggy_failed, out_shape=list(ts_out.shape), trace_reload_exact=max_diff < 1e-6),
        measurements=dict(max_diff=round(max_diff, 8), traced_pt_bytes=file_bytes),
        passed=c1_ok,
    ))

    # 2. Trace vs Script on dynamic control flow (correcting source comment: traced([-1.0]) == -2.0, scripted([-1.0]) == -3.0)
    cf = ControlFlowNet().eval()
    traced_cf = torch.jit.trace(cf, torch.tensor([1.0]))
    scripted_cf = torch.jit.script(cf)
    neg_in = torch.tensor([-1.0])
    traced_neg = float(traced_cf(neg_in).item())
    scripted_neg = float(scripted_cf(neg_in).item())

    loop_m = LoopScriptNet().eval()
    scripted_loop = torch.jit.script(loop_m)
    x8 = torch.randn(2, 8)
    loop_diff = float((loop_m(x8, steps=3) - scripted_loop(x8, 3)).abs().max().item())
    c2_ok = traced_neg == -2.0 and scripted_neg == -3.0 and loop_diff < 1e-6
    cases.append(dict(
        name="trace_vs_script_control_flow",
        inputs=dict(trace_example=[1.0], test_input=[-1.0], loop_steps=3),
        prerequisites="对比 torch.jit.trace 固化单分支与 torch.jit.script 保留动态 if/for 控制流",
        action="向用正数追踪和脚本化的控制流模型输入 [-1.0],验证 trace 固定走 *2 输出 -2.0,script 走 *3 输出 -3.0,且循环脚本输出一致。",
        expected=dict(traced_neg=-2.0, scripted_neg=-3.0, loop_script_exact=True),
        actual=dict(traced_neg=traced_neg, scripted_neg=scripted_neg, loop_script_exact=loop_diff < 1e-6),
        passed=c2_ok,
    ))

    # 3. Offline ResNet18 (weights=None instead of deprecated pretrained=True) trace + save/load
    res = models.resnet18(weights=None).eval()
    img224 = torch.randn(1, 3, 224, 224)
    with torch.inference_mode():
        res_eager = res(img224)
        res_traced = torch.jit.trace(res, img224)
        res_ts = res_traced(img224)
    res_diff = float((res_eager - res_ts).abs().max().item())
    c3_ok = list(res_ts.shape) == [1, 1000] and res_diff < 1e-5
    cases.append(dict(
        name="resnet18_offline_weights_none_export",
        inputs=dict(model="resnet18(weights=None)", input_shape=[1, 3, 224, 224]),
        prerequisites="使用新版 weights=None 离线实例化 ResNet18(替代弃用 pretrained=True),完成 TorchScript 追踪校验",
        action="验证离线 ResNet18 追踪后输出 [1, 1000] 且与 Eager 推理误差 <1e-5。",
        expected=dict(out_shape=[1, 1000], eager_matches_traced=True),
        actual=dict(out_shape=list(res_ts.shape), eager_matches_traced=res_diff < 1e-5),
        measurements=dict(max_diff=round(res_diff, 7)),
        passed=c3_ok,
    ))

    # 4. Freeze & optimize_for_inference (Conv+BN folding)
    conv_bn = nn.Sequential(nn.Conv2d(3, 16, 3, padding=1), nn.BatchNorm2d(16), nn.ReLU(), nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(16, 4)).eval()
    sample32 = torch.randn(2, 3, 16, 16)
    with torch.inference_mode():
        base_y = conv_bn(sample32)
        tr_cb = torch.jit.trace(conv_bn, sample32)
        opt_cb = torch.jit.optimize_for_inference(torch.jit.freeze(tr_cb))
        opt_y = opt_cb(sample32)
    opt_diff = float((base_y - opt_y).abs().max().item())
    c4_ok = opt_diff < 1e-5 and list(opt_y.shape) == [2, 4]
    cases.append(dict(
        name="freeze_and_optimize_for_inference",
        inputs=dict(pipeline="trace -> freeze -> optimize_for_inference"),
        prerequisites="eval() 模式下冻结模块并执行推理图优化(折叠 Conv+BN)",
        action="比较原始 Eager 与 freeze+optimize_for_inference 输出,确认数值误差 <1e-5。",
        expected=dict(out_shape=[2, 4], optimized_matches_eager=True),
        actual=dict(out_shape=list(opt_y.shape), optimized_matches_eager=opt_diff < 1e-5),
        measurements=dict(max_diff=round(opt_diff, 7)),
        passed=c4_ok,
    ))

    # 5. Dynamic INT8 quantization of Linear layers + serialized size reduction
    big_mlp = nn.Sequential(nn.Linear(128, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 10)).eval()
    q_mlp = torch.ao.quantization.quantize_dynamic(big_mlp, {nn.Linear}, dtype=torch.qint8)
    xq = torch.randn(4, 128)
    with torch.inference_mode():
        y_fp = big_mlp(xq)
        y_q = q_mlp(xq)
    with tempfile.TemporaryDirectory() as tmp:
        p_fp = Path(tmp) / "fp32.pt"
        p_q = Path(tmp) / "int8.pt"
        torch.save(big_mlp.state_dict(), p_fp)
        torch.save(q_mlp.state_dict(), p_q)
        fp_bytes = p_fp.stat().st_size
        q_bytes = p_q.stat().st_size
    q_diff = float((y_fp - y_q).abs().max().item())
    c5_ok = q_bytes < fp_bytes * 0.5 and bool(torch.isfinite(y_q).all().item()) and q_diff < 0.1
    cases.append(dict(
        name="dynamic_quantization_linear_export",
        inputs=dict(dtype="qint8", target_module="nn.Linear"),
        prerequisites="使用 torch.ao.quantization.quantize_dynamic 量化线性层权重并比较序列化体积",
        action="验证动态 INT8 量化后权重文件缩减超过 50%,且输出有限并与 FP32 接近(误差 <0.1)。",
        expected=dict(size_reduced_over_50pct=True, outputs_finite=True, close_to_fp32=True),
        actual=dict(size_reduced_over_50pct=q_bytes < fp_bytes * 0.5, outputs_finite=bool(torch.isfinite(y_q).all().item()), close_to_fp32=q_diff < 0.1),
        measurements=dict(fp32_bytes=fp_bytes, int8_bytes=q_bytes, size_ratio=round(q_bytes / fp_bytes, 3), max_diff=round(q_diff, 5)),
        passed=c5_ok,
    ))

    # 6. Mobile lite (.ptl) save & external ONNX / ONNX Runtime / CoreML boundary check
    has_onnx = importlib.util.find_spec("onnx") is not None
    has_ort = importlib.util.find_spec("onnxruntime") is not None
    has_coreml = importlib.util.find_spec("coremltools") is not None
    with tempfile.TemporaryDirectory() as tmp:
        ptl_path = Path(tmp) / "mobile_model.ptl"
        tr_cb._save_for_lite_interpreter(str(ptl_path))
        ptl_bytes = ptl_path.stat().st_size
    c6_ok = ptl_bytes > 0
    cases.append(dict(
        name="onnx_and_mobile_export_boundary",
        inputs=dict(mobile_format=".ptl"),
        prerequisites="保存本地移动端 Lite Interpreter 文件并如实探测可选外部依赖 onnx/onnxruntime/coremltools",
        action="验证 _save_for_lite_interpreter 成功产出非空 .ptl,并记录缺失的跨框架运行时作为外部部署待核验项。",
        expected=dict(ptl_generated=True),
        actual=dict(ptl_generated=ptl_bytes > 0),
        measurements=dict(ptl_bytes=ptl_bytes, onnx_installed=has_onnx, onnxruntime_installed=has_ort, coremltools_installed=has_coreml),
        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()
核对 128×8×8 报错与 128×16×16 修正追踪、trace([-1])=-2.0 对比 script([-1])=-3.0、离线 ResNet18 零误差追踪、freeze+optimize_for_inference 零误差、INT8 体积缩减至 26.9% 及 .ptl 生成。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a409.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:PyTorch

课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip

下载课程关联工程包:PyTorch

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a439.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

torch.jit.trace 只记录示例输入 [1.0] 经过的 x * 2 计算分支并丢弃 if 判断,因此输入 [-1.0] 仍执行 -1.0 * 2 = -2.0;应改用 torch.jit.script 编译保留完整控制流。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习