kshitij12345 commented on a change in pull request #14992: [MXNET-978] Support 
higher order gradient for `log`.
URL: https://github.com/apache/incubator-mxnet/pull/14992#discussion_r288657874
 
 

 ##########
 File path: src/operator/tensor/elemwise_unary_op_basic.cc
 ##########
 @@ -1069,13 +1069,73 @@ The storage type of ``log2`` output is always dense
 .set_attr<nnvm::FGradient>("FGradient", ElemwiseGradUseIn{"_backward_log2"});
 
 MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_log,
-                                                  
unary_bwd<mshadow_op::log_grad>);
+                                                  
unary_bwd<mshadow_op::log_grad>)
+.set_attr<nnvm::FGradient>("FGradient",
+  [](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) {
+    // For f(x) -> f = log
+    // f''(x) = -1 * (f'(x) * f'(x))
+    auto gx = nnvm::NodeEntry{n};
+    auto ggx_mid = MakeNode("elemwise_mul", n->attrs.name + 
"_backward_mid_grad_grad",
+                            {gx, gx}, nullptr, &n);
+    auto ggx = MakeNode("negative", n->attrs.name + "_backward_grad_grad",
+                        {nnvm::NodeEntry{ggx_mid}}, nullptr, &n);
+
+    std::vector<nnvm::NodeEntry> ret;
+
+    ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + 
"_backward_grad_grad",
+                             {ograds[0], gx}, nullptr, &n));
+    ret.emplace_back(MakeNode("elemwise_mul", n->attrs.name + 
"_backward_grad_grad_inp",
+                             {ograds[0], nnvm::NodeEntry{ggx}}, nullptr, &n));
+    return ret;
+  });
 
 MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(_backward_log10,
-                                                  
unary_bwd<mshadow_op::log10_grad>);
+                                                  
unary_bwd<mshadow_op::log10_grad>)
+.set_attr<nnvm::FGradient>("FGradient",
+  [](const nnvm::NodePtr& n, const std::vector<nnvm::NodeEntry>& ograds) {
+    // For f(x) -> f = log10
+    // f'(x) = 1 / (log(10) * x)
+    // f''(x) = -1 * (f'(x) * 1/x)
+    auto gx = nnvm::NodeEntry{n, 0, 0};
 
 Review comment:
   For natural `log`,
   we have with us in `gradient` function, `gx` i.e. `1/x` as well as `x`.
   Since, second derivative of log is `-(gx * gx)` = `-1/(x^2)`. We use the 
pattern.
   
   Considering `log2` (similar case for `log10`)
   we have with us, `gx` i.e. `1/(log(2) * x)` as well as `x`.
   Since second derivative is `-1/(log(2) * x * x)`
   which we get in the code using `negative(gx * reciprocal(x))`, where 
`gx=1/(log(2) * x`.
   Another way to get that will be `negative(gx * gx * log(2.0))`.

----------------------------------------------------------------
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

Reply via email to