Skip to content

[Operator Mechanism] Fix tile_grad for high rank - #79975

Open
liuhao2638 wants to merge 17 commits into
PaddlePaddle:developfrom
liuhao2638:align-tile-fix
Open

liuhao2638 wants to merge 17 commits into
PaddlePaddle:developfrom
liuhao2638:align-tile-fix

Conversation

@liuhao2638

@liuhao2638 liuhao2638 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR Category

Operator Mechanism

PR Types

Bug fixes

Description

基于 #79752 继续修改:去掉 tile_grad 的 Eigen 回退,CPU、GPU 都与 torch repeat_backward 逐位对齐。

改动

  1. GPU:前导维逐个调 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 逐维相同。
  2. CPU:同样的步骤复用 funcs::ReduceGradTermsCascade(内部调用 align sum && mean on cpu with torch in single thread #79568 的 TorchCompatibleReduceSum),整型也走这条路径。
  3. 只有前导维需要求和时,最后一次求和直接写 x_grad,省一次 D2D 拷贝。与 torch 一样逐个对前导维(含 repeat=1 的维)求和,修复 [4] tile [1,3,2] 时对错维求和的问题。没有维被 tile 时把 out_grad 拷贝给 x_grad。torch 在这里直接返回 grad,靠 AccumulateGrad 检查引用计数后再决定是否 clone;Paddle 的 GradTensorHolder 原地累加、不检查别名,共用显存会让 x.clear_grad() 把 y.grad 一起清零,所以保留拷贝。
  4. 删除 Eigen TileBackward 和回退判断。
  5. 测试:新增 TestTileGradHighRank(x_rank=7,含 repeat=1 的前导维);TestTileGradFP8EigenFallback 改为 TestTileGradFP8。

验证

CUDA 13.2,torch 2.12.0+cu132。对比对象:

#79752 目前只测了 GPU 逐位对齐,GPU 耗时和 CPU 数据待补。

GPU 逐位对齐:每格是 fp64 / fp32 / fp16 / bf16 下与 torch 不一致的元素个数。

case x 形状 repeat_times develop #79752 本 PR
lead_dim [256,256] [8,1,1] 38007 / 38112 / 0 / 0 0 / 0 / 0 / 0 0 / 0 / 0 / 0
multi_axis [64,64,32] [2,3,2] 83213 / 83534 / 0 / 0 0 / 0 / 0 / 0 0 / 0 / 0 / 0
long_reduce_small_grad [16] [65536] 16 / 16 / 0 / 0 0 / 0 / 0 / 0 0 / 0 / 0 / 0
row_broadcast_1M [1,4096] [4096,1] 3992 / 3992 / 2 / 0 0 / 0 / 0 / 0 0 / 0 / 0 / 0
mid_2d [1024,1024] [4,8] 796860 / 796510 / 3 / 0 0 / 0 / 0 / 0 0 / 0 / 0 / 0
big_5d [8,8,16,16,64] [2,2,1,2,2] 688807 / 689157 / 0 / 0 0 / 0 / 0 / 0 0 / 0 / 0 / 0
rank7_mixed [8,2,8,2,8,2,8] [2,1,2,1,2,1,2] 21486 / 21597 / 0 / 0 21486 / 21597 / 0 / 0 0 / 0 / 0 / 0
rank7_all_tiled [4]*7 [2]*7 14217 / 14152 / 0 / 0 14217 / 14152 / 0 / 0 0 / 0 / 0 / 0
rank7_uneven [3,2,1,2,2,3] [2,2,3,2,1,2,2] 58 / 57 / 28 / 30 58 / 57 / 28 / 30 0 / 0 / 0 / 0

#79752 在后三个 case 上交错形状超过 9 维,回退 Eigen。

GPU 耗时(μs,nsys 统计每次调用的 kernel + memcpy + memset)

case fp32 torch fp32 develop fp32 本 PR bf16 torch bf16 develop bf16 本 PR
lead_dim 2.6 2.7 2.4 2.6 6.0 2.4
multi_axis 4.8 5.7 3.9 6.2 12.3 5.2
long_reduce_small_grad 7.1 9.8 6.5 6.9 13.7 6.4
row_broadcast_1M 33.9 233.4 32.4 18.0 287.1 16.5
mid_2d 50.4 49.8 47.9 39.5 128.2 37.9
big_5d 29.0 53.1 26.8 22.7 92.3 20.3
rank7_all_tiled 9.5 42.6 8.5 15.2 51.5 12.6
rank7_mixed 4.7 9.7 4.3 6.0 13.2 5.0

CPU 逐位对齐:每格是 fp64 / fp32 / int32 / int64 下的不一致元素个数。浮点对 1 线程 torch 比较,整型对 numpy 精确求和比较。

case develop 本 PR
lead_dim 0 / 0 / 0 / 0 0 / 0 / 0 / 0
multi_axis 85472 / 85544 / 0 / 0 0 / 0 / 0 / 0
long_reduce_small_grad 16 / 16 / 0 / 0 0 / 0 / 0 / 0
row_broadcast_1M 3990 / 4011 / 0 / 0 0 / 0 / 0 / 0
mid_2d 800475 / 798779 / 0 / 0 0 / 0 / 0 / 0
big_5d 729291 / 729699 / 0 / 0 0 / 0 / 0 / 0
rank7_mixed 22731 / 22791 / 0 / 0 0 / 0 / 0 / 0
rank7_all_tiled 14496 / 14483 / 0 / 0 0 / 0 / 0 / 0
rank7_uneven 62 / 63 / 0 / 0 0 / 0 / 0 / 0

CPU 耗时(ms,15 次取中位数;Paddle CPU 求和是单线程,torch 设为 1 线程;"–" 为未测)

case fp32 torch fp32 develop fp32 本 PR int64 torch int64 develop int64 本 PR
lead_dim – 0.648 0.084 – 0.576 0.309
multi_axis 8.49 2.07 6.61 11.15 1.75 7.00
long_reduce_small_grad – 2.21 0.269 – 4.34 0.325
row_broadcast_1M 6.48 111.9 3.51 25.42 153.6 35.95
mid_2d 49.69 36.41 45.38 67.76 31.32 49.61
big_5d 136.1 33.36 112.5 111.0 38.93 120.4
rank7_mixed 4.23 1.84 3.54 3.54 1.86 3.73
rank7_all_tiled 24.65 3.35 27.50 21.51 3.78 28.29
rank7_uneven – 0.014 0.036 – 0.013 0.042

CPU 上本 PR 与 1 线程 torch 耗时相当(累加顺序相同)。develop 的 Eigen 在 multi_axis、mid_2d、big_5d、rank7_* 上更快,在其余 case 上更慢。

单测

test_tile_op.py 57 个、test_reduce_op.py 179 个、test_index_put_op.py 86 个、test_index_elementwise.py 11 个、test_einsum_v2.py 73 个、test_kron_op.py 44 个、test_expand_v2_op.py 92 个、test_std_layer.py 29 个通过。

是否引起精度变化

是

omoYang and others added 7 commits September 9, 2026 01:55
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-Review-Bot

Paddle-Review-Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Paddle-Bot Review Board (review完成)

序号 位置 优先级 规则来源 状态
1 前导补齐维求和跳过导致梯度错误 P0 仓库规则:基础评审规则
默认规则
✅
2 PR 标题与描述中 fp8 求和说明与实现不符 P3 仓库规则:基础评审规则 ✅
3 未平铺时梯度与 out_grad 共享存储 P2 仓库规则:基础评审规则 ✅

可维护性建议(总分 86.9 / 100,只给建议,不影响评审结论)

序号 位置 维度 状态
1 高秩求和注释中的非常规标记 AI 生成债务 ✅
2 测试参考函数未使用的形参 逻辑清晰度 ✅
3 高秩归约视图重复推导 中层优雅度 ✅
4 x_shape 以空向量作哨兵 API 表面一致性 ✅
5 MAX_DIMS 全局上调影响共享计算器 跨模块架构 ✅
各维度得分(仅评本 PR 改动,点击展开)
85 抽象适配度
85 API 表面一致性
4
85 跨模块架构
5
85 设计一致性
85 错误处理一致性
85 高层优雅度
85 未完成迁移
85 中层优雅度
3
86 测试策略
87 契约一致性
88 AI 生成债务
1
88 约定偏离
88 依赖健康度
88 底层优雅度
88 命名质量
88 类型安全
88.5 逻辑清晰度
2
90 初始化耦合
92 包组织结构
— 鉴权一致性

Powered by Nyanpasu claude with Opus 5.5 默认推理级别, please check the suggestions carefully.

Comment thread paddle/phi/kernels/reduce_sum_kernel.cc Resolved
Comment thread test/legacy_test/test_tile_op.py Resolved
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 Paddle-Review-Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 当前 head 已删除 GPU sum / sum_raw 的 fp8 注册和 TestSumFP8,但 PR 描述第 4、6 点仍列出这两项,验证部分标注的 head 也仍是 4e65a30。请同步更新描述。

@Paddle-Review-Bot Paddle-Review-Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 PR 标题中的「support fp8 sum」与当前实现不符(sum / sum_raw 已不再注册 fp8),请同步修改标题。

Keep DenseTensorIterator and ReduceGpuKernel identical to develop. tile_grad's
interleaved view goes through ReduceSumGpuKernelWithShape, which builds a
ReduceViewIterator from vector shape/strides.

@Paddle-Review-Bot Paddle-Review-Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 PR 标题中的「support fp8 sum」与当前实现不符(sum / sum_raw 已不再注册 fp8),请同步修改标题。

@Paddle-Review-Bot Paddle-Review-Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 PR 标题中的「support fp8 sum」与当前实现不符(sum / sum_raw 已不再注册 fp8),请同步修改标题。

The reduce iterator already coalesces adjacent kept dims, so merging
untiled dims by hand is no longer needed.

@Paddle-Review-Bot Paddle-Review-Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 PR 标题中的「support fp8 sum」与当前实现不符(sum / sum_raw 已不再注册 fp8),请同步修改标题。

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.

@Paddle-Review-Bot Paddle-Review-Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 PR 标题中的「support fp8 sum」与当前实现不符(sum / sum_raw 已不再注册 fp8),请同步修改标题。

// 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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;如果要省掉这次拷贝,需要先在累加路径上处理别名。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已在 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 保留拷贝。

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已确认: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.
@liuhao2638 liuhao2638 changed the title [Operator Mechanism] Fix tile_grad for high rank and support fp8 sum [Operator Mechanism] Fix tile_grad for high rank Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants