快捷方式

ExecuTorch 入门

本节旨在描述将 PyTorch 模型转换为 ExecuTorch 并运行所需的步骤。要使用该框架,您通常需要执行以下步骤:

  • 安装 ExecuTorch python 包和运行时库。

  • 为目标硬件配置导出 PyTorch 模型。

  • 在您的开发平台使用 ExecuTorch 运行时 API 运行模型。

  • 使用 ExecuTorch 运行时将模型部署到目标平台。

系统要求

安装 ExecuTorch 主机库(导出模型和从 Python 运行所需)需要满足以下条件。目标最终用户设备的具体要求取决于后端。有关更多信息,请参阅相应的后端文档。

  • Python 3.10 - 3.12

  • g++ 版本 7 或更高,clang++ 版本 5 或更高,或另一个兼容 C++17 的工具链。

  • Linux 或 MacOS 操作系统 (Arm 或 x86)。

    • 通过 WSL 支持 Windows。

安装

要使用 ExecuTorch,您需要安装 Python 包和相应的平台特定运行时库。 Pip 是安装 ExecuTorch python 包的推荐方式。

此包包含导出 PyTorch 模型所需的依赖项,以及用于模型测试和评估的 Python 运行时绑定。考虑在虚拟环境中安装 ExecuTorch,例如 condavenv 提供的环境。

pip install executorch

要从源代码构建框架,请参阅从源代码构建。Backend delegate 可能需要额外的依赖项。有关更多信息,请参阅相应的后端文档。


准备模型

导出是将 PyTorch 模型转换为 ExecuTorch 运行时使用的 .pte 文件格式的过程。这通过 Python API 完成。常见的模型(如 Llama 3.2)的 PTE 文件可以在 HuggingFace 的 ExecuTorch 社区下找到。这些模型已经为 ExecuTorch 导出和降级,可以直接部署,无需经过降级过程。

导出、降级和验证 MobileNet V2 的完整示例可在 Colab 笔记本中找到。

要求

  • 一个 PyTorch 模型。

  • 示例模型输入,通常是 PyTorch tensors。您应该能够使用这些输入成功运行 PyTorch 模型。

  • 一个或多个目标硬件后端。

选择后端

ExecuTorch 为各种硬件提供硬件加速。最常用的后端包括用于 Arm 和 x86 CPU 的 XNNPACK,Core ML(用于 iOS),Vulkan(用于 Android GPU),以及 Qualcomm(用于高通芯片驱动的 Android 手机)。

对于移动用例,考虑将 XNNPACK 用于 Android,将 Core ML 或 XNNPACK 用于 iOS 作为第一步。有关更多信息,请参阅硬件后端

导出

导出使用 Python API 完成。ExecuTorch 在导出过程中提供了高度的定制性,但典型的流程如下。本示例使用 torchvision 中 MobileNet V2 图像分类模型的实现,但此过程支持任何符合导出规范的 PyTorch 模型。对于使用 Hugging Face 模型的用户,您可以在 huggingface/optimum-executorch 仓库中找到支持的模型列表。

import torch
import torchvision.models as models
from torchvision.models.mobilenetv2 import MobileNet_V2_Weights
from executorch.backends.xnnpack.partition.xnnpack_partitioner import XnnpackPartitioner
from executorch.exir import to_edge_transform_and_lower

model = models.mobilenetv2.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).eval()
sample_inputs = (torch.randn(1, 3, 224, 224), )

et_program = to_edge_transform_and_lower(
    torch.export.export(model, sample_inputs),
    partitioner=[XnnpackPartitioner()]
).to_executorch()

with open("model.pte", "wb") as f:
    f.write(et_program.buffer)

如果模型需要可变输入大小,您需要在 export 调用中指定可变的维度和边界。有关更多信息,请参阅模型导出和降级

要定位的硬件后端由 to_edge_transform_and_lower 的 partitioner 参数控制。在此示例中,使用 XnnpackPartitioner 来定位移动 CPU。有关如何使用每个后端的信息,请参阅特定后端文档

量化也可以在此阶段完成,以减少模型大小和运行时。量化是后端特定的。有关支持的量化方案的完整描述,请参阅目标后端的文档。

测试模型

成功生成 .pte 文件后,通常使用 Python 运行时 API 在开发平台上验证模型。这可用于在设备上运行之前评估模型精度。

对于本示例中使用的 torchvision 的 MobileNet V2 模型,图像输入预期为归一化的 float32 张量,其维度为 (batch, channels, height, width)。有关此模型的输入和输出张量格式的更多信息,请参见 torchvision.models.mobilenet_v2

import torch
from executorch.runtime import Runtime
from typing import List

runtime = Runtime.get()

input_tensor: torch.Tensor = torch.randn(1, 3, 224, 224)
program = runtime.load_program("model.pte")
method = program.load_method("forward")
output: List[torch.Tensor] = method.execute([input_tensor])
print("Run succesfully via executorch")

from torchvision.models.mobilenetv2 import MobileNet_V2_Weights
import torchvision.models as models

eager_reference_model = models.mobilenetv2.mobilenet_v2(weights=MobileNet_V2_Weights.DEFAULT).eval()
eager_reference_output = eager_reference_model(input_tensor)

