Feature/azaytsev/merge to master (#2786)
[platform/upstream/dldt.git] / ngraph / python / src / ngraph / opset2 / ops.py
1 # ******************************************************************************
2 # Copyright 2017-2020 Intel Corporation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #     http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 # ******************************************************************************
16
17 """! Factory functions for all ngraph ops."""
18 from typing import Callable, Iterable, List, Optional, Set, Union
19
20 import numpy as np
21 from functools import partial
22
23 from ngraph.impl import Node, Shape
24 from ngraph.impl.op import Constant, Parameter
25 from ngraph.opset_utils import _get_node_factory
26 from ngraph.utils.decorators import binary_op, nameable_op, unary_op
27 from ngraph.utils.input_validation import (
28     assert_list_of_ints,
29     check_valid_attributes,
30     is_non_negative_value,
31     is_positive_value,
32 )
33 from ngraph.utils.node_factory import NodeFactory
34 from ngraph.utils.tensor_iterator_types import (
35     GraphBody,
36     TensorIteratorSliceInputDesc,
37     TensorIteratorMergedInputDesc,
38     TensorIteratorInvariantInputDesc,
39     TensorIteratorBodyOutputDesc,
40     TensorIteratorConcatOutputDesc,
41 )
42 from ngraph.utils.types import (
43     NodeInput,
44     NumericData,
45     NumericType,
46     ScalarData,
47     TensorShape,
48     as_node,
49     as_nodes,
50     get_dtype,
51     get_element_type,
52     get_element_type_str,
53     make_constant_node,
54 )
55
56 _get_node_factory_opset2 = partial(_get_node_factory, "opset2")
57
58 # -------------------------------------------- ops ------------------------------------------------
59
60
61 @nameable_op
62 def batch_to_space(
63     data: NodeInput,
64     block_shape: NodeInput,
65     crops_begin: NodeInput,
66     crops_end: NodeInput,
67     name: Optional[str] = None,
68 ) -> Node:
69     """! Perform BatchToSpace operation on the input tensor.
70
71     BatchToSpace permutes data from the batch dimension of the data tensor into spatial dimensions.
72
73     @param data: Node producing the data tensor.
74     @param block_shape: The sizes of the block of values to be moved.
75     @param crops_begin: Specifies the amount to crop from the beginning along each axis of `data`.
76     @param crops_end: Specifies the amount to crop from the end along each axis of `data`.
77     @param name: Optional output node name.
78     @return The new node performing a BatchToSpace operation.
79     """
80     return _get_node_factory_opset2().create(
81         "BatchToSpace", as_nodes(data, block_shape, crops_begin, crops_end)
82     )
83
84
85 @unary_op
86 def gelu(node: NodeInput, name: Optional[str] = None) -> Node:
87     r"""! Perform Gaussian Error Linear Unit operation element-wise on data from input node.
88
89     Computes GELU function:
90
91     \f[ f(x) = 0.5\cdot x\cdot(1 + erf( \dfrac{x}{\sqrt{2}}) \f]
92
93     For more information refer to:
94     `Gaussian Error Linear Unit (GELU) <https://arxiv.org/pdf/1606.08415.pdf>`_
95
96     @param node: Input tensor. One of: input node, array or scalar.
97     @param name: Optional output node name.
98     @return The new node performing a GELU operation on its input data element-wise.
99     """
100     return _get_node_factory_opset2().create("Gelu", [node])
101
102
103 @nameable_op
104 def mvn(
105     data: Node,
106     across_channels: bool = False,
107     normalize_variance: bool = False,
108     eps: float = 1e-9,
109     name: str = None,
110 ) -> Node:
111     r"""! Perform Mean Variance Normalization operation on data from input node.
112
113     Computes MVN on the input tensor `data` (called `X`) using formula:
114
115     \f[ Y = \dfrac{X-EX}{\sqrt{E(X-EX)^2}} \f]
116
117     @param data: The node with data tensor.
118     @param across_channels: Denotes if mean values are shared across channels.
119     @param normalize_variance: Denotes whether to perform variance normalization.
120     @param eps: The number added to the variance to avoid division by zero
121                when normalizing the value. Scalar value.
122     @param name: Optional output node name.
123     @return The new node performing a MVN operation on input tensor.
124     """
125     return _get_node_factory_opset2().create(
126         "MVN",
127         [data],
128         {"across_channels": across_channels, "normalize_variance": normalize_variance, "eps": eps},
129     )
130
131
132 @nameable_op
133 def reorg_yolo(input: Node, stride: List[int], name: Optional[str] = None) -> Node:
134     """! Return a node which produces the ReorgYolo operation.
135
136     @param input:   Input data
137     @param stride:  Stride to reorganize input by
138     @param name:    Optional name for output node.
139     @return ReorgYolo node
140     """
141     return _get_node_factory_opset2().create("ReorgYolo", [input], {"stride": stride})
142
143
144 @nameable_op
145 def roi_pooling(
146     input: NodeInput,
147     coords: NodeInput,
148     output_size: TensorShape,
149     spatial_scale: NumericData,
150     method: str,
151     name: Optional[str] = None,
152 ) -> Node:
153     """! Return a node which produces an ROIPooling operation.
154
155     @param input:          Input feature map {N, C, ...}
156     @param coords:         Coordinates of bounding boxes
157     @param output_size:    Height/Width of ROI output features (shape)
158     @param spatial_scale:  Ratio of input feature map over input image size (float)
159     @param method:         Method of pooling - string: "max" or "bilinear"
160     @return               ROIPooling node
161     """
162     method = method.lower()
163     return _get_node_factory_opset2().create(
164         "ROIPooling",
165         as_nodes(input, coords),
166         {"output_size": Shape(output_size), "spatial_scale": spatial_scale, "method": method},
167     )
168
169
170 @nameable_op
171 def space_to_batch(
172     data: NodeInput,
173     block_shape: NodeInput,
174     pads_begin: NodeInput,
175     pads_end: NodeInput,
176     name: Optional[str] = None,
177 ) -> Node:
178     """! Perform SpaceToBatch operation on the input tensor.
179
180     SpaceToBatch permutes data tensor blocks of spatial data into batch dimension.
181     The operator returns a copy of the input tensor where values from spatial blocks dimensions
182     are moved in the batch dimension
183
184     @param data: Node producing the data tensor.
185     @param block_shape: The sizes of the block of values to be moved.
186     @param pads_begin: Specifies the padding for the beginning along each axis of `data`.
187     @param pads_end: Specifies the padding for the ending along each axis of `data`.
188     @param name: Optional output node name.
189     @return The new node performing a SpaceToBatch operation.
190     """
191     return _get_node_factory_opset2().create(
192         "SpaceToBatch", as_nodes(data, block_shape, pads_begin, pads_end)
193     )