larroy commented on a change in pull request #14779: Fully connected, higher
order grad
URL: https://github.com/apache/incubator-mxnet/pull/14779#discussion_r298756303
##########
File path: tests/python/unittest/test_higher_order_grad.py
##########
@@ -129,6 +135,83 @@ def check_second_order_unary(x, op, grad_grad_op):
# Validate the gradients.
assert_almost_equal(expected_grad_grad, x.grad.asnumpy())
+class RandomShapes(object):
+ def __init__(self, dim, startdim=1):
+ self.dim = dim
+ self.curdim = startdim
+
+ def __iter__(self):
+ return self
+
+ def next(self):
+ return self.__next__()
+
+ def __next__(self):
+ if self.curdim > self.dim:
+ raise StopIteration
+ shape = rand_shape_nd(self.curdim)
+ x = nd.random.normal(shape=shape)
+ self.curdim += 1
+ return x
+
+
+@with_seed()
+def test_dense_backward():
+ for x in RandomShapes(4,2):
+ net = gluon.nn.Sequential()
+ with net.name_scope():
+ net.add(gluon.nn.Dense(1))
+
+ net.initialize(mxnet.initializer.Constant(.5))
+ x.attach_grad()
+ with ag.record():
+ y = net.forward(x)
+ x_grad = ag.grad(heads=y, variables=x, create_graph=True,
retain_graph=True)[0]
+ x_grad.backward()
+ same(x.grad, nd.zeros(4))
+
+ with ag.record():
+ y = net.forward(x)
+ x_grad = ag.grad(heads=y, variables=x, create_graph=True,
retain_graph=True)[0]
+ random_multiplier = nd.random.uniform_like(x_grad)
+ z = (random_multiplier * x_grad).sum()
+ z.backward()
+ same(x.grad, nd.zeros(4))
+
+ with ag.record():
Review comment:
numerical gradient, changing w and verifying that the first gradient changes
but not the second one.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
[email protected]
With regards,
Apache Git Services