Coverage for mlprodict/onnxrt/ops_cpu/op_leaky_relu.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v7.1.0, created at 2023-02-04 02:28 +0100

1# -*- encoding: utf-8 -*- 

2# pylint: disable=E0203,E1101,C0111 

3""" 

4@file 

5@brief Runtime operator. 

6""" 

7from textwrap import dedent 

8from ._op import OpRunUnaryNum 

9 

10 

11def _leaky_relu(x, alpha): 

12 sign = (x > 0).astype(x.dtype) 

13 sign -= ((sign - 1) * alpha).astype(x.dtype) 

14 return x * sign 

15 

16 

17def _leaky_relu_inplace(x, alpha): 

18 sign = (x > 0).astype(x.dtype) 

19 sign -= ((sign - 1) * alpha).astype(x.dtype) 

20 x *= sign 

21 

22 

23class LeakyRelu(OpRunUnaryNum): 

24 

25 atts = {'alpha': 0.01} 

26 

27 def __init__(self, onnx_node, desc=None, **options): 

28 OpRunUnaryNum.__init__(self, onnx_node, desc=desc, 

29 expected_attributes=LeakyRelu.atts, 

30 **options) 

31 

32 def _run(self, x, attributes=None, verbose=0, fLOG=None): # pylint: disable=W0221 

33 if self.inplaces.get(0, False) and x.flags['WRITEABLE']: 

34 return self._run_inplace(x) 

35 return (_leaky_relu(x, self.alpha), ) 

36 

37 def _run_inplace(self, x): 

38 _leaky_relu_inplace(x, self.alpha) 

39 return (x, ) 

40 

41 def to_python(self, inputs): 

42 return (dedent( 

43 """ 

44 import numpy 

45 def _leaky_relu(x, alpha): 

46 sign = (x > 0).astype(x.dtype) 

47 sign -= ((sign - 1) * alpha).astype(x.dtype) 

48 return x * sign 

49 """), f"return _leaky_relu({inputs[0]}, alpha)")