You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Feature Request: C++ gradient for SoftmaxCrossEntropyWithLogits #12686
Hi, I'm really interested in the work because it is a little challenge for me. #12391 of @bpiel seems like a perfect example to imitate, right? I could be more confident if more detailed guide are given or someone would like to shepherd it. Thanks.
@facaiy the outline of the code looks fine, one change would be to use
grad_outputs->push_back(NoGradient())
rather than null to indicate gradients should not be propagated.
One thing you may run into is that that python has various utilities (e.g. tensor_util.constant_value()) that don't yet have equivalents available in C++. Should you find yourself writing a long stack of utilities, one strategy might be to start with gradients that have fewer dependencies. Some options might be functions like Erf and LGamma in math_ops. You can look at c++ implementations like Tanh to see how to structure the code and tests.
re: @kbsriram's point about missing Python utilities, for SoftmaxCrossEntropyWithLogitsGrad, you can skip the tensor_util.constant_value() call and leave a TODO to implement it in C++. This is OK in this case since the IsZero() check is an optimization anyway (I think...).
@kbsriram@skye Thanks for your enlightening and detailed guide. I agree that it's better to start with easier task at first. Hence, I'd like to work on LGamma and Erf as suggested.
If someone else is interested in SoftmaxCrossEntropyWithLogitsGrad as well, please let us know, and just go head and take over it.
I would like to take over this feature. What level of C++ expertise is needed. I'm a total C++ noob but am seeing this as an opportunity to learn the language as well as make a meaningful contribution. I was just checking at the python code and this line caught my eye softmax = nn_ops.softmax(logits)
I presume the C++ equivalent of nn_ops.softmax(logits) is implemented somewhere - I couldn't find out where. Is this correct ? Can someone please point out where to find the equivalent c++ implementation for nn_ops.softmax.
Apologies for the delayed response, you don't need to use the .backprop in your test. You just write the usage of the op as normal. The gradient checker will add gradients and verify that they match the numerical gradient.
Here is an example of another test in that same file that does this. The only thing you need to make sure of is that the x shape and y shape match what SoftMaxWithCrossEntropyLogits does, which i believe you have correct.
TEST_F(NNGradTest, Conv2DGrad) {
TensorShape shape({1, 2, 2, 1});
auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
Tensor filter = test::AsTensor<float>({0.5f}, {1, 1, 1, 1});
const std::vector<int> strides{1, 1, 1, 1};
auto y = Conv2D(scope_, x, filter, strides, "SAME");
RunTest(x, shape, y, shape);
}
Hey @suharshs and @skye Thanks and sorry for the delayed response. I haven't gone cold on this - still working. Trying to run the correct RunTest variant. Will keep you posted here soon.
candidate function not viable: no known conversion from 'tensorflow::ops::SoftmaxCrossEntropyWithLogits' to 'const value_type' (aka 'const tensorflow::Output') for 1st argument
At the line where I am adding the outputs to the OutputList vector. Since the RunTest variant requires an OutputList I did it this way. Perhaps there is another way to do this ?
SoftmaxCrossEntropyWithLogits call returns an Output as per the documentation. How it returns multiple outputs is not clear to me. Can you guys please help out with that ?
Thanks @skye That solved the error. I had tried this before but had called loss and backdrop as methods :). I overlooked the fact that they are just attributes.
Now the output shapes are not matching. I am trying to fix that. The error messages are quite hard to interpret.
[ RUN ] NNGradTest.SoftmaxCrossEntropyWithLogitsGrad
tensorflow/cc/gradients/nn_grad_test.cc:55: Failure
Expected: ::tensorflow::Status::OK()
Which is: OK
To be equal to: ((ComputeGradientError<float, float, float>( scope_, xs, x_shapes, ys, y_shapes, &max_error)))
Which is: Invalid argument: Dimensions must be equal, but are 3 and 5 for 'MatMul' (op: 'MatMul') with input shapes: [5,3], [5,3].
So clearly one of the matrices need to be of shape [3,5] but which one. So I am just trying all combinations in the inputs and outputs.
Could this be an actual bug in your SoftmaxCrossEntropyWithLogits function? If you can't find the bug, post what you have so far in a PR and I can try to take a look.
@skye - Revisiting this after a long gap. Sorry but I am unable to process the matrix shape mismatch error. Here is my test case
TEST_F(NNGradTest, SoftmaxCrossEntropyWithLogitsGrad) {
TensorShape shape({5,3});
TensorShape lossShape({5});
auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
auto l = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
OutputList inputs = OutputList();
OutputList outputs = OutputList();
std::vector<TensorShape> inputShapes = std::vector<TensorShape>();
std::vector<TensorShape> outputShapes = std::vector<TensorShape>();
inputShapes.push_back(shape);
outputShapes.push_back(shape);
outputShapes.push_back(lossShape);
auto y = SoftmaxCrossEntropyWithLogits(scope_, x, l);
inputs.push_back(x);
outputs.push_back(y.backprop);
outputs.push_back(y.loss);
RunTest(inputs, inputShapes, outputs, outputShapes);
}
The shapes of backprop and loss seem to be appropriate - {5,3} and {5}. There is no way for me to print the shapes of the loss and backprop as the Output data structure doesn't have those APIs. Can you please advise what's wrong ? Here's the error.
To be equal to: ((ComputeGradientError<float, float, float>( scope_, xs, x_shapes, ys, y_shapes, &max_error)))
Which is: Invalid argument: Shape must be rank 2 but is rank 1 for 'MatMul' (op: 'MatMul') with input shapes: [5], [5,3].
Here's my code:
Status SoftmaxCrossEntropyWithLogitsGrad(const Scope& scope,
const Operation& op,
const std::vector<Output>&
grad_inputs,
std::vector<Output>* grad_outputs) {
// Softmax gradient with cross entropy logits function
// We multiply the backprop for cost with the gradients - op.output[1]
// There is no gradient for labels
std::cout << "Step 1" << "\n";
auto softmaxGrad = op.output(1);
auto gradLoss = grad_inputs[0];
auto gradGrad = grad_inputs[1];
auto tempGrad = Mul(scope, gradLoss, softmaxGrad);
// TODO: Check if this sufficient, need a check for null ?
if (gradGrad.op().output_type(0) != 0) {
auto logits = op.input(0);
auto softmax = ops::Softmax(scope, logits);
auto prod = ops::MatMul(scope, gradGrad, softmax);
auto squeezeProd = ops::Squeeze(scope, prod);
auto fProd = Sub(scope, gradGrad, squeezeProd);
auto grad = Add(scope, tempGrad, fProd);
grad_outputs->push_back(grad);
grad_outputs->push_back(ops::MatMul(scope, gradLoss, ops::LogSoftmax(scope, logits)));
grad_outputs->push_back(NoGradient());
}
return scope.status();
}
Hey @pbanavara, just a heads up that I'm pretty slammed this week so I can't look into this right now :( Sorry to keep you hanging. Maybe someone else cc'd can take a look, otherwise I'll try to make some time next week.
I have added to the conversation surrounding this issue in the pull request pbanavara made. I am cross commenting here just so readers can find the results of the discussion.
Activity
skye commentedon Aug 29, 2017
@bpiel you're working on this right?
@suharshs FYI
bpiel commentedon Aug 29, 2017
@skye Not currently. If I start, I will post here. If someone else starts first, hopefully they'll post here.
facaiy commentedon Aug 29, 2017
Hi, I'm really interested in the work because it is a little challenge for me. #12391 of @bpiel seems like a perfect example to imitate, right? I could be more confident if more detailed guide are given or someone would like to shepherd it. Thanks.
suharshs commentedon Aug 30, 2017
@facaiy Happy to review your PR. :)
@kbsriram may also be interested in reviewing/guiding.
facaiy commentedon Aug 30, 2017
Thanks, @suharshs .
I have read the code in python side,
If I understand correctly, the arguments
grad_lossandgrad_gradin python side will be packed ingrad_inputsin C++ side, right?Namely, the outline of code in C++ should like:
Please correct me if I'm wrong.
kbsriram commentedon Aug 30, 2017
@facaiy the outline of the code looks fine, one change would be to use
grad_outputs->push_back(NoGradient())rather than
nullto indicate gradients should not be propagated.One thing you may run into is that that python has various utilities (e.g. tensor_util.constant_value()) that don't yet have equivalents available in C++. Should you find yourself writing a long stack of utilities, one strategy might be to start with gradients that have fewer dependencies. Some options might be functions like Erf and LGamma in
math_ops. You can look at c++ implementations like Tanh to see how to structure the code and tests.skye commentedon Aug 30, 2017
re: @kbsriram's point about missing Python utilities, for SoftmaxCrossEntropyWithLogitsGrad, you can skip the tensor_util.constant_value() call and leave a TODO to implement it in C++. This is OK in this case since the IsZero() check is an optimization anyway (I think...).
facaiy commentedon Aug 31, 2017
@kbsriram @skye Thanks for your enlightening and detailed guide. I agree that it's better to start with easier task at first. Hence, I'd like to work on
LGammaandErfas suggested.If someone else is interested in
SoftmaxCrossEntropyWithLogitsGradas well, please let us know, and just go head and take over it.pbanavara commentedon Sep 22, 2017
I would like to take over this feature. What level of C++ expertise is needed. I'm a total C++ noob but am seeing this as an opportunity to learn the language as well as make a meaningful contribution. I was just checking at the python code and this line caught my eye
softmax = nn_ops.softmax(logits)I presume the C++ equivalent of nn_ops.softmax(logits) is implemented somewhere - I couldn't find out where. Is this correct ? Can someone please point out where to find the equivalent c++ implementation for nn_ops.softmax.
facaiy commentedon Sep 22, 2017
@pbanavara
tensorflow::ops::Softmax?skye commentedon Sep 22, 2017
Hi @pbanavara, @facaiy is correct. We have functions for every op in both Python and C++. I would look at the C++ API documentation (https://www.tensorflow.org/api_guides/cc/guide, https://www.tensorflow.org/api_docs/cc/group/core) and existing gradient functions to get a feel for what they look like. Also make sure you can successfully build TensorFlow before you start writing code. Maybe I'm overly familiar with the code, but I don't think gradient functions should be too hard to start with. If SoftmaxCrossEntropyWithLogitsGrad proves to be too complicated you can also try a simpler one. Good luck, and looking forward to a PR!
pbanavara commentedon Sep 25, 2017
@facaiy @skye Thank you for the pointers. I will start working on this and will ping you guys once I have the tests working.
suharshs commentedon Sep 25, 2017
Also, if you want instructions for adding the c++ gradient functions see here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/cc/gradients/README.md
14 remaining items
suharshs commentedon Nov 6, 2017
Apologies for the delayed response, you don't need to use the
.backpropin your test. You just write the usage of the op as normal. The gradient checker will add gradients and verify that they match the numerical gradient.Here is an example of another test in that same file that does this. The only thing you need to make sure of is that the x shape and y shape match what SoftMaxWithCrossEntropyLogits does, which i believe you have correct.
suharshs commentedon Nov 6, 2017
You will also need to use the last override of RunTest which can handle multiple outputs and inputs.
pbanavara commentedon Nov 13, 2017
Hey @suharshs and @skye Thanks and sorry for the delayed response. I haven't gone cold on this - still working. Trying to run the correct RunTest variant. Will keep you posted here soon.
pbanavara commentedon Nov 13, 2017
Ok did some amateurish stuff ...
I get this error
candidate function not viable: no known conversion from 'tensorflow::ops::SoftmaxCrossEntropyWithLogits' to 'const value_type' (aka 'const tensorflow::Output') for 1st argumentAt the line where I am adding the outputs to the OutputList vector. Since the RunTest variant requires an OutputList I did it this way. Perhaps there is another way to do this ?
SoftmaxCrossEntropyWithLogits call returns an Output as per the documentation. How it returns multiple outputs is not clear to me. Can you guys please help out with that ?
skye commentedon Nov 13, 2017
It's a little confusing, but SoftmaxCrossEntropyWithLogits has two outputs, 'loss' and 'backprop'. These are public properties of the returned SoftmaxCrossEntropyWithLogits instance (see https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/softmax-cross-entropy-with-logits), so can be accessed in your code via
y.lossandy.backprop. Both of these should be added theoutputslist I think.pbanavara commentedon Nov 14, 2017
Thanks @skye That solved the error. I had tried this before but had called loss and backdrop as methods :). I overlooked the fact that they are just attributes.
Now the output shapes are not matching. I am trying to fix that. The error messages are quite hard to interpret.
So clearly one of the matrices need to be of shape [3,5] but which one. So I am just trying all combinations in the inputs and outputs.
skye commentedon Nov 15, 2017
Could this be an actual bug in your SoftmaxCrossEntropyWithLogits function? If you can't find the bug, post what you have so far in a PR and I can try to take a look.
pbanavara commentedon Nov 15, 2017
pbanavara commentedon Nov 22, 2017
@skye Have submitted a PR. I will keep debugging the test case fail issue in the interim. Please let me know if you find some obvious mistake.
pbanavara commentedon Jan 28, 2018
@skye - Revisiting this after a long gap. Sorry but I am unable to process the matrix shape mismatch error. Here is my test case
The shapes of backprop and loss seem to be appropriate - {5,3} and {5}. There is no way for me to print the shapes of the loss and backprop as the Output data structure doesn't have those APIs. Can you please advise what's wrong ? Here's the error.
Here's my code:
skye commentedon Feb 1, 2018
Hey @pbanavara, just a heads up that I'm pretty slammed this week so I can't look into this right now :( Sorry to keep you hanging. Maybe someone else cc'd can take a look, otherwise I'll try to make some time next week.
pbanavara commentedon Feb 15, 2018
Hey @skye no worries at all. please comment when you can.
rajha-korithrien commentedon Apr 20, 2018
I have added to the conversation surrounding this issue in the pull request pbanavara made. I am cross commenting here just so readers can find the results of the discussion.
Fix: tensorflow#12686 SoftmaxCrossEntropyWithLogits