Paddle icon indicating copy to clipboard operation
Paddle copied to clipboard

gather 重复index计算梯度有问题

Open Yelrose opened this issue 7 years ago • 2 comments

paddle 1.4

gather函数如果输入index有多个重复index,梯度计算有问题。下面是复现程序

import paddle.fluid as fluid
import numpy as np

ones = fluid.layers.fill_constant(shape=[5, 1], dtype="float32", value=1)
ones.stop_gradient=False
ind = fluid.layers.data("index", shape=[2], dtype="int32", append_batch_size=False)
output = fluid.layers.gather(ones, ind)
loss = fluid.layers.reduce_sum(output)
optimizer = fluid.optimizer.Momentum(learning_rate=0.2, momentum=0.1)
optimizer.minimize(loss)

place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(program=fluid.default_startup_program())
o = np.random.randn(2, 5)
o = np.array(o, dtype="float32")


prog = fluid.default_main_program()
var_dict = {}
for var in prog.list_vars():
    var_dict[var.name] = var

feed_dict = {"index": np.array([1, 3], dtype="int32")}
ret = exe.run(fluid.default_main_program(),
    feed=feed_dict,
    fetch_list=[var_dict["fill_constant_0.tmp_0@GRAD"] ], return_numpy=True)
print("Index [1, 3]")
print("Paddle Grads:")
print(ret[0])
‘’‘
 loss = ones[1] + ones[3]
 grad supposed to be
 grad = [0, 1, 0 ,1 ,0 ]
 actual_grad = [0,1,0,1,0]
 correct
’‘’

feed_dict = {"index": np.array([1, 1], dtype="int32")}
ret = exe.run(fluid.default_main_program(),
    feed=feed_dict,
    fetch_list=[var_dict["fill_constant_0.tmp_0@GRAD"] ], return_numpy=True)
print("Index [1, 1]")
print("Paddle Grads:")
print(ret[0])
‘’‘
 loss = ones[1] + ones[1]
 grad supposed to be
 grad = [0, 2, 0 , 0 ,0 ]
 actual_grad = [0,1,0,0, 0]
 correct
’‘’

目前,观察fluid/operators/gather_op.h的代码,发现里面使用的是ScatterAssign函数进行梯度更新。pytorch以前也有这样的issue,见https://github.com/pytorch/pytorch/issues/1631

Yelrose avatar May 20 '19 14:05 Yelrose

gather op在实现的时候 应该是没有考虑有重复index的问题,这个需要修一下

kuke avatar May 21 '19 12:05 kuke

Since you haven't replied for more than a year, we have closed this issue/pr. If the problem is not solved or there is a follow-up one, please reopen it at any time and we will continue to follow up. 由于您超过一年未回复,我们将关闭这个issue/pr。 若问题未解决或有后续问题,请随时重新打开,我们会继续跟进。

paddle-bot-old avatar May 22 '20 10:05 paddle-bot-old