"""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()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。
入口文件:projects/pytorch-torchscript-onnx-export-lab/explore-export-pipelines.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-export-pipelines.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a409.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a439.zip