Skip to content

Fix bug on the gradients graph computation caused by an Assign node - C++ API - #12397

Merged
martinwicke merged 9 commits into
tensorflow:masterfrom
theflofly:gradients-bug-assign-node
Sep 5, 2017
Merged

martinwicke merged 9 commits into
tensorflow:masterfrom
theflofly:gradients-bug-assign-node

Conversation

@theflofly

Copy link
Copy Markdown
Contributor

The gradient computation in the C++ API works as follow.
Let's say that we have the following graph:

                Tanh
                  |
         Assign MatMul
         /    \ /    \
      Const   Var   Const

Here our Output is Tanh and our Input is Var. The gradient method does a BFS from Var to Tanh to count for each node how many backprop we should expect. If a node has two outgoing edges, it will be ready only when both would have been backpropagated and the gradient summed. In our case, Var has 2, Assign 0, MatMul 1. These values are saved into a pending array.

Then the gradient method does a BFS from Tanh to Var, this is the actual backpropagation, the error is backpropagated until we reach Var. When a Node is reached, pending is decreased by one and if pending == 0, the Node is ready and is added to the queue of Nodes to be processed. If it is not ready, it will be reached again in the future and will be ready at some point.

In our case, doing a BFS from Var to Tanh give us 2 expected gradients, one from Assign and one from MatMul, whereas doing a BFS from Tanh to Var, we will reach Var only once, because we can't reach Assign from Tanh. In that case, the pending count will never reach Zero, Var will never be ready and the BFS will end. At the end, a check is done and if pending nodes are still there, an error is raised.

This PR updates the gradient method to ignore nodes that have 0 outgoing edges and are not in the list of Output (Tanh is the only one in the list of outputs in our case).

The unit tests have been updated to use Variable with Assign nodes and not Const, because differentiating w.r.t Const make less sense and the error would have been catched before.

@tensorflow-jenkins

Copy link
Copy Markdown
Collaborator

Can one of the admins verify this patch?

@skye skye left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: does this bug also manifest in the following situation?

    Tanh1  Tanh2
     |      |
  MatMul1 MatMul2
   /    \ /    \
Const1 Const2  Const3

And then we take the gradient of Tanh2 w.r.t. Const2. Will Const2 still have a pending count of 2, which only gets decreased to 1 since the BFS from Const2 to Tanh2 doesn't traverse MatMul1?

// Construct forward graph.
auto x = Const(scope, {{1.0, 2.0}, {3.0, 4.0}});
auto y = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto x = ThreeNodeVariable(scope, {{1.0, 2.0}, {3.0, 4.0}});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please keep the existing tests as-is, unless there's a good reason to switch to ThreeNodeVariable (which I don't think there is, since we're take the gradient w.r.t. to the Const nodes so it shouldn't make a difference). The Const nodes are simpler to reason about, and also your changes make the comment diagrams inaccurate.

Instead, can you add a new test case that repros the problem? This should make it easier to see the potential problem, and should also remove the need for the VariableHelper class and multiple inheritance.

@theflofly theflofly Aug 23, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@skye: I chose to edit the tests because as far as I know we don't differentiate w.r.t a Const. Else people will differentiate w.r.t a Const W1 for instance and then create an ApplyGradientDescent node that updates W1 using the collected gradient. Updating a Const is in opposition to the term const.

So a test passing with Const nodes is worthless because in reality it will not be done like that but with Variables (I may be wrong?).

And more importantly, everything was working fine with Const nodes but wasn't with Variable nodes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right that differentiating w.r.t. Const nodes isn't realistic and prevented us from catching this error. However, it makes the unit tests simpler and easier to understand. The tests aren't worthless, they just test specific functionality, which is the idea of a unit test.

