用XNNPACK后端导出并运行ExecuTorch模型
该教程介绍如何借助ExecuTorch的XNNPACK Delegate在CPU硬件上加速模型,涵盖将模型导出并序列化为二进制文件、以XNNPACK后端为目标、在受支持平台运行,以及构建、链接与性能分析等环节。
## 使用 XNNPACK 后端构建和运行 ExecuTorch[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#building-and-running-executorch-with-xnnpack-backend>) 以下的教程将让您熟悉如何利用ExecuTorch XNNPACK 代表器来加速您的 ML 模型使用 CPU 硬件. 它会将一个模型导出并序列化到一个二进制文件,目标为 XNNPACK 代表器后端,并在一个被支持的目标平台上运行模型.要快速启动,请使用ExecuTorch寄存器中的脚本,并附有关于导出和生成二进制文件的说明,用于演示流量的几个样板模型. 在这个教程中你会学到什么 : 在此教程中, 您将学习如何导出一个 XNNPACK 降级模型并在目标平台上运行 。 在开始之前,建议您通过下列途径: - [设置 ExecuTorch](<https://docs.pytorch.org/executorch/stable/getting-started-setup.html>) - [模式下调教学](<https://docs.pytorch.org/executorch/stable/tutorials/export-to-executorch-tutorial.html>) - [ExecuTorch XNNPACK 代表](<https://docs.pytorch.org/executorch/stable/backends/xnnpack/xnnpack-overview.html>) ## 将一个模型降低到 XNNPACK[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#lowering-a-model-to-xnnpack>) ``` import torch import torchvision.models as models from torch.export import export, ExportedProgram from torchvision.models.mobilenetv2 import MobileNet_V2_Weights from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner from executorch.exir import EdgeProgramManager, ExecutorchProgramManager, to_edge_transform_and_lower from executorch.exir.backend.backend_api import to_backend mobilenet_v2 = models.mobilenetv2.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).eval() sample_inputs = (torch.randn(1, 3, 224, 224), ) exported_program: ExportedProgram = export(mobilenet_v2, sample_inputs) edge: EdgeProgramManager = to_edge_transform_and_lower( exported_program, partitioner=[XnnpackPartitioner()], ) ``` 我们将用这个例子 [MobileNetV2](<https://pytorch.org/hub/pytorch_vision_mobilenet_v2/>) 从 TorchVision 库下载的预试模型。在导出模型后,降低模型的流量开始 `to_edge`我们叫它: `to_backend` 与 pi 键 `XnnpackPartitioner`。分区器将识别适合 XNNPACK 后端 代表使用的子图。随后,识别的子图将与 XNNPACK 代表平缓缓图进行序列化,每个子图将替换为给 XNNPACK 代表的电话。 ``` >>> print(edge.exported_program().graph_module) GraphModule( (lowered_module_0): LoweredBackendModule() (lowered_module_1): LoweredBackendModule() ) def forward(self, b_features_0_1_num_batches_tracked, ..., x): lowered_module_0 = self.lowered_module_0 lowered_module_1 = self.lowered_module_1 executorch_call_delegate_1 = torch.ops.higher_order.executorch_call_delegate(lowered_module_1, x); lowered_module_1 = x = None getitem_53 = executorch_call_delegate_1[0]; executorch_call_delegate_1 = None aten_view_copy_default = executorch_exir_dialects_edge__ops_aten_view_copy_default(getitem_53, [1, 1280]); getitem_53 = None aten_clone_default = executorch_exir_dialects_edge__ops_aten_clone_default(aten_view_copy_default); aten_view_copy_default = None executorch_call_delegate = torch.ops.higher_order.executorch_call_delegate(lowered_module_0, aten_clone_default); lowered_module_0 = aten_clone_default = None getitem_52 = executorch_call_delegate[0]; executorch_call_delegate = None return (getitem_52,) ``` 我们在上方降低后打印图表, 以显示插入的新节点, 称为 XNNPACK 代表。 正在授权给 XNNPACK 的子图是每个呼叫站点的第一个参数 。 可以观察到, 大部分 `convolution-relu-add` 块和 `linear` 块可以被授权给 XNNPACK 。我们也可以看到无法被降级到 XNNPACK 代表的运算符,例如 `clone` 财务报告和财务报告 `view_copy`. ``` exec_prog = edge.to_executorch() with open("xnnpack_mobilenetv2.pte", "wb") as file: exec_prog.write_to_file(file) ``` 在降低到XNNPACK程序之后,我们可以准备用于执行器,并将模型保存为一种 `.pte` 文档。 `.pte` 是一个二进制格式,用于存储序列化的 ExecuTorch 图。 ## 将一个量化模型降为 XNNPACK[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#lowering-a-quantized-model-to-xnnpack>) XNNPACK 代表也可以执行对称的定量模型。要了解定量流并学习如何对模型进行定量,请参见: [量化概况.](<https://docs.pytorch.org/executorch/stable/quantization-overview.html>)为了这个辅导,我们将利用 `quantize()` 方便添加到 python 帮助器函数 `executorch/executorch/examples` 文件夹。 ``` from torch.export import export from executorch.exir import EdgeCompileConfig, to_edge_transform_and_lower mobilenet_v2 = models.mobilenetv2.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).eval() sample_inputs = (torch.randn(1, 3, 224, 224), ) mobilenet_v2 = export(mobilenet_v2, sample_inputs).module() # 2-stage export for quantization path from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e from executorch.backends.xnnpack.quantizer.xnnpack_quantizer import ( get_symmetric_quantization_config, XNNPACKQuantizer, ) def quantize(model, example_inputs): """This is the official recommended flow for quantization in pytorch 2.0 export""" print(f"Original model: {model}") quantizer = XNNPACKQuantizer() # if we set is_per_channel to True, we also need to add out_variant of quantize_per_channel/dequantize_per_channel operator_config = get_symmetric_quantization_config(is_per_channel=False) quantizer.set_global(operator_config) m = prepare_pt2e(model, quantizer) # calibration m(*example_inputs) m = convert_pt2e(m) print(f"Quantized model: {m}") # make sure we can export to flat buffer return m quantized_mobilenetv2 = quantize(mobilenet_v2, sample_inputs) ``` 量化需要两个阶段的导出。 `export` API在将其交付给 `quantize` 工具功能 。 在进行量化步骤后, 我们现在可以利用 XNNPACK 代表器来降低量化输出模型图。 从这里看, 程序与未量化模型降低到 XNNPACK 的程序相同 。 ``` # Continued from earlier... edge = to_edge_transform_and_lower( export(quantized_mobilenetv2, sample_inputs), compile_config=EdgeCompileConfig(_check_ir_validity=False), partitioner=[XnnpackPartitioner()] ) exec_prog = edge.to_executorch() with open("qs8_xnnpack_mobilenetv2.pte", "wb") as file: exec_prog.write_to_file(file) ``` ## 下调 `aot_compiler.py` 脚本[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#lowering-with-aot-compiler-py-script>) 我们还提供了一个脚本来快速降低并导出一些实例模型。 您可以运行脚本来生成降低的fp32和定量模型。 这个脚本只是为方便起见, 并且执行前两节列出的所有步骤 。 ``` python -m examples.xnnpack.aot_compiler --model_name="mv2" --quantize --delegate ``` 在上述例子中注意到, - 编号 `-—model_name` 指定要使用的模型 - 编号 `-—quantize` 旗帜控制模式是否应该量化 - 编号 `-—delegate` 旗帜可以控制我们是否试图将图中的部分降为XNNPACK代表. 生成的模型文件将被命名 `[model_name]_xnnpack_[qs8/fp32].pte` 取决于所提供的论据。 ## 使用 CMake 运行 XNNPACK 模型[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#running-the-xnnpack-model-with-cmake>) 在导出 XNNPACK 委托模型后, 我们现在可以尝试使用 CMake 的示例输入来运行它。 我们可以构建并使用 executor_runner, 这是 ExecuTorch 运行时的样本包。 XNNPACK 后端通过编译旗启用 。 `-DEXECUTORCH_BUILD_XNNPACK=ON`我们首先将 CMake 建筑配置成这样: ``` # cd to the root of executorch repo cd executorch # Get a clean cmake-out directory ./install_executorch.sh --clean mkdir cmake-out # Configure cmake cmake \ -DCMAKE_INSTALL_PREFIX=cmake-out \ -DCMAKE_BUILD_TYPE=Release \ -DEXECUTORCH_BUILD_EXECUTOR_RUNNER=ON \ -DEXECUTORCH_BUILD_EXTENSION_DATA_LOADER=ON \ -DEXECUTORCH_BUILD_EXTENSION_MODULE=ON \ -DEXECUTORCH_BUILD_EXTENSION_TENSOR=ON \ -DEXECUTORCH_BUILD_XNNPACK=ON \ -DEXECUTORCH_ENABLE_LOGGING=ON \ -DPYTHON_EXECUTABLE=python \ -Bcmake-out . ``` 然后,你可以 运行时间的共建网 ``` cmake --build cmake-out -j9 --target install --config Release ``` 现在,你应该能够 找到可执行文件 建造在 `./cmake-out/executor_runner` 您可以用您创建的模型运行可执行文件 ``` ./cmake-out/executor_runner --model_path=./mv2_xnnpack_fp32.pte # or to run the quantized variant ./cmake-out/executor_runner --model_path=./mv2_xnnpack_q8.pte ``` ## 与 XNNPACK 后端建立和链接[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#building-and-linking-with-the-xnnpack-backend>) 您可以构建 XNNPACK 后端 [CMake 目标](<https://github.com/pytorch/executorch/blob/main/backends/xnnpack/CMakeLists.txt#L83>),并将其与Android 或 iOS 应用程序等应用程序二进制链接。欲了解更多信息,请查看此软件 [资源](<https://docs.pytorch.org/executorch/stable/using-executorch-android.html>) 下一个 ## 剖析[#](<https://docs.pytorch.org/executorch/stable/tutorial-xnnpack-delegate-lowering.html#profiling>) 能够进行剖面分析 `executor_runner` 传旗 `-DEXECUTORCH_ENABLE_EVENT_TRACER=ON` 财务报告和财务报告 `-DEXECUTORCH_BUILD_DEVTOOLS=ON` 到构建命令(添加) `-DENABLE_XNNPACK_PROFILING=ON` 这将在运行推断时启用 ETDump 生成,并启用命令行旗进行剖析(参见 `executor_runner --help` 详细情况请查阅。
查看原始来源