蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。explore-model-deployment.py
explore-model-deployment.py241 行
"""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()
本例需在 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。

入口文件:projects/pytorch-model-deployment-lab/explore-model-deployment.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-model-deployment.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows CPU、CPython 3.12.14、PyTorch 2.10.0+cpu。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PyTorch

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

下载课程关联工程包:PyTorch

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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