Return the gradients for TopK. Args: op: The TopKOp for which we need to generate gradients. grad: Tensor. The gradients passed to the TopKOp. Returns: A list of two tensors, the first being the gradient w.r.t to the input and TopK, and the second being the gradient w.r.t. to t
(op, grad, _)
| 1100 | @ops.RegisterGradient("TopK") |
| 1101 | @ops.RegisterGradient("TopKV2") |
| 1102 | def _TopKGrad(op, grad, _): |
| 1103 | """Return the gradients for TopK. |
| 1104 | |
| 1105 | Args: |
| 1106 | op: The TopKOp for which we need to generate gradients. |
| 1107 | grad: Tensor. The gradients passed to the TopKOp. |
| 1108 | |
| 1109 | Returns: |
| 1110 | A list of two tensors, the first being the gradient w.r.t to the input and |
| 1111 | TopK, and the second being the gradient w.r.t. to the indices (all zero). |
| 1112 | """ |
| 1113 | in_shape = array_ops.shape(op.inputs[0]) |
| 1114 | ind_shape = array_ops.shape(op.outputs[1]) |
| 1115 | |
| 1116 | # int32 is not supported on GPU hence up-casting |
| 1117 | ind_lastdim = array_ops.gather( |
| 1118 | math_ops.cast(ind_shape, dtypes.int64), |
| 1119 | array_ops.size(ind_shape) - 1) |
| 1120 | # Flatten indices to 2D. |
| 1121 | ind_2d = array_ops.reshape(op.outputs[1], array_ops.stack([-1, ind_lastdim])) |
| 1122 | |
| 1123 | in_lastdim = array_ops.gather( |
| 1124 | math_ops.cast(in_shape, dtypes.int64), |
| 1125 | array_ops.size(in_shape) - 1) |
| 1126 | outerdim = array_ops.shape(ind_2d)[0] |
| 1127 | # Compute linear indices (flattened to 1D). |
| 1128 | ind = array_ops.reshape( |
| 1129 | ind_2d + math_ops.cast( |
| 1130 | array_ops.expand_dims( |
| 1131 | math_ops.range(0, |
| 1132 | math_ops.cast(outerdim, dtypes.int64) * in_lastdim, |
| 1133 | in_lastdim), -1), dtypes.int32), [-1]) |
| 1134 | |
| 1135 | # Substitute grad to appropriate locations and fill the rest with zeros, |
| 1136 | # finally reshaping it to the original input shape. |
| 1137 | return [ |
| 1138 | array_ops.reshape( |
| 1139 | array_ops.scatter_nd( |
| 1140 | array_ops.expand_dims(ind, -1), array_ops.reshape(grad, [-1]), |
| 1141 | [math_ops.reduce_prod(in_shape)]), in_shape), |
| 1142 | array_ops.zeros([], dtype=dtypes.int32) |
| 1143 | ] |
| 1144 | |
| 1145 | |
| 1146 | @ops.RegisterGradient("NthElement") |
nothing calls this directly
no test coverage detected