MNN推理引擎教程 · 05-Backend双层抽象与调度执行链

05 - 运行时架构:Backend/Runtime 双层抽象与调度执行链

所属系列:MNN 推理引擎教程 | 前置:04-KVCache与状态复用 | 下一篇:06-CPU后端深潜与GEMM内核
证据基线:commit da16b74d。主战场 source/core/Backend.hpp、source/core/Backend.cpp、source/core/Schedule.cpp、source/core/Pipeline.cpp、source/core/Session.cpp、express/module/StaticModule.cpp。设备内部行为(各 GPU backend 的 kernel 实现)标注 Unknown,07 章展开。

本篇知识图谱

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
37
38
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((Backend与调度执行链))
双层抽象
Backend 契约
Info type numThread mode
StorageType 四态
onAcquire onCopyBuffer
getMetaPtr KV便签
Runtime 契约
onCreate出Backend
onGabageCollect
onMeasure探测
AllocatorType Eager Defer
张量内存
halide_buffer_t
InsideDescribe
四种MemoryType
Region视图
Execution onResize onExecute
注册中心
GetExtraCreator静态map
needCheck探测位
registerBackend条件编译
AUTO调度
八级优先级表
backupType回退
Power_Low探测
Schedule生成pipelineInfo
执行链
StaticModule内嵌Session
Session run逐Pipeline
Pipeline execute逐command
Execution onExecute
GPU兜底
onMeasure initCostLong
Turn back to cpu
整组重置重建

本篇目标

  1. 建立 Backend/Runtime 双层抽象的完整心智模型:谁管内存、谁管设备、谁管算子。
  2. 看懂注册中心的静态 map + needCheck 探测位,以及 MNN_FORWARD_AUTO 的八级优先级表与两级回退。
  3. 纵向走通一条执行链:StaticModule::onForward → Session::run → Pipeline::execute → Execution::onExecute。
  4. 理解 GPU init 过慢时"整组重置回退 CPU"的兜底机制。

1. 双层抽象:Backend 与 Runtime 各管什么

source/core/Backend.hpp 是全仓后端的宪法(Observed in source):

Backend(:88-290)——“一块设备上的执行现场”。构造即绑定 forward type(:144-146)。核心契约:

契约 行号 语义
Info{type, numThread/gpuMode, user, mode} :92-110 创建参数;mode 分 DIRECT(onExecute 直接跑)/ INDIRECT(记录-回放)
onCreate(inputs, outputs, op) :162-163 算子工厂:给定 Op 造 Execution,不支持返回 nullptr
onResizeBegin/End :168-179 resize 两阶段回调(可在此录制/合并 command)
onExecuteBegin/End :187-191 执行前后钩子(GPU 提交/等待的挂点)
onAcquire/onRelease/onClearBuffer、onCopyBuffer :203/:211/:243/:250 内存四件套,按 StorageType 语义分配
onMapTensor/onSync :265/:273 GPU tensor map/unmap
getMetaPtr/setMetaPtr :278-283 04 章 KV 便签的存放点

StorageType 四态(:113-137)规定了 buffer 生命周期语义:STATIC(用了就放,onClearBuffer 不动它)、DYNAMIC(可复用,onClearBuffer 回收池)、DYNAMIC_SEPERATE(不复用,但 onClearBuffer 统一放)、DYNAMIC_IN_EXECUTION——同一套 API,四种释放策略。

Runtime(:293-416)——“设备上下文工厂”。onCreate(config, origin) 造 Backend(:326);onReset(:331)、onGabageCollect(level)(:339,0-100 清扫强度)、onGetMemoryInMB(:344)是资源管理面;onMeasure(inputs, outputs, op, OpInfo)(:381-384)预检算子并上报 initCostLong/executionCost——第 7 节的回退机制全靠它。AllocatorType(:306-309)Eager/Defer 两态是 07 章内存体系的入口。还有两个"跨后端共享"的槽:void* pMeta(:412,04 章注入链的广播终点)与 mCancelled/异步 future(:392-395)。

**RuntimeCreator(:419 起)**是第三层:注册表里的条目,onCreate(Backend::Info) 造 Runtime。

2. 张量内存:halide_buffer_t + InsideDescribe

