You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Conv2dBroadcast.py 1.5 kB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. from __future__ import absolute_import
  2. import numpy as np
  3. from .Node import Op
  4. from .Conv2dReduceSum import conv2d_reducesum_op
  5. from .ZerosLike import zeroslike_op
  6. from ..gpu_links import broadcast_to
  7. class Conv2d_BroadcastToOp(Op):
  8. def __init__(self, node_A, node_B, ctx=None):
  9. super().__init__(Conv2d_BroadcastToOp, [node_A, node_B], ctx)
  10. def compute(self, input_vals, output_val, stream_handle=None):
  11. if self.on_cpu:
  12. shapeW = input_vals[1].shape
  13. shapeW = list(shapeW)
  14. tmp = shapeW[1]
  15. shapeW[1] = shapeW[3]
  16. shapeW[3] = tmp
  17. output_val[:] = np.broadcast_to(
  18. input_vals[0].asnumpy(), input_vals[1].asnumpy().shape).swapaxes(1, 3)
  19. else:
  20. broadcast_to(input_vals[0], output_val, stream_handle)
  21. def gradient(self, output_grad):
  22. grad_A = conv2d_reducesum_op(output_grad, ctx=self.raw_ctx)
  23. return [grad_A, None]
  24. def infer_shape(self, input_shapes):
  25. assert len(input_shapes) == 2
  26. return input_shapes[1]
  27. def conv2d_broadcastto_op(node_A, node_B, ctx=None):
  28. """Creates a node that represents np.broadcast_to(node_A, node_B.shape).
  29. Parameters:
  30. ----
  31. node_a : Node
  32. The Node to be bcast.
  33. node_b : Node
  34. Another Node with the target shape.
  35. Returns:
  36. ----
  37. A new Node instance created by Op.
  38. """
  39. return Conv2d_BroadcastToOp(node_A, node_B, ctx=ctx)