• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Code for backpropagation using the tape utilities."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import collections
22
23from tensorflow.python import pywrap_tensorflow
24from tensorflow.python.ops.unconnected_gradients import UnconnectedGradients
25from tensorflow.python.util import compat
26
27VSpace = collections.namedtuple("VSpace", [
28    "aggregate_fn", "num_elements_fn", "zeros_fn", "ones_fn", "graph_shape_fn"
29])
30
31
32def imperative_grad(
33    tape,
34    target,
35    sources,
36    output_gradients=None,
37    unconnected_gradients=UnconnectedGradients.NONE):
38  """Computes gradients from the imperatively defined tape on top of the stack.
39
40  Works by filtering the tape, computing how many downstream usages are of each
41  tensor and entry, and repeatedly applying backward functions until we have
42  gradients for all sources.
43
44  Args:
45   tape: the gradient tape which stores the trace.
46   target: either a Tensor or list of Tensors to be differentiated.
47   sources: list of Tensors for which we want gradients
48   output_gradients: if not None, a list of gradient provided for each Target,
49    or None if we are to use the target's computed downstream gradient.
50   unconnected_gradients: determines the value returned if the target and
51    sources are unconnected. When 'none' the value returned is None wheras when
52    'zero' a zero tensor in the same shape as the sources is returned.
53
54  Returns:
55   the gradient wrt each of the sources.
56
57  Raises:
58    ValueError: if the arguments are invalid.
59    RuntimeError: if something goes wrong.
60  """
61  try:
62    unconnected_gradients = UnconnectedGradients(unconnected_gradients)
63  except ValueError:
64    raise ValueError(
65        "Unknown value for unconnected_gradients: %r" % unconnected_gradients)
66
67  return pywrap_tensorflow.TFE_Py_TapeGradient(
68      tape._tape,  # pylint: disable=protected-access
69      target,
70      sources,
71      output_gradients,
72      compat.as_str(unconnected_gradients.value))
73