Closed
Python 自定义 Allocator 回调丢失指针返回值 #1135
KaranocaVeAdd on Oct 18Closed at 24 days ago
Oct 18 Associated pull request
Oct 18 Modify description of issue
ykl999
Oct 18 Comments:
Oct 18 Comments:
你好,相关pyacl接口的问题已收到,我们会尽快check文档与代码的合理性


Oct 18 Assign ykl999 as responsible person
26 days ago Associated pull request
wuqifan
26 days ago Comments:
26 days ago Comments:
感谢反馈,已确认该问题。修复前,Python 自定义 Allocator 的 alloc 和 alloc-advise 回调返回的地址未传回 C 侧;get-address 回调的参数也未按元组构造,导致回调调用失败。
关联修复为 PR #5616,使用 Issue 所列基线和 PR 当前提交分别构建 pyACL 后进行回调对照测试:基线中前两个回调返回空指针,get-address 未能进入 Python 回调;PR 版本中三个回调均能返回预期地址。
另外,验证时发现 alloc 的分配大小超过 32 位范围时会发生截断,您也提交了对应的issue https://gitcode.com/cann/runtime/issues/1251 ,我们会一并推进合入,感谢对pyacl的修复和贡献!


25 days ago Associated pull request
ykl999
24 days ago Comments:
24 days ago Comments:
pr已合入,issue关闭


24 days ago changed custom state from 进行中 to 已解决
24 days ago Close issue
22 days ago Added label: resolved
Python 自定义 Allocator 回调丢失指针返回值
问题
Python 运行时包装公开了自定义 Allocator 的申请、建议申请和 block 地址查询回调,但三个 C++ trampoline 都丢弃 Python 回调的返回值并固定返回空指针。
aclrtAllocatorAllocFunc、aclrtAllocatorAllocAdviseFunc和aclrtAllocatorGetAddrFromBlockFunc的 C API 类型均要求返回void *。因此 Python 回调即使返回有效地址整数,底层仍收到空指针,申请 block 或取得 device 地址都会失败。此外,get-address trampoline 使用
Py_BuildValue("k", block)构造回调参数。单个转换项会产生标量,而PyObject_CallObject要求参数为 tuple;所以该 Python 回调在当前实现中会因参数类型错误而无法执行。证据
固定源码为
c06e4cccb34ae5c5b616544250718879927da0d7。python/pyACL/rt/rt_allocator.cpp中AllocatorAllocFunc、AllocatorAllocAdviseFunc与AllocatorSetGetAddrFromBlockFunc调用 Python 函数后只递减返回对象引用,随后都返回nullptr。include/external/acl/acl_rt_allocator.h将上述三种回调分别声明为返回void *。example/3_memory_advanced/allocator/0_custom_allocator/main.cpp的 C 示例从 alloc 回调接收 block、从 get-address 回调接收地址,并立即检查两个返回值非空后使用地址。allocator_set_alloc_func_to_desc、allocator_set_alloc_advise_func_to_desc和allocator_set_get_addr_from_block_func_to_desc;Python 指针参数在python/pyACL/utils_methods.cpp中通过PyLong_AsVoidPtr从整数转换。复现
初始化 ACL 并创建 stream,创建并注册 Allocator descriptor;将 Python alloc、alloc-advise 和 get-address 回调分别设为返回不同非零地址整数的函数。通过
aclrtAllocatorGetByStream取出已注册的 C 回调并调用:alloc 和 alloc-advise 的 Python 函数会被调用,但 C 回调结果为 NULL;调用 get-address 时,Python 函数不会执行,并出现argument list must be a tuple。正式 Python 用法是在单算子执行或动态 shape 模型推理前注册 Allocator 并触发相应内存操作。最小 probe 通过 ctypes 直接调用已注册的 C 回调,以免依赖完整模型。
修复方向
将 get-address 的单参数构造改为 tuple;在持有 GIL 时把 Python 回调返回的地址整数用
PyLong_AsVoidPtr转成void *并返回。约定None表示空指针,转换失败时清除 Python 异常、记录错误并返回空指针。同步补全 Python 文档中的回调返回值约定。关联 PR: https://gitcode.com/cann/runtime/merge_requests/5616