I think a good solution to the lack of coverage would be to have one or two "real world" tests that differentiate realistic graphs (we'll hopefully get these automatically when we switch the Python code to use this code under the hood). But I don't think we should add this much complexity to all of our existing unit tests in order to get slightly more coverage. For now, let's stick with the new tests you wrote that cover this particular case.

@theflofly

Copy link
Copy Markdown
Contributor Author

@skye: Yes the bug also manifest in this situation. I'll open an issue and work on a solution.

@theflofly

Copy link
Copy Markdown
Contributor Author

@skye: I made changes in the gradient computation method to handle the case you outlined, I create a vector of boolean called reachable_nodes that I initialize doing a BFS from output to input. When counting how many node should be backpropagated for a given node, I only count it if reachable_nodes[node id] is equals to true. The same thing is done in the python gradient method.

I added two more test cases for the case you outlined.

I did not remove the stuff about ThreeNodeVariable because even if Const is simpler to use, it is particularly because we used Const and not Variable that we didn't see this bug before. I'll wait for your comment on that last point.

@theflofly theflofly changed the title Fix bug on the gradients graph computation caused by an Assign node. Fix bug on the gradients graph computation caused by an Assign node - C++ API Aug 23, 2017
Comment thread tensorflow/cc/framework/gradients.cc Outdated
// If a node is not reachable when doing a BFS from the outputs
// we don't expect it to receive a backpropagated gradient.
// It will not be counted in num_expected_backprops.
std::vector<bool> reachable_nodes(scope_.graph()->num_node_ids(), false);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is already quite long, can you break this out into a new function? Something like GetReachableNodes().

Comment thread tensorflow/cc/framework/gradients.cc Outdated
// handle computing gradients over small subgraphs from a very large graph.
pending_.resize(scope_.graph()->num_node_ids(), 0);
{
// If a node is not reachable when doing a BFS from the outputs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please move this comment to where you use reachable_nodes. I think it makes more sense there (e.g. num_expected_backprops isn't defined yet).

// Construct forward graph.
auto x = Const(scope, {{1.0, 2.0}, {3.0, 4.0}});
auto y = Const(scope, {{1.0, 0.0}, {0.0, 1.0}});
auto x = ThreeNodeVariable(scope, {{1.0, 2.0}, {3.0, 4.0}});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right that differentiating w.r.t. Const nodes isn't realistic and prevented us from catching this error. However, it makes the unit tests simpler and easier to understand. The tests aren't worthless, they just test specific functionality, which is the idea of a unit test.

I think a good solution to the lack of coverage would be to have one or two "real world" tests that differentiate realistic graphs (we'll hopefully get these automatically when we switch the Python code to use this code under the hood). But I don't think we should add this much complexity to all of our existing unit tests in order to get slightly more coverage. For now, let's stick with the new tests you wrote that cover this particular case.

@theflofly

Copy link
Copy Markdown
Contributor Author

@skye: Normally all your comments have been followed.

@skye skye left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking good! It's mostly style comments at this point.

void GetTensors(const Scope& scope, const std::vector<Output>& assign_vars,
OutputList tensors, std::vector<Tensor>* out) {
ClientSession session(scope);
TF_CHECK_OK(session.Run(assign_vars, nullptr));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of making special GetTensors overloads that do two Run calls, just call GetTensors() twice in your tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually as-is GetTensors instantiates a new ClientSession at each call nonetheless I need to use the same session twice. If you don't want the overload I can instantiate and use a session directly from the test, what do you think?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh duh. What you have is fine then.

Comment thread tensorflow/cc/framework/gradients.cc Outdated

// If a node is reachable when doing a BFS from outputs toward inputs
// its id used as index in reachable_nodes is set to true.
void GetReachableNodes(std::vector<bool>* reachable_nodes);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Return the vector directly instead of using an output param (move semantics make this efficient).

Comment thread tensorflow/cc/framework/gradients.cc Outdated
reachable_nodes->clear();
reachable_nodes->resize(scope_.graph()->num_node_ids(), false);

std::deque<Node*> queue_reachable;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: queue_reachable sounds strange to me, just rename to 'queue'

Comment thread tensorflow/cc/framework/gradients.cc Outdated

std::deque<Node*> queue_reachable;
for (const Output& out : outputs_) {
if (!reachable_nodes->at(out.node()->id())) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use [] instead of at() (it's more idiomatic, and we don't use exceptions) (here and below)

Comment thread tensorflow/cc/framework/gradients.cc Outdated
queue_reachable.pop_front();
for (const Edge* e : n->in_edges()) {
if (e->IsControlEdge()) continue;
LOG(INFO) << e->src()->DebugString();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove LOG

Comment thread tensorflow/cc/framework/gradients.cc Outdated
for (const Edge* e : n->out_edges()) {
if (e->IsControlEdge()) continue;
++num_expected_backprops;
// If a node is not reachable when doing a BFS from the outputs

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can just say: "If a node is not reachable from outputs_, ..."

Comment thread tensorflow/cc/framework/gradients.cc Outdated
std::vector<Output>* grad_outputs);

// If a node is reachable when doing a BFS from outputs toward inputs
// its id used as index in reachable_nodes is set to true.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about: "Returns a list mapping whether each node in the graph is reachable from outputs_. Keyed by node id."

Comment thread tensorflow/cc/framework/gradients.cc Outdated
{
std::vector<bool> reachable_nodes;
GetReachableNodes(&reachable_nodes);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a TODO to check that inputs_ are reachable from outputs_ here? (It would be easy to add the check now, but let's save it for another PR since it will require another test case.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved std::vector<bool> reachable_nodes = GetReachableNodes(); at the beginning of the method as we'll check the errors at the beginning (the TODO).

{grad_outputs[0]}, &outputs);

// the gradients from m1 and m2 will be summed to compute the gradient
// w.r.t y

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add this comment to the above test as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Above the output given to AddSymbolicGradients is m1 so the gradient is backpropagated from m1 but not from m2, so there is no sum. Here the output given to AddSymbolicGradients is {m1, m2} so the gradients from m1 and m2 are summed. That's why the comment is only here. I guess it should be like that?
Else I agree with all others comments and will update soon.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah right. Can you comment how you computed the gradient for above test then?

Comment thread tensorflow/cc/framework/testutil.h Outdated

// Computes the outputs listed in 'tensors', returns the tensors in 'out'.
// Take a vector of Output as extra parameters if some Variable should
// be assigned before the session run call.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Grammar nit: change the second sentence to:
assign_vars are extra outputs that should be run e.g. to assign values to variables.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like you changed the comment below, also change it up here please.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, my bad.

@theflofly

Copy link
Copy Markdown
Contributor Author

@skye Updated following your comments.

@skye skye left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll approve after you fix the one last comment :)

@skye skye left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks for this contribution!

@jhseu

jhseu commented Aug 24, 2017

Copy link
Copy Markdown
Contributor

Jenkins, test this please

@theflofly

Copy link
Copy Markdown
Contributor Author

@jhseu The failing tests seem unrelated to the PR content no?

@bpiel

bpiel commented Aug 26, 2017

Copy link
Copy Markdown
Contributor

@theflofly I had those same two checks fail and fixed them just by merging master back into my branch. Worth a try?

@theflofly

Copy link
Copy Markdown
Contributor Author

@bpiel done, let's see.

@skye

skye commented Aug 29, 2017

Copy link
Copy Markdown
Contributor

@martinwicke why does it say "TF Code Review — Waiting for status to be reported"? Do I need to do something else?

@martinwicke

Copy link
Copy Markdown
Member

It means someone has to run the tests.

Jenkins, test this please!

@bpiel

bpiel commented Aug 29, 2017

Copy link
Copy Markdown
Contributor

One test failing. https://ci.tensorflow.org/job/tensorflow-pull-requests-cpu-python3/6212/console

//bazel_pip/tensorflow/contrib/timeseries/python/timeseries:input_pipeline_test FAILED in 19.4s
  /var/lib/jenkins/workspace/tensorflow-pull-requests-cpu-python3/bazel-ci_build-cache/.cache/bazel/_bazel_jenkins/eab0d61a99b6696edb3d2aff87b585e8/execroot/workspace/bazel-out/local-py3-opt/testlogs/bazel_pip/tensorflow/contrib/timeseries/python/timeseries/input_pipeline_test/test.log

Executed 703 out of 703 tests: 702 tests pass and 1 fails locally.
PIP tests-on-install FAILED

@theflofly

Copy link
Copy Markdown
Contributor Author

@bpiel I merged with master once again... If someone has some insights?

@bpiel

bpiel commented Aug 29, 2017

Copy link
Copy Markdown
Contributor

I have a branch with this branch merged into it. I attempted to run the failing test (from above), but it passed for me. Not sure what that means.

$ sudo tensorflow/tools/ci_build/ci_build.sh CPU bazel test //tensorflow/contrib/timeseries/python/timeseries:input_pipeline_test

(...lots of stuff...)

[3,132 / 3,133] Testing //tensorflow/contrib/timeseries/python/timeseries:input_pipeline_test
PASS: //tensorflow/contrib/timeseries/python/timeseries:input_pipeline_test
Target //tensorflow/contrib/timeseries/python/timeseries:input_pipeline_test up-to-date:
  bazel-bin/tensorflow/contrib/timeseries/python/timeseries/input_pipeline_test
INFO: Elapsed time: 1113.296s, Critical Path: 65.63s
//tensorflow/contrib/timeseries/python/timeseries:input_pipeline_test    PASSED in 6.4s

@theflofly

Copy link
Copy Markdown
Contributor Author

@bpiel Thanks for your help on the issue. Let's wait to hear from the google team but it would be great if this could be merged.

@bpiel

bpiel commented Aug 30, 2017 •

Copy link
Copy Markdown
Contributor

@theflofly Thank you for taking this on! I'm relying on the C API TF_AddGradients function and would be completely blocked if I didn't have access to your code. It fixes a MAJOR bug.

@theflofly

Copy link
Copy Markdown
Contributor Author

@bpiel Thanks for the kind words. Does it work if us contributor are writing:
Jenkins, test this please!

@martinwicke

Copy link
Copy Markdown
Member

Jenkins, test this please.

No it doesn't work. Sorry.

@martinwicke
martinwicke merged commit c898144 into tensorflow:master Sep 5, 2017
@bpiel

bpiel commented Sep 5, 2017

Copy link
Copy Markdown
Contributor

🎉 thanks!

@theflofly

Copy link
Copy Markdown
Contributor Author

Thanks! :)

@theflofly
theflofly deleted the gradients-bug-assign-node branch September 5, 2017 16:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants