Skip to content

Gradients in C and C++ APIs #6268

Closed
Closed

Description

@kmalakoff

I have started porting Tensorflow to Node.js and was wondering about the status of gradients support in the C and C++ APIs:

Could I ask for some help and / or offer some assistance? A couple of ideas:

  1. I would be happy to test the work-in-progress API in Node.js using either of both C or C++. I have tried both APIs and would be happy to maintain both as a test case.
  2. I would be happy to receive some guidance from someone on the tensorflow team on how to implement gradients / training without an official API. I see from this issue (Make the gradient computation available in the C api #4473) that it might be possible, but it has been hard to study the Python and OCAML code to understand what to do. Some pseudocode or links to existing code that would need to replicated could be enough.
  3. Something else? For example, I could help move the gradient API forward by working with someone on the tensorflow team.

Let me know if you have any suggestions for a path forward. Thank you!

Activity

  1. andydavis1 commented on Dec 15, 2016

    @andydavis1
    Contributor

    We are developing C++ gradients support here (and it is a work in progress): https://github.com/tensorflow/tensorflow/tree/master/tensorflow/cc/gradients
    However, we have not yet exposed these through the C API.
    Thank you for your offer to help. We will add "contributions welcome" for work items where we can use community support.

  2. kmalakoff commented on Dec 16, 2016

    @kmalakoff
    Author

    Thank you for the information. I will try integrating the gradient functionality for some training cases in C++ over the weekend.

    Quick follow up on the C vs C++ APIs...I was wondering about their internal use at Google and recommendations in general. Specifically: 1) why there are both C variants given the extra work to support multiple APIs? 2) which one I should be focussing on?

    I'm assuming that the C++ API is the most commonly used one internally at Google (ignoring Python for a second) and maybe the C API was developed mainly for porting purposes (eg. more support with a variety of compilers and easier integration across more languages and platforms)? Thank you in advance for any insights into the reasoning and where to focus.

    I'll scan through the "contributions welcome" labels after giving the gradients code a try with an eye on porting to other languages.

  3. asimshankar commented on Dec 16, 2016

    @asimshankar
    Contributor

    Thanks for your offer to assist @kmalakoff !

    @andydavis1 and @suharshs have been slowly chugging along gradients in C++ (using the REGISTER_OP_GRADIENT macro). The broad plan is to (1) have gradients for every op registered in C++, (2) Add a C API call equivalent of tf.gradients that uses these.

    @andydavis1 or @suharshs might have suggestions on the most effective way for you to contribute towards this.

  4. Hebali commented on Dec 16, 2016

    @Hebali

    Thanks @kmalakoff, @andydavis1, @asimshankar and @suharshs.

    I am also interested in this functionality for a TensorFlow creative coding wrapper I am writing for Cinder and OpenFrameworks. I'd be willing to contribute as well.

    On a related note, I wonder if anyone can comment on whether there is planned support in the C/C++ API for graph collections (TRAINABLE_VARIABLES, LOCAL_VARIABLES, etc) as per this discussion.

  5. kmalakoff commented on Dec 16, 2016

    @kmalakoff
    Author

    I've reviewed the gradient folder and the changes to it over time. I've seen this code before and found it a little difficult to reverse engineer the API to understand how it could be used to implement training with back propagation.

    One idea to help point me in the right direction would be to do one pass through solving a real problem (eg. approach this using idea 2 above using a vertical slice through a real-world test case). For example, in this comment, you can see that someone was considering to implement MNIST probably because the provided example was missing the full flow needed for solving for weights in a neural network using back propagation. If we could write pseudocode or an actual test for this limited and classic MNIST example to outline the use of the proposed API, it could be a good way for me to get started.

  6. malmaud commented on Feb 16, 2017

    @malmaud
    Contributor

    I know timeline forecasts are always tricky, but I was wondering if you could provide a rough ETA for when you think gradient calculation might be exposed in the C API - is it more a matter of weeks, months, years?

  7. self-assigned this
    on Feb 17, 2017
  8. suharshs commented on Feb 18, 2017

    @suharshs

    @kmalakoff Thank you for your offer to help out with our C++ gradients.

    Here are some instructions for anyone who wants to help out:

    Gradients are currently being ported from
    python
    to C++ (in this directory).

    Contributions are welcome and much appreciated; please follow the instructions
    below.

    1. Create the op gradient function in foo_grad.cc corresponding to the
      foo_grad.py file where the op originated (i.e. array_grad.py op
      gradients should be written in array_grad.cc).

    2. Write the op gradient with the following naming scheme:

      Status OpNameGrad(const Scope& scope, const Operation& op,
                        const std::vector<Output>& grad_inputs,
                        std::vector<Output>* grad_outputs) {
        ...
        return scope.status();
      }
      REGISTER_GRADIENT_OP("OpName", OpNameGrad);
      
    3. Ops gradients are implemented by using the C++
      API
      .

    4. Tests should be included in foo_grad_test.cc. Please see
      array_grad_test.cc
      for an many examples. Tests are as simple as, creating a placeholder input
      for the op's inputs and calling RunTest (RunTest uses a gradient
      checker

      to verify that the theoretical gradient matches the numeric gradient). For
      example:

      TEST_F(ArrayGradTest, IdentityGrad) {
        TensorShape shape({5, 2});
        auto x = Placeholder(scope_, DT_FLOAT, Placeholder::Shape(shape));
        auto y = Identity(scope_, x);
        RunTest(x, shape, y, shape);
      }
      

    NOTE: There are some ops that require features from the C++ API that are not yet
    implemented.

    • Ops that require PartialTensorShape information cannot yet be implemented.

    • Ops that require SparseTensor or IndexSlices (currently only in python)
      cannot yet be implemented.

    • Maybe more.

  9. suharshs commented on Feb 18, 2017

    @suharshs

    @malmaud As you said C++ gradient calculation is not currently exposed via the C api; I will look into adding that in the next few weeks. That being said, many ops do not yet have C++ gradients implemented, so the exposed API may break for some unknown ops. In these cases contributions using the above instructions would be much appreciated :)

  10. eaplatanios commented on Mar 28, 2017

    @eaplatanios
    Contributor

    @suharshs Is there any estimate on when the C++ gradient calculation will be exposed via the C API?

  11. suharshs commented on Mar 28, 2017

    @suharshs
  12. eaplatanios commented on Mar 28, 2017

    @eaplatanios
    Contributor

    Sounds good! Thanks for the update Suharsh! :)

  13. added a commit that references this issue on Apr 15, 2017
  14. 2 remaining items

  15. eaplatanios commented on May 3, 2017

    @eaplatanios
    Contributor

    @suharshs Thanks a lot for this update!

    I am wondering why we need to include tensorflow/cc/gradients. I see that a lot more gradients are implemented in tensorflow/core/ops/*_grad.cc. Can we not use those directly?

    Thank you!

  16. suharshs commented on May 3, 2017

    @suharshs

    The gradients defined in tensorflow/core/ops/*_grad.cc are not the c++ gradients, they are gradients for FunctionDef's. Very confusing I know :(. We are hoping to simplify/maybe make the FunctionDef's use the c++ gradients defined in tensorflow/cc/gradients eventually.

    For now, the gradients defined in tensorflow/core/ops should be ignored.

  17. eaplatanios commented on May 3, 2017

    @eaplatanios
    Contributor

    @suharshs I see. That's pretty confusing indeed. And I guess this involves a lot of potential duplicate implementations. I'm generally unclear with respect to "functions" in the context of TensorFlow graphs. In any case, if I want to use gradients currently through JNI, should I import all the *_grad.cc files from tensorflow/cc/gradients in my JNI bindings file? What prevents you from importing those in the C API directly so that they're always available?

  18. eaplatanios commented on May 3, 2017

    @eaplatanios
    Contributor

    @suharshs Actually, I'm not super familiar with C++ and I'm a bit unclear as to how to include those files. I currently only include the c_api.h file in my project (a Scala API for TensorFlow) and the linker takes care of linking that to the libtensorflow.so library functions. What should I do to use gradients? Should I specify some flags when compiling libtensorflow.so or should I add something to my JNI bindings header files? Thank you!

  19. suharshs commented on May 3, 2017

    @suharshs

    You are right that we should include these by default. I will look into that and get back to you. Thanks!

  20. eaplatanios commented on May 3, 2017

    @eaplatanios
    Contributor

    @suharshs Thanks! In the meantime, I just wanted ti ask if you plan to add support for gradients of control flow ops any time soon, as well as if there are any plans for indexed slices and sparse tensor gradients. Thanks a lot for the prompt responses!:)

  21. suharshs commented on May 3, 2017

    @suharshs

    I don't have any new gradients prioritized at the moment. But for specific ones, new issues for each desired gradient function, or pull requests would be appreciated.

  22. eaplatanios commented on May 3, 2017

    @eaplatanios
    Contributor

    @suharshs Thank you! I created a new issue for some gradients that are very useful for building machine learning models here.

    Control flow is not absolutely necessary I guess, but it can be very useful for RNNs. However, the gradient implementation is not as simple as registering a gradient for an op. I think it has to be considered while performing back-propagation as a special case (similar to what the Python API does).

  23. added a commit that references this issue on May 5, 2017
  24. fferroni commented on Jul 19, 2017

    @fferroni

    @suharshs Hi, I am trying to find ways of getting gradients for the various variables in my network, so I can use these with ApplyGradientDescent or similar. This is for example how I define a single layer MLP:

    I am a bit lost with the various C or C++ APIs. I just relied on the r1.2 API guide for the ops etc. I presume that currently it's possible to define an optimization routine?

    Thanks!

    tensorflow::Scope *root;
    ...
    std::string scope = "test";
    auto curr = root->NewSubScope(scope);
    
    // input
    auto input_scope = curr.NewSubScope("input");
    auto state_placeholder = tensorflow::ops::Placeholder(input_scope.WithOpName("state"), tensorflow::DT_FLOAT);
    auto action_placeholder = tensorflow::ops::Placeholder(input_scope.WithOpName("action"), tensorflow::DT_FLOAT);
    
    // operations
    // layer 1
    int layer_1_neurons = 400;
    auto layer_1_scope = curr.NewSubScope("dense_1");
    auto W1 = tensorflow::ops::Variable(layer_1_scope.WithOpName("W"), {state_dim, layer_1_neurons}, tensorflow::DT_FLOAT);
    vars_to_fetch.push_back(scope+"/dense_1/W");
    auto assignW1 = tensorflow::ops::Assign(layer_1_scope.WithOpName("W_init"), W1, tensorflow::ops::TruncatedNormal(layer_1_scope, {state_dim, layer_1_neurons}, tensorflow::DT_FLOAT));
    var_init_list.push_back(scope+"/dense_1/W_init");
    auto b1 = tensorflow::ops::Variable(layer_1_scope.WithOpName("b"), {layer_1_neurons}, tensorflow::DT_FLOAT);
    vars_to_fetch.push_back(scope+"/dense_1/b");
    auto assignb1 = tensorflow::ops::Assign(layer_1_scope.WithOpName("b_init"), b1, tensorflow::ops::ZerosLike(layer_1_scope, tensorflow::Tensor(tensorflow::DT_FLOAT, {layer_1_neurons})));
    var_init_list.push_back(scope+"/dense_1/b_init");
    auto m1 = tensorflow::ops::MatMul(layer_1_scope, state_placeholder, W1);
    auto a1 = tensorflow::ops::BiasAdd(layer_1_scope, m1, b1);
    
  25. suharshs commented on Jul 19, 2017

    @suharshs

    @fferroni you may be interested in the status of #11377

  26. Oceania2018 commented on Feb 22, 2019

    @Oceania2018
    Contributor

    Gradient ported from python to C# now. So we can use gradient in .NET, and it's using r1.13 branch.
    Check this issue.

  27. vmullig commented on Nov 6, 2019

    @vmullig

    What is the current status of gradients in the C API now? Is it possible to compute gradients using that API, or is it necessary to use the C++ API?

  28. removed their assignment
    on Nov 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

type:feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions