ExecuTorch端侧推理教程 · 03-运行时核心Module与Method解释器

03 - 运行时核心:Module、Method 与解释器指令循环

所属系列:ExecuTorch 端侧推理教程 | 前置:02-AOT导出工具链与量化 | 下一篇:04-内存规划与零分配运行时
证据基线:commit 8c3f75df(version.txt = 1.6.0)。本章所有 文件:行号 均在本 checkout 实测。

本篇知识图谱

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((Module Method 解释器))
三层 C++ API
Program 字节码容器
Method 可执行方法
Module facade 门面
execute 四步调用链
解释器主循环
chain 循环 外层
instruction 循环 内层
输入与并发防御
ET_MAX_INSTRUCTIONS 上限
结束 reset_execution
五类指令
KernelCall 调算子
DelegateCall 交后端
JumpFalseCall 条件跳转
MoveCall 引用搬家
FreeCall 释放数据指针
算子分发
resolve_operator 加载期
TensorMeta dtype dim_order
KernelKey 字符串形态
fallback 兜底语义
定长全局注册表 2000 槽
执行期零字符串查找

本篇目标

  1. 分清三层 C++ API 的分工:Program 是字节码容器,Method 是可执行单元,Module 是面向 App 的门面。
  2. 逐行读懂解释器主循环:chain 套 instruction 的双循环、两个防御设计、五类指令各自的执行语义。
  3. 吃透算子分发机制:op 名 + KernelKey 如何在加载期一次 resolve 成函数指针写入 chain.kernels_,让执行期零字符串查找。
  4. 理解定长全局注册表(2000 槽)与 fallback kernel 的兜底逻辑。

1. 三层 C++ API:Program / Method / Module

设备端 API 分三层,由外到内:

  • Module(extension/module/module.h:51):注释原文 “A facade class for loading programs and executing methods within them”。支持 LoadMode::File(整读)与 Mmap(按页映射,:56-60)。App 代码只需要它。
  • Method(runtime/executor/method.h):一个可独立执行的计算方法(如 forward)。关键类型 OpFunction = void (*)(KernelRuntimeContext&, Span<EValue*>)(method.h:53)——每个已解析算子在运行时的形态就是一个普通函数指针。
  • Program:.pte 反序列化后的字节码容器,持有全部 Method 的序列化计划与常量数据。

门面到解释器的调用链(Observed in source,extension/module/module.cpp:672-690):Module::execute(method_name, input_values) = load_method → 逐 index method->set_input → method->execute() → get_outputs 打包。01 章已画过全图;本章沉到 Method::execute 内部。

2. 解释器主循环(runtime/executor/method.cpp:1950-2027)

Method::execute()(:1950)是引擎心脏,结构极简——外层 chain 循环套内层 instruction 循环:

1
2
3
4
5
6
7
8
9
for (step_state_.chain_idx = 0; ...; ++step_state_.chain_idx) {   // :1978
Chain& chain = chains_[step_state_.chain_idx];
step_state_.instr_idx = 0;
while (step_state_.instr_idx < chain.s_chain_->instructions()->size()) { // :1990
...
auto status = execute_instruction(); // :2014
...
}
}

循环前后有三个防御设计(Observed in source):

  1. 前置校验:initialized() 才能执行(:1956-1959)、无并发执行(in_progress() 用 step_state_ 判断,:1945-1948 与 :1960-1961)、全部输入已 set(:1963-1969)。
  2. 防死循环上限:instruction_count >= kMaxInstructions 时报 “Possible infinite loop detected… raise the limit by rebuilding with -DET_MAX_INSTRUCTIONS=<value>” 并返回 Error::InvalidProgram(:1991-2003)。上限来自编译宏:kMaxInstructions = ET_MAX_INSTRUCTIONS(:53)。防的是 JumpFalseCall 控制流把解释器锁死——字节码是 AOT 产物,出错时用户手里只有这个宏能救(Derived:为何用编译期常量而非运行时配置,见 §5)。
  3. 收尾归零:执行完 reset_execution()(:2026),注释明示「连续执行必须先经 reset api」;每条指令前 temp allocator 复位(:1971-1973),每条指令后也复位(:1856 注释)。

3. 五类指令(execute_instruction,method.cpp:1719-1856)

execute_instruction() 是一个大 switch(:1719)。flatbuffer 加载/验证期的同名 case 在 :1213-1315;下表合并两侧证据(行号前者=执行分支,后者=加载分支):

指令 执行分支 加载分支 语义(Observed in source)
KernelCall :1720-1755 :1213 chain.kernels_[instr_idx] (context, args)(:1727)——直接调加载期解析好的函数指针;失败时用 op_index 从序列化计划取 op->name()->c_str() 打详细日志(:1733-1743)
DelegateCall :1756-1802 :1245 校验 delegate_index < n_delegate_(:1764-1771),构造 BackendExecutionContext(含 delegates_[idx].scratch(),:1772-1776),delegates_[idx].Execute(...)(:1777-1779)整段子图交给后端
JumpFalseCall :1803-1821 :1300 取 cond 值(:1812-1813),false 时 next_instr_idx = destination_instruction(:1815-1817)——唯一的控制流指令
MoveCall :1822-1830 :1308 mutable_value(move_to) = get_value(move_from)(:1829)——EValue 引用搬家(循环携带的中间量)
FreeCall :1831-1848 :1315 tryToTensor 后 internal::reset_data_ptr(t.get())(:1838-1847)——把生命周期结束的 planned 张量数据指针交还,为下轮执行复用(与第 04 章的内存规划联动)
default :1849-1854 — 未知指令 → Error::InvalidProgram

一个值得记住的细节:KernelCall 失败日志会打印算子名与逐参数 type id(:1744-1750),注释承认这是失败路径「慢一点无所谓」——可见日志与性能在这里是明确分层的。

4. 算子分发:加载期解析,执行期零查找

4.1 resolve_operator 四步(method.cpp:902-1011)

每个 KernelCall 指令在 Method 加载期(加载分支 KernelCall case 内,调用点 :1230)走 Method::resolve_operator(:902):

  1. 拼 op 名(:911-926):serialization_plan_->operators()->Get(op_index) 取 op + overload,populate_operator_name 拼成完整名(如 aten::add.out)。
  2. 抽 TensorMeta(:928-976):遍历该指令的实参 EValue,对每个 tensor 抽两样——meta[count].dtype_ = tensor.scalar_type()(:955)与 dim_order_(:956-973,get_dim_order 提取)。TensorMeta 缓冲先试 temp allocator、不够再回退 method allocator(:931-940)。
  3. 两级查表(:978-990):lambda 先查 method-scoped kernel_registry_(:981-988),失败回退全局注册表(:989)。
  4. 写槽位(:1003):kernels[kernel_index] = op_function.get()——函数指针落进 chain 的 kernels 数组。找不到则报 “Missing operator: [idx] 名字”(:993-997)。

4.2 KernelKey:字符串形态的特化键

KernelKey(runtime/kernel/operator_registry.h:119)实测不是数值结构,而是一根预生成字符串(Observed in source,头注释 :100-113):

  • 格式 "v<version>/<dtype>;<dim_order,...>|<dtype>;<dim_order,...>",示例 v1/7;0,1,2,3|1;0,1,2,3,4,5,6,7(:110)——两个 tensor:dtype=7 + 维度序 0,1,2,3、dtype=1 + 维度序 0,1,…,7;
  • 注释明说由 kernel yaml 生成、用户不应手工构造(:115-117);
  • fallback key = nullptr(is_fallback(),:156-158):equals 里 fallback 与一切特化键相等(:148-152),特化键之间才 strcmp(:153-155)。

即「dtype/dim-order 特化」在编译期就烧成了字符串键,加载期只做一次字符串比较来选 kernel。

4.3 定长全局注册表与查找

注册表本体在 runtime/kernel/operator_registry.cpp:22-62(Observed in source):

  • 容量三级解析(:30-42):用户宏 -DMAX_KERNEL_NUM → selective build 生成的 EXECUTORCH_SELECTED_MAX_KERNEL_NUM → 默认 kMaxOperators=250 × kMaxKernelsPerOp=8 = 2000 槽(:39-41)。
  • 静态零内存(:51-59):因 Kernel 含自定义构造的 KernelKey,为避免静态初始化期构造,直接分配 zeroed KernelBuffer 数组再用 reinterpret_cast 当 Kernel* 表——无堆、无动态初始化,MCU 友好。
  • 计数器 num_registered_kernels(:62),注册入口 register_kernels_internal(:65-,静态初始化期调用)。

查找 get_op_function_from_registry(:250-281):make_kernel_key_string 把 TensorMeta 数组编码成 key 字符串(:254-257)→ 遍历表 strcmp 匹配 op 名(:261)→ KernelKey 精确相等即返回 op_(:262-264),否则记 fallback_idx(:265-267)→ 遍历完无精确命中就用 fallback(:269-271)→ 仍无则 “kernel ‘%s’ not found.” + Error::OperatorMissing(:272-275)。全局版只是把表参数换成 get_registered_kernels()(:282-289)。选择规则一句话:同名先挑特化键,全表没有特化才落 fallback(Derived,自 :261-271 行为)。

4.4 零查找闭环

Chain 结构定义在 method.cpp:259-267:s_chain_(flatbuffer 引用)+ argument_lists_(每指令实参列表)+ kernels_(:266,注释原文 “Each instruction will have one kernel (not for delegate).”)。闭环就是:

1
2
加载期(一次): op 名 + TensorMeta → make_kernel_key_string → 注册表查找 → kernels_[instr_idx] = 函数指针   (:1230 → :902 → :1003)
执行期(每次): chain.kernels_[instr_idx](context, args) (:1727,直接调用,无任何字符串/哈希查找)

5. 为什么这样设计(Derived)

  • 定长表 + 静态零内存(operator_registry.cpp:51-62):嵌入式目标可能禁用静态动态构造、堆分配有限——2000 槽上限换来零初始化成本,代价用 -DMAX_KERNEL_NUM / selective build 收缩或扩张(:30-42)。
  • 字符串 KernelKey 而非数值键:键由 kernel yaml 在构建期生成,调试时直接可读(v1/7;0,1,...),且 fallback 语义用一个 nullptr 天然表达;代价是加载期一次 strcmp 遍历——但那是每 Method 加载一次,不是每 token 每算子。
  • 编译期防死循环上限(:53):端侧没有作业系统兜底超时,无限循环 = 烧电死机;用一个重建才可调的宏把风险限制在构建期决策里。
  • 主循环里 chain「今天顺序执行」(:1975-1976 注释原文 “Chains are executed sequentially today, but future async designs may branch…”)——为异步执行留了结构口子。

本篇小结

  • 三层 API:Module(module.h:51 facade,File/Mmap 两种 LoadMode)→ Method(OpFunction 即 void (*)(KernelRuntimeContext&, Span<EValue*>),method.h:53)→ Program。Module::execute 四步链(module.cpp:672-690)。
  • 主循环(method.cpp:1950-2027):chain 套 instruction 双循环,三个防御(输入/并发校验、ET_MAX_INSTRUCTIONS 上限 :53+:1991-2003、收尾 reset :2026)。
  • 五类指令:KernelCall(:1727 直调函数指针)/ DelegateCall(:1777 交后端含 scratch)/ JumpFalseCall(:1816 跳转)/ MoveCall(:1829 引用搬家)/ FreeCall(:1847 还数据指针)。
  • 算子分发:加载期 resolve_operator(:902-1011)用 op 名 + TensorMeta{dtype, dim_order} 编码成 KernelKey 字符串,两级注册表(method-scoped 优先)解析成函数指针写入 chain.kernels_(:266/:1003);执行期 :1727 零查找直调。
  • 注册表:定长 2000 槽三级容量解析(operator_registry.cpp:30-42)+ 静态零内存(:51-59)+ 精确命中优先、fallback 兜底(:250-281)。

前置:02-AOT导出工具链与量化 | 下一篇:04-内存规划与零分配运行时 | 回目录