MCPcopy Create free account
hub / github.com/DeepRec-AI/DeepRec / _TopKGrad

Function _TopKGrad

tensorflow/python/ops/nn_grad.py:1102–1143  ·  view source on GitHub ↗

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, _)

Source from the content-addressed store, hash-verified

1100@ops.RegisterGradient("TopK")
1101@ops.RegisterGradient("TopKV2")
1102def _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")

Callers

nothing calls this directly

Calls 9

reshapeMethod · 0.80
shapeMethod · 0.45
gatherMethod · 0.45
castMethod · 0.45
sizeMethod · 0.45
stackMethod · 0.45
expand_dimsMethod · 0.45
rangeMethod · 0.45
scatter_ndMethod · 0.45

Tested by

no test coverage detected