Pull Request has been successfully merged by CANN-robot.
(Thank you for luozhonglin's contribution.)变更摘要
此 PR 为 Engram 弹性缓冲区添加了训练模式的前向/反向支持(engram_fetch_train + engram_fetch_grad),通过引入 withGrad 参数区分推理和训练路径。核心思路是:训练前向使用新增的 aclnnEngramFetch 算子(withGrad=1),输出 fetched 张量及 save-for-backward 的上下文张量(perm、sendCounts、recvCounts、recvLocalEntry、numRecv);训练反向使用新增的 aclnnEngramFetchGrad 算子产生稀疏梯度。同时修正了 tiling 侧 rankSize 的获取方式,从 recvCounts dim0 而非 sendCounts dim0 推导(避免 32 字节对齐填充导致的偏差),并新增 QueryHcclBufferResource 支持 HCCL 默认 buffer 作为训练 a2a 收发缓冲。
主要改动
ElasticBuffer新增训练前向方法EngramFetchTrain:静态方法,图模式CustomOp兼容,调用aclnnEngramFetch(withGrad=1)完成 fetched + 5 个上下文张量的输出,同时在 Python 层注册了对应的 meta 和 PrivateUse1 实现。ElasticBuffer新增训练反向方法EngramFetchGrad:实例方法(不注册为图模式 CustomOp),通过aclnnEngramFetchGrad融合内核生成gradUnique和uniqueLocalEntry,含numUnique.item()device sync 以获取实际行数并做 narrow 截断。- Tiling 侧
rankSize获取逻辑修正:rankSize从recvCountsdim0 获取,不再要求recvCountsdim0 与sendCountsdim0 相等,因为sendCounts可能有 32 字节对齐 padding 导致 dim0 偏大。 EngramContextBuilder新增QueryHcclBufferResource:训练态通过HcclGetHcclBufferFunc/HcclChannelGetHcclBufferFunc查询各 rank 的 HCCL 默认 buffer 地址并填充virtualAddrList,作为 a2a 收发缓冲;Build方法新增withGrad参数控制走新路径还是旧的GetHcclCommResource。- Python 层新增
EngramFetchCtx数据类:封装训练前向的 save-for-backward 上下文,engram_fetch在with_grad=True时返回(fetched, ctx)元组;同时ElasticBuffer.__init__新增with_grad参数,engram_write额外缓存localStorageAddr、commBufferSize、rankSize。


Thanks for your pull-request.
The full list of commands accepted by me can be found at here。
You can get sig-info at here
PR Approval Progress
✅ Congratulations! All modules have met the lgtm and approve requirements.
Module Approval Details
| module | lgtm status | approve status |
|---|---|---|
| mc2 | ✅ 刘丹, 蒋礼锐, chenjunjian11 (3/2) | ✅ 刘丹 (1/1) |
| sig-ops-transformer | ✅ 刘丹, 蒋礼锐 (2/2) | ✅ 刘丹 (1/1) |
💡 Tip:
- Committer can comment
/approveor/lgtm- Commenting
/approveimplies both code review (lgtm) and intent to merge (approve)
CLA Signature Pass
luozhonglin222, thanks for your pull request. All authors of the commits have signed the CLA. 👍


The MR can not be merged, because of CodeReview discussion not resolved
If you want to solve this problem, you can click here to do it in the FAQs.


描述
engram算子支持训练HOST代码,前向复用现有接口,增加相应参数,反向增加新接口
关联的Issue
测试
本地验证
文档更新
更新torch_extension/cann_ops_transformer/docs/zh/ElasticBuffer.md
类型标签
PR 代码检视报告
检视概览
mc2/engram_fetch/op_host/op_tiling/arch35/engram_fetch_tiling.cpp(Tiling)mc2/engram_fetch_grad/op_host/op_tiling/arch35/engram_fetch_grad_tiling.cpp(Tiling)mc2/engram_fetch_grad/op_kernel/engram_fetch_grad_tiling_data.h(Kernel 结构定义)torch_extension/cann_ops_transformer/ops/csrc/elastic_buffer.cpp(Host C++ 扩展)torch_extension/cann_ops_transformer/ops/elastic_buffer.py(Python 接口)变更核心说明
本 PR 的核心变更:
rankSize的获取来源由sendCounts dim0改为recvCounts dim0。因sendCounts在 32b 对齐时 dim0 可能为rankSize * 8(padding),导致rankSize被错误放大 8 倍。反向 grad tiling 中错误的rankSize传入预编译 kernel 驱动 a2a 通信循环,可能导致virtualAddrList/hcommHandle数组越界(上限HCCL_MAX_RANK_SIZE=1024)。recvCounts dim0 == sendCounts dim0(rankSize)等式校验(32b 对齐下该等式不成立,原校验会误报)。EngramFetchTrain/EngramFetchGrad的 ElasticBuffer Host+Python 接口,训练态使用 HCCL 默认 buffer(QueryHcclBufferResource)。检视统计
发现问题(HIGH 置信度)
[GEN-4.2] 禁止使用魔鬼数字/字符串
问题描述:新增函数
EngramFetchTrain中,at::empty({rankSize * 8}, intOpts)使用裸字面量8作为 sendCounts 的 32 字节对齐 padding 因子(8 = 32B / sizeof(int32_t))。该数字含义非自明,仅有行末注释// 32b对齐辅助说明,但未定义为命名常量。同文件常量区(47-56 行)已定义HCCL_MAX_RANK_SIZE、BUFFER_ALIGNMENT、DIM_TWO等命名常量,仓内其他文件亦遵循常量命名惯例,此处裸8违反既定约定。代码片段(
torch_extension/cann_ops_transformer/ops/csrc/elastic_buffer.cpp行 937-955):{ auto dtype = static_cast<at::ScalarType>(dtypeEnum); int64_t numTokens = indices.size(0); auto fetched = at::empty({numTokens, hiddenSize}, at::TensorOptions().dtype(dtype).device(indices.device())); auto intOpts = at::TensorOptions().dtype(at::kInt).device(indices.device()); int64_t maxR = numMaxTokensPerRank * rankSize; at::Tensor perm = at::empty({numTokens}, intOpts); at::Tensor sendCounts = at::empty({rankSize * 8}, intOpts); // 32b对齐 <-- 魔鬼数字 8 at::Tensor recvCounts = at::empty({rankSize}, intOpts); at::Tensor recvLocalEntry = at::empty({maxR}, intOpts); at::Tensor numRecv = at::empty({1}, intOpts); if (numTokens > 0) { constexpr int64_t withGrad = 1; ACLNN_CMD(aclnnEngramFetch, context, indices, localStorageAddr, fetched, perm, sendCounts, recvCounts, recvLocalEntry, numRecv, hiddenSize, numEntries, numMaxTokensPerRank, commBufferSize, withGrad); } return std::make_tuple(fetched, perm, sendCounts, recvCounts, recvLocalEntry, numRecv); }假设检验证据:
正向证据:
自信值 = 40% + 30% + 20% = 90% >= 70% -> 判定违规
修复建议:将对齐因子提取为命名常量(语义 = 32B 对齐 / sizeof(int32_t)),置于文件常量区或函数内:
// 32B 对齐下 int32 元素数 = 32 / sizeof(int32_t) constexpr int64_t SEND_COUNTS_ALIGN_FACTOR = 8; at::Tensor sendCounts = at::empty({rankSize * SEND_COUNTS_ALIGN_FACTOR}, intOpts);需关注(MED 置信度)
[TOPK-7] Tiling 外部输入校验
问题描述:前向 Tiling
engram_fetch_tiling.cpp的 PR 变更将rankSize来源从sendCountsOutShape.dim0(有>0校验)改为recvCountsOutShape.dim0(缺失>0校验)。CheckTrainingParams对sendCountsOutShape校验了dim0 > 0(行 394-399),但对recvCountsOutShape仅校验了 nullptr 和 dimNum==1(行 401-409),遗漏了dim0 > 0校验,形成校验不对称。实际触发风险较低(上游 HCCL 校验 rankSize in [2,1024] 保证 dim0>=2),但属防御纵深缺口。代码片段(
mc2/engram_fetch/op_host/op_tiling/arch35/engram_fetch_tiling.cpp行 520-528):if (isTraining) { auto permOutShape = context->GetOutputShape(PERM_OUT_INDEX); auto recvCountsOutShape = context->GetOutputShape(RECV_COUNTS_OUT_INDEX); // PR 变更 auto recvLocalEntryOutShape = context->GetOutputShape(RECV_LOCAL_ENTRY_OUT_INDEX); if (permOutShape != nullptr && recvCountsOutShape != nullptr) { tilingData.rankSize = static_cast<uint32_t>(recvCountsOutShape->GetStorageShape().GetDim(0)); // dim0 未校验 > 0 } if (recvLocalEntryOutShape != nullptr) { tilingData.totalRecv = recvLocalEntryOutShape->GetStorageShape().GetDim(0); }假设检验证据:
正向证据:
recvCountsOutShape.dim0作为新 rankSize 来源,未校验>0CheckTrainingParams与SetTilingData作用域内均无recvCountsOutShape.dim0 > 0校验rankSize来源变更在 diff 变更范围内dim0=0,workspace 偏移表为 0,前向 kernel 用commContext.rankSize(真实值>=2)访问可能越界负向证据:
ValidateRankSize校验 rankSize in [2,1024];输出张量以 HCCL 校验后 rankSize 分配自信值 = 35% + 30% + 20% + 15% + 10% - 20% - 15% = 75% >= 70% -> 判定需关注
修复建议:在
CheckTrainingParams中recvCountsOutShape的 dimNum 校验后补充dim0 > 0校验,与sendCountsOutShape保持对称:OP_TILING_CHECK( recvCountsOutShape->GetStorageShape().GetDim(0) <= 0, OP_LOGE_FOR_INVALID_VALUE( nodeName, "recvCountsOut", (std::string("dim0=") + std::to_string(recvCountsOutShape->GetStorageShape().GetDim(0))).c_str(), "> 0"), return ge::GRAPH_FAILED);[SEC-1.3] 禁止使用编译器"未定义行为"
问题描述:
EngramFetchTrain和EngramFetchGrad中计算maxR = numMaxTokensPerRank * rankSize为有符号整数乘法(int64_t),未做溢出预检查。有符号整数溢出是 ISO C++ 标准明确的未定义行为(UB)。同文件中EngramWrite(行 879-883)和GetEngramStorageSizeHint(行 1086-1088)已有溢出保护先例,新增代码与既有模式不一致。实际触发概率极低(rankSize <= 1024,溢出需 numMaxTokensPerRank > 9e15),故置信度定为 MED。代码片段1(
torch_extension/cann_ops_transformer/ops/csrc/elastic_buffer.cpp行 937-955):ElasticBuffer::EngramFetchTrainOutput ElasticBuffer::EngramFetchTrain(const at::Tensor &context, const at::Tensor &indices, int64_t hiddenSize, int64_t numEntries, int64_t dtypeEnum, const at::Tensor &localStorageAddr, int64_t numMaxTokensPerRank, int64_t commBufferSize, int64_t rankSize) { auto dtype = static_cast<at::ScalarType>(dtypeEnum); int64_t numTokens = indices.size(0); auto fetched = at::empty({numTokens, hiddenSize}, at::TensorOptions().dtype(dtype).device(indices.device())); auto intOpts = at::TensorOptions().dtype(at::kInt).device(indices.device()); int64_t maxR = numMaxTokensPerRank * rankSize; // <-- 有符号乘法无溢出保护(UB 风险) at::Tensor perm = at::empty({numTokens}, intOpts); at::Tensor sendCounts = at::empty({rankSize * 8}, intOpts); at::Tensor recvCounts = at::empty({rankSize}, intOpts); at::Tensor recvLocalEntry = at::empty({maxR}, intOpts); at::Tensor numRecv = at::empty({1}, intOpts);代码片段2(
torch_extension/cann_ops_transformer/ops/csrc/elastic_buffer.cpp行 975-989):EnsureEngramContext(); TORCH_CHECK(!destroyed_, "engram_fetch_grad cannot be called after destroy"); TORCH_CHECK(withGrad_, "engram_fetch_grad requires with_grad=True"); TORCH_CHECK(engramWriteCalled_, "engram_fetch_grad must be called after at least one engram_write"); int64_t hidden = gradFetched.size(1); uint32_t rankSize = engramCommContext_.rankSize; int64_t maxR = numMaxTokensPerRank_ * static_cast<int64_t>(rankSize); // <-- 有符号乘法无溢出保护 auto gradUnique = at::empty({maxR, hidden}, at::TensorOptions().dtype(gradFetched.dtype()).device(gradFetched.device())); auto uniqueLocalEntry = at::empty({maxR}, at::TensorOptions().dtype(at::kInt).device(gradFetched.device())); auto numUnique = at::empty({1}, at::TensorOptions().dtype(at::kInt).device(gradFetched.device()));假设检验证据:
正向证据:
numMaxTokensPerRank * rankSize有符号乘法无溢出预检查,有符号整数溢出是 ISO C++ UB>0,无上限校验负向证据:
ValidateRankSize校验 rankSize in [2,1024],但 numMaxTokensPerRank 无上限校验,仅部分覆盖自信值 = 40% + 30% + 20% + 15% + 10% - 15% = 100% -> cap 后 MED(因物理触发概率极低)
修复建议(参照同文件
GetEngramStorageSizeHint:1086-1088的"先除后乘"预检查模式):// EngramFetchTrain (942 行前) TORCH_CHECK(rankSize > 0 && numMaxTokensPerRank <= INT64_MAX / rankSize, "numMaxTokensPerRank * rankSize overflow"); int64_t maxR = numMaxTokensPerRank * rankSize; // EngramFetchGrad (982 行前) TORCH_CHECK(rankSize > 0 && numMaxTokensPerRank_ <= INT64_MAX / static_cast<int64_t>(rankSize), "numMaxTokensPerRank_ * rankSize overflow"); int64_t maxR = numMaxTokensPerRank_ * static_cast<int64_t>(rankSize);[GEN-1.1] 对所有外部数据进行合法性检查
问题描述:新增函数
QueryHcclBufferResource(训练态 HCCL buffer 查询路径)中,本地 buffer 做了空指针+大小校验,但远端 buffer 既未做空指针校验、也未做大小校验,存在不对称。remoteBuffer来自 HCCL 外部 APIHcclChannelGetHcclBufferFunc返回,属外部数据。若 API 成功返回但 buffer 为空,virtualAddrList[i]会被写入 0,后续 kernel 据此地址做远端 a2a 读取会导致空地址访问崩溃。代码片段(
torch_extension/cann_ops_transformer/ops/csrc/elastic_buffer.cpp行 398-417):void *localBuffer = nullptr; uint64_t localBufferSize = 0; auto hcclRet = HcclGetHcclBufferFunc(commHandle, &localBuffer, &localBufferSize); TORCH_CHECK(hcclRet == HCCL_SUCCESS, "HcclGetHcclBuffer failed, ret=", hcclRet); TORCH_CHECK(localBuffer != nullptr && localBufferSize > 0, // <-- 本地有空校验 "HCCL default buffer is null or empty, size=", localBufferSize); resources.commBufferSize = static_cast<int64_t>(localBufferSize); resources.context.virtualAddrList[rankId] = reinterpret_cast<uint64_t>(localBuffer); for (uint32_t i = 0; i < resources.context.rankSize; ++i) { if (i == rankId) continue; void *remoteBuffer = nullptr; uint64_t remoteBufSize = 0; hcclRet = HcclChannelGetHcclBufferFunc(commHandle, resources.context.hcommHandle[i], &remoteBuffer, &remoteBufSize); TORCH_CHECK(hcclRet == HCCL_SUCCESS, "HcclChannelGetHcclBuffer(peer=", i, ") failed, ret=", hcclRet); resources.context.virtualAddrList[i] = reinterpret_cast<uint64_t>(remoteBuffer); // <-- 远端无空校验 }假设检验证据:
正向证据:
负向证据:无有效负向证据(
hcclRet==HCCL_SUCCESS仅校验 API 调用状态,本地路径的空校验证明 SUCCESS != 非空)自信值 = 30% + 30% + 20% = 80% -> MED(因 HCCL API 语义存在不确定性)
修复建议:在 415 行后、416 行前增加远端 buffer 空校验,与本地路径保持一致:
TORCH_CHECK(remoteBuffer != nullptr, "HCCL remote buffer is null for peer=", i); resources.context.virtualAddrList[i] = reinterpret_cast<uint64_t>(remoteBuffer);