[Accuracy diff No.106] Fix accuracy diff for paddle.nn.functional.adaptive_avg_pool2d API #74077
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.nn.functional.adaptive_avg_pool2d 反向的精度问题。增加单测判断梯度和是否符合预期。
错误出现的原因在于 KernelPool2DGrad 中对 pool_size的计算错误,原本的 pool_size 由 pool_height(即 input_height / output_height 向上取整) 和 pool_width 乘积计算得出,但是实际上这样每个位置都会产生误差(除非 input_height 可以被 output_height整除),设Y=adaptive_avg_pool2d(X),对于这个算子我们期望 Y 反向传播回来的梯度可以均匀分配到输入X所有相关的元素上,也就是说X各元素的梯度和与Y各元素的梯度和应该相等,可以验证原本的算法是做不到这点的。
根据adaptive_avg_pool2d的定义我们可以知道,对于Y的每个元素 pool_size 是可能不同的,使用 input_height / output_height 向上取整这个定值是不对的。
$\textbf{min} (\lceil \frac{(k+1) h_i}{h_o} \rceil , h_i)-\textbf{max} (\lfloor \frac{k h_i}{h_o} \rfloor, 0)$
正确的计算方法如下:
可通过下列代码复现
其他内容:
为了提升可读性,给 FastDivMod 结构体添加了 DivCeil方法,其他使用 Divmod 的代码后续也可以优化。
Pcard-67164