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_tfe 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", 29 "zeros_like_fn", "ones_like_fn", "graph_shape_fn" 30]) 31 32 33def imperative_grad(tape, 34 target, 35 sources, 36 output_gradients=None, 37 sources_raw=None, 38 unconnected_gradients=UnconnectedGradients.NONE): 39 """Computes gradients from the imperatively defined tape on top of the stack. 40 41 Works by filtering the tape, computing how many downstream usages are of each 42 tensor and entry, and repeatedly applying backward functions until we have 43 gradients for all sources. 44 45 Args: 46 tape: the gradient tape which stores the trace. 47 target: either a Tensor or list of Tensors to be differentiated. 48 sources: list of Tensors for which we want gradients 49 output_gradients: if not None, a list of gradient provided for each Target, 50 or None if we are to use the target's computed downstream gradient. 51 sources_raw: if not None, a list of the source python objects from which the 52 sources were generated. Should have the same length as sources. Only needs 53 to be populated if unconnected_gradients is 'zero'. 54 unconnected_gradients: determines the value returned if the target and 55 sources are unconnected. When 'none' the value returned is None wheras when 56 'zero' a zero tensor in the same shape as the sources is returned. 57 58 Returns: 59 the gradient wrt each of the sources. 60 61 Raises: 62 ValueError: if the arguments are invalid. 63 RuntimeError: if something goes wrong. 64 """ 65 try: 66 unconnected_gradients = UnconnectedGradients(unconnected_gradients) 67 except ValueError: 68 raise ValueError( 69 "Unknown value for unconnected_gradients: %r" % unconnected_gradients) 70 71 return pywrap_tfe.TFE_Py_TapeGradient( 72 tape._tape, # pylint: disable=protected-access 73 target, 74 sources, 75 output_gradients, 76 sources_raw, 77 compat.as_str(unconnected_gradients.value)) 78