ExecuTorch端侧推理教程 · 09-构建体系与进阶专题

09 - 构建体系、多语言绑定与进阶专题

所属系列:ExecuTorch 端侧推理教程 | 前置:08-批处理调度与服务化 | 下一篇:无(系列终章)| 回目录
证据基线: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
28
29
30
31
32
33
34
35
36
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((构建体系与进阶))
CMake 开关矩阵
83 个 define_overridable_option
PAL 日志枚举校验
CPU 与选择性构建互斥
IF_ON REQUIRES 依赖 DSL
OPTIMIZE_SIZE 模式
平台预设
configurePresets 30+
android ios zephyr riscv
llm-release GPU 家族
build 与 workflow 预设
pip wheel 三轨
源码轨 editable minimal
nightly 轨 pinned 切换
CPU 与 CUDA wheel 矩阵
多语言绑定
ExecuTorchModule pybind
_llm_runner 模块加 pyi
WASM JsModule
initWebGPU 开关
多模态
MultimodalRunner
encoder 到 embeddings
embedding 拼接
decoder KV 自回归
cross_attention 子模块
devtools 与测试
etdump inspector
pte_tool
size_analysis_tool
etrecord
runtime kernels 测试树
全系列阅读路线

本篇目标

  1. 掌握 CMake 选项矩阵:83 个 define_overridable_option 开关、FATAL_ERROR 强校验与 IF_ON ... REQUIRES 依赖 DSL,配 30+ 平台预设选型。
  2. 分清 pip wheel 三轨构建(源码轨 / nightly 轨 / CPU-CUDA wheel 矩阵)。
  3. 一览多语言绑定:pybind 双模块(ExecuTorchModule + _llm_runner)与 WASM/WebGPU。
  4. 进阶专题收束全系列:多模态四件套、devtools 工具箱、测试布局与源码阅读路线。

1. CMake 开关矩阵:83 个开关 + 强校验

tools/cmake/preset/default.cmake:19-405 集中定义全部选项,全部走 define_overridable_option 宏——实测 grep -c 'define_overridable_option(' = 83 个(Observed in source)。代表性开关(:19-60 区段):EXECUTORCH_ENABLE_LOGGING(debug 构建默认开)、EXECUTORCH_BUILD_COREML/COREAI、EXECUTORCH_FLATBUFFERS_MAX_ALIGNMENT(STRING 1024,exir 可调张量对齐)、EXECUTORCH_PAL_DEFAULT(posix/minimal/android 三选一)、EXECUTORCH_ENABLE_PROGRAM_VERIFICATION/EVENT_TRACER/BUNDLE_IO、EXECUTORCH_OPTIMIZE_SIZE(体积优化模式,第 05 章调度器的 -fno-exceptions 即来自它)。

选项不是随便组合的,default.cmake 里有三重强校验(Observed in source):

  • 互斥:EXECUTORCH_BUILD_CPU 与选择性构建不能共存——三个 EXECUTORCH_SELECT_OPS_* 变量任一非空即 FATAL_ERROR "EXECUTORCH_BUILD_CPU does not support selective kernel builds"(:537-545);
  • 依赖 DSL:IF_ON EXECUTORCH_BUILD_NATIVE_CPU REQUIRES EXECUTORCH_BUILD_XNNPACK EXECUTORCH_BUILD_KERNELS_OPTIMIZED(:601-604)——声明式依赖,缺了构建期直接拦下;
  • 枚举/存在性:EXECUTORCH_PAL_DEFAULT 文件不存在 FATAL(:606-613,提示三个合法值);EXECUTORCH_LOG_LEVEL 非 Debug/Info/Error/Fatal 即 FATAL(:619-623)。

选型口诀承第 01 章(CMakePresets.json configurePresets :3-428):平台预设给「整套合理开关组合」,default.cmake 的 83 个开关是预设背后的自由度。

2. pip wheel 三轨构建

