Skip to content

Feature Request: C++ gradient for SoftmaxCrossEntropyWithLogits #12686

Closed

Description

@bpiel

Implement the gradient for SoftmaxCrossEntropyWithLogits in c++ so that it is available for TF_AddGradients.

This is the python code that I believe would need to be ported:

@ops.RegisterGradient("SoftmaxCrossEntropyWithLogits")

Activity

  1. skye commented on Aug 29, 2017

    @skye
    Contributor

    @bpiel you're working on this right?

    @suharshs FYI

  2. added
    type:feature
    on Aug 29, 2017
  3. bpiel commented on Aug 29, 2017

    @bpiel
    ContributorAuthor

    @skye Not currently. If I start, I will post here. If someone else starts first, hopefully they'll post here.

  4. added
    stat:contribution welcome
    on Aug 29, 2017
  5. facaiy commented on Aug 29, 2017

    @facaiy
    Member

    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.

  6. suharshs commented on Aug 30, 2017

    @suharshs

    @facaiy Happy to review your PR. :)
    @kbsriram may also be interested in reviewing/guiding.

  7. facaiy commented on Aug 30, 2017

    @facaiy
    Member

    Thanks, @suharshs .

    I have read the code in python side,

    @ops.RegisterGradient("SoftmaxCrossEntropyWithLogits")
    def _SoftmaxCrossEntropyWithLogitsGrad(op, grad_loss, grad_grad):

    If I understand correctly, the arguments grad_loss and grad_grad in python side will be packed in grad_inputs in C++ side, right?

    Namely, the outline of code in C++ should like:

    Status SoftmaxCrossEntropyWithLogitsGrad(const Scope& scope, const Operation& op,
                                             const std::vector<Output>& grad_inputs,
                                             std::vector<Output>* grad_outputs) {
      auto grad_loss = grad_inputs[0];
      auto grad_grad = grad_inputs[1];
    
      // migrate the implementation in python here.
      // code...........
      // auto grad = .....
    
      grad_outputs->push_back(grad);
      grad_outputs->push_back(null);
      return scope.status();
    }
    REGISTER_GRADIENT_OP("SoftmaxCrossEntropyWithLogitsGrad", SoftmaxCrossEntropyWithLogitsGrad);

    Please correct me if I'm wrong.

  8. kbsriram commented on Aug 30, 2017

    @kbsriram
    Contributor

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

  9. skye commented on Aug 30, 2017

    @skye
    Contributor

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

  10. facaiy commented on Aug 31, 2017

    @facaiy
    Member

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

  11. pbanavara commented on Sep 22, 2017

    @pbanavara
    Contributor

    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.

  12. facaiy commented on Sep 22, 2017

    @facaiy
    Member
  13. skye commented on Sep 22, 2017

    @skye
    Contributor

    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!

  14. pbanavara commented on Sep 25, 2017

    @pbanavara
    Contributor

    @facaiy @skye Thank you for the pointers. I will start working on this and will ping you guys once I have the tests working.

  15. suharshs commented on Sep 25, 2017

    @suharshs
  16. 14 remaining items

  17. suharshs commented on Nov 6, 2017

    @suharshs

    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);
    }
    
  18. suharshs commented on Nov 6, 2017

    @suharshs

    You will also need to use the last override of RunTest which can handle multiple outputs and inputs.

    void RunTest(const OutputList& xs, const std::vector<TensorShape>& x_shapes,
               const OutputList& ys, const std::vector<TensorShape>& y_shapes) 
    
  19. pbanavara commented on Nov 13, 2017

    @pbanavara
    Contributor

    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.

  20. pbanavara commented on Nov 13, 2017

    @pbanavara
    Contributor

    Ok did some amateurish stuff ...

      OutputList inputs = OutputList();
      std::vector<TensorShape> shapes = std::vector<TensorShape>();
      OutputList outputs = OutputList();
      inputs.push_back(x);
      shapes.push_back(shape);
      auto y = SoftmaxCrossEntropyWithLogits(scope_, x, l);
      outputs.push_back(y);
      RunTest(inputs, shapes, outputs, shapes);
    
    

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

  21. skye commented on Nov 13, 2017

    @skye
    Contributor

    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.loss and y.backprop. Both of these should be added the outputs list I think.

  22. pbanavara commented on Nov 14, 2017

    @pbanavara
    Contributor

    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.

  23. skye commented on Nov 15, 2017

    @skye
    Contributor

    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.

  24. pbanavara commented on Nov 15, 2017

    @pbanavara
    Contributor
  25. pbanavara commented on Nov 22, 2017

    @pbanavara
    Contributor

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

  26. pbanavara commented on Jan 28, 2018

    @pbanavara
    Contributor

    @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();
    }
    
  27. skye commented on Feb 1, 2018

    @skye
    Contributor

    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.

  28. pbanavara commented on Feb 15, 2018

    @pbanavara
    Contributor

    Hey @skye no worries at all. please comment when you can.

  29. rajha-korithrien commented on Apr 20, 2018

    @rajha-korithrien

    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.

  30. added a commit that references this issue on Jul 13, 2018
    7fe0ae1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    stat:contribution welcometype:feature

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions