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.

LeakyRelu.py 2.5 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from __future__ import absolute_import
  2. import numpy as np
  3. from .Node import Op
  4. from .._base import DNNL_LIB
  5. """
  6. from ..cpu_links import leaky_relu as cpu_leaky_relu
  7. from ..cpu_links import leaky_relu_gradient as cpu_leaky_relu_gradient
  8. """
  9. from ..gpu_links import leaky_relu
  10. from ..gpu_links import leaky_relu_gradient
  11. class LeakyReluOp(Op):
  12. def __init__(self, node_A, const_val, ctx=None):
  13. super().__init__(LeakyReluOp, [node_A], ctx)
  14. self.const_attr = const_val
  15. self.desc = self.name + '(%s, %s)' % (node_A.name, str(const_val))
  16. def compute(self, input_vals, output_val, stream_handle=None):
  17. if self.on_cpu:
  18. raise NotImplementedError
  19. else:
  20. leaky_relu(input_vals[0], self.const_attr,
  21. output_val, stream_handle)
  22. def gradient(self, output_grad):
  23. return [leaky_relu_gradient_op(self.inputs[0], output_grad, self.const_attr, ctx=self.raw_ctx)]
  24. def infer_shape(self, input_shapes):
  25. assert len(input_shapes) == 1
  26. return input_shapes[0]
  27. class LeakyReluGradientOp(Op):
  28. def __init__(self, node_A, node_B, const_val, ctx=None):
  29. super().__init__(LeakyReluGradientOp, [node_A, node_B], ctx)
  30. self.const_attr = const_val
  31. self.desc = self.name + \
  32. '(%s, %s, %s)' % (node_A.name, node_B.name, str(const_val))
  33. def compute(self, input_vals, output_val, stream_handle=None):
  34. if self.on_cpu:
  35. raise NotImplementedError
  36. else:
  37. leaky_relu_gradient(
  38. input_vals[0], input_vals[1], self.const_attr, output_val, stream_handle)
  39. def gradient(self, output_grad):
  40. raise NotImplementedError
  41. def infer_shape(self, input_shapes):
  42. assert len(input_shapes) == 2
  43. return input_shapes[0]
  44. def leaky_relu_op(node, alpha, ctx=None):
  45. """Rectified Linear Unit.
  46. Parameters:
  47. ----
  48. node : Node
  49. Input variable.
  50. alpha : float
  51. LeakyRelu's alpha
  52. Returns:
  53. ----
  54. A new Node instance created by Op.
  55. """
  56. return LeakyReluOp(node, alpha, ctx=ctx)
  57. def leaky_relu_gradient_op(node_A, node_B, alpha, ctx=None):
  58. """Computes the gradient of the ReLU function.
  59. Parameters:
  60. ----
  61. node_A : Node
  62. LeakyRelu input.
  63. node_B : Node
  64. Previous gradient node.
  65. alpha : float
  66. LeakyRelu alpha
  67. Returns:
  68. ----
  69. A new Node instance created by Op.
  70. """
  71. return LeakyReluGradientOp(node_A, node_B, alpha, ctx=ctx)