Python 侧的三条构建轨道(前两轨第 导读 已铺,第三轨本章补齐):

  • 源码轨:install_executorch.py(main 三步 install_executorch.py:215-259)——--editable 改 exir 源码免重装、--minimal 剪掉示例依赖、--optional-dependency ethos_u|vgf|openvino 接 NPU extras;
  • nightly 轨:默认拉 PyTorch nightly(:230 use_pytorch_nightly = not args.use_pt_pinned_commit),CI 用 --use-pt-pinned-commit 锁定版复现回归;版本号经 setup.py:1294-1296 落自 version.txt;
  • 平台 wheel 矩阵轨:setup.py 的 _cuda_train()(:717-724,Observed in source)——wheel 按 CUDA major 版本分轨(“or "" for a CPU wheel”),发布行的 CU_VERSION/DESIRED_CUDA 字段定 target train,非 release 构建回退到本机 toolkit。所以 PyPI 上 wheel 是「CPU 行 + 各 CUDA train 行」的矩阵,不是单一包。

3. 多语言绑定:pybind 双模块与 WASM/WebGPU

3.1 pybind:一个运行时模块 + 一个 LLM 模块

  • 通用运行时绑定(extension/pybindings/pybindings.cpp:6021 起,Observed in source):py::class_<PyModule>(m, "ExecuTorchModule")——plan_execute(:6023)、method_meta(:6029)、method_names(:6034)、run_method(:6035)、forward(:6043+);后接 ExecuTorchProgram(:6121-6145 区段,num_methods 等)。第 01 章 executorch.runtime pybind 的 Runtime/Program/Method 三个类型即出自这一族。
  • LLM 绑定(extension/llm/runner/pybindings.cpp:254,Observed in source):PYBIND11_MODULE(_llm_runner, m)——GenerationConfig(:261)、Stats(:312,含 on_sampling_begin/end :333-334)、Image(:358)等类;配套类型 stub extension/llm/runner/_llm_runner.pyi(文件头 “Type stubs for _llm_runner module”)让 Python 侧有补全。extension_llm_runner 是独立静态库(runner/CMakeLists.txt:40),CUDA 可用时注入 CUDA_AVAILABLE 宏(:74)。

3.2 WASM:浏览器里的解释器

extension/wasm/wasm_bindings.cpp:707-732(Observed in source):EMSCRIPTEN_BINDINGS(WasmBindings) 导出——EXECUTORCH_WASM_WEBGPU 开关下暴露 initWebGPU(:708-710)——WebGPU 后端经同一个委派体系接进来(第 06 章 backends/webgpu);ScalarType/Tag 枚举逐一映射(:711-715);event tracer 开启时导出 ETDumpResult.buffer(:717-721,供 JS 侧取 profiling 数据);JsModule 全 API:load / getMethods / loadMethod / getMethodMeta / etdump / execute / forward(:723-732)——与 C++ Module facade(第 03 章)同构。

4. 多模态:MultimodalRunner 与四件套

extension/llm/runner/multimodal_runner.h:48-78(Observed in source):MultimodalRunner : public IRunner(:78),docstring 自述支持 “LLaVA, CLIP-based vision-language models, and speech-to-text models”(:52-53)。管线四件套按 docstring Key Features(:57-65):

  1. 混合输入:std::vector<MultimodalInput> 任意顺序混排文本/图像/音频(:58-59);
  2. 模态 encoder:非文本模态(images, audio)→ embeddings(:60);
  3. embedding 拼接:Text tokenizer 出文本 embedding,与视觉 embedding “stitched together based on input ordering”(:61-62)——顺序即语义;
  4. text decoder:带 KV cache 自回归生成,pos_ 内部状态跨调用追踪 KV 位置(:63-64)。

用法示例就在 docstring(:67-76):make_text_input("Describe this image:") + make_image_input(...) 后直接 generate(inputs, config, token_callback, stats_callback)——第 07 章 IRunner 的 prefill(MultimodalInput...)(irunner.h:158-163)正是它的入口。cross-attention 路线以 examples/models/llama3_2_vision/cross_attention/cross_attention_mask.h 为代表(grep 实测),vision token 经交叉注意力注入 decoder,而非 embedding 拼接。

5. devtools:etdump、pte_tool、size analysis

devtools/ 目录 ls 实测全家桶:etdump/、etrecord/、inspector/、pte_tool/、size_analysis_tool/、backend_debug/、bundled_program/、debug_format/、intermediate_output_tap/。三个高频工具:

  • etdump + inspector:.pte 需 event tracer 构建(CMake EXECUTORCH_ENABLE_EVENT_TRACER=ON,§1;01 章引用的 runtime/init.py docstring(:38-41)亦有提示),运行产出 etdump,inspector 解析成时间线/逐算子事件——第 03 章主循环里的 EventTracerProfileOpScope(method.cpp:1722 等)就是它的数据源(Derived);
  • pte_tool:直接解剖 .pte(方法名、元信息、委派段),diff 两个 pte 找差异——AOT 改动回归排查的第一站;
  • size_analysis_tool:按 op/kernel 报告体积构成,与 EXECUTORCH_OPTIMIZE_SIZE、选择性构建(第 05 章)配套做瘦身。

etrecord(导出期快照 eager→edge→backend 各阶段图)与 bundled_program 也是集成调试的常客(Derived,自目录与 01 章 generate_etrecord 参数 export/export.py:59)。

6. 测试布局与全系列阅读路线

6.1 测试地图

实测布局:runtime/test/(test_runtime.py、test_runtime_etdump_gen.py、test_runtime_xnnpack.py——Python 驱动的端到端运行时测试);kernels/portable/test/(14 个文件,逐算子单测);extension/llm/*/test/(batching/sampler/runner 各自单元测试,08 章 CellCache 的 seq 语义即在此验证);export/tests/(02 章 from executorch.export import export 的官方用例 test_executorch_export.py:12);backends/*/test/ 与 devtools 自测。惯例:runtime 用 pytest 驱动真实 Module,kernel 层 gtest 逐 op(Derived,自文件构成)。

6.2 全系列源码阅读路线

十读 ExecuTorch 的三条主线(对照 llama.cpp 系列 的读码路线):

  1. 数据流主线(.pte 怎么来、怎么跑):01 全景 → 02 导出流水线 → 03 解释器 → 04 内存规划。读懂这条即可集成。
  2. 算力主线(算子在哪执行):05 CPU 三层 → 06 委派体系 → 09 本章绑定/构建。读懂这条即可接硬件/改 kernel。
  3. LLM 主线(端侧服务):07 Runner/KV/采样 → 08 批处理/服务化。读懂这条即可跑端侧 LLM 服务。

建议动过的锚点全部用函数名重新校验(rg "resolve_operator" -n runtime/ 式检索),行号只是本 commit 的快照。

本篇小结

  • 构建两层:CMake 侧 default.cmake 集中定义 83 个开关(:19-405)+ 三重强校验(互斥 :537-545、IF_ON REQUIRES DSL :601-604、枚举/存在性 :606-623)+ 30+ 平台预设(CMakePresets.json :3-428);pip 侧三轨——源码(install_executorch.py:215-259)/ nightly(pinned 可切)/ CPU-CUDA wheel 矩阵(setup.py:717-724)。
  • 绑定双模块:pybind 的 ExecuTorchModule(pybindings.cpp:6021)与 _llm_runner(runner/pybindings.cpp:254,配 .pyi stub);WASM 导出 JsModule 同构 C++ facade,EXECUTORCH_WASM_WEBGPU 接 WebGPU(wasm_bindings.cpp:707-732)。
  • 多模态四件套(multimodal_runner.h:57-65):混合 MultimodalInput → 模态 encoder → embedding 顺序拼接 → decoder 自回归 + KV;cross-attention 路线见 llama3_2_vision。
  • devtools 五件(etdump/etrecord/inspector/pte_tool/size_analysis_tool)覆盖「跑起来」到「瘦下去」;测试布局 runtime pytest 端到端 + kernel gtest 单测。
  • 全系列阅读路线三条主线:数据流(01→02→03→04)、算力(05→06→09)、LLM(07→08)。

前置:08-批处理调度与服务化 | 回目录