Repository navigation
[Operator Mechanism] Fix tile_grad for high rank - #79975
liuhao2638 wants to merge 17 commits into
Conversation
This reverts commit 079e1c5.
float8 has no SumKernel implementation, so TileGradCompatKernel returns false and tile_grad falls back to the Eigen TileBackward path. Add a dygraph test on float8_e4m3fn / float8_e5m2 to verify the fallback is reachable and yields a well-formed gradient (it would raise "no kernel found for float8" if wrongly routed to the reduce_sum path).
Merge adjacent dims before reducing so tile_grad works when the expanded rank exceeds DDim::kMaxRank, and drop the Eigen fallback. Register fp8 (float8_e4m3fn / float8_e5m2) SumKernel so fp8 tile_grad goes through the same reduce path.
Paddle-Bot Review Board (review完成)
可维护性建议(总分 86.9 / 100,只给建议,不影响评审结论)
各维度得分(仅评本 PR 改动,点击展开)
Powered by Nyanpasu claude with Opus 5.5 默认推理级别, please check the suggestions carefully. |
The interleaved reduce view can reach 14 dims. Pass it to the iterator as a shape vector and raise the offset calculator's MAX_DIMS to torch's 25, so ranks above DDim::kMaxRank no longer take a second rounding pass. The last leading-dim sum writes x_grad directly instead of going through a copy.
- Drop leading unsqueezed dims with repeat 1 by reshape, so every Sum({0})
reduces a real repeat dim; add backward tests for them.
- Share the reduce view between ReviewReduceResult and the x_shape path,
and make x_shape std::optional.
- Keep MAX_DIMS = DDim::kMaxRank: each reduce OffsetCalculator only sees the
kept or the reduced dims, at most rank(x) <= 7 for tile.
- tile_grad_ref uses repeat_times; ponytail comment -> NOTE.
The CPU path split interleaved shapes beyond DDim::kMaxRank into two SumKernel passes, which grouped the float additions differently from torch. Call the torch-compatible cascade sum directly with the shape as a vector, so CPU, like GPU, reduces all repeat axes at once.
…stration The leading-dim sums called SumKernel, which only instantiates for the registered dtypes, so sum/sum_raw had to register float8. Calling ReduceGpuKernel directly runs the same kernel and instantiates for fp8 in tile_grad's own unit, so the sum registration and TestSumFP8 are removed.
Paddle-Review-Bot
left a comment
There was a problem hiding this comment.
当前 head 已删除 GPU
sum / sum_raw 的 fp8 注册和 TestSumFP8,但 PR 描述第 4、6 点仍列出这两项,验证部分标注的 head 也仍是 4e65a30。请同步更新描述。
Keep DenseTensorIterator and ReduceGpuKernel identical to develop. tile_grad's interleaved view goes through ReduceSumGpuKernelWithShape, which builds a ReduceViewIterator from vector shape/strides.
The reduce iterator already coalesces adjacent kept dims, so merging untiled dims by hand is no longer needed.
Build sum_dims while building grad_size, sum every leading unsqueezed dim as torch does, and let ReduceViewIterator compute contiguous strides from the shapes so ReduceResultView is no longer needed.
| // TensorCopy may change the dims of dx | ||
| if (sum_dims.empty()) { | ||
| // Nothing is tiled: return out_grad itself, as torch does. | ||
| x_grad->ShareDataWith(cur); |
There was a problem hiding this comment.
repeat 全为 1 时,这里让
x_grad 与 out_grad 共用同一块存储。这会让其他持有 out_grad 的张量被原地改写。torch 能直接返回 grad,是因为它的 InputBuffer / AccumulateGrad 在累加前会检查引用计数,必要时改用非原地相加或 clone。Paddle 的 GradTensorHolder::add(paddle/fluid/eager/grad_tensor_holder.cc)首次是直接 buffer_tensor = grad_tensor,再次累加时用 TensorAdd 原地写入,不检查别名。
可复现场景:y = paddle.tile(x, [1, 1]); y.retain_grads(); (y.sum() + x.sum()).backward()。tile 分支先到达时,x 的梯度缓冲与 y.grad 共用存储,第二路梯度原地加进去后 y.grad 也会变成 2。之后调用 x.clear_grad()(置零)或原地梯度裁剪,同样会改动 y.grad 和 hook 保存的梯度。改动前的 Copy 没有这个问题。建议恢复 Copy;如果要省掉这次拷贝,需要先在累加路径上处理别名。
There was a problem hiding this comment.
已在 d3dc5ab 改回 Copy。
复现结果(498d507a2e,CPU/GPU 相同):y = paddle.tile(x, [1, 1]); y.retain_grads(); y.sum().backward() 之后 x.grad 与 y.grad 的 data_ptr 相同,x.clear_grad() 会把 y.grad 清成 0。y.sum() + x.sum() 两种顺序下累加结果都正确(x.grad=2,y.grad=1),没有复现累加被改写,但 clear_grad 已能说明问题。
torch 在 repeat_backward 里同样直接返回 grad,靠 AccumulateGrad 的 is_tensor_stealable(use_count 超出预期时 clone)和 InputBuffer 的 can_accumulate_inplace 避免别名;Paddle 的 GradTensorHolder 没有这层检查,所以 tile_grad 保留拷贝。
There was a problem hiding this comment.
已确认:d3dc5abe48 恢复了 Alloc + Copy,x_grad 不再与 out_grad 共用存储,此项已解决。也感谢更正:累加被改写的场景没有复现,实际可见的影响是 clear_grad 连带清零 y.grad,我原来的描述高估了累加那条路径。
Paddle's GradTensorHolder accumulates in place without checking aliases, so sharing out_grad's storage would let x's grad accumulation and clear_grad modify y.grad.
PR Category
Operator Mechanism
PR Types
Bug fixes
Description
基于 #79752 继续修改:去掉 tile_grad 的 Eigen 回退,CPU、GPU 都与 torch
repeat_backward逐位对齐。改动
ReduceGpuKernel求和后,把每个 tiled 维拆成[repeat_i, x_i],对交错形状(最多 14 维)做一次求和。DDim 最多 9 维,为此新增ReduceViewIterator(reduce_view_iterator.h),继承DenseTensorIteratorBase,直接用 vector 描述 shape(按连续布局计算 stride),复用基类的维度重排和合并,再交给GPUReduceScheduler;入口是新增的ReduceSumGpuKernelWithShape。DenseTensorIterator和ReduceGpuKernel的接口与实现都不变。交错形状与 torch 的grad_size逐维相同。funcs::ReduceGradTermsCascade(内部调用 align sum && mean on cpu with torch in single thread #79568 的TorchCompatibleReduceSum),整型也走这条路径。[4]tile[1,3,2]时对错维求和的问题。没有维被 tile 时把 out_grad 拷贝给 x_grad。torch 在这里直接返回 grad,靠AccumulateGrad检查引用计数后再决定是否 clone;Paddle 的GradTensorHolder原地累加、不检查别名,共用显存会让x.clear_grad()把y.grad一起清零,所以保留拷贝。TileBackward和回退判断。TestTileGradHighRank(x_rank=7,含 repeat=1 的前导维);TestTileGradFP8EigenFallback改为TestTileGradFP8。验证
CUDA 13.2,torch 2.12.0+cu132。对比对象:
TileBackward)ShareDataWith改回Copy,表中 case 都不走这个分支,代码与已测过的 0e9a69f 相同)#79752 目前只测了 GPU 逐位对齐,GPU 耗时和 CPU 数据待补。
GPU 逐位对齐:每格是 fp64 / fp32 / fp16 / bf16 下与 torch 不一致的元素个数。
#79752 在后三个 case 上交错形状超过 9 维,回退 Eigen。
GPU 耗时(μs,nsys 统计每次调用的 kernel + memcpy + memset)
CPU 逐位对齐:每格是 fp64 / fp32 / int32 / int64 下的不一致元素个数。浮点对 1 线程 torch 比较,整型对 numpy 精确求和比较。
CPU 耗时(ms,15 次取中位数;Paddle CPU 求和是单线程,torch 设为 1 线程;"–" 为未测)
CPU 上本 PR 与 1 线程 torch 耗时相当(累加顺序相同)。develop 的 Eigen 在 multi_axis、mid_2d、big_5d、rank7_* 上更快,在其余 case 上更慢。
单测
test_tile_op.py57 个、test_reduce_op.py179 个、test_index_put_op.py86 个、test_index_elementwise.py11 个、test_einsum_v2.py73 个、test_kron_op.py44 个、test_expand_v2_op.py92 个、test_std_layer.py29 个通过。是否引起精度变化
是