Repository navigation
Conversation
Add DualEndVirtualMemoryAutoGrowthBestFitAllocator, an optional replacement
for the large pool of the virtual-memory auto-growth allocator. It reserves
one virtual address range the size of the physical budget and grows two kinds
of blocks towards each other: ordinary ("stable") blocks from the low end and
"evictable" blocks from the high end.
Evictable blocks hold data the caller is able to reproduce, for example
activations that a recompute boundary can replay. When a stable allocation
does not fit, the pool walks the evictable blocks from the low end upwards and
asks an eviction hook to release them. Because the two kinds share one address
range and eviction follows address order, the physical pages freed this way
are exactly the ones the stable allocation needs, so no page has to be moved.
Evictable blocks are placed in allocation order, which makes eviction release
the most recent ones first. If the hook declines (the block is still in use),
the allocation is retried in the free window above it instead.
The pool is off by default and is only built when
FLAGS_use_virtual_memory_auto_growth_evictable_end is set, so the default
allocation path is unchanged.
Python entry points: vmm_evictable() tags allocations made inside the scope,
and the eviction hook, the query hook and the routing window let the caller
decide what may be evicted and which allocations are placed in the evictable
end.
Paddle-Bot Review Board (review完成)可维护性建议(总分 84.8 / 100,只给建议,不影响评审结论)
各维度得分(仅评本 PR 改动,点击展开)
Powered by Nyanpasu claude with DeepSeek-V4.1-Flash 默认推理级别, please check the suggestions carefully. |
| #if defined(PADDLE_WITH_CUDA) | ||
| // Build a BlockPart describing a single VMM chunk `[ptr, ptr+size)` on `device` | ||
| // by looking up the backing handle registered by CUDAVirtualMemAllocator. | ||
| BlockPart MakeBlockPart(void* ptr, size_t size, int device); |
There was a problem hiding this comment.
MakeBlockPart 现在只在 PADDLE_WITH_CUDA 下声明/定义,但无条件参与编译的 virtual_memory_auto_growth_best_fit_allocator.cc 在第 259、321 行直接调用它;迁移前该函数在该 .cc 内自带 #else PADDLE_THROW(...) 的非 CUDA 兜底。paddle/phi/core/memory/allocation/CMakeLists.txt 把该 .cc 放在无条件的 ALLOCATOR_SRCS 中,因此 CPU-only 以及任何未定义 PADDLE_WITH_CUDA 的构建会出现 MakeBlockPart was not declared in this scope 编译失败。建议在 mem_utils.cc 恢复非 CUDA 分支并让声明对所有平台可见,或给 virtual_memory_auto_growth_best_fit_allocator.cc 的定义与调用补齐同样的平台宏保护。
| phi::Allocation* | ||
| DualEndVirtualMemoryAutoGrowthBestFitAllocator::AllocateBorrowed( | ||
| size_t size, uintptr_t from) { | ||
| uintptr_t w = from; |
There was a problem hiding this comment.
AllocateBorrowed 的窗口下界 w 来自锁外计算(AllocateUnrouted 中第 431/436/453 行的 w/borrow_from/pinned_end),PlanWindow 的返回值也在释放 spinlock_ 后才传入。加锁后没有把 w 重新对齐到当前 StableEnd():另一线程若在两次加锁之间把 stable 端推进到 w 之上,[w, w+size) 就覆盖了已分配的 stable 块;下面的 ob 只扫描 live_evictable_/live_borrowed_,会得到 ob == 0,随后 FreeBlockContaining(w, end) 命中该 stable 块并抛出 PreconditionNotMet("target range is not free.")。该类声明了 IsAllocThreadSafe() == true,多线程分配时会以内部错误中断。建议在 AllocateBorrowed 持锁后先执行 w = std::max(w, StableEnd()) 再查找空闲块。
| virtual void Visit(VirtualMemoryAutoGrowthBestFitAllocator* allocator); | ||
| virtual void Visit( | ||
| VirtualMemoryAutoGrowthBestFitMultiScalePoolAllocator* allocator); | ||
| virtual void Visit(DualEndVirtualMemoryAutoGrowthBestFitAllocator* allocator); |
There was a problem hiding this comment.
新增的 Visit(DualEndVirtualMemoryAutoGrowthBestFitAllocator*) 只有 AllBlocksInfoVisitor 覆写,FreeMemoryMetricsVisitor(mem_visitor.h:123)、TryAllocVisitor(:181)、VMMFreeBlocksInfoVisitor(:227)与 VmmTensorPartsVisitor(:379)仍只处理 VirtualMemoryAutoGrowthBestFitAllocator。开启 FLAGS_use_virtual_memory_auto_growth_evictable_end 后大池是 dual-end 类型,这些访问会落到 AllocatorVisitor 的默认 no-op:paddle.device.cuda.vmm_max_free_size() 返回 0,TryAllocBatch 恒为 false;api_gen_utils.cc 的 NeedCompact 在大显存阈值下会反复判定需要 compact,而本 PR 的 CompactImpl 对 dual-end 直接返回 0,形成空转;_share_cuda 的 TryShareTensorViaVMM 找不到 parts 后回退到面向 cudaMalloc 的 cudaIpcGetMemHandle,而 dual-end 指针是 cuMemAddressReserve 预留的 VMM VA。建议基于 SnapshotBlockInfo()/all_blocks_ 为上述 visitor 补 dual-end 重载,或让上游显式识别并跳过该池。
|
|
||
| // Stable blocks grow up from the low end, evictable blocks grow down from the | ||
| // high end. | ||
| TEST(DualEndVMMAllocator, DualEndPlacement) { |
There was a problem hiding this comment.
DualEndPlacement、FreeDoesNotUnmap、StableEndShrinksOnFree、EvictableSkipsStableHoles、PlainBestFitStillWorks 都没有设置 FLAGS_vmm_dual_end_budget_in_mb(第 144/158/185 行的用例才用了 BudgetFlag)。此时 InitOnce 走 budget = cudaMemGetInfo 可用显存 - FLAGS_vmm_dual_end_reserve_in_mb(默认 4096 MiB),并 PADDLE_ENFORCE_GT(avail, reserve)。在空闲显存不足 4 GiB 的 CI GPU、共享卡或 MIG 切片上,这些用例会直接以 ResourceExhausted 失败,测试结果依赖运行时显存状态。建议所有用例统一用 BudgetFlag 固定预算,去掉对默认 reserve 的隐式依赖。
| if (!large_allocator) { | ||
| // The large pool is not a plain best-fit allocator (e.g. the dual-end | ||
| // allocator, which never unmaps and does not support compaction). | ||
| VLOG(1) << "Skip Memory Compact: large pool does not support compaction"; |
There was a problem hiding this comment.
CompactImpl 为“大池不是普通 best-fit”补了跳过提示,但 PreAlloc()(同文件第 518-541 行)仍用 dynamic_pointer_cast<VirtualMemoryAutoGrowthBestFitAllocator> 取大池。开启 FLAGS_use_virtual_memory_auto_growth_evictable_end 后转换失败,FLAGS_vmm_large_pool_pre_alloc_in_mb 会被静默忽略且无任何日志;同时类注释(.h:101-104)仍称该分配器组合了 VirtualMemoryAutoGrowthBestFitAllocator。建议在 PreAlloc 的 large_allocator 为空分支补一致的 VLOG,并更新类注释说明大池可为 dual-end。
| (va - virtual_mem_base_) % granularity_ == 0 && size % granularity_ == 0, | ||
| true, | ||
| common::errors::InvalidArgument( | ||
| "MapAt requires a granularity-aligned range, got va offset %d, " |
| // Unmap and release a backing returned by MapAt() and delete it. The caller | ||
| // must ensure no GPU work still uses the range (cuMemUnmap does not | ||
| // synchronize). | ||
| void UnmapAt(phi::Allocation* backing); |
There was a problem hiding this comment.
💡 可维护性建议(抽象适配度,不阻塞合入):本 PR 给共享的 CUDAVirtualMemAllocator 新增了 UnmapAt()(R74)与 QueryGranularity()(R78),但全仓库没有调用点:dual-end 池析构直接 delete backing,粒度在 InitOnce 中经 granularity() 获取。头文件关于 mu_ 的注释还写着 “MapAt() / UnmapAt() ... are called from the dual-end pool”,与实现不符;若将来误用 UnmapAt,它会 delete 仍被 backings_ 持有的 Allocation,造成双重释放。建议删除这两个接口并同步修正注释;确实需要时再随调用方一起提交。
| std::make_shared<VirtualMemoryAutoGrowthBestFitAllocator>( | ||
| cuda_allocator_large, platform::GpuMinChunkSize(), p); | ||
| std::shared_ptr<Allocator> vmm_allocator_large; | ||
| if (FLAGS_use_virtual_memory_auto_growth_evictable_end) { |
There was a problem hiding this comment.
💡 可维护性建议(高层优雅度,不阻塞合入):同一段“按 FLAGS_use_virtual_memory_auto_growth_evictable_end 在 DualEnd 与 V1 之间选择 large pool”的 if/else 在 allocator_facade.cc 的两处构造路径中被逐字复制(R1144-R1157 与 R1239-R1248),且第一处带 4 行说明、第二处没有,已经开始漂移。建议抽取一个文件内工厂函数(如 MakeVmmLargeAllocator(...))集中 flag 分支与构造,两处调用它,避免后续只改一处。
| // only after the pool has already evicted every evictable block it could, | ||
| // and its caller has a fallback (allocate stable / recompute). Waiting | ||
| // for other threads to free memory would just stall it for retry_time_. | ||
| if (tls_prefer_evictable) throw; |
There was a problem hiding this comment.
💡 可维护性建议(跨模块架构,不阻塞合入):通用重试装饰器 RetryAllocator 现在无条件读取双端特性头 vmm_routing_allocator.h 中的 tls_prefer_evictable(R88),把“是否等待重试”的通用策略绑定到 CUDA 放置提示。即使未开启 FLAGS_use_virtual_memory_auto_growth_evictable_end,用户只要包一层 vmm_evictable(),区间内任意来源的 BadAlloc 都会跳过既有等待重试。建议让 dual-end 抛出可区分的异常类型(如继承 BadAlloc 的专用类型),RetryAllocator 只对该类型立即重抛,避免通用分配器反向依赖具体特性。
| // block exists; it does not create a separate pool. Free does not read this | ||
| // tag: freed blocks always return to the shared large-pool free list and may be | ||
| // reused by either stable or evictable requests. | ||
| inline thread_local bool tls_prefer_evictable = false; |
There was a problem hiding this comment.
💡 可维护性建议(命名质量,不阻塞合入):同目录所有 *_allocator.h 都声明了 Allocator 子类,但本文件只包含 thread_local 标记与作用域守卫,没有任何分配器,按文件名检索实现的读者会落空。建议重命名为概念化名称(如 vmm_evictable_scope.h 或 vmm_routing.h),并同步更新 pybind.cc、retry_allocator.cc、dual-end 实现与测试中的 include。
The pool reached the branch only with FLAGS_vmm_dual_end_stable_in_evictable_holes, which was off by default and is not needed: a stable request that cannot grow at the stable end already falls back to the window above the block in the way, which covers the same case and does not need a flag.
Paddle-Review-Bot
left a comment
There was a problem hiding this comment.
请求修改:在最新 head 上复核,此前的阻塞问题仍未修复——MakeBlockPart 仅在 PADDLE_WITH_CUDA 下声明/定义,而无条件参与编译的 virtual_memory_auto_growth_best_fit_allocator.cc(第 259、321 行)仍直接调用它,非 CUDA 构建会编译失败。其余 P2/P3 问题在本次 head 上保持不变,具体位置与证据见既有内联评论。
Codecov Report❌ Patch coverage is ❌ Your patch status has failed because the patch coverage (81.47%) is below the target coverage (90.00%). You can increase the patch coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## develop #80044 +/- ##
==========================================
Coverage ? 81.47%
==========================================
Files ? 10
Lines ? 583
Branches ? 0
==========================================
Hits ? 475
Misses ? 108
Partials ? 0 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
The plan window asked a query hook which evictable blocks were in use, so a stable request could pick a window above them before evicting anything. That only pays off when the evictable end can hold a block someone is using at eviction time. A caller that places only what autograd saved in the evictable end never has a block in use at the door: those blocks are untouched between the point that produced them and the backward that reads them, so eviction can always walk in address order and there is no block below to protect. The planning pass then costs a Python round trip per block for an answer that never changes. Removed FLAGS_vmm_dual_end_plan_window, SetDualEndQueryHook (and its libpaddle._set_dual_end_query_hook binding), PlanWindow() and its counters. AllocateBorrowed stays as the fallback: if the evict hook declines a block, the request still borrows the window above it instead of failing. Added DualEndLive(ptrs), exposed as libpaddle._dual_end_live(ptrs): a host-side lookup that reports, per address, whether a live block of any dual-end pool starts there. It is for a caller that routed a region's allocations into the evictable end and afterwards has to tell the tensors the region still holds from the temporaries it already released, without touching device memory. Each pool takes its spinlock once for the whole batch and filters by its own address range first. The header states the limit of what it answers: "is there a live block at this address now", not "is the allocation made there still alive". Free returns a block to the free list and a later request may carve out the same address, so a caller pairing this with a routing window must resolve repeated addresses inside that window itself.
Paddle-Review-Bot
left a comment
There was a problem hiding this comment.
请求修改:在最新 head 上复核,此前的阻塞问题仍未修复——MakeBlockPart 仅在 PADDLE_WITH_CUDA 下声明/定义,而无条件参与编译的 virtual_memory_auto_growth_best_fit_allocator.cc 仍直接调用它,非 CUDA 构建会编译失败。其余 P2/P3 问题与本次新增的初始化数据竞争见内联评论。
| void DualEndVirtualMemoryAutoGrowthBestFitAllocator::MarkLive( | ||
| const std::vector<uintptr_t>& ptrs, std::vector<bool>* out) const { | ||
| std::lock_guard<SpinLock> guard(spinlock_); | ||
| if (base_ == 0) return; // not initialized yet |
There was a problem hiding this comment.
本提交新增的 MarkLive()(第 600 行起)在持有 spinlock_ 时读取 base_/limit_,但 InitOnce()(第 263-266 行)是在 std::call_once 内、未持有 spinlock_ 的情况下写入这些字段;CollectStats()(第 554 行起)同样如此。std::call_once 只同步调用它的线程,DualEndStats()/DualEndLive() 的调用方从不调用 InitOnce(),因此当一个线程首次在该池上分配、另一个线程同时查询统计/存活性时,这些读写之间没有 happens-before 关系,构成数据竞争(UB,TSAN 会报告),与类声明的线程安全不符;实际表现可能只是在初始化窗口内返回 false,但仍属未定义行为。建议在 call_once 内写这四个字段时持有 spinlock_(此时尚无人持锁,不会死锁),或改用带 release/acquire 的原子初始化标志,并让 MarkLive/CollectStats 的早退判断基于该标志。
PR Category
Execute Infrastructure
PR Types
New features
Description
Adds
DualEndVirtualMemoryAutoGrowthBestFitAllocator, an optional replacement forthe large pool of the virtual-memory auto-growth allocator (V1 path).
Motivation
Training setups that recompute activations have two kinds of allocations with very
different value: data that must stay resident, and data the caller can reproduce on
demand (for example activations a recompute boundary can replay). The existing pool
treats both the same, so a peak in the resident working set fails even when a large
amount of reproducible data is holding memory that could have been given up.
Design
The pool reserves one virtual address range the size of the physical budget and grows
the two kinds of blocks towards each other:
Stable blocks grow upwards from the low end, evictable blocks downwards from the high
end, and the unmapped window
[s, c)in between is the remaining physical budget.When a stable allocation does not fit, the pool walks the evictable blocks from the
low end upwards and asks an eviction hook to release them. The two kinds share one
address range and eviction follows address order, so the physical pages released this
way are exactly the ones the stable allocation needs: nothing has to be unmapped and
remapped elsewhere. Evictable blocks are placed in allocation order, which makes
eviction release the most recently placed ones first.
This rests on a contract with the caller. The evictable end is for data the caller has
declared it can produce again, and only for that: not for a value it is about to hand
to the next consumer. A block that is still referenced downstream cannot be released
when asked, and because the two ends share one address range, such a block sits in the
way of every stable allocation above it. If the caller keeps the end free of them, no
evictable block is in use between the moment it is placed and the moment the caller
replays it, so walking bottom-up in address order always succeeds and eviction never
has to look for another window.
The declined case is still handled rather than fatal: if the hook says no, the
allocation is retried in the free window above that block instead of failing, so one
pinned block does not stop the resident end from growing. With the contract above this
path is a safety net, not the normal route.
An evictable allocation that would cross
sfails withBadAllocinstead of evictinganything: the caller has a fallback (recompute), the resident data does not.
Freenever unmaps. Blocks return to a shared free list and either end can reuse them.Python entry points
core.vmm_evictable()core.vmm_prefer_evictable()libpaddle._set_dual_end_evict_hook(fn)Falsedeclineslibpaddle._dual_end_route_begin/_end()libpaddle._dual_end_live(ptrs)libpaddle._dual_end_stats(reset)_dual_end_liveanswers "is there a live block at this address now", not "is theallocation made there still alive":
Freereturns a block to the free list and a laterrequest may be carved out of the same address. A caller pairing it with a routing
window has to resolve addresses that repeat inside that window itself.
Flags
use_virtual_memory_auto_growth_evictable_endfalsevmm_dual_end_budget_in_mb00derives it from free memory minus the reservevmm_dual_end_reserve_in_mb4096The pool is only built when the first flag is set, so the default path is unchanged.
Tests
test/cpp/fluid/memory/dual_end_vmm_allocator_test.cc(9 cases) covers the placementof both ends, that
Freedoes not unmap, that each end skips the other's holes, thatthe ends never overlap, that eviction walks bottom-up and reuses pages in place, that a
declined block makes the allocation borrow the window above it, that the liveness query
reports live blocks of either end and nothing else, and that the plain best-fit pool is
unaffected when the flag is off.
test/legacy_test/test_dual_end_vmm_allocator.py(15 cases) covers the Python surface:the scope (entry/exit, nesting, restoring the outer value, not swallowing exceptions),
the statistics snapshot, the liveness query, and the hook and routing entry points.
是否引起精度变化
否
This is an allocator: it changes where data is placed, not how it is computed, and no
reduction order is affected. Note that evicting a block means its contents are produced
again by the caller; whether that reproduction is bit-exact is a property of the
caller's recompute path, not of this pool.