已合并
Support broadcast scenarios in the cdist backward operator. #5279
HandsoemLemon创建于 6月26日
Support broadcast scenarios in the cdist backward operator. #5279
已合并
Pull Request已成功合入, 合并人@ascend-robot
(感谢 HandsoemLemon 的贡献)6月26日 创建了 pull request,commit 1bd986b3
6月26日 添加了label:ascend-cla/yes
ascend-robot
6月26日 评论:
6月26日 评论:
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 |
|---|---|---|
| repo-Ascend/op-plugin | ✅ zichun_ye, chengpeng25 (2/2) | ✅ zichun_ye (1/1) |
💡 Tip:
- Committer can comment
/approveor/lgtm- Commenting
/approveimplies both code review (lgtm) and intent to merge (approve)
CLA Signature Pass
HandsoemLemon, thanks for your pull request. All authors of the commits have signed the CLA. 👍


6月26日 添加了label:needs-issue
ascend-robot
6月26日 评论:
6月26日 评论:
Linking Issue Notice
@HandsoemLemon , the pull request must be linked to at least one issue.
If an issue has already been linked, but the needs-issue label remains, you can remove the label by commenting /check-issue .


此处折叠了126条消息 查看更多
zichun_ye
7月1日 评论:
7月1日 评论:
/approve


7月1日 添加了label:approvedlgtm
7月1日 关闭了关联的issue
7月1日 合入了pull request
ascend-robot
7月1日 评论:
7月1日 评论:
Pull Request 已合并或已关闭。
If you want to solve this problem, you can click here to do it in the FAQs.


【合入来源】
【修改方案】
修改原因:
在调用cdistbackward算子时,aclnncdistbackward算子需要接收的out的shape为x1与x2(除最后两维)的broadcast结果,否则会产生报错
PyTorch 语义是右对齐广播,不是左对齐
torch.cdist 的 batch 维广播必须和 at::infer_size 一致。
原生torch 的 Distance.cpp、NPU 的 cdist_npu_output_size、前向 CdistKernelNpu.cpp 都是右对齐广播。
所以 _cdist_backward 里如果手工按“前面维度一一对应”去比,维度不同的时候会出错。
aclnnCdistBackward 是低层 kernel,不负责理解原始 Python 入参的广播语义
它要求传入的 x1/x2/grad/cdist 已经对齐到 kernel 需要的 shape。
因此 x2 也必须 expand 到和 x1 一致的 broadcast batch 空间,否则 kernel 的 pairwise 计算没有正确坐标。
在计算完毕后的aten.sum.dim_IntList 是 autograd 生成的,来源不是 cdist kernel,而是 autograd 对 broadcast backward 的标准处理。所以如果算子里不在 reduce_sum,如果重复归约,可能导致结果不对。
【具体修改方案】
保留 p 的转换和兼容分支
double p -> float p_cast
inf 映射成 -1
保留低版本 SoC / 兼容路径
按 PyTorch 标准广播规则计算 batch shape
取 x1.shape[:-2] 和 x2.shape[:-2]
用 at::infer_size(batch_tensor1, batch_tensor2) 得到广播后的 batch 维
同时 expand x1 和 x2,由于boradcast可能在非连续场景下导致精度问题,所以
x1 expand 到 broadcast_batch + [r1, c1]
x2 expand 到 broadcast_batch + [r2, c2]
两者都 contiguous() 后再传给 NPU kernel
out 按 expanded x1 的 shape 分配
_cdist_backward 的返回值语义是“第一个输入的梯度”
所以返回 shape 应该是 x1 broadcast 后的 shape,而不是原始 x1 shape
【资料变更】
不涉及
【接口变更】
不涉及
【功能验证】
【CheckList】