ZTWHHH commited on
Commit
8e36323
·
verified ·
1 Parent(s): cdf33a7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. llava_next/share/terminfo/a/a210 +0 -0
  3. llava_next/share/terminfo/a/a80 +0 -0
  4. llava_next/share/terminfo/a/a980 +0 -0
  5. llava_next/share/terminfo/a/aa4080 +0 -0
  6. llava_next/share/terminfo/a/aaa+unk +0 -0
  7. llava_next/share/terminfo/a/aaa-22 +0 -0
  8. llava_next/share/terminfo/a/aaa-24-rv +0 -0
  9. llava_next/share/terminfo/a/aaa-30 +0 -0
  10. llava_next/share/terminfo/a/aaa-36 +0 -0
  11. llava_next/share/terminfo/a/aaa-48-rv +0 -0
  12. llava_next/share/terminfo/a/aaa-60-rv +0 -0
  13. llava_next/share/terminfo/a/abm85 +0 -0
  14. llava_next/share/terminfo/a/absolute +0 -0
  15. llava_next/share/terminfo/a/adds980 +0 -0
  16. llava_next/share/terminfo/a/adm1a +0 -0
  17. llava_next/share/terminfo/a/adm2 +0 -0
  18. llava_next/share/terminfo/a/alto-heath +0 -0
  19. llava_next/share/terminfo/a/altos-2 +0 -0
  20. llava_next/share/terminfo/a/altos2 +0 -0
  21. llava_next/share/terminfo/a/ansi+cpr +0 -0
  22. llava_next/share/terminfo/a/ansi+rca +0 -0
  23. llava_next/share/terminfo/a/ansi+rep +0 -0
  24. llava_next/share/terminfo/a/ansi-mtabs +0 -0
  25. llava_next/share/terminfo/a/ansi80x30 +0 -0
  26. llava_next/share/terminfo/a/ansi80x60-mono +0 -0
  27. llava_next/share/terminfo/a/ap-vm80 +0 -0
  28. llava_next/share/terminfo/a/apple-80 +0 -0
  29. llava_next/share/terminfo/a/apple2e +0 -0
  30. llava_next/share/terminfo/a/apple2e-p +0 -0
  31. llava_next/share/terminfo/a/arm100 +0 -0
  32. llava_next/share/terminfo/a/att4415-w-nl +0 -0
  33. llava_next/share/terminfo/a/att4415-w-rv-n +0 -0
  34. llava_next/share/terminfo/a/att4418-w +0 -0
  35. llava_next/share/terminfo/a/att5310 +0 -0
  36. llava_next/share/terminfo/a/att5410 +0 -0
  37. llava_next/share/terminfo/a/att5410-w +0 -0
  38. llava_next/share/terminfo/a/att5418 +0 -0
  39. llava_next/share/terminfo/a/att5425-nl +0 -0
  40. llava_next/share/terminfo/a/att610-103k-w +0 -0
  41. llava_next/share/terminfo/a/att615 +0 -0
  42. llava_next/share/terminfo/a/att6386 +0 -0
  43. llava_next/share/terminfo/a/att730r-41 +0 -0
  44. llava_next/share/terminfo/a/avt-rv +0 -0
  45. llava_next/share/terminfo/a/avt-w-rv +0 -0
  46. llava_next/share/terminfo/a/aws +0 -0
  47. openflamingo/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.11 +3 -0
  48. openflamingo/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 +3 -0
  49. videochat2/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.so +3 -0
  50. videochat2/lib/python3.10/site-packages/tensorflow/python/ops/array_grad.py +1234 -0
.gitattributes CHANGED
@@ -836,3 +836,7 @@ parrot/lib/python3.10/site-packages/torch/lib/libc10_cuda.so filter=lfs diff=lfs
836
  parrot/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
837
  parrot/lib/python3.10/site-packages/frozenlist/_frozenlist.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
838
  parrot/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
836
  parrot/lib/python3.10/site-packages/torch/_inductor/__pycache__/ir.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
837
  parrot/lib/python3.10/site-packages/frozenlist/_frozenlist.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
838
  parrot/lib/python3.10/site-packages/torch/fx/experimental/__pycache__/symbolic_shapes.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
839
+ videochat2/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.so filter=lfs diff=lfs merge=lfs -text
840
+ openflamingo/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 filter=lfs diff=lfs merge=lfs -text
841
+ openflamingo/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.11 filter=lfs diff=lfs merge=lfs -text
842
+ videochat2/lib/python3.10/site-packages/tensorflow/python/platform/_pywrap_cpu_feature_guard.so filter=lfs diff=lfs merge=lfs -text
llava_next/share/terminfo/a/a210 ADDED
Binary file (822 Bytes). View file
 
llava_next/share/terminfo/a/a80 ADDED
Binary file (481 Bytes). View file
 
llava_next/share/terminfo/a/a980 ADDED
Binary file (444 Bytes). View file
 
llava_next/share/terminfo/a/aa4080 ADDED
Binary file (473 Bytes). View file
 
llava_next/share/terminfo/a/aaa+unk ADDED
Binary file (1.24 kB). View file
 
llava_next/share/terminfo/a/aaa-22 ADDED
Binary file (1.26 kB). View file
 
llava_next/share/terminfo/a/aaa-24-rv ADDED
Binary file (1.3 kB). View file
 
llava_next/share/terminfo/a/aaa-30 ADDED
Binary file (1.29 kB). View file
 
llava_next/share/terminfo/a/aaa-36 ADDED
Binary file (1.27 kB). View file
 
llava_next/share/terminfo/a/aaa-48-rv ADDED
Binary file (1.32 kB). View file
 
llava_next/share/terminfo/a/aaa-60-rv ADDED
Binary file (1.28 kB). View file
 
llava_next/share/terminfo/a/abm85 ADDED
Binary file (735 Bytes). View file
 
llava_next/share/terminfo/a/absolute ADDED
Binary file (2.7 kB). View file
 
llava_next/share/terminfo/a/adds980 ADDED
Binary file (444 Bytes). View file
 
llava_next/share/terminfo/a/adm1a ADDED
Binary file (350 Bytes). View file
 
llava_next/share/terminfo/a/adm2 ADDED
Binary file (402 Bytes). View file
 
llava_next/share/terminfo/a/alto-heath ADDED
Binary file (641 Bytes). View file
 
llava_next/share/terminfo/a/altos-2 ADDED
Binary file (1.11 kB). View file
 
llava_next/share/terminfo/a/altos2 ADDED
Binary file (1.11 kB). View file
 
llava_next/share/terminfo/a/ansi+cpr ADDED
Binary file (658 Bytes). View file
 
llava_next/share/terminfo/a/ansi+rca ADDED
Binary file (350 Bytes). View file
 
llava_next/share/terminfo/a/ansi+rep ADDED
Binary file (308 Bytes). View file
 
llava_next/share/terminfo/a/ansi-mtabs ADDED
Binary file (464 Bytes). View file
 
llava_next/share/terminfo/a/ansi80x30 ADDED
Binary file (1.5 kB). View file
 
llava_next/share/terminfo/a/ansi80x60-mono ADDED
Binary file (1.25 kB). View file
 
llava_next/share/terminfo/a/ap-vm80 ADDED
Binary file (203 Bytes). View file
 
llava_next/share/terminfo/a/apple-80 ADDED
Binary file (207 Bytes). View file
 
llava_next/share/terminfo/a/apple2e ADDED
Binary file (395 Bytes). View file
 
llava_next/share/terminfo/a/apple2e-p ADDED
Binary file (431 Bytes). View file
 
llava_next/share/terminfo/a/arm100 ADDED
Binary file (1.47 kB). View file
 
llava_next/share/terminfo/a/att4415-w-nl ADDED
Binary file (1.4 kB). View file
 
llava_next/share/terminfo/a/att4415-w-rv-n ADDED
Binary file (1.41 kB). View file
 
llava_next/share/terminfo/a/att4418-w ADDED
Binary file (910 Bytes). View file
 
llava_next/share/terminfo/a/att5310 ADDED
Binary file (1.87 kB). View file
 
llava_next/share/terminfo/a/att5410 ADDED
Binary file (1.14 kB). View file
 
llava_next/share/terminfo/a/att5410-w ADDED
Binary file (1.15 kB). View file
 
llava_next/share/terminfo/a/att5418 ADDED
Binary file (906 Bytes). View file
 
llava_next/share/terminfo/a/att5425-nl ADDED
Binary file (1.63 kB). View file
 
llava_next/share/terminfo/a/att610-103k-w ADDED
Binary file (1.7 kB). View file
 
llava_next/share/terminfo/a/att615 ADDED
Binary file (1.61 kB). View file
 
llava_next/share/terminfo/a/att6386 ADDED
Binary file (1.42 kB). View file
 
llava_next/share/terminfo/a/att730r-41 ADDED
Binary file (1.91 kB). View file
 
llava_next/share/terminfo/a/avt-rv ADDED
Binary file (1.25 kB). View file
 
llava_next/share/terminfo/a/avt-w-rv ADDED
Binary file (1.25 kB). View file
 
llava_next/share/terminfo/a/aws ADDED
Binary file (1.07 kB). View file
 
openflamingo/lib/python3.10/site-packages/nvidia/cusparse/lib/libcusparse.so.11 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e154ed32bc4827f19c1ca0e1c1753e642505e38747006364284b865bf981d311
3
+ size 239685008
openflamingo/lib/python3.10/site-packages/nvidia/nccl/lib/libnccl.so.2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d5e5d9d2280dd4e34ab57f542a32a3fb6d009fe4ce84c074df3eae99b008c72d
3
+ size 240931768
videochat2/lib/python3.10/site-packages/tensorflow/lite/python/metrics/_pywrap_tensorflow_lite_metrics_wrapper.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9688c564ce5b804be05287f437542d1e967dfabdf8a4871c2a53382350510455
3
+ size 3769112
videochat2/lib/python3.10/site-packages/tensorflow/python/ops/array_grad.py ADDED
@@ -0,0 +1,1234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2015 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
+ """Gradients for operators defined in array_ops.py."""
16
+
17
+ from tensorflow.compiler.tf2xla.ops import gen_xla_ops
18
+ from tensorflow.python import pywrap_tfe
19
+ from tensorflow.python.eager import context
20
+ from tensorflow.python.framework import constant_op
21
+ from tensorflow.python.framework import dtypes
22
+ from tensorflow.python.framework import indexed_slices as indexed_slices_lib
23
+ from tensorflow.python.framework import ops
24
+ from tensorflow.python.framework import sparse_tensor
25
+ from tensorflow.python.framework import tensor
26
+ from tensorflow.python.framework import tensor_shape
27
+ from tensorflow.python.framework import tensor_util
28
+ from tensorflow.python.ops import array_ops
29
+ from tensorflow.python.ops import array_ops_stack
30
+ from tensorflow.python.ops import cond
31
+ from tensorflow.python.ops import control_flow_util
32
+ from tensorflow.python.ops import gen_array_ops
33
+ from tensorflow.python.ops import gen_math_ops
34
+ from tensorflow.python.ops import gen_resource_variable_ops
35
+ from tensorflow.python.ops import math_ops
36
+ from tensorflow.python.ops import sparse_ops
37
+
38
+
39
+ @ops.RegisterGradient("Pack")
40
+ def _PackGrad(op: ops.Operation, grad):
41
+ """Gradient for pack op."""
42
+ return array_ops_stack.unstack(
43
+ grad, num=op.get_attr("N"), axis=op.get_attr("axis"))
44
+
45
+
46
+ @ops.RegisterGradient("Unpack")
47
+ def _UnpackGrad(op: ops.Operation, *grads):
48
+ """Gradient for unpack op."""
49
+ return array_ops_stack.stack(grads, axis=op.get_attr("axis"))
50
+
51
+
52
+ def _ConcatGradHelper(
53
+ op: ops.Operation, grad, start_value_index, end_value_index, dim_index
54
+ ):
55
+ """Gradient for concat op.
56
+
57
+ Args:
58
+ op: An operation.
59
+ grad: `Tensor` or `IndexedSlices` representing the gradients with respect to
60
+ each output of the op.
61
+ start_value_index: An integer index of the first value in the op.inputs.
62
+ end_value_index: An integer index of the last value in the op.inputs.
63
+ dim_index: An integer index of concat_dim or axis parameter in op.inputs.
64
+
65
+ Returns:
66
+ Tensors representing the partial gradients with respect to each input
67
+ of the op.
68
+
69
+ Raises:
70
+ ValueError: if concat_dim/axis is not statically known.
71
+ """
72
+
73
+ def _CreateDenseMaskAndBegin(sizes, concat_dim):
74
+ """Create variables for iteratively slicing a dense gradients tensor."""
75
+ # Since shape is 1-D, shape_of_shape = [rank-of-inputs]
76
+ shape_of_shape = array_ops.shape(sizes[0])
77
+ # Make a vector of length equal to the input's dimensions,
78
+ # with 0's everywhere and 1 in the concat dim position.
79
+ # Note: Can't use sparse_to_dense since it isn't GPU-capable (for now)
80
+ mask = array_ops.concat([
81
+ array_ops.zeros(
82
+ array_ops.expand_dims(concat_dim, 0), dtype=dtypes.int32), [1],
83
+ array_ops.zeros(shape_of_shape - concat_dim - 1, dtype=dtypes.int32)
84
+ ], 0)
85
+ begin = array_ops.zeros(shape_of_shape, dtype=dtypes.int32)
86
+ return mask, begin
87
+
88
+ def _ExtractInputShapes(inputs):
89
+ """Extract the shapes of a set of input tensors."""
90
+ if context.executing_eagerly():
91
+ return array_ops.shape_n(inputs)
92
+ sizes = []
93
+ fully_known = True
94
+ for x in inputs:
95
+ input_shape = array_ops.shape(x)
96
+ if not isinstance(input_shape,
97
+ tensor.Tensor) or input_shape.op.type != "Const":
98
+ fully_known = False
99
+ break
100
+ sizes.append(input_shape)
101
+
102
+ if fully_known:
103
+ return sizes
104
+ else:
105
+ return array_ops.shape_n(inputs)
106
+
107
+ # Degenerate concatenation, just return grad.
108
+ if len(op.inputs) == 2:
109
+ return grad + [None] if end_value_index <= dim_index else [None] + grad
110
+
111
+ concat_dim = op.inputs[dim_index]
112
+ input_values = op.inputs[start_value_index:end_value_index]
113
+
114
+ out_grads = []
115
+ if isinstance(grad, tensor.Tensor):
116
+ if context.executing_eagerly() or isinstance(concat_dim, ops.EagerTensor):
117
+ # Using mod here for convenience since concat_dim is already verified
118
+ # in concat implementation to be within the allowed [-rank, rank) range.
119
+ non_neg_concat_dim = (
120
+ concat_dim._numpy().item(0) % input_values[0]._rank()) # pylint: disable=protected-access
121
+ # All inputs are guaranteed to be EagerTensors in eager mode
122
+ sizes = pywrap_tfe.TFE_Py_TensorShapeSlice(input_values,
123
+ non_neg_concat_dim)
124
+ out_grads = array_ops.split(grad, sizes, non_neg_concat_dim)
125
+ else:
126
+ if constant_op.is_constant(concat_dim):
127
+ # If concat_dim is a constant defined in a different context,
128
+ # then we duplicate it in the current context to avoid passing it
129
+ # through an Enter node.
130
+ # This is a small optimization in general, but it is required when
131
+ # compiling with XLA, as XLA needs the concat input to be folded into a
132
+ # constant.
133
+ grad_context = control_flow_util.GetOutputContext(grad.op)
134
+ dim_context = control_flow_util.GetOutputContext(concat_dim.op)
135
+ if dim_context != grad_context:
136
+ value = tensor_util.constant_value(concat_dim)
137
+ concat_dim = constant_op.constant(value=value, dtype=concat_dim.dtype)
138
+
139
+ # Using mod here for convenience since concat_dim is already verified
140
+ # in concat implementation to be within the allowed [-rank, rank) range.
141
+ non_neg_concat_dim = concat_dim % array_ops.rank(input_values[0])
142
+
143
+ # Get the inputs' tensor shapes
144
+ sizes = _ExtractInputShapes(input_values)
145
+ # The magic number of 16 was found through benchmarking a range of sizes
146
+ # on CPUs and a Maxwell TitanX. A speedup was seen in a large majority of
147
+ # cases when switching implementations at N=16, but it is possible that
148
+ # there will be a small number of performance regressions.
149
+ if len(sizes) > 16:
150
+ # extract the size of each input along the concat dimension
151
+ sizes = array_ops.squeeze(
152
+ array_ops.slice(
153
+ array_ops_stack.stack(sizes, axis=1), [non_neg_concat_dim, 0],
154
+ [1, -1]))
155
+ out_grads = array_ops.split(grad, sizes, non_neg_concat_dim)
156
+ else:
157
+ offset = gen_array_ops.concat_offset(non_neg_concat_dim, sizes)
158
+ for (begin, size) in zip(offset, sizes):
159
+ out_grads.append(array_ops.slice(grad, begin, size))
160
+ elif isinstance(grad, indexed_slices_lib.IndexedSlices):
161
+ # Using mod here for convenience since concat_dim is already verified
162
+ # in concat implementation to be within the allowed [-rank, rank) range.
163
+ non_neg_concat_dim = concat_dim % array_ops.rank(input_values[0])
164
+ concat_dim_static = tensor_util.constant_value(concat_dim)
165
+ if concat_dim_static is None:
166
+ raise ValueError("Can only compute IndexedSlices gradient with "
167
+ "statically-known concat_dim")
168
+ if concat_dim_static < 0:
169
+ rank = tensor_util.constant_value(array_ops.rank(input_values[0]))
170
+ if rank is None:
171
+ raise ValueError("Can only compute IndexedSlices gradient with "
172
+ "negative concat_dim when first value rank is "
173
+ "statically-known.")
174
+ concat_dim_static %= rank
175
+ # Get the inputs' tensor shapes
176
+ sizes = [array_ops.shape(x) for x in input_values]
177
+ if concat_dim_static > 0:
178
+ # IndexedSlices, non_neg_concat_dim > 0. Each input gets IndexedSlices
179
+ # gradients with all the indices, but with grad.values sliced accordingly.
180
+ # This is like the Tensor case, except shape(grad.values)[0] is not equal
181
+ # to shape(sizes[i])[0], since only a subset of the dim-0 values are
182
+ # stored.
183
+ mask, begin = _CreateDenseMaskAndBegin(sizes, non_neg_concat_dim)
184
+ for size in sizes:
185
+ new_values = array_ops.slice(
186
+ grad.values, begin,
187
+ array_ops.concat([[-1], array_ops.slice(size, [1], [-1])], 0))
188
+ out_grads.append(
189
+ indexed_slices_lib.IndexedSlices(new_values, grad.indices, size))
190
+ # Lint complains begin = begin + ...
191
+ begin = math_ops.add(begin, size * mask)
192
+ else:
193
+ # IndexedSlices, concat_dim == 0. Each input gets IndexedSlices gradients
194
+ # only for the relevant indices.
195
+ start = constant_op.constant(0, dtype=grad.indices.dtype)
196
+ for size in sizes:
197
+ size_concat_dim = array_ops.gather(size, non_neg_concat_dim)
198
+ if size_concat_dim.dtype != grad.indices.dtype:
199
+ size_concat_dim = math_ops.cast(
200
+ size_concat_dim, dtype=grad.indices.dtype)
201
+ end = start + size_concat_dim
202
+ # Compute the 1-D Tensor of indices relevant for this input.
203
+ indices_to_select = array_ops.squeeze(
204
+ array_ops.where(
205
+ math_ops.logical_and(grad.indices >= start,
206
+ grad.indices < end)),
207
+ axis=[1])
208
+ new_indices = array_ops.gather(grad.indices, indices_to_select) - start
209
+ new_values = array_ops.gather(grad.values, indices_to_select)
210
+ out_grads.append(
211
+ indexed_slices_lib.IndexedSlices(new_values, new_indices, size))
212
+ start = end
213
+ else:
214
+ raise TypeError("Expected Tensor or IndexedSlices, got %s" % type(grad))
215
+
216
+ return (out_grads + [None] if end_value_index <= dim_index else [None] +
217
+ out_grads)
218
+
219
+
220
+ @ops.RegisterGradient("Concat")
221
+ def _ConcatGrad(op: ops.Operation, grad):
222
+ return _ConcatGradHelper(
223
+ op,
224
+ grad,
225
+ start_value_index=1,
226
+ end_value_index=len(op.inputs),
227
+ dim_index=0)
228
+
229
+
230
+ @ops.RegisterGradient("ConcatV2")
231
+ def _ConcatGradV2(op: ops.Operation, grad):
232
+ return _ConcatGradHelper(
233
+ op, grad, start_value_index=0, end_value_index=-1, dim_index=-1)
234
+
235
+
236
+ ops.NotDifferentiable("ConcatOffset")
237
+
238
+
239
+ @ops.RegisterGradient("Slice")
240
+ def _SliceGrad(op: ops.Operation, grad):
241
+ """Gradient for Slice op."""
242
+ # Create an Nx2 padding where the first column represents how many
243
+ # zeros are to be prepended for each dimension, and the second
244
+ # column indicates how many zeros are appended.
245
+ #
246
+ # The number of zeros to append is the shape of the input
247
+ # elementwise-subtracted by both the begin vector and sizes vector.
248
+ #
249
+ # Some more reshaping is needed to assemble this tensor with the
250
+ # right dimensions.
251
+ input_vec = op.inputs[0]
252
+ begin_vec = op.inputs[1]
253
+ input_rank = array_ops.rank(input_vec)
254
+ index_dtype = begin_vec.dtype
255
+ slice_size = array_ops.shape(op.outputs[0], out_type=index_dtype)
256
+ if control_flow_util.GraphOrParentsInXlaContext(ops.get_default_graph()):
257
+ return gen_xla_ops.xla_dynamic_update_slice(array_ops.zeros_like(input_vec),
258
+ grad, begin_vec), None, None
259
+
260
+ shape = array_ops_stack.stack([input_rank, 1])
261
+ before_pad = array_ops.reshape(begin_vec, shape)
262
+ after_pad = array_ops.reshape(
263
+ array_ops.shape(input_vec, out_type=index_dtype) - slice_size - begin_vec,
264
+ shape)
265
+ paddings = array_ops.concat([before_pad, after_pad], 1)
266
+ return array_ops.pad(grad, paddings), None, None
267
+
268
+
269
+ @ops.RegisterGradient("StridedSlice")
270
+ def _StridedSliceGrad(op: ops.Operation, grad):
271
+ """Gradient for StridedSlice op."""
272
+ begin = op.inputs[1]
273
+ end = op.inputs[2]
274
+ strides = op.inputs[3]
275
+ # StridedSliceGrad requires `x`, `begin`, `end` and `strides` to be of the
276
+ # same dtype so we build a shape of the same type as other args.
277
+ # Note that the choice of `begin` for specifying `out_type` is arbitrary.
278
+ # We could choose any of {begin|end|strides}.dtype since they are required to
279
+ # be the same.
280
+ x = array_ops.shape(op.inputs[0], out_type=begin.dtype)
281
+
282
+ x_static = tensor_util.constant_value(x)
283
+ x = x_static if x_static is not None else x
284
+ begin_static = tensor_util.constant_value(begin)
285
+ begin = begin_static if begin_static is not None else begin
286
+ end_static = tensor_util.constant_value(end)
287
+ end = end_static if end_static is not None else end
288
+ strides_static = tensor_util.constant_value(strides)
289
+ strides = strides_static if strides_static is not None else strides
290
+
291
+ return array_ops.strided_slice_grad(
292
+ x,
293
+ begin,
294
+ end,
295
+ strides,
296
+ grad,
297
+ begin_mask=op.get_attr("begin_mask"),
298
+ end_mask=op.get_attr("end_mask"),
299
+ ellipsis_mask=op.get_attr("ellipsis_mask"),
300
+ new_axis_mask=op.get_attr("new_axis_mask"),
301
+ shrink_axis_mask=op.get_attr("shrink_axis_mask")), None, None, None
302
+
303
+
304
+ @ops.RegisterGradient("StridedSliceGrad")
305
+ def _StridedSliceGradGrad(op: ops.Operation, grad):
306
+ """Gradient for StridedSliceGrad op."""
307
+ begin = op.inputs[1]
308
+ end = op.inputs[2]
309
+ strides = op.inputs[3]
310
+
311
+ return None, None, None, None, array_ops.strided_slice(
312
+ grad,
313
+ begin,
314
+ end,
315
+ strides,
316
+ begin_mask=op.get_attr("begin_mask"),
317
+ end_mask=op.get_attr("end_mask"),
318
+ ellipsis_mask=op.get_attr("ellipsis_mask"),
319
+ new_axis_mask=op.get_attr("new_axis_mask"),
320
+ shrink_axis_mask=op.get_attr("shrink_axis_mask"))
321
+
322
+
323
+ @ops.RegisterGradient("TensorStridedSliceUpdate")
324
+ def _TensorStridedSliceUpdateGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring
325
+ begin = op.inputs[1]
326
+ end = op.inputs[2]
327
+ strides = op.inputs[3]
328
+ begin_mask = op.get_attr("begin_mask")
329
+ end_mask = op.get_attr("end_mask")
330
+ ellipsis_mask = op.get_attr("ellipsis_mask")
331
+ new_axis_mask = op.get_attr("new_axis_mask")
332
+ shrink_axis_mask = op.get_attr("shrink_axis_mask")
333
+ def Apply(f, *args):
334
+ return f(*args,
335
+ begin_mask=begin_mask,
336
+ end_mask=end_mask,
337
+ shrink_axis_mask=shrink_axis_mask,
338
+ new_axis_mask=new_axis_mask,
339
+ ellipsis_mask=ellipsis_mask)
340
+ dy = Apply(array_ops.strided_slice,
341
+ grad, begin, end, strides)
342
+ dx = Apply(array_ops.tensor_strided_slice_update,
343
+ grad, begin, end, strides, array_ops.zeros_like(dy))
344
+
345
+ # The value is potentially broadcast to the shape of the strided slice, so we
346
+ # may need to adjust dy.
347
+ slice_shape = array_ops.shape(dy, out_type=begin.dtype)
348
+ value_shape = array_ops.shape(op.inputs[4], out_type=slice_shape.dtype)
349
+
350
+ _, reduction_axes = gen_array_ops.broadcast_gradient_args(
351
+ slice_shape, value_shape)
352
+ dy_reshaped = math_ops.reduce_sum(dy, axis=reduction_axes, keepdims=True)
353
+ dy = array_ops.reshape(dy_reshaped, value_shape)
354
+
355
+ return dx, None, None, None, dy
356
+
357
+
358
+ @ops.RegisterGradient("Split")
359
+ def _SplitGrad(op: ops.Operation, *grads):
360
+ return None, array_ops.concat(list(grads), op.inputs[0])
361
+
362
+
363
+ @ops.RegisterGradient("SplitV")
364
+ def _SplitVGrad(op: ops.Operation, *grads):
365
+ returnval = array_ops.concat(list(grads), op.inputs[2])
366
+ returnval = [returnval] + [
367
+ None,
368
+ ] * (
369
+ len(op.inputs) - 1)
370
+ return returnval
371
+
372
+
373
+ ops.NotDifferentiable("Const")
374
+
375
+
376
+ @ops.RegisterGradient("Diag")
377
+ def _DiagGrad(_, grad):
378
+ return array_ops.diag_part(grad)
379
+
380
+
381
+ @ops.RegisterGradient("DiagPart")
382
+ def _DiagPartGrad(_, grad):
383
+ return array_ops.diag(grad)
384
+
385
+
386
+ @ops.RegisterGradient("MatrixDiag")
387
+ def _MatrixDiagGrad(_, grad):
388
+ return array_ops.matrix_diag_part(grad)
389
+
390
+
391
+ @ops.RegisterGradient("MatrixDiagV2")
392
+ def _MatrixDiagV2Grad(op: ops.Operation, grad):
393
+ return array_ops.matrix_diag_part(
394
+ grad, k=op.inputs[1]), None, None, None, None
395
+
396
+
397
+ @ops.RegisterGradient("MatrixDiagV3")
398
+ def _MatrixDiagV3Grad(op: ops.Operation, grad):
399
+ return array_ops.matrix_diag_part(
400
+ grad, k=op.inputs[1], align=op.get_attr("align")), None, None, None, None
401
+
402
+
403
+ @ops.RegisterGradient("MatrixDiagPart")
404
+ def _MatrixDiagPartGrad(op: ops.Operation, grad):
405
+ matrix_shape = op.inputs[0].get_shape()[-2:]
406
+ if matrix_shape.is_fully_defined() and matrix_shape[0] == matrix_shape[1]:
407
+ return array_ops.matrix_diag(grad)
408
+ else:
409
+ return array_ops.matrix_set_diag(array_ops.zeros_like(op.inputs[0]), grad)
410
+
411
+
412
+ @ops.RegisterGradient("MatrixDiagPartV2")
413
+ def _MatrixDiagPartV2Grad(op: ops.Operation, grad):
414
+ """Gradient for MatrixDiagPartV2."""
415
+ matrix_shape = op.inputs[0].get_shape()[-2:]
416
+ if matrix_shape.is_fully_defined():
417
+ return array_ops.matrix_diag(
418
+ grad,
419
+ k=op.inputs[1],
420
+ num_rows=matrix_shape[0],
421
+ num_cols=matrix_shape[1]), None, None
422
+ else:
423
+ return array_ops.matrix_set_diag(
424
+ array_ops.zeros_like(op.inputs[0]), grad, k=op.inputs[1]), None, None
425
+
426
+
427
+ @ops.RegisterGradient("MatrixDiagPartV3")
428
+ def _MatrixDiagPartV3Grad(op: ops.Operation, grad):
429
+ """Gradient for MatrixDiagPartV3."""
430
+ matrix_shape = op.inputs[0].get_shape()[-2:]
431
+ align = op.get_attr("align")
432
+ if matrix_shape.is_fully_defined():
433
+ return array_ops.matrix_diag(
434
+ grad,
435
+ k=op.inputs[1],
436
+ num_rows=matrix_shape[0],
437
+ num_cols=matrix_shape[1],
438
+ align=align), None, None
439
+ else:
440
+ return array_ops.matrix_set_diag(
441
+ array_ops.zeros_like(op.inputs[0]), grad, k=op.inputs[1],
442
+ align=align), None, None
443
+
444
+
445
+ @ops.RegisterGradient("MatrixSetDiag")
446
+ def _MatrixSetDiagGrad(op: ops.Operation, grad):
447
+ """Gradient for MatrixSetDiag."""
448
+ input_shape = op.inputs[0].get_shape().merge_with(grad.get_shape())
449
+ diag_shape = op.inputs[1].get_shape()
450
+ batch_shape = input_shape[:-2].merge_with(diag_shape[:-1])
451
+ matrix_shape = input_shape[-2:]
452
+ if batch_shape.is_fully_defined() and matrix_shape.is_fully_defined():
453
+ diag_shape = batch_shape.as_list() + [min(matrix_shape.as_list())]
454
+ else:
455
+ with ops.colocate_with(grad):
456
+ grad_shape = array_ops.shape(grad)
457
+ grad_rank = array_ops.rank(grad)
458
+ batch_shape = array_ops.slice(grad_shape, [0], [grad_rank - 2])
459
+ matrix_shape = array_ops.slice(grad_shape, [grad_rank - 2], [2])
460
+ min_dim = math_ops.reduce_min(matrix_shape)
461
+ diag_shape = array_ops.concat([batch_shape, [min_dim]], 0)
462
+ grad_input = array_ops.matrix_set_diag(
463
+ grad, array_ops.zeros(diag_shape, dtype=grad.dtype))
464
+ grad_diag = array_ops.matrix_diag_part(grad)
465
+ return (grad_input, grad_diag)
466
+
467
+
468
+ @ops.RegisterGradient("MatrixSetDiagV2")
469
+ def _MatrixSetDiagGradV2(op: ops.Operation, grad):
470
+ """Gradient for MatrixSetDiagV2."""
471
+ diag_shape = op.inputs[1].get_shape()
472
+ if not diag_shape.is_fully_defined():
473
+ # Need to know the values of `d_lower` and `d_upper` to infer diag_shape.
474
+ grad_shape = array_ops.shape(grad)
475
+ batch_shape = grad_shape[:-2]
476
+ matrix_shape = grad_shape[-2:]
477
+ diag_index = array_ops.reshape(op.inputs[2], [-1]) # Converts to vector.
478
+ d_lower = diag_index[0]
479
+ d_upper = diag_index[-1] # Works both when len(diag_index) is 1 and 2.
480
+ y_offset = cond.cond(
481
+ math_ops.less(d_upper, 0), lambda: d_upper, lambda: 0)
482
+ x_offset = cond.cond(
483
+ math_ops.greater(d_lower, 0), lambda: -d_lower, lambda: 0)
484
+
485
+ max_diag_len = math_ops.minimum(matrix_shape[0] + y_offset,
486
+ matrix_shape[1] + x_offset)
487
+ # pylint: disable=g-long-lambda
488
+ # pyformat: disable
489
+ postfix = cond.cond(
490
+ math_ops.equal(d_lower, d_upper),
491
+ lambda: ops.convert_to_tensor([max_diag_len]),
492
+ lambda: ops.convert_to_tensor([d_upper - d_lower + 1,
493
+ max_diag_len]))
494
+ # pyformat: enable
495
+ # pylint: enable=g-long-lambda
496
+ diag_shape = array_ops.concat([batch_shape, postfix], 0)
497
+
498
+ grad_input = array_ops.matrix_set_diag(
499
+ grad, array_ops.zeros(diag_shape, dtype=grad.dtype), k=op.inputs[2])
500
+ grad_diag = array_ops.matrix_diag_part(grad, k=op.inputs[2])
501
+ return (grad_input, grad_diag, None)
502
+
503
+
504
+ @ops.RegisterGradient("MatrixSetDiagV3")
505
+ def _MatrixSetDiagGradV3(op: ops.Operation, grad):
506
+ """Gradient for MatrixSetDiagV3."""
507
+ diag_shape = op.inputs[1].get_shape()
508
+ align = op.get_attr("align")
509
+ if not diag_shape.is_fully_defined():
510
+ # Need to know the values of `d_lower` and `d_upper` to infer diag_shape.
511
+ grad_shape = array_ops.shape(grad)
512
+ batch_shape = grad_shape[:-2]
513
+ matrix_shape = grad_shape[-2:]
514
+ diag_index = array_ops.reshape(op.inputs[2], [-1]) # Converts to vector.
515
+ d_lower = diag_index[0]
516
+ d_upper = diag_index[-1] # Works both when len(diag_index) is 1 and 2.
517
+ y_offset = cond.cond(
518
+ math_ops.less(d_upper, 0), lambda: d_upper, lambda: 0)
519
+ x_offset = cond.cond(
520
+ math_ops.greater(d_lower, 0), lambda: -d_lower, lambda: 0)
521
+
522
+ max_diag_len = math_ops.minimum(matrix_shape[0] + y_offset,
523
+ matrix_shape[1] + x_offset)
524
+ # pylint: disable=g-long-lambda
525
+ # pyformat: disable
526
+ postfix = cond.cond(
527
+ math_ops.equal(d_lower, d_upper),
528
+ lambda: ops.convert_to_tensor([max_diag_len]),
529
+ lambda: ops.convert_to_tensor([d_upper - d_lower + 1,
530
+ max_diag_len]))
531
+ # pyformat: enable
532
+ # pylint: enable=g-long-lambda
533
+ diag_shape = array_ops.concat([batch_shape, postfix], 0)
534
+
535
+ grad_input = array_ops.matrix_set_diag(
536
+ grad,
537
+ array_ops.zeros(diag_shape, dtype=grad.dtype),
538
+ k=op.inputs[2],
539
+ align=align)
540
+ grad_diag = array_ops.matrix_diag_part(grad, k=op.inputs[2], align=align)
541
+ return (grad_input, grad_diag, None)
542
+
543
+
544
+ @ops.RegisterGradient("MatrixBandPart")
545
+ def _MatrixBandPartGrad(op: ops.Operation, grad):
546
+ num_lower = op.inputs[1]
547
+ num_upper = op.inputs[2]
548
+ return (array_ops.matrix_band_part(grad, num_lower, num_upper), None, None)
549
+
550
+
551
+ # Edit Distance has no gradient (but can be used to eval seq2seq or CTC).
552
+ ops.NotDifferentiable("EditDistance")
553
+
554
+
555
+ @ops.RegisterGradient("Fill")
556
+ def _FillGrad(_, grad):
557
+ return None, math_ops.reduce_sum(grad)
558
+
559
+
560
+ ops.NotDifferentiable("ZerosLike")
561
+ ops.NotDifferentiable("OnesLike")
562
+
563
+
564
+ @ops.RegisterGradient("PreventGradient")
565
+ def _PreventGradientGrad(op: ops.Operation, _):
566
+ raise LookupError("Gradient explicitly disabled. Reason: %s" %
567
+ op.get_attr("message"))
568
+
569
+
570
+ def _IndexedSlicesToTensorNoWarning(indexed_slices):
571
+ """Converts an IndexedSlices to a Tensor without sparse->dense warnings."""
572
+ if not isinstance(indexed_slices, indexed_slices_lib.IndexedSlices):
573
+ # If it is not IndexedSlices, it's better be a tensor.
574
+ return indexed_slices
575
+ if indexed_slices.dense_shape is None:
576
+ raise ValueError(
577
+ "Tensor conversion requested for IndexedSlices without dense_shape: %s"
578
+ % str(indexed_slices))
579
+ return math_ops.unsorted_segment_sum(indexed_slices.values,
580
+ indexed_slices.indices,
581
+ indexed_slices.dense_shape[0])
582
+
583
+
584
+ @ops.RegisterGradient("Gather")
585
+ def _GatherGrad(op: ops.Operation, grad):
586
+ """Gradient for Gather op."""
587
+ # params can be large, so colocate the shape calculation with it.
588
+ params = op.inputs[0]
589
+ with ops.colocate_with(params):
590
+ params_shape = array_ops.shape(params)
591
+
592
+ # Build appropriately shaped IndexedSlices
593
+ indices = op.inputs[1]
594
+ size = array_ops.expand_dims(array_ops.size(indices), 0)
595
+ values_shape = array_ops.concat([size, params_shape[1:]], 0)
596
+ values = array_ops.reshape(
597
+ _IndexedSlicesToTensorNoWarning(grad), values_shape)
598
+ indices = array_ops.reshape(indices, size)
599
+ return [indexed_slices_lib.IndexedSlices(values, indices, params_shape), None]
600
+
601
+
602
+ def _GetBatchIndices(params_shape, indices, batch_dims):
603
+ """Addds the batch offsets to the given indices and returns the results."""
604
+ batch_indices = indices
605
+ indices_dtype = indices.dtype.base_dtype
606
+ casted_params_shape = math_ops.cast(params_shape, indices_dtype)
607
+ accum_dim_value = array_ops.ones((), dtype=indices_dtype)
608
+ for dim in range(batch_dims, 0, -1):
609
+ dim_value = casted_params_shape[dim - 1]
610
+ accum_dim_value *= casted_params_shape[dim]
611
+ start = array_ops.zeros((), dtype=indices_dtype)
612
+ step = array_ops.ones((), dtype=indices_dtype)
613
+ dim_indices = math_ops.range(start, dim_value, step)
614
+ dim_indices *= accum_dim_value
615
+ dim_shape = array_ops.concat([
616
+ array_ops.tile([1], [dim - 1]), [dim_value],
617
+ array_ops.tile([1], [array_ops.rank(indices) - dim])
618
+ ], axis=0)
619
+ batch_indices += array_ops.reshape(dim_indices, dim_shape)
620
+
621
+ return batch_indices
622
+
623
+
624
+ def _BatchGatherGrad(params_shape, values, indices, batch_dims,
625
+ gather_dim_size):
626
+ """Returns the gradient of GatherV2 with batch dimensions."""
627
+
628
+ # Axis is the first non-batch dimension.
629
+ indices_size = array_ops.expand_dims(array_ops.size(indices), 0)
630
+ if batch_dims:
631
+ values_shape = array_ops.shape(values)
632
+ # Add the batch offsets to indices and flatten the batch dimensions.
633
+ outer_shape = values_shape[:batch_dims]
634
+ inner_shape = values_shape[batch_dims:][1:]
635
+ batch_size = gen_math_ops.prod(outer_shape, [0], False)
636
+ flat_values_shape = array_ops.concat([[-1], inner_shape], 0)
637
+ gather_dim_size *= batch_size
638
+
639
+ indices = _GetBatchIndices(params_shape, indices, batch_dims)
640
+ values = array_ops.reshape(
641
+ _IndexedSlicesToTensorNoWarning(values), flat_values_shape)
642
+
643
+ indices = array_ops.reshape(indices, indices_size)
644
+ params_grad = math_ops.unsorted_segment_sum(values, indices, gather_dim_size)
645
+
646
+ if batch_dims:
647
+ # Put back the batch dimensions.
648
+ params_grad = array_ops.reshape(
649
+ params_grad, array_ops.concat([outer_shape, flat_values_shape], 0))
650
+
651
+ return params_grad
652
+
653
+
654
+ @ops.RegisterGradient("GatherV2")
655
+ def _GatherV2Grad(op: ops.Operation, grad):
656
+ """Gradient for GatherV2 op."""
657
+ # params can be large, so colocate the shape calculation with it.
658
+ #
659
+ # params can be very large for sparse model, array_ops.shape raises
660
+ # exception on the Windows platform when any dimension is larger than
661
+ # int32. params_shape is not used in optimizer apply_sparse gradients,
662
+ # so it's fine to convert it back to int32 regardless of truncation.
663
+ params = op.inputs[0]
664
+ with ops.colocate_with(params):
665
+ params_shape = array_ops.shape(params, out_type=ops.dtypes.int64)
666
+ params_shape = math_ops.cast(params_shape, dtypes.int32)
667
+
668
+ indices = op.inputs[1]
669
+ indices_size = array_ops.expand_dims(array_ops.size(indices), 0)
670
+ axis = op.inputs[2]
671
+ axis_static = tensor_util.constant_value(axis)
672
+ batch_dims = int(op.get_attr("batch_dims"))
673
+
674
+ if batch_dims < 0:
675
+ if indices.shape.ndims is None:
676
+ raise ValueError(
677
+ f"Currently, it is unsupported to take the gradient of tf.gather "
678
+ f"when batch_dims < 0 and the rank of the indices is unknown. Please "
679
+ f"pass a positive batch_dims or use tf.ensure_shape to update the "
680
+ f"shape of indices when calling tf.gather. Got "
681
+ f"batch_dims={batch_dims} and indices={indices}")
682
+ batch_dims += indices.shape.ndims
683
+
684
+ # For axis 0 gathers, build an appropriately shaped IndexedSlices.
685
+ if axis_static == 0:
686
+ if context.executing_eagerly():
687
+ with ops.device(indices_size.device):
688
+ params_tail_shape = array_ops.identity(params_shape)[1:]
689
+ else:
690
+ params_tail_shape = params_shape[1:]
691
+ values_shape = array_ops.concat([indices_size, params_tail_shape], 0)
692
+ values = array_ops.reshape(
693
+ _IndexedSlicesToTensorNoWarning(grad), values_shape)
694
+ indices = array_ops.reshape(indices, indices_size)
695
+ params_grad = indexed_slices_lib.IndexedSlices(values, indices,
696
+ params_shape)
697
+ else:
698
+ # Handle axis by transposing the axis dimension to be the first non-batch
699
+ # dimension, compute the gradient and transpose the result back.
700
+ outer_shape = params_shape[:axis]
701
+ inner_shape = params_shape[axis:][1:]
702
+ values_shape = array_ops.concat([outer_shape, [-1], inner_shape], 0)
703
+
704
+ values_dims = array_ops.size(values_shape)
705
+ axis_dims = array_ops.size(outer_shape)
706
+
707
+ outer_batches_indices = math_ops.range(batch_dims)
708
+ batch_axis_indices = math_ops.range(batch_dims, axis_dims)
709
+ inner_axes_indices = math_ops.range(axis_dims + 1, values_dims)
710
+
711
+ values = array_ops.reshape(
712
+ _IndexedSlicesToTensorNoWarning(grad), values_shape)
713
+
714
+ # Move values[axis] up to values[batch_dims]
715
+ transpose_dims = array_ops.concat([
716
+ outer_batches_indices, [axis_dims], batch_axis_indices,
717
+ inner_axes_indices
718
+ ], 0)
719
+ values_transpose = array_ops.transpose(values, transpose_dims)
720
+ params_shape_transpose = array_ops.gather(params_shape, transpose_dims)
721
+
722
+ params_grad = _BatchGatherGrad(params_shape_transpose, values_transpose,
723
+ indices, batch_dims, params_shape[axis])
724
+
725
+ # Inverts the above transpose by moving dimension batch_dims back to its
726
+ # original position.
727
+ invert_transpose_dims = array_ops.concat([
728
+ outer_batches_indices, batch_axis_indices + 1, [batch_dims],
729
+ inner_axes_indices
730
+ ], 0)
731
+ params_grad = array_ops.transpose(params_grad, invert_transpose_dims)
732
+
733
+ if not isinstance(params_grad, indexed_slices_lib.IndexedSlices):
734
+ # Prevents mismatches in shapes when some tensor dimensions are zero.
735
+ params_grad = array_ops.reshape(
736
+ params_grad,
737
+ array_ops.shape(params)
738
+ )
739
+
740
+ return [params_grad, None, None]
741
+
742
+
743
+ @ops.RegisterGradient("GatherNd")
744
+ def _GatherNdGrad(op: ops.Operation, grad):
745
+ ref = op.inputs[0]
746
+ indices = op.inputs[1]
747
+ ref_shape = array_ops.shape(ref, out_type=indices.dtype)
748
+ if indices.shape.ndims == 2 and indices.shape.dims[-1].value == 1:
749
+ ref_grad = indexed_slices_lib.IndexedSlices(
750
+ grad, array_ops.squeeze(indices, axis=-1), ref_shape)
751
+ else:
752
+ ref_grad = array_ops.scatter_nd(indices, grad, ref_shape)
753
+ return [ref_grad, None]
754
+
755
+
756
+ @ops.RegisterGradient("ResourceGatherNd")
757
+ def _ResourceGatherNdGrad(op: ops.Operation, grad): # pylint: disable=missing-docstring
758
+ ref = op.inputs[0]
759
+ indices = op.inputs[1]
760
+ ref_shape = gen_resource_variable_ops.variable_shape(ref, indices.dtype)
761
+ if indices.shape.ndims == 2 and indices.shape.dims[-1].value == 1:
762
+ ref_grad = indexed_slices_lib.IndexedSlices(
763
+ grad, array_ops.squeeze(indices, axis=-1), ref_shape)
764
+ else:
765
+ ref_grad = array_ops.scatter_nd(indices, grad, ref_shape)
766
+ return [ref_grad, None]
767
+
768
+
769
+ @ops.RegisterGradient("CheckNumerics")
770
+ def _CheckNumericsGrad(op: ops.Operation, grad):
771
+ """Gradient for check_numerics op."""
772
+ return array_ops.check_numerics(
773
+ grad,
774
+ "Not a number (NaN) or infinity (Inf) values detected in gradient. %s" %
775
+ op.get_attr("message"))
776
+
777
+
778
+ @ops.RegisterGradient("CheckNumericsV2")
779
+ def _CheckNumericsV2Grad(op: ops.Operation, grad):
780
+ """Gradient for check_numerics op."""
781
+ return array_ops.check_numerics_v2(
782
+ grad,
783
+ "Not a number (NaN) or infinity (Inf) values detected in gradient. %s" %
784
+ op.get_attr("message"))
785
+
786
+
787
+ @ops.RegisterGradient("PlaceholderWithDefault")
788
+ @ops.RegisterGradient("Identity")
789
+ def _IdGrad(_, grad):
790
+ return grad
791
+
792
+
793
+ @ops.RegisterGradient("_EagerConst")
794
+ def _EagerConstGrad(_, grad):
795
+ raise AssertionError(
796
+ "This op should never interact with gradient APIs. Please file a bug.")
797
+
798
+
799
+ @ops.RegisterGradient("RefIdentity")
800
+ def _RefIdGrad(_, grad):
801
+ return grad
802
+
803
+
804
+ @ops.RegisterGradient("IdentityN")
805
+ def _IdNGrad(_, *grad):
806
+ return grad
807
+
808
+
809
+ ops.NotDifferentiable("StopGradient")
810
+
811
+
812
+ @ops.RegisterGradient("Reshape")
813
+ def _ReshapeGrad(op: ops.Operation, grad):
814
+ return [
815
+ array_ops.reshape(
816
+ _IndexedSlicesToTensorNoWarning(grad), array_ops.shape(op.inputs[0])),
817
+ None
818
+ ]
819
+
820
+
821
+ ops.NotDifferentiable("InvertPermutation")
822
+
823
+
824
+ def _ReshapeToInput(op: ops.Operation, grad):
825
+ """Reshapes the gradient to the shape of the original input."""
826
+ return array_ops.reshape(
827
+ _IndexedSlicesToTensorNoWarning(grad), array_ops.shape(op.inputs[0]))
828
+
829
+
830
+ @ops.RegisterGradient("ExpandDims")
831
+ def _ExpandDimsGrad(op: ops.Operation, grad):
832
+ return [_ReshapeToInput(op, grad), None]
833
+
834
+
835
+ @ops.RegisterGradient("Squeeze")
836
+ def _SqueezeGrad(op: ops.Operation, grad):
837
+ return _ReshapeToInput(op, grad)
838
+
839
+
840
+ @ops.RegisterGradient("Transpose")
841
+ def _TransposeGrad(op: ops.Operation, grad):
842
+ """Returns unshuffle(grad)."""
843
+ p = op.inputs[1]
844
+ return [array_ops.transpose(grad, array_ops.invert_permutation(p)), None]
845
+
846
+
847
+ @ops.RegisterGradient("ConjugateTranspose")
848
+ def _ConjugateTransposeGrad(op: ops.Operation, grad):
849
+ """Returns conj(unshuffle(grad))."""
850
+ p = op.inputs[1]
851
+ return [
852
+ array_ops.transpose(
853
+ grad, array_ops.invert_permutation(p), conjugate=True), None
854
+ ]
855
+
856
+
857
+ ops.NotDifferentiable("Shape")
858
+
859
+ ops.NotDifferentiable("ShapeN")
860
+
861
+ ops.NotDifferentiable("Rank")
862
+
863
+ ops.NotDifferentiable("Size")
864
+
865
+
866
+ @ops.RegisterGradient("Tile")
867
+ def _TileGrad(op: ops.Operation, grad):
868
+ """Sum reduces grad along the tiled dimensions."""
869
+ input_shape = array_ops.shape(op.inputs[0], out_type=op.inputs[1].dtype)
870
+ # We interleave multiples and input_shape to get split_shape,
871
+ # reshape grad to split_shape, and reduce along all even
872
+ # dimensions (the tiled dimensions) to get the result
873
+ # with shape input_shape. For example
874
+ # input_shape = [20, 30, 40]
875
+ # multiples = [2, 3, 4]
876
+ # split_shape = [2, 20, 3, 30, 4, 40]
877
+ # axes = [0, 2, 4]
878
+ split_shape = array_ops.reshape(
879
+ array_ops.transpose(array_ops_stack.stack([op.inputs[1], input_shape])),
880
+ [-1])
881
+ axes = math_ops.range(0, array_ops.size(split_shape), 2)
882
+ # Sum reduces grad along the first dimension for IndexedSlices
883
+ if isinstance(grad, indexed_slices_lib.IndexedSlices):
884
+ input_shape_0 = math_ops.cast(input_shape[0], grad.indices.dtype)
885
+ grad = math_ops.unsorted_segment_sum(
886
+ grad.values, math_ops.mod(grad.indices, input_shape_0), input_shape_0)
887
+ split_shape = array_ops.concat([[1], split_shape[1:]], axis=0)
888
+ input_grad = math_ops.reduce_sum(array_ops.reshape(grad, split_shape), axes)
889
+ # Fix shape inference
890
+ if not context.executing_eagerly():
891
+ input_grad.set_shape(op.inputs[0].get_shape())
892
+ return [input_grad, None]
893
+
894
+
895
+ ops.NotDifferentiable("BroadcastGradientArgs")
896
+
897
+
898
+ def _PadGrad(op: ops.Operation, grad):
899
+ """Gradient for Pad."""
900
+ # Pad introduces values around the original tensor, so the gradient function
901
+ # slices the original shape out of the gradient."""
902
+ x = op.inputs[0]
903
+ a = op.inputs[1] # [Rank(x), 2]
904
+ # Takes a slice of a. The 1st column. [Rank(x), 1].
905
+ pad_before = array_ops.slice(a, [0, 0],
906
+ array_ops_stack.stack([array_ops.rank(x), 1]))
907
+ # Make it a 1-D tensor.
908
+ begin = array_ops.reshape(pad_before, [-1])
909
+ sizes = array_ops.shape(x, out_type=begin.dtype)
910
+ x_grad = array_ops.slice(grad, begin, sizes)
911
+ if len(op.inputs) == 3:
912
+ return x_grad, None, None
913
+ else:
914
+ return x_grad, None
915
+
916
+
917
+ ops.RegisterGradient("Pad")(_PadGrad)
918
+ ops.RegisterGradient("PadV2")(_PadGrad)
919
+
920
+
921
+ # ReverseSequence is just a permutation. The gradient permutes back.
922
+ @ops.RegisterGradient("ReverseSequence")
923
+ def _ReverseSequenceGrad(op: ops.Operation, grad):
924
+ seq_lengths = op.inputs[1]
925
+ return [
926
+ array_ops.reverse_sequence(
927
+ grad,
928
+ batch_axis=op.get_attr("batch_dim"),
929
+ seq_axis=op.get_attr("seq_dim"),
930
+ seq_lengths=seq_lengths), None
931
+ ]
932
+
933
+
934
+ @ops.RegisterGradient("Reverse")
935
+ def _ReverseGrad(op: ops.Operation, grad):
936
+ reverse_dims = op.inputs[1]
937
+ return gen_array_ops.reverse(grad, reverse_dims), None
938
+
939
+
940
+ @ops.RegisterGradient("ReverseV2")
941
+ def _ReverseV2Grad(op: ops.Operation, grad):
942
+ axis = op.inputs[1]
943
+ return array_ops.reverse_v2(grad, axis), None
944
+
945
+
946
+ @ops.RegisterGradient("SpaceToBatch")
947
+ def _SpaceToBatchGrad(op: ops.Operation, grad):
948
+ # Its gradient is the opposite op: BatchToSpace.
949
+ block_size = op.get_attr("block_size")
950
+ return [
951
+ array_ops.batch_to_space(grad, op.inputs[1], block_size=block_size), None
952
+ ]
953
+
954
+
955
+ @ops.RegisterGradient("SpaceToBatchND")
956
+ def _SpaceToBatchNDGrad(op: ops.Operation, grad):
957
+ # Its gradient is the opposite op: BatchToSpaceND.
958
+ return [
959
+ array_ops.batch_to_space_nd(grad, op.inputs[1], op.inputs[2]), None, None
960
+ ]
961
+
962
+
963
+ @ops.RegisterGradient("BatchToSpace")
964
+ def _BatchToSpaceGrad(op: ops.Operation, grad):
965
+ # Its gradient is the opposite op: SpaceToBatch.
966
+ block_size = op.get_attr("block_size")
967
+ return [
968
+ array_ops.space_to_batch(grad, op.inputs[1], block_size=block_size), None
969
+ ]
970
+
971
+
972
+ @ops.RegisterGradient("BatchToSpaceND")
973
+ def _BatchToSpaceNDGrad(op: ops.Operation, grad):
974
+ # Its gradient is the opposite op: SpaceToBatchND.
975
+ return [
976
+ array_ops.space_to_batch_nd(grad, op.inputs[1], op.inputs[2]), None, None
977
+ ]
978
+
979
+
980
+ @ops.RegisterGradient("SpaceToDepth")
981
+ def _SpaceToDepthGrad(op: ops.Operation, grad):
982
+ # Its gradient is the opposite op: DepthToSpace.
983
+ block_size = op.get_attr("block_size")
984
+ data_format = op.get_attr("data_format")
985
+ if data_format == "NCHW_VECT_C":
986
+ raise ValueError("Cannot compute SpaceToDepth gradient with NCHW_VECT_C. "
987
+ "NCHW_VECT_C requires qint8 data type.")
988
+ return array_ops.depth_to_space(grad, block_size, data_format=data_format)
989
+
990
+
991
+ @ops.RegisterGradient("DepthToSpace")
992
+ def _DepthToSpaceGrad(op: ops.Operation, grad):
993
+ # Its gradient is the opposite op: SpaceToDepth.
994
+ block_size = op.get_attr("block_size")
995
+ data_format = op.get_attr("data_format")
996
+ if data_format == "NCHW_VECT_C":
997
+ raise ValueError("Cannot compute DepthToSpace gradient with NCHW_VECT_C. "
998
+ "NCHW_VECT_C requires qint8 data type.")
999
+ return array_ops.space_to_depth(grad, block_size, data_format=data_format)
1000
+
1001
+
1002
+ ops.NotDifferentiable("OneHot")
1003
+
1004
+
1005
+ @ops.RegisterGradient("MirrorPad")
1006
+ def _MirrorPadGrad(op: ops.Operation, grad):
1007
+ mode = op.get_attr("mode")
1008
+ return [gen_array_ops.mirror_pad_grad(grad, op.inputs[1], mode=mode), None]
1009
+
1010
+
1011
+ @ops.RegisterGradient("MirrorPadGrad")
1012
+ def _MirrorPadGradGrad(op: ops.Operation, grad):
1013
+ mode = op.get_attr("mode")
1014
+ return [gen_array_ops.mirror_pad(grad, op.inputs[1], mode=mode), None]
1015
+
1016
+
1017
+ @ops.RegisterGradient("QuantizeAndDequantize")
1018
+ def _QuantizeAndDequantizeGrad(_, grad):
1019
+ return grad
1020
+
1021
+
1022
+ @ops.RegisterGradient("QuantizeAndDequantizeV2")
1023
+ def _QuantizeAndDequantizeV2Grad(_, grad):
1024
+ return [grad, None, None]
1025
+
1026
+
1027
+ @ops.RegisterGradient("QuantizeAndDequantizeV3")
1028
+ def _QuantizeAndDequantizeV3Grad(_, grad):
1029
+ # Only propagate the gradient for the unquantized input.
1030
+ return [grad, None, None, None]
1031
+
1032
+
1033
+ @ops.RegisterGradient("ExtractImagePatches")
1034
+ def _ExtractImagePatchesGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring
1035
+ input_bhwc = array_ops.shape(op.inputs[0], out_type=dtypes.int64)
1036
+ batch_size, rows_in, cols_in, channels = array_ops_stack.unstack(input_bhwc)
1037
+
1038
+ output_bhwc = array_ops.shape(op.outputs[0], out_type=dtypes.int64)
1039
+ rows_out, cols_out = array_ops_stack.unstack(output_bhwc[1:3])
1040
+
1041
+ _, ksize_r, ksize_c, _ = op.get_attr("ksizes")
1042
+
1043
+ # Create indices matrix for input tensor.
1044
+ # Note that 0 is preserved for padding location,
1045
+ # so indices for input start from 1 to 1 + rows_in * cols_in.
1046
+ input_indices_num = rows_in * cols_in
1047
+ # XLA version of extract_image_patches does not support int64,
1048
+ # using float32 instead.
1049
+ input_idx = array_ops.reshape(
1050
+ math_ops.range(1, input_indices_num + 1, dtype=ops.dtypes.float32),
1051
+ (1, rows_in, cols_in, 1),
1052
+ )
1053
+ input_idx_patched = gen_array_ops.extract_image_patches(
1054
+ input_idx, op.get_attr("ksizes"), op.get_attr("strides"),
1055
+ op.get_attr("rates"), op.get_attr("padding"))
1056
+ input_idx_patched = math_ops.cast(input_idx_patched, dtypes.int64)
1057
+
1058
+ grad_expanded = array_ops.transpose(
1059
+ array_ops.reshape(
1060
+ _IndexedSlicesToTensorNoWarning(grad),
1061
+ (batch_size, rows_out, cols_out, ksize_r, ksize_c, channels)),
1062
+ (1, 2, 3, 4, 0, 5))
1063
+ grad_flat = array_ops.reshape(grad_expanded, (-1, batch_size * channels))
1064
+
1065
+ # Shift all input indices back. Padding locations will have "-1" value
1066
+ # which is fortunately ignored by segmented sum.
1067
+ segment_ids = array_ops.reshape(input_idx_patched, [-1]) - 1
1068
+ grad_out = math_ops.unsorted_segment_sum(
1069
+ grad_flat, segment_ids, num_segments=input_indices_num
1070
+ )
1071
+
1072
+ grad_out = array_ops.reshape(
1073
+ grad_out, (rows_in, cols_in, batch_size, channels)
1074
+ )
1075
+ grad_out = array_ops.transpose(grad_out, (2, 0, 1, 3))
1076
+
1077
+ return [grad_out]
1078
+
1079
+
1080
+ @ops.RegisterGradient("ExtractVolumePatches")
1081
+ def _ExtractVolumePatchesGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring
1082
+ batch_size, planes_in, rows_in, cols_in, channels = [
1083
+ dim.value for dim in op.inputs[0].shape.dims
1084
+ ]
1085
+ input_bphwc = array_ops.shape(op.inputs[0])
1086
+ batch_size = input_bphwc[0]
1087
+ channels = input_bphwc[4]
1088
+
1089
+ # Create indices matrix for input tensor.
1090
+ # Note that 0 is preserved for padding location,
1091
+ # so indices for input start from 1 to 1 + rows_in * cols_in.
1092
+ input_indices_num = 1 + planes_in * rows_in * cols_in
1093
+ input_idx = array_ops.reshape(
1094
+ math_ops.range(1, input_indices_num, dtype=ops.dtypes.int64),
1095
+ (1, planes_in, rows_in, cols_in, 1))
1096
+ input_idx_patched = gen_array_ops.extract_volume_patches(
1097
+ input_idx, op.get_attr("ksizes"), op.get_attr("strides"),
1098
+ op.get_attr("padding"))
1099
+
1100
+ # Create indices matrix for output tensor.
1101
+ _, planes_out, rows_out, cols_out, _ = [
1102
+ dim.value for dim in op.outputs[0].shape.dims
1103
+ ]
1104
+ _, ksize_p, ksize_r, ksize_c, _ = op.get_attr("ksizes")
1105
+ # Indices for output start from 0.
1106
+ prc_indices_num = planes_out * rows_out * cols_out
1107
+ output_indices_num = prc_indices_num * ksize_p * ksize_r * ksize_c
1108
+ output_idx = array_ops.reshape(
1109
+ math_ops.range(output_indices_num, dtype=ops.dtypes.int64),
1110
+ (1, planes_out, rows_out, cols_out, ksize_p * ksize_r * ksize_c))
1111
+
1112
+ # Construct mapping table for indices: (input -> output).
1113
+ idx_matrix = array_ops.concat([
1114
+ array_ops.expand_dims(input_idx_patched, axis=-1),
1115
+ array_ops.expand_dims(output_idx, axis=-1)
1116
+ ],
1117
+ axis=-1)
1118
+ idx_map = array_ops.reshape(idx_matrix, (-1, 2))
1119
+
1120
+ sp_shape = (input_indices_num, output_indices_num)
1121
+ sp_mat_full = sparse_tensor.SparseTensor(
1122
+ idx_map, array_ops.ones([output_indices_num], dtype=grad.dtype), sp_shape)
1123
+ # Remove all padding locations [0, :].
1124
+ sp_mat = sparse_ops.sparse_slice(sp_mat_full, (1, 0),
1125
+ (input_indices_num - 1, output_indices_num))
1126
+
1127
+ grad_expanded = array_ops.transpose(
1128
+ array_ops.reshape(
1129
+ _IndexedSlicesToTensorNoWarning(grad),
1130
+ (batch_size, planes_out, rows_out, cols_out, ksize_p, ksize_r,
1131
+ ksize_c, channels)), (1, 2, 3, 4, 5, 6, 0, 7))
1132
+ grad_flat = array_ops.reshape(grad_expanded, (-1, batch_size * channels))
1133
+
1134
+ jac = sparse_ops.sparse_tensor_dense_matmul(sp_mat, grad_flat)
1135
+
1136
+ grad_out = array_ops.reshape(
1137
+ jac, (planes_in, rows_in, cols_in, batch_size, channels))
1138
+ grad_out = array_ops.transpose(grad_out, (3, 0, 1, 2, 4))
1139
+
1140
+ return [grad_out]
1141
+
1142
+
1143
+ @ops.RegisterGradient("ScatterNd")
1144
+ def _ScatterNdGrad(op: ops.Operation, grad):
1145
+ indices = op.inputs[0]
1146
+ updates_grad = array_ops.gather_nd(grad, indices)
1147
+ return [None, updates_grad, None]
1148
+
1149
+
1150
+ @ops.RegisterGradient("TensorScatterUpdate")
1151
+ def _TensorScatterUpdateGrad(op: ops.Operation, grad):
1152
+ indices = op.inputs[1]
1153
+ updates_grad = array_ops.gather_nd(grad, indices)
1154
+ tensor_grad = array_ops.tensor_scatter_update(
1155
+ array_ops.identity(grad), indices,
1156
+ array_ops.zeros_like(op.inputs[2], dtype=grad.dtype))
1157
+ return [tensor_grad, None, updates_grad]
1158
+
1159
+
1160
+ @ops.RegisterGradient("TensorScatterAdd")
1161
+ def _TensorScatterAddGrad(op: ops.Operation, grad):
1162
+ indices = op.inputs[1]
1163
+ updates_grad = array_ops.gather_nd(grad, indices)
1164
+ tensor_grad = array_ops.identity(grad)
1165
+ return [tensor_grad, None, updates_grad]
1166
+
1167
+
1168
+ def _TensorScatterMinOrMaxGrad(op: ops.Operation, grad):
1169
+ """Gradient for TensorScatterMin and TensorScatterMax."""
1170
+ indices = op.inputs[1]
1171
+ x = op.inputs[0]
1172
+ y = op.inputs[2]
1173
+ output = op.outputs[0]
1174
+ x_indicators = math_ops.cast(math_ops.equal(x, output), grad.dtype)
1175
+ y_output = array_ops.gather_nd(output, indices)
1176
+ y_indicators = math_ops.cast(math_ops.equal(y, y_output), grad.dtype)
1177
+ ys_indicators = array_ops.scatter_nd(
1178
+ indices, y_indicators, array_ops.shape(x, out_type=indices.dtype))
1179
+ indicators = x_indicators + ys_indicators # All elements are >= 1.
1180
+ # If there are multiple minimum or maximum elements then the gradient will be
1181
+ # divided between them.
1182
+ x_grad = grad * x_indicators / indicators
1183
+ y_grad = array_ops.gather_nd(grad / indicators, indices) * y_indicators
1184
+ return [x_grad, None, y_grad]
1185
+
1186
+
1187
+ @ops.RegisterGradient("TensorScatterMax")
1188
+ def _TensorScatterMaxGrad(op: ops.Operation, grad):
1189
+ """Gradient for TensorScatterMax op."""
1190
+ return _TensorScatterMinOrMaxGrad(op, grad)
1191
+
1192
+
1193
+ @ops.RegisterGradient("TensorScatterMin")
1194
+ def _TensorScatterMinGrad(op: ops.Operation, grad):
1195
+ """Gradient for TensorScatterMin op."""
1196
+ return _TensorScatterMinOrMaxGrad(op, grad)
1197
+
1198
+
1199
+ @ops.RegisterGradient("TensorScatterSub")
1200
+ def _TensorScatterSubGrad(op: ops.Operation, grad):
1201
+ indices = op.inputs[1]
1202
+ updates_grad = array_ops.gather_nd(grad, indices)
1203
+ tensor_grad = array_ops.identity(grad)
1204
+ return [tensor_grad, None, -updates_grad]
1205
+
1206
+
1207
+ @ops.RegisterGradient("ScatterNdNonAliasingAdd")
1208
+ def _ScatterNdNonAliasingAddGrad(op: ops.Operation, grad):
1209
+ indices = op.inputs[1]
1210
+ updates_grad = array_ops.gather_nd(grad, indices)
1211
+ return [grad, None, updates_grad]
1212
+
1213
+
1214
+ @ops.RegisterGradient("BroadcastTo")
1215
+ def _BroadcastToGrad(op: ops.Operation, grad): # pylint:disable=missing-function-docstring
1216
+ input_value = op.inputs[0]
1217
+ broadcast_shape = op.inputs[1]
1218
+ shape_dtype = dtypes.int32
1219
+ if isinstance(broadcast_shape, tensor.Tensor):
1220
+ shape_dtype = broadcast_shape.dtype
1221
+
1222
+ input_value_shape = array_ops.shape(input_value, out_type=shape_dtype)
1223
+ if not isinstance(broadcast_shape, ops.EagerTensor):
1224
+ broadcast_shape_static = tensor_shape.TensorShape(
1225
+ tensor_util.try_evaluate_constant(broadcast_shape))
1226
+ if broadcast_shape_static.is_fully_defined():
1227
+ broadcast_shape = constant_op.constant(
1228
+ broadcast_shape_static.as_list(), dtype=shape_dtype)
1229
+ _, reduction_axes = gen_array_ops.broadcast_gradient_args(
1230
+ broadcast_shape, input_value_shape)
1231
+ updates_grad_reshaped = math_ops.reduce_sum(
1232
+ grad, axis=reduction_axes, keepdims=True)
1233
+ updates_grad = array_ops.reshape(updates_grad_reshaped, input_value_shape)
1234
+ return [updates_grad, None]