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.

Sqrt.py 2.3 kB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from __future__ import absolute_import
  2. import numpy as np
  3. from .Node import Op
  4. from .._base import DNNL_LIB
  5. from ..cpu_links import sqrt as cpu_sqrt
  6. from ..cpu_links import rsqrt as cpu_rsqrt
  7. from ..gpu_links import matrix_sqrt
  8. from ..gpu_links import matrix_rsqrt
  9. class SqrtOp(Op):
  10. def __init__(self, node_A, ctx=None):
  11. super().__init__(SqrtOp, [node_A], ctx)
  12. def compute(self, input_vals, output_val, stream_handle=None):
  13. if self.on_cpu:
  14. if DNNL_LIB['DnnlSqrt']:
  15. cpu_sqrt(input_vals[0], output_val)
  16. else:
  17. output_val[:] = np.sqrt(input_vals[0].asnumpy())
  18. else:
  19. matrix_sqrt(input_vals[0], output_val, stream_handle)
  20. def gradient(self, output_grad):
  21. return [0.5 * rsqrt_op(self.inputs[0], ctx=self.raw_ctx) * output_grad]
  22. def infer_shape(self, input_shapes):
  23. assert len(input_shapes) == 1
  24. return input_shapes[0]
  25. class ReciprocalSqrtOp(Op):
  26. def __init__(self, node_A, ctx=None):
  27. super().__init__(ReciprocalSqrtOp, [node_A], ctx)
  28. def compute(self, input_vals, output_val, stream_handle=None):
  29. if self.on_cpu:
  30. if DNNL_LIB['DnnlReciprocalSqrt']:
  31. cpu_rsqrt(input_vals[0], output_val)
  32. else:
  33. output_val[:] = 1 / np.sqrt(input_vals[0].asnumpy())
  34. else:
  35. matrix_rsqrt(input_vals[0], output_val, stream_handle)
  36. def gradient(self, output_grad):
  37. from .Division import div_op
  38. return [-0.5 * div_op(rsqrt_op(self.inputs[0], ctx=self.raw_ctx), self.inputs[0], ctx=self.raw_ctx) * output_grad]
  39. def infer_shape(self, input_shapes):
  40. assert len(input_shapes) == 1
  41. return input_shapes[0]
  42. def sqrt_op(node, ctx=None):
  43. """Calculate square root of a matrix elementwisely.
  44. Parameters:
  45. ----
  46. node : Node
  47. Input variable.
  48. Returns:
  49. ----
  50. A new Node instance created by Op.
  51. """
  52. return SqrtOp(node, ctx=ctx)
  53. def rsqrt_op(node, ctx=None):
  54. """Calculate the reciprocal of square root of a matrix elementwisely.
  55. Parameters:
  56. ----
  57. node : Node
  58. Input variable.
  59. Returns:
  60. ----
  61. A new Node instance created by Op.
  62. """
  63. return ReciprocalSqrtOp(node, ctx=ctx)