larroy commented on a change in pull request #14613: [MXNET-978] Higher order gradient support for some unary operators URL: https://github.com/apache/incubator-mxnet/pull/14613#discussion_r289244479
########## File path: src/operator/tensor/elemwise_unary_op_trig.cc ########## @@ -63,7 +82,27 @@ The storage type of ``cos`` output is always dense )code" ADD_FILELINE) .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_cos"}); -MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(_backward_cos, unary_bwd<mshadow_op::cos_grad>); +MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(_backward_cos, unary_bwd<mshadow_op::cos_grad>) +.set_attr<nnvm::FGradient>("FGradient", + [](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) { + // f(x) = cos(x) + // f'(x) = -sin(x) + // f''(x) = -cos(x) + auto grad_x = nnvm::NodeEntry(n); + auto grad_grad_x_mid = MakeNode("cos", n->attrs.name + "_mid_grad_grad", + {n->inputs[1]}, nullptr, &n); + auto grad_grad_x = MakeNode("negative", n->attrs.name + "_backward_grad_grad", + {nnvm::NodeEntry(grad_grad_x_mid)}, nullptr, &n); + std::vector<nnvm::NodeEntry> ret; + // for the backward of the _backward_cos node + // first input is the ograd and second input is x (because ElemwiseUseIn) + ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad", + {ograds[0], grad_x}, nullptr, &n)); + ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad_in", + {ograds[0], nnvm::NodeEntry(grad_grad_x)}, nullptr, &n)); Review comment: The argument is by value, so it needs to be an rvalue if you want it moved two times, otherwise is copied, then moved. So is best: ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + "_backward_grad_grad_in", {ograds[0], nnvm::NodeEntry(std::move(grad_grad_x))}, nullptr, &n)); Having a shared ptr by value then move into a class seem to be the accepted idiom nowadays. Since it allows both move and copy semantics, depending if the caller passes an rvalue or not. ---------------------------------------------------------------- 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: us...@infra.apache.org With regards, Apache Git Services