在 C++ 中运行 ExecuTorch 模型教程¶
作者: Jacob Szwejbka
在本教程中,我们将介绍如何使用更详细的较低级别 API 在 C++ 中运行 ExecuTorch 模型:准备、设置输入、执行模型和检索输出。但是,如果您正在寻找开箱即用的更简单的界面,请考虑尝试 Module Extension Tutorial。MemoryManager
有关 ExecuTorch 运行时的高级概述,请参阅运行时概述,以及有关 每个 API 请参阅 运行时 API 参考。这是一个功能齐全的 C++ 模型运行器版本,设置 ExecuTorch 文档展示了如何构建和运行它。
先决条件¶
您将需要一个 ExecuTorch 模型来遵循。我们将使用
从 导出到 ExecuTorch 教程生成的模型。SimpleConv
模型加载¶
运行模型的第一步是加载它。ExecuTorch 使用称为 a 的抽象来处理检索文件数据的细节,然后表示加载的状态。DataLoader
.pte
Program
用户可以定义自己的 以满足其特定系统的需要。在本教程中,我们将使用 ,但您可以在 Example Data Loader Implementations 下查看 ExecuTorch 项目提供的其他选项。DataLoader
FileDataLoader
我们需要做的就是提供构造函数的文件路径。FileDataLoader
using executorch::aten::Tensor;
using executorch::aten::TensorImpl;
using executorch::extension::FileDataLoader;
using executorch::extension::MallocMemoryAllocator;
using executorch::runtime::Error;
using executorch::runtime::EValue;
using executorch::runtime::HierarchicalAllocator;
using executorch::runtime::MemoryManager;
using executorch::runtime::Method;
using executorch::runtime::MethodMeta;
using executorch::runtime::Program;
using executorch::runtime::Result;
using executorch::runtime::Span;
Result<FileDataLoader> loader =
FileDataLoader::from("/tmp/model.pte");
assert(loader.ok());
Result<Program> program = Program::load(&loader.get());
assert(program.ok());
设置 MemoryManager¶
接下来,我们将设置 .MemoryManager
ExecuTorch 的原则之一是让用户控制运行时使用的内存来自何处。今天(2023 年底),用户需要提供 2 个不同的分配器:
方法分配器:用于在加载时分配运行时结构。Tensor 元数据、内部指令链和其他运行时状态等内容都来自此。
MemoryAllocator
Method
Planned Memory (计划内存):A 包含 1 个或多个内存竞技场,其中放置了内部可变张量数据缓冲区。在加载时,内部张量的数据指针被分配给其中的各种偏移量。这些偏移量的位置和竞技场的大小是由内存提前规划确定的。
HierarchicalAllocator
Method
在此示例中,我们将从 中动态检索计划内存 arenas 的大小,但对于无堆环境,用户可以提前检索此信息并静态分配 arena。我们还将对方法分配器使用基于 malloc 的分配器。Program
Program
// Method names map back to Python nn.Module method names. Most users will only
// have the singular method "forward".
const char* method_name = "forward";
// MethodMeta is a lightweight structure that lets us gather metadata
// information about a specific method. In this case we are looking to get the
// required size of the memory planned buffers for the method "forward".
Result<MethodMeta> method_meta = program->method_meta(method_name);
assert(method_meta.ok());
std::vector<std::unique_ptr<uint8_t[]>> planned_buffers; // Owns the Memory
std::vector<Span<uint8_t>> planned_arenas; // Passed to the allocator
size_t num_memory_planned_buffers = method_meta->num_memory_planned_buffers();
// It is possible to have multiple layers in our memory hierarchy; for example,
// SRAM and DRAM.
for (size_t id = 0; id < num_memory_planned_buffers; ++id) {
// .get() will always succeed because id < num_memory_planned_buffers.
size_t buffer_size =
static_cast<size_t>(method_meta->memory_planned_buffer_size(id).get());
planned_buffers.push_back(std::make_unique<uint8_t[]>(buffer_size));
planned_arenas.push_back({planned_buffers.back().get(), buffer_size});
}
HierarchicalAllocator planned_memory(
{planned_arenas.data(), planned_arenas.size()});
// Version of MemoryAllocator that uses malloc to handle allocations rather then
// a fixed buffer.
MallocMemoryAllocator method_allocator;
// Assemble all of the allocators into the MemoryManager that the Executor will
// use.
MemoryManager memory_manager(&method_allocator, &planned_memory);
加载方法¶
在 ExecuTorch 中,我们从 at 方法粒度加载和初始化。许多程序只有一个方法 'forward' 。 是完成初始化的地方,从设置 Tensor 元数据到初始化委托等。Program
load_method
Result<Method> method = program->load_method(method_name);
assert(method.ok());
设置输入¶
现在我们有了方法,我们需要先设置它的输入 执行推理。在这种情况下,我们知道我们的模型需要一个 (1, 3, 256, 256) sized float 张量。
根据模型的内存规划方式,计划的内存可能会或可能 不包含用于输入和输出的缓冲区。
如果输出没有进行内存规划,则用户需要使用 'set_output_data_ptr' 设置输出数据指针。在这种情况下,我们只假设我们的模型是导出的,输入和输出由内存计划处理。
// Create our input tensor.
float data[1 * 3 * 256 * 256];
Tensor::SizesType sizes[] = {1, 3, 256, 256};
Tensor::DimOrderType dim_order = {0, 1, 2, 3};
TensorImpl impl(
ScalarType::Float, // dtype
4, // number of dimensions
sizes,
data,
dim_order);
Tensor t(&impl);
// Implicitly casts t to EValue
Error set_input_error = method->set_input(t, 0);
assert(set_input_error == Error::Ok);
执行推理¶
现在我们的方法已加载并设置了我们的输入,我们可以执行推理。我们通过调用 .execute
Error execute_error = method->execute();
assert(execute_error == Error::Ok);
检索输出¶
一旦我们的推理完成,我们就可以检索我们的输出。我们知道我们的模型只返回一个输出张量。这里的一个潜在陷阱是,我们得到的输出归 .用户应注意在对其执行任何更改之前克隆其输出,或者如果他们需要它的生命周期与 .Method
Method
EValue output = method->get_output(0);
assert(output.isTensor());
结论¶
本教程演示了如何使用低级运行时 API 运行 ExecuTorch 模型,这些 API 提供对内存管理和执行的精细控制。但是,对于大多数使用案例,我们建议使用模块 API,它可以在不牺牲灵活性的情况下提供更简化的体验。有关更多详细信息,请查看 Module Extension Tutorial。