print("Comparing against original PyTorch module")
print(torch.allclose(output[0], eager_reference_output, rtol=1e-3, atol=1e-5))

有关导出和运行模型的完整示例,请参阅我们的示例 GitHub 仓库

此外,如果您使用 Hugging Face 模型,huggingface/optimum-executorch 库简化了使用熟悉的 Hugging Face API 在 ExecuTorch 中端到端运行这些模型的过程。请访问该仓库查看具体示例和支持的模型。


在设备上运行

ExecuTorch 提供了 Java、Objective-C 和 C++ 的运行时 API。

快速链接

Android

安装

ExecuTorch 为 Android 用途提供了 Java 绑定,可用于 Java 和 Kotlin。要将库添加到您的应用,请将以下依赖项添加到 gradle 构建规则中。

# app/build.gradle.kts
dependencies {
  implementation("org.pytorch:executorch-android:0.6.0-rc3")
}

# See latest available versions in https://mvnrepository.com/artifact/org.pytorch/executorch-android

运行时 API

可以使用 Module 类加载和运行模型

import org.pytorch.executorch.EValue;
import org.pytorch.executorch.Module;
import org.pytorch.executorch.Tensor;

// …

Module model = Module.load("/path/to/model.pte");

Tensor input_tensor = Tensor.fromBlob(float_data, new long[] { 1, 3, height, width });
EValue input_evalue = EValue.from(input_tensor);
EValue[] output = model.forward(input_evalue);
float[] scores = output[0].toTensor().getDataAsFloatArray();

有关在 Android 上运行模型的完整示例,请参阅 DeepLabV3AndroidDemo。有关 Android 开发的更多信息,包括从源代码构建、Java API 的完整描述以及从 Android native 代码使用 ExecuTorch 的信息,请参阅在 Android 上使用 ExecuTorch

iOS

安装

ExecuTorch 通过 C++ 支持 iOS 和 MacOS,并提供 CoreML、MPS 和 CPU 的硬件后端。iOS 运行时库作为 .xcframework 目标的集合提供,并以 Swift PM 包的形式提供。

要开始使用 Xcode,请转到 File > Add Package Dependencies。将 ExecuTorch 仓库的 URL 粘贴到搜索栏中并选中它。确保将分支名称更改为所需的 ExecuTorch 版本,格式为“swiftpm-”,(例如,“swiftpm-0.6.0”)。也可以手动将 ExecuTorch 依赖项添加到 package 文件中。有关更多信息,请参阅在 iOS 上使用 ExecuTorch

运行时 API

可以使用 C++ API 从 Objective-C 加载和运行模型。

有关 iOS 集成的更多信息,包括 API 参考、日志设置和从源代码构建,请参阅在 iOS 上使用 ExecuTorch

C++

ExecuTorch 提供 C++ API,可用于嵌入式或移动设备。与其它语言绑定相比,C++ API 提供了更高的控制级别,允许进行高级内存管理、数据加载和平台集成。

安装

CMake 是 ExecuTorch C++ 运行时首选的构建系统。要在 CMake 中使用,将 ExecuTorch 仓库克隆为项目的子目录,并使用 CMake 的 add_subdirectory("executorch") 来包含依赖项。executorch 目标以及 kernel 和 backend 目标将可用于链接。运行时也可以独立构建以支持不同的工具链。有关构建集成、目标和交叉编译的详细描述,请参阅将 ExecuTorch 与 C++ 结合使用

git clone -b release/0.6 https://github.com/pytorch/executorch.git
# CMakeLists.txt
add_subdirectory("executorch")
...
target_link_libraries(
  my_target
  PRIVATE executorch
          extension_module_static
          extension_tensor
          optimized_native_cpu_ops_lib
          xnnpack_backend)

运行时 API

提供了高级和低级 C++ API。低级 API 独立于平台,不动态分配内存,最适合资源受限的嵌入式系统。高级 API 是低级 API 的便捷包装,并使用动态内存分配和标准库结构来减少冗余。

ExecuTorch 使用 CMake 进行 native 构建。集成通常通过克隆 ExecuTorch 仓库并使用 CMake add_subdirectory 添加依赖项来完成。

使用高级 API 加载和运行模型可以按如下方式完成

#include <executorch/extension/module/module.h>
#include <executorch/extension/tensor/tensor.h>

using namespace ::executorch::extension;

// Load the model.
Module module("/path/to/model.pte");

// Create an input tensor.
float input[1 * 3 * 224 * 224];
auto tensor = from_blob(input, {1, 3, 224, 224});

// Perform an inference.
const auto result = module.forward(tensor);

if (result.ok()) {
  // Retrieve the output data.
  const auto output = result->at(0).toTensor().const_data_ptr<float>();
}

有关 C++ API 的更多信息,请参阅在 C++ 中使用 Module Extension 运行 ExecuTorch 模型在 C++ 中管理 Tensor 内存

有关构建和运行 C++ 应用程序的完整示例,请参阅我们的示例 GitHub 仓库


下一步

ExecuTorch 提供了高度的定制性,以支持各种硬件目标。根据您的用例,考虑探索以下页面中的一个或多个:

文档

查阅 PyTorch 全面的开发者文档

查看文档

教程

获取针对初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题解答

查看资源