ExecuTorch端侧推理教程 · 04-内存规划与零分配运行时

04 - 内存规划与零分配运行时

所属系列:ExecuTorch 端侧推理教程 | 前置:03-运行时核心Module与Method解释器 | 下一篇:05-CPUKernel三层与算子优化
证据基线: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
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#eef2ff','primaryTextColor':'#1b1b1f','primaryBorderColor':'#6366f1','lineColor':'#6366f1','textColor':'#1b1b1f','fontSize':'15px'}}}%%
mindmap
root((内存规划与零分配))
内存哲学
编译期算好地址
运行时只解析指针
嵌入式无堆依赖
Python 端 greedy 规划
TensorSpec 带 lifetime
按 allocated_memory 降序
bucket 复用约束
allow_overlapping_allocations
mem_id 写入 spec
规划结果进 PTE
AllocationDetails flatbuffer
memory_id offset_low high
运行时指针解析
HierarchicalAllocator 索引即 id
getMemPlannedPtr
memory_id 减 1 hack
get_offset_address
MemoryManager 三分配器
method 加载期
planned 张量数据
temp 每指令复位
bump 只前移无 free
reset 回卷
加载期定址
delegate scratch
gen_delegate_scratch
备胎与 Device
malloc caching allocator
Device 仅指针算术
planned_buffer_devices

本篇目标

  1. 建立「地址在编译期定、运行时只解析」的内存哲学:greedy 规划按 lifetime 约束给每张量算出 mem_id/mem_offset,烧进 .pte。
  2. 读懂运行时侧的被动角色:HierarchicalAllocator 按 memory_id 索引预置缓冲区,getMemPlannedPtr 只做指针算术。
  3. 掌握 MemoryManager 三分配器(method/planned/temp)的分工与对齐 bump 分配器「只前移无 free、reset 回卷」的契约。
  4. 看清 delegate scratch 的加载期定址,以及桌面侧 malloc/caching 备胎与 Device 抽象现状。

1. 内存哲学:为什么要在编译期算好地址

llama.cpp 运行时现场建图、现场 ggml 分配;vLLM 靠显存池动态调度。ExecuTorch 的答案最激进:中间张量的地址在导出期就全部算完。手机/MCU 场景的动机(Derived,自证据反推):没有堆管理器的裸机也能跑(只需要一块静态内存池);地址固定意味着碎片不存在;每 token 推理的内存路径完全可预测。第 03 章的 FreeCall(method.cpp:1847 还数据指针)与每指令 temp 复位(:1856)都是这套哲学在执行期的延伸。

2. Python 端 greedy 内存规划

入口 greedy(alignment, specs, graph_module, ...)(exir/memory_planning.py:997-1063,Observed in source):

  1. 输入:specs 是带 lifetime 的 TensorSpec 集合(docstring 原文 “specs: Set of TensorSpec objects with updated lifetimes”,:1010);allow_overlapping_allocations 默认 True,注释注明该开关为 Vulkan 关闭重叠分配而生(:1014-1017)。
  2. 按大小降序:bisect.insort(sorted_specs, spec, key=lambda x: x.allocated_memory) 后 reverse(:1028-1032)——大张量先安家。
  3. mem_id 落定:spec 无 mem_id 时赋 1(:1038-1042,0 号历史保留);随后 spec.realign(alignment)(:1043)。共享权重(storage_base)延迟到 _resolve_storage_base_specs(:1045-1055)。
  4. bucket 复用:每个 spec 调 pick_shared_obj(:1049-1053)从同 mem_id 的 SharedObject 池里找宿主。

pick_shared_obj(:711 起)的 docstring 把规则写成了证明(Observed in source):

  • spec 的 lifetime 与 bucket 不重叠 → 复用该 bucket,offset=0,扩张 bucket lifetime;
  • 重叠 → 收集 bucket 内所有重叠 spec 的 offset,取 max,把新 spec 放在 max_offset + 该 spec 尺寸 处——同一地址绝不给两个同时活着的张量,重叠的可以错开 offset 共存;
  • 全不满足或 spec 比现有 bucket 都大 → 开新 bucket。

结果聚合为每 mem_id 的 bufsizes(:1057-1062)。这套贪心的正确性证明直接写在 docstring 里(“Proof of correctness … by induction”)。

3. 规划结果如何进 .pte

规划产出(mem_id/offset/size)经 emit 序列化成 flatbuffer AllocationDetails——字段 MemoryOffsetLow/MemoryOffsetHigh/MemoryId 在生成代码 exir/_serialize/generated/executorch_flatbuffer/AllocationDetails.py:40-47 可见,测试里也有 memory_id=1, memory_offset_high=0, memory_offset_low=16 的构造(exir/_serialize/test/test_flatbuffer_program.py:89-91)(Observed in source)。spec → AllocationDetails 的桥接在序列化层(Derived:字段齐备且运行时读取端见 §4,桥接细节未逐行追)。

4. 运行时:只做指针解析

4.1 HierarchicalAllocator:索引即 memory_id

runtime/core/hierarchical_allocator.h:25 定义 HierarchicalAllocator,构造契约(:29-36 注释原文):“Memory IDs are based on the index into buffers: buffers[N] will have a memory ID of N”,且 buffers[N].size() 必须 ≥ MethodMeta::non_const_buffer_size(N)——App 侧按 .pte 元信息预置一块块内存池,运行时拿 index 取池。它不分配、不回收,只有地址算术。

4.2 getMemPlannedPtr:把 offset 变成指针

加载/解析期把 AllocationDetails 变成真指针的唯一入口 getMemPlannedPtr(runtime/executor/tensor_parser_exec_aten.cpp:164-196,Observed in source):