Tensor 的本体是 halide_buffer_t mBuffer; struct InsideDescribe* mDescribe;(include/MNN/Tensor.hpp:312-313)——buffer 只存"维度/类型/设备指针",真正的调度元信息全在 InsideDescribe(source/core/TensorUtils.hpp:41-104)。四种内存态(MemoryType,:58-70):MEMORY_BACKEND(内存来自 Backend)、MEMORY_HOST(张量自持 host 内存)、MEMORY_VIRTUAL(无内存,纯视图)、MEMORY_OUTSIDE(内存来自外部)——与 Backend 的 StorageType 正交:前者描述"内存从哪来",后者描述"内存怎么还"。Region/View(:42-51)描述跨张量视图(src/dst 视图 + origin 指针),是几何系统做 raster 的原料。

Execution 契约(source/core/Execution.hpp):构造绑定 Backend(:31-33);onResize(inputs, outputs)(:45-48,默认 NO_ERROR,形状变化时重排 buffer)+ onExecute(:55-58,纯虚,真正计算)——"先 resize 后 execute"是所有后端所有算子的统一两拍。

3. 注册中心:静态 map + needCheck 探测位

source/core/Backend.cpp:24-30 的 GetExtraCreator 返回进程级单例 map<MNNForwardType, pair<const RuntimeCreator*, bool>>——bool 就是 needCheck 位。

  • 注册:MNNInsertExtraRuntimeCreator(type, creator, needCheck)(:120-128):重复类型直接断言失败(:122-125),否则插入。
  • 查询:MNNGetExtraRuntimeCreator(type)(:100-118):先 registerBackend() 确保单次初始化(:101),map 未命中返回 nullptr(:105-107);命中且 needCheck <mark> false 直接返回 creator(:108-110);needCheck true 则现场 onCreate 一个 Runtime 试跑,成功才认(:111-117)——这是 NPU 类后端"声明了但设备不在"的探测机制。
  • 初始化:registerBackend()(:62-98,00 章已拆):std::call_once 内 CPU 无条件注册(:68),其余 CoreML/NNAPI/QNN/RKNN/Hexagon/OpenCL/Metal/NeuroPilot 各自挂在编译宏下(:73-96)。

4. MNN_FORWARD_AUTO:八级优先级与两级回退

Schedule::getAppropriateType(source/core/Schedule.cpp:111-137)把 AUTO 翻译成具体后端(Observed in source):

1
2
3
4
5
6
7
8
9
10
11
12
13
std::array<MNNForwardType, 8> priorityList {          // Schedule.cpp:114-123
MNN_FORWARD_USER_0, //HIAI
MNN_FORWARD_NN, //CoreML
MNN_FORWARD_USER_1, //TensoRT
MNN_FORWARD_CUDA, //CUDA
MNN_FORWARD_OPENCL, //OpenCL
MNN_FORWARD_METAL, //METAL
MNN_FORWARD_VULKAN, //Vulkan
MNN_FORWARD_CPU, //CPU
};
for (auto bn : priorityList) {
if (MNNGetExtraRuntimeCreator(bn) != nullptr) { type = bn; break; } // :125-129
}

两级回退:

  1. backupType(:131-135):选定类型查不到 creator 时,打印警告并落到 config.backupType。
  2. Power_Low 探测(:139-151,仅 OpenCL):backendConfig->power == Power_Low 时现场建 Runtime 查 STATUS_SUPPORT_POWER_LOW(:146-147),不支持则再退 backupType——PowerMode 枚举在 include/MNN/MNNForwardType.h:107。

5. Schedule::schedule:逐后端生成 pipelineInfo

Schedule::schedule(:291-331)把 net+configs 变成执行计划(Observed in source):

  1. 初始化默认 Backend 并灌常量张量(:296-308);initTensors 全量建张量(:309-311)。
  2. 对每个 ScheduleConfig(:314-329):compute.type = getAppropriateType(config)(:316)——AUTO 在此被解析;AUTO 命中 OpenCL/Metal 时默认 MNN_GPU_TUNING_FAST 对应的 numThread=16(:318-322,注释:AUTO set default gpu-mode);_scheduleUnit 按 config 切出该后端负责的算子清单(:325),与 BackendCache 配对入 result。
  3. scheduleInfo.pipelineInfo = std::move(result)(:331)——每个后端一个 Pipeline,Pipeline 内是逐 Op 的 OpCacheInfo。

6. 纵向执行链:StaticModule → Session → Pipeline → Execution

以 03 章 forwardRaw 调到的 selectModule->onForward(llm.cpp:743)为起点,一条 LLM 前向的实际下潜路径(Observed in source):

第一层:StaticModule::onForward(express/module/StaticModule.cpp:809-849)。StaticModule 是"编译期确定形状"的模块,内嵌一个 Session(构造时 mSession.reset(new Session(std::move(scheduleInfo), ...)),:556)。onForward 四拍:先 applyMetaToRuntime() 广播 KV 便签(:811-814,04 章注入链第 3 级);决定 runResize/runCompute(:816-817,mShapeInferSeperate 分离模式下形状推理与计算可拆);_resize(inputs)(:841)同步输入张量尺寸;_execute()(:844)。

第二层:_execute → Session::run。_execute(express/module/StaticModule.cpp:793-806)就是 mSession->run()(:801/:804,Debug 模式走 runWithCallBack)。Session::run(source/core/Session.cpp:271-289):未 resize 直接报错(:277-280),然后逐 Pipeline 执行:for (auto& iter : mPipelines) { iter->execute(); }(:283-287),任一失败即返回。

第三层:Pipeline::execute(source/core/Pipeline.cpp:1359-1409):_copyInputs(:1360)搬输入 → _enterExecute(:1361-1365)→ 逐 OpCacheInfo(跳过 CONSTANT,:1369-1371)逐 command(:1373):视图类 command 只做校验(_viewRoot/_validBufferView,:1374-1380);普通 command 到达终点——

1
2
auto code = cmd.execution->onExecute(cmd.workInputs, cmd.workOutputs);   // Pipeline.cpp:1401
if (NO_ERROR != code) { _exitExecute(); return code; } // :1402-1405

每条 command 一个 Execution,一次 onExecute 一拍;command 的 inputs/outputs(cmd.workInputs/workOutputs)是 resize 阶段由内存规划器分配好的张量——执行期不再分配。跨后端边界由 _copyInputs/geometry raster 处理(07 章展开)。

对照:llama.cpp 的对应物是 ggml_backend_sched 图切分 + 各 backend 的 compute 接口(《llama.cpp推理引擎教程》阶段四);MNN 把"切分结果"物化成静态的 pipelineInfo 常驻复用,执行期零调度开销——端侧确定性优先的设计取向。

7. 兜底:GPU init 过慢整组重置回退 CPU

Pipeline::resize 阶段的自动调优(Pipeline.cpp:1282-1319,Observed in source):条件是非 CPU 后端且开了 autoSetOpType(:1282)。流程:

  1. 逐 command 调 mRuntime->onMeasure(...)(:1294)——Runtime 的预检接口(Backend.hpp:381),返回 initCostLong(“该算子初始化很贵”)。
  2. 统计 initCostLong 的算子数,达 mTuneAttr.maxTuningNumber 提前停(:1301-1303)。
  3. 只要有一个贵算子:打印 "Turn back to cpu"(:1306),整组重置——清空所有 executionCache、command 的 execution 置空、_recycleDynamicMemory 回收动态内存(:1307-1315)。
  4. 有异步工作则 _pushTuningTask(:1316-1318);最后 mBackend.reset(mCpuRuntime->onCreate(nullptr, mBackupBackend.get()))(:1319)——本 Pipeline 的后端整体换成 CPU。

设计意图(Derived):某些 NPU/GPU 首次初始化个别算子开销巨大(如离线编译),与其整图慢,不如判定后整体退回 CPU——代价是放弃该 Pipeline 的 GPU 加速,换来确定性延迟。

本篇小结

  • 双层抽象各司其职:Backend = 设备执行现场(算子工厂 + 内存四件套 + meta 槽),Runtime = 设备上下文工厂(创建 Backend、GC、onMeasure 预检),RuntimeCreator = 注册表条目。
  • 张量 = halide_buffer_t(数据面)+ InsideDescribe(调度面),四种 MemoryType 与四种 StorageType 正交;Execution 契约 = onResize + onExecute 两拍。
  • 注册中心是"静态 map + needCheck 探测位":CPU 无条件,其余按宏;needCheck 的条目查询时现场试建 Runtime。
  • AUTO = 固定八级优先级表(HIAI→CoreML→TensorRT→CUDA→OpenCL→Metal→Vulkan→CPU)+ backupType 回退 + OpenCL Power_Low 二次探测。
  • 执行链四层:StaticModule::onForward(广播 meta、_resize、_execute)→ Session::run(逐 Pipeline)→ Pipeline::execute(逐 command)→ cmd.execution->onExecute(:1401)。
  • GPU 兜底:onMeasure 探到 initCostLong 算子即"Turn back to cpu",整组清 execution、换 mCpuRuntime->onCreate 的新 Backend。
  • 下一章潜到最底层:CPU 后端的 ISA 分发与 GEMM 内核——06-CPU后端深潜与GEMM内核。

前置:04-KVCache与状态复用 | 下一篇:06-CPU后端深潜与GEMM内核 | 回目录:README