Add a section of how to link IE with CMake project (#99)
[platform/upstream/dldt.git] / model-optimizer / mo / middle / passes / pool.py
1 """
2  Copyright (c) 2018 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 import networkx as nx
18 import numpy as np
19
20 from mo.graph.graph import create_edge
21 from mo.middle.pattern_match import apply_pattern
22 from mo.ops.op import Op, PermuteAttrs
23 from mo.ops.reshape import Reshape
24
25
26 def mean_to_avgpool_action(graph: nx.MultiDiGraph, matches: dict):
27     if matches['axis'].value is None or matches['input'].shape is None:
28         return
29     dims = len(matches['input'].shape)
30     ones = np.ones(dims, dtype=np.int64)
31     axis = np.array(matches['axis'].value)
32     axis = axis if axis.ndim != 0 else np.array([axis], dtype=np.int64)
33
34     mean = graph.node[matches['mean'].node]
35     mean['stride'] = np.array(ones)
36     # TODO: need to check axis with real layout
37     spatial_dims = np.array(axis)
38     mean['spatial_dims'] = spatial_dims
39     mean['pad'] = np.zeros((dims, 2), np.int64)
40     mean['pad_spatial_shape'] = np.array(mean['pad'][spatial_dims])
41     window = np.array(ones)
42     window[spatial_dims] = matches['input'].shape[spatial_dims]
43     mean['window'] = window
44     mean['TF_op'] = mean['op']
45     mean['op'] = 'AvgPool'
46     mean['pool_method'] = 'avg'
47     mean['rounding_type'] = 'ceil'
48     mean['exclude_pad'] = 'true'
49     mean['kernel_spatial'] = window[spatial_dims]
50     graph.remove_edge(matches['axis'].node, matches['mean'].node)
51     mean['permute_attrs'] = PermuteAttrs().update_attrs(attrs=[('pad', 'input:0'),
52                                                                ('stride', 'input:0'),
53                                                                ('window', 'input:0'),
54                                                                ('spatial_dims', 'input:0')])
55
56     if matches['mean'].keep_dims == False:
57         output = matches['mean'].out_node()
58         pool_node = matches['mean']
59
60         # Keep dims for AvgPool
61         shape = np.array(output.shape)
62         for idx in spatial_dims:
63             shape = np.insert(shape, idx, 1)
64
65         graph.remove_edge(pool_node.id, output.id)
66         # Create new data for pool with all dims
67         pool_data = Op.create_data_node(graph, pool_node, {'shape': np.array(shape)})
68         # Create and connect reshape node
69         reshape_op = Reshape(graph, {'dim': np.array(output.shape)})
70         reshape_node = reshape_op.create_node([pool_data], dict(name='Reshape_',
71                                                                 permute_attrs=PermuteAttrs().update_attrs(attrs=[('dim', 'output:0')])))
72         create_edge(reshape_node, output)
73
74
75 def mean_to_avgpool(graph: nx.MultiDiGraph):
76     """
77     Translate Mean as a average pooling with kernel size equals to reduced dimensions and with no padding.
78     """
79     apply_pattern(
80         graph,
81         nodes=[
82             ('input', dict(kind='data')),
83             ('axis', dict(kind='data')),
84             ('mean', dict(kind='op', op='Mean'))],
85         edges=[
86             ('input', 'mean', {'in': 0}),
87             ('axis', 'mean', {'in': 1})],
88         action=mean_to_avgpool_action
89     )
90     return graph