1
2
3
4
const uint32_t memory_id = allocation_info->memory_id() - 1;        // :176
const uint32_t memory_offset_low = allocation_info->memory_offset_low(); // :181
... memory_offset |= static_cast<size_t>(memory_offset_high) << 32; // :186
return allocator->get_offset_address(memory_id, memory_offset, nbytes); // :195

三处细节值得记:

  • memory_id() - 1 的注释原文 “-1 is a hack to get the memory ids 0 aligned because previously 0 was reserved”(:173-175)——0 号 id 历史保留的债留到了运行时;
  • offset 是 64 位兼容设计:flatbuffer 原本只有 uint32,大模型需要 64 位,高位挪进独立字段 memory_offset_high 拼接(:178-186),size_t 放不下时报 NotSupported(:188-194);
  • 最后一行 get_offset_address(memory_id, memory_offset, nbytes)——没有 malloc、没有 free、没有查找表重建,就是 base + offset。

5. MemoryManager 三分配器与 bump 契约

5.1 三分配器分工(runtime/executor/memory_manager.h:55-65)

MemoryManager 构造函数(Observed in source,docstring :34-53):

分配器 类型 生命周期 用途
method_allocator MemoryAllocator* 必须活过 Method 加载 Method 与其内部结构(解析期的 TensorMeta、函数指针数组都从这里出)
planned_memory HierarchicalAllocator* 必须活过 Method 可变张量数据;大小必须与 MethodMeta::num_memory_planned_buffers() / memory_planned_buffer_size(N) 一致(:44-46)
temp_allocator MemoryAllocator* 每条指令后复位 kernel/delegate 执行期临时数据(:52-53 注释原文 “will be reset after every kernel or delegate call”)

校验:method_allocator != temp_allocator 否则 ET_CHECK_MSG 崩(:62-64)。与第 03 章呼应:主循环每指令前后复位 temp(method.cpp:1856 注释、execute 入口 :1971-1973)。

5.2 bump 分配器:只前移,无 free

MemoryAllocator(runtime/core/memory_allocator.h:38)是单指针 bump 分配器:

  • kDefaultAlignment = alignof(void*)(:45);
  • allocate(size, alignment)(:89-119):alignPointer(cur_) 对齐 → 容量检查(:105-111,报 “Memory allocation failed: %zuB requested”)→ cur_ = end 前移(:118)→ 返回 start。没有任何逐块释放接口——头注释 :35-37 原文 “call allocator.allocate() to keep iterating cur_ pointer”;
  • 唯一的「回收」是 reset():cur_ = begin_,注释 “It does nothing to the contents”(:198-201)——回卷但不擦写,temp allocator 每指令 reset 靠的就是它。

契约由此而来:分配序 = 生命周期序,谁后分配谁先亡(栈式);乱序释放在这个模型里不存在,所以 FreeCall 只是还指针不是还内存。

5.3 delegate scratch 也在加载期定址

委派后端的暂存缓冲同样走「编译期规划、加载期解析」:flatbuffer 的 DelegateScratch 由 gen_delegate_scratch 解析成字节 Span(method.cpp:295,docstring “Resolves the memory-planned scratch a delegate call declared into the byte…”),存进 call site 的 scratch_ 成员(:148-155 注释 “The memory-planned scratch this delegate’s call site declared, resolved…”);执行期 DelegateCall 直接用 delegates_[idx].scratch()(:1776,见第 03 章)。后端执行期不再向宿主要内存(Derived:除非后端自带分配器)。

6. 备胎与 Device 抽象现状

  • 桌面备胎:extension/memory_allocator/ 提供 malloc_memory_allocator.h 与 cpu_caching_malloc_allocator.h/.cpp(目录 ls 实测)——malloc 直通与带缓存的 malloc 变体,给不想预置内存池的桌面/原型场景兜底。
  • Device 抽象现状:HierarchicalAllocator 有第二构造,接受 per-buffer 的 planned_buffer_devices(hierarchical_allocator.h:50-62),注释原文很克制:“May contain a mix of CPU and device pointers — HierarchicalAllocator only does pointer arithmetic, so device pointers are valid”(:41-43)——设备指针只是被算术的数字,同步/调度不归它管。tensor 侧 getPlannedBufferDevice(tensor_parser_exec_aten.cpp:200-204)读同一元数据,无 device 元数据即 host memory(:201 注释)。结论(Derived):Device 目前是「类型+索引」的标注层,不是 vLLM 式的执行引擎抽象;真正的异构执行走委派后端(第 06 章)。

本篇小结

  • 内存哲学一句话:地址在编译期定死,运行时只解析——greedy 按 lifetime 约束算 mem_id/offset(memory_planning.py:997-1063,bucket 复用规则 :711),烧进 .pte 的 AllocationDetails(MemoryOffsetLow/High,AllocationDetails.py:40-47)。
  • 运行时被动三件套:HierarchicalAllocator 索引即 memory_id(hierarchical_allocator.h:29-36);getMemPlannedPtr 做 memory_id()-1 + 64 位 offset 拼接 + get_offset_address(tensor_parser_exec_aten.cpp:164-196);delegate scratch 也在加载期解析定址(method.cpp:295、:148-155、:1776)。
  • MemoryManager 三分配器(memory_manager.h:55-65):method 加载期 / planned 张量数据(大小契约对 MethodMeta)/ temp 每指令复位;bump 分配器只前移无 free(memory_allocator.h:89-119)、reset 回卷(:198-201),分配序=生命周期序。
  • 备胎 malloc/caching 在 extension/memory_allocator/;Device 目前只是「类型+索引」标注 + 指针算术(hierarchical_allocator.h:41-43),异构执行仍归委派后端。

前置:03-运行时核心Module与Method解释器 | 下一篇:05-CPUKernel三层与算子优化 | 回目录