Implementation of gradients().
(ys,
xs,
grad_ys=None,
name="gradients",
colocate_gradients_with_ops=False,
gate_gradients=False,
aggregation_method=None,
stop_gradients=None,
unconnected_gradients=UnconnectedGradients.NONE,
src_graph=None)
| 515 | |
| 516 | |
| 517 | def _GradientsHelper(ys, |
| 518 | xs, |
| 519 | grad_ys=None, |
| 520 | name="gradients", |
| 521 | colocate_gradients_with_ops=False, |
| 522 | gate_gradients=False, |
| 523 | aggregation_method=None, |
| 524 | stop_gradients=None, |
| 525 | unconnected_gradients=UnconnectedGradients.NONE, |
| 526 | src_graph=None): |
| 527 | """Implementation of gradients().""" |
| 528 | if context.executing_eagerly(): |
| 529 | raise RuntimeError("tf.gradients is not supported when eager execution " |
| 530 | "is enabled. Use tf.GradientTape instead.") |
| 531 | if src_graph is None: |
| 532 | src_graph = ops.get_default_graph() |
| 533 | try: |
| 534 | unconnected_gradients = UnconnectedGradients(unconnected_gradients) |
| 535 | except ValueError: |
| 536 | raise ValueError( |
| 537 | "Unknown value for unconnected_gradients: %r" % unconnected_gradients) |
| 538 | |
| 539 | # If src_graph is a _FuncGraph (i.e. a function body), gather it and all |
| 540 | # ancestor graphs. This is necessary for correctly handling captured values. |
| 541 | func_graphs = [] |
| 542 | curr_graph = src_graph |
| 543 | while _IsFunction(curr_graph): |
| 544 | func_graphs.append(curr_graph) |
| 545 | if isinstance(curr_graph, FuncGraph): |
| 546 | curr_graph = curr_graph.outer_graph |
| 547 | else: |
| 548 | assert isinstance(curr_graph, framework_function._FuncGraph) # pylint: disable=protected-access |
| 549 | curr_graph = curr_graph._outer_graph # pylint: disable=protected-access |
| 550 | |
| 551 | ys = _AsList(ys) |
| 552 | xs = _AsList(xs) |
| 553 | stop_gradients = [] if stop_gradients is None else _AsList(stop_gradients) |
| 554 | if grad_ys is None: |
| 555 | grad_ys = [None] * len(ys) |
| 556 | else: |
| 557 | grad_ys = _AsList(grad_ys) |
| 558 | |
| 559 | with ops.name_scope( |
| 560 | name, "gradients", |
| 561 | list(ys) + list(xs) + list(stop_gradients) + list(grad_ys)) as grad_scope: |
| 562 | # Get a uid for this call to gradients that can be used to help |
| 563 | # cluster ops for compilation. |
| 564 | gradient_uid = ops.get_default_graph().unique_name("uid") |
| 565 | ys = ops.convert_n_to_tensor_or_indexed_slices(ys, name="y") |
| 566 | xs = [ |
| 567 | x.handle if resource_variable_ops.is_resource_variable(x) else x |
| 568 | for x in xs |
| 569 | ] |
| 570 | xs = ops.internal_convert_n_to_tensor_or_indexed_slices( |
| 571 | xs, name="x", as_ref=True) |
| 572 | xs_set = object_identity.ObjectIdentitySet(xs) |
| 573 | grad_ys = _DefaultGradYs(grad_ys, ys, colocate_gradients_with_ops, |
| 574 | gradient_uid) |
nothing calls this directly
no test coverage detected