PyTorch ExecuTorch支持Cortex-M与CMSIS-NN加速
Bringing ExecuTorch to Arm Cortex-M CPUs
Edge AI 从业者关注端侧部署,这篇详细拆解了如何在资源受限的MCU上跑通PyTorch模型,提供了完整的代码工作流与性能数据,极具工程参考价值。
TL;DR
- Deploying PyTorch models on microcontrollers has historically required converting to other framework formats, maintaining separate toolchains, and debugging cross-framework numerical mismatches. ExecuTorch eliminates this conversion step entirely.
- The Cortex-M backend enables PyTorch models to run directly on Arm Cortex-M CPUs with Arm CMSIS-NN acceleration. It supports all capability tiers (Scalar, DSP, and MVE/Helium) from a single workflow.
- We benchmark four of the five models from the MLPerf Tiny suite on the Alif Ensemble E8. Each model runs in 21.5 ms or less and uses under 90 KiB of RAM on a single Cortex-M55 core.
- For heterogeneous SoCs, the Cortex-M backend also provides the CPU execution path alongside Ethos-U NPU delegation.
- Minimal binary footprint. The ExecuTorch core runtime is under 20 KiB of flash, and operator selective build links only the operators your model needs, so total code size scales with the model rather than the framework.
- 历史上,在微控制器上部署 PyTorch 模型需要转换为其他框架格式、维护独立工具链,并调试跨框架的数值不匹配问题。ExecuTorch 完全消除了这一转换步骤。
- Cortex-M 后端使 PyTorch 模型能够直接在带有 Arm CMSIS-NN 加速功能的 Arm Cortex-M CPU 上运行。它通过单一工作流支持所有能力层级(标量、DSP 和 MVE/Helium)。
- 我们在 Alif Ensemble E8 上对 MLPerf Tiny 套件中的五个模型中的四个进行了基准测试。每个模型在单个 Cortex-M55 核心上运行时间不超过 21.5 毫秒,且使用的 RAM 少于 90 KiB。
- 对于异构 SoC,Cortex-M 后端除了提供 Ethos-U NPU 委托外,还提供了 CPU 执行路径。
- 极小的二进制占用空间。ExecuTorch 核心运行时占用的闪存不到 20 KiB,算子选择性构建仅链接模型所需的算子,因此总代码大小随模型规模扩展,而非随框架扩展。
Background
背景
Microcontrollers power billions of always-on devices: wearables, industrial sensors, voice interfaces, and smart home appliances. These devices operate under extreme constraints: often less than 1 MB of SRAM, single-digit megabytes of flash, and power budgets measured in milliwatts. Despite these limitations, there’s growing demand to run meaningful ML workloads on these platforms and the hardware is evolving to meet it. Modern Cortex-M based microcontroller units (MCUs) now include DSP & vector ISAs, large tightly-coupled memories (TCMs), and power-efficient NPUs such as the Arm Ethos-U NPU that make ML inference more practical in resource constrained devices.
微控制器驱动着数十亿常开设备:可穿戴设备、工业传感器、语音接口和智能家居电器。这些设备在极端限制下运行:SRAM 通常不足 1 MB,闪存为个位数 MB 级别,功耗预算以毫瓦计。尽管存在这些限制,在这些平台上运行有意义的机器学习工作负载的需求日益增长,硬件也在不断演进以满足这一需求。基于现代 Cortex-M 的微控制器单元 (MCU) 现在包括 DSP 和向量 ISA、大型紧耦合内存 (TCM),以及如 Arm Ethos-U NPU 等能效型 NPU,使得在资源受限的设备中进行 ML 推理更加可行。
Until now, deploying ML on Cortex-M meant leaving the PyTorch ecosystem. Developers had to convert models to alternative formats, maintain separate toolchains for training and deployment, and debug numerical mismatches introduced during conversion. For teams that train in PyTorch, which accounts for over 90% of the research code published at top ML conferences, this translation step adds friction to every iteration cycle.
在此之前,在 Cortex-M 上部署 ML 意味着要离开 PyTorch 生态系统。开发者必须将模型转换为替代格式,为训练和部署维护独立的工具链,并调试转换过程中引入的数值不匹配问题。对于在 PyTorch 中训练的团队而言(顶级 ML 会议发表的研究报告中有超过 90% 使用 PyTorch),这一翻译步骤给每次迭代周期都增加了摩擦。
ExecuTorch was designed to eliminate this gap. Arm MCU support has been available through the Ethos-U NPU, and the Cortex-M backend extends it to Cortex-M CPUs, so a model can run on parts with or without an accelerator. The trained PyTorch model is exported, quantized and lowered for the device within the same stack that serves models on mobile, desktop and server.
ExecuTorch 旨在消除这一差距。Arm MCU 支持已通过 Ethos-U NPU 提供,而 Cortex-M 后端将其扩展至 Cortex-M CPU,因此模型可以在有无加速器的部件上运行。经过训练的 PyTorch 模型在同一堆栈内导出、量化并针对设备进行降级处理,该堆栈同时服务于移动、桌面和服务器端的模型。
The Cortex-M Backend
Cortex-M 后端
The ExecuTorch Cortex-M backend replaces standard PyTorch operators with CMSIS-NN-backed custom operators through ahead-of-time compiler passes. At inference time, these operators call directly into Arm’s CMSIS-NN library, an open source collection of optimized neural network kernels for Cortex-M processors.
ExecuTorch Cortex-M 后端通过提前编译(ahead-of-time)编译器通道,将标准 PyTorch 算子替换为基于 CMSIS-NN 的自定义算子。在推理时,这些算子直接调用 Arm 的 CMSIS-NN 库,这是一个针对 Cortex-M 处理器优化的开源神经网络内核集合。
Key properties:
关键特性:
- CMSIS-NN accelerated. Quantized operations (linear, conv, add, mul, softmax, activations, etc.) are replaced with optimized implementations that call CMSIS-NN functions and additional optimized Cortex-M implementations directly.
- Target-aware compilation. The CPU variant (M0 through M85) and ISA tier are specified at compile time, so the correct CMSIS-NN backend is selected, eliminating runtime dispatch overhead.
- Purpose-built quantizer. Produces INT8 quantized graphs matching the data layout requirements of CMSIS-NN kernels, using PyTorch’s PT2E quantization framework.
- Single compiler toolchain. The Cortex-M lowering path operates directly on the ExecuTorch edge dialect, keeping the compilation pipeline simple and debuggable.
- CMSIS-NN 加速。量化操作(线性、卷积、加法、乘法、softmax、激活函数等)被替换为优化实现,直接调用 CMSIS-NN 函数以及额外的优化 Cortex-M 实现。
- 目标感知编译。CPU 变体(M0 到 M85)和指令集架构(ISA)层级在编译时指定,因此会选择正确的 CMSIS-NN 后端,消除运行时分派开销。
- 专用量化器。使用 PyTorch 的 PT2E 量化框架,生成符合 CMSIS-NN 内核数据布局要求的 INT8 量化图。
- 单一编译器工具链。Cortex-M 降级路径直接在 ExecuTorch edge dialect 上运行,使编译流程保持简单且可调试。
Cortex-M Capability Tiers
Cortex-M 能力层级
The backend targets the full Cortex-M spectrum:
该后端面向完整的 Cortex-M 系列:
| Tier | Cores | Key Feature | Use Case |
|---|---|---|---|
| Scalar | M0, M0+, M3, M23 | Standard ARM instructions | Ultra-low-cost, minimal silicon |
| DSP | M4, M7, M33, M35P | SIMD multiply-accumulate | Mid-range MCUs, signal processing |
| MVE (aka Helium) | M55, M85 | 128-bit vector ops, beat-based execution | High-performance MCU ML inference |
| 层级 | 核心 | 关键特性 | 用例 |
|---|---|---|---|
| 标量 | M0, M0+, M3, M23 | 标准 ARM 指令 | 超低成本、最小硅片面积 |
| DSP | M4, M7, M33, M35P | SIMD 乘加运算 | 中端 MCU、信号处理 |
| MVE(又称 Helium) | M55, M85 | 128 位向量运算、基于节拍执行 | 高性能 MCU ML 推理 |
Arm Helium technology is where the biggest performance gains are. CMSIS-NN leverages Helium’s beat-based execution model to pipeline data movement and compute, providing significant throughput gains for the depthwise and pointwise convolutions common in edge ML architectures. That said, the same workflow targets all variants. The target configuration selects the appropriate backend automatically.
Arm Helium 技术带来了最大的性能提升。CMSIS-NN 利用 Helium 的基于节拍的执行模型来流水线化数据移动和计算,为边缘 ML 架构中常见的深度卷积和逐点卷积提供显著的吞吐量提升。话虽如此,相同的工作流适用于所有变体。目标配置会自动选择适当的后端。
ExecuTorch is Embedded Friendly
ExecuTorch 对嵌入式环境友好
Unlike mobile or cloud environments that must accommodate varied hardware at runtime, microcontroller deployments target a fixed hardware profile. Embedded developers possess precise knowledge of their deployment target, including the exact CPU core, available ISA extensions, SRAM allocation, and flash capacity.
与必须在运行时适应各种硬件的移动或云环境不同,微控制器部署针对固定的硬件配置文件。嵌入式开发人员对其部署目标拥有精确的知识,包括确切的 CPU 核心、可用的 ISA 扩展、SRAM 分配和闪存容量。
ExecuTorch’s ahead-of-time stack is designed to exploit this. ExecuTorch makes target-specific decisions at compile time: graph-level optimizations, memory planning, weight packing, and kernel selection are all target-aware at compile time.
ExecuTorch 的提前编译栈旨在利用这一点。ExecuTorch 在编译时做出特定于目标的决策:图级优化、内存规划、权重打包和内核选择在编译时都是目标感知的。
Concretely, for Cortex-M this means:
具体而言,对于 Cortex-M 来说这意味着:
- Graph-level compute elimination. Redundant dtype conversions, quantize/dequantize pairs, and memory format transposes are removed during lowering, so only necessary compute reaches the device.
- Quantization parameter folding. Scale and zero-point arithmetic is precomputed into integer multiplier/shift form at export, so quantized kernel inference stays entirely in fixed-point.
- AOT weight layout transposition. Convolution weights are transposed from PyTorch’s native layout (OIHW) to CMSIS-NN’s expected format (OHWI) at export time. The permute cost is paid once during compilation and never at inference.
- Static memory planning across heterogeneous memories. All tensor and scratch buffers are allocated and laid out ahead of time, with support for spanning multiple memory regions (e.g., TCM and SRAM). Developers can also customize placement to put latency-critical buffers in fast local memory. No heap allocator, no fragmentation, and no runtime memory management required.
- Target-specific operator replacement. The CortexMPassManager selects CMSIS-NN kernel variants matched to your core’s ISA tier (Scalar, DSP, or MVE) at compile time, not at runtime.
- 图级计算消除。在 lowering(降低)过程中,移除冗余的 dtype 转换、量化/反量化对以及内存格式转置,因此只有必要的计算才会到达设备。
- 量化参数折叠。导出时,比例和零点算术运算被预计算为整数乘数/移位形式,因此量化内核推理完全保持在定点运算中。
- AOT 权重布局转置。卷积权重在导出时从 PyTorch 的原生布局(OIHW)转置为 CMSIS-NN 期望的格式(OHWI)。置换成本仅在编译期间支付一次,推理时不再产生。
- 跨异构存储器的静态内存规划。所有张量和临时缓冲区均预先分配并布局,支持跨越多个内存区域(例如 TCM 和 SRAM)。开发者还可以自定义放置策略,将延迟敏感的缓冲区放入快速本地存储器中。无需堆分配器,无碎片问题,也无需运行时内存管理。
- 针对特定目标的算子替换。CortexMPassManager 在编译时根据核心指令集架构层级(Scalar、DSP 或 MVE)选择匹配的 CMSIS-NN 内核变体,而非在运行时选择。
Developer Workflow
开发者工作流
import torch
from torchao.quantization.pt2e.quantize_pt2e import convert_pt2e, prepare_pt2e
from executorch.backends.cortex_m.edge_compile_config import cortex_m_edge_compile_config
from executorch.backends.cortex_m.passes.cortex_m_pass_manager import CortexMPassManager
from executorch.backends.cortex_m.quantizer.quantizer import CortexMQuantizer
from executorch.backends.cortex_m.target_config import CortexM, CortexMTargetConfig
from executorch.exir import to_edge_transform_and_lower
# 1. Export
model = MyModel().eval()
example_inputs = (torch.randn(1, 1, 49, 10),)
exported = torch.export.export(model, example_inputs)
# 2. Quantize and calibrate
quantizer = CortexMQuantizer(use_explicit_layout=True)
prepared = prepare_pt2e(exported.module(), quantizer)
for sample in calibration_data:
prepared(sample)
quantized = convert_pt2e(prepared)
# 3. Re-export the quantized model
quantized_exported = torch.export.export(quantized, example_inputs)
# 4. Lower to Edge and apply the Cortex-M passes
pass_manager = CortexMPassManager(
target_config=CortexMTargetConfig(cpu=CortexM.M55),
use_explicit_layout=True,
)
edge = to_edge_transform_and_lower(
quantized_exported,
compile_config=cortex_m_edge_compile_config(),
transform_passes=pass_manager,
)
# 5. Serialize for integration into firmware
et_program = edge.to_executorch()
with open("model.pte", "wb") as f:
f.write(et_program.buffer)The resulting .pte binary is linked into firmware alongside the ExecuTorch runtime and CMSIS-NN library, then flashed to the device. At runtime, inference executes the precompiled graph with minimal runtime overhead and no dynamic memory allocation for tensors.
生成的 .pte 二进制文件与 ExecuTorch 运行时和 CMSIS-NN 库一起链接到固件中,然后烧录到设备上。在运行时,推理执行预编译的图,具有极低的运行时开销,且不为张量进行动态内存分配。
Using the Cortex-M Backend Alongside Ethos-U
在 Ethos-U 旁边使用 Cortex-M 后端
更进一步:量化金融体系
看懂新闻只是起点——沿量化金融路径,把它变成能交付的工程能力