Fix paddle.dist & paddle.nn.functional.normalize #74448
Merged
+79 −28
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
PR Category
Operator Mechanism
PR Types
Bug fixes
Description
修复
paddle.dist与paddle.nn.functional.normalize两个算子共用一个kernel,所以放在一起分析
inf,而 Torch 输出正常数值;reduce_sum(pow(...))的中间计算过程中发生溢出;inf或nan;-现象:Paddle 和 Torch 都能反向计算出结果,但差距极大(最大超过 160)。
-原因:查看torch源码,发现两者反向计算公式基本一致,但对特殊值 0 的处理不同。
Paddle:使用 1 / (norm + eps),导致较大数值。
Torch:使用 mask 将这些位置梯度直接置为 0。
优化:参考 Torch 的处理方式,对 norm == 0 的位置直接 mask 为 0,误差从上百缩小至 0.2 以内。
示例前后对比:
修改前:
修改后:
4.最终修改内容
• 在 float16 模式下,将中间计算提至 float32 精度,避免溢出。
• 修复整数类型溢出问题,使用 int64_t 替代潜在溢出的 int32。
• 对于 Torch 输出 inf/nan 的反向 case,跳过精度对齐测试。
• 优化反向 norm == 0 情况的处理方式,使用 mask 替代除法以减少误差。
Pcard-92269