Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / freeze_placeholder_value.py
1 """
2  Copyright (c) 2018-2019 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 logging as log
18
19 import numpy as np
20
21 from mo.front.common.replacement import FrontReplacementSubgraph
22 from mo.graph.graph import Graph
23 from mo.middle.passes.convert_data_type import SUPPORTED_DATA_TYPES
24 from mo.ops.const import Const
25 from mo.utils.error import Error
26
27
28 class FreezePlaceholderValue(FrontReplacementSubgraph):
29     """
30     Replaces existing placeholder to Constant node with provided value. It takes value from freeze_placeholder as
31     a string and casts it to actual node data type
32     """
33     enabled = True
34     graph_condition = [lambda graph: graph.graph['freeze_placeholder'] is not None]
35
36     def run_after(self):
37         from extensions.front.restore_ports import RestorePorts
38         return [RestorePorts]
39
40     def run_before(self):
41         from extensions.front.pass_separator import FrontStart
42         return [FrontStart]
43
44     @staticmethod
45     def pattern():
46         return dict(
47             nodes=[('placeholder', dict(kind='op', op='Placeholder'))],
48             edges=[]
49         )
50
51     def replace_sub_graph(self, graph: Graph, match: dict):
52         ph = match['placeholder']
53         if ph.name in graph.graph['freeze_placeholder']:
54             name = ph.name
55             if ph.has_and_set('data_type'):
56                 data_type = ph.data_type
57             else:
58                 data_type = SUPPORTED_DATA_TYPES[graph.graph['cmd_params'].data_type][0]
59             string_value = graph.graph['freeze_placeholder'][name]
60             try:
61                 if data_type != np.bool:
62                     value = np.array(string_value, dtype=data_type)
63                 elif data_type == np.bool and graph.graph['fw'] == 'tf':
64                     from mo.front.tf.common import tf_data_type_cast
65                     if isinstance(string_value, list):
66                         casted_list = list()
67                         for v in np.array(string_value):
68                             casted_list.append(tf_data_type_cast[ph.data_type](v))
69                         value = np.array(string_value, dtype=data_type)
70                     else:
71                         value = tf_data_type_cast[ph.data_type](string_value)
72                 else:
73                     raise Error("Can not cast value {} to {} data_type".format(string_value, data_type))
74             except:
75                 raise Error("Can not cast value {} to {} data_type".format(string_value, data_type))
76             try:
77                 value = np.reshape(a=value, newshape=ph.shape)
78             except:
79                 raise Error("Can not reshape value {} to shape {}".format(value, ph.shape))
80             out_edges = list(graph.out_edges(ph.id, data=True))
81             new_node = Const(graph).create_node(
82                 attrs={'value': value, 'data_type': type(value), 'name': name + '/const_placeholder',
83                        'shape': ph.shape})
84             graph.erase_node(ph)
85             graph.add_edges_from([(new_node.id, v, attrs) for u, v, attrs in out_edges])
86             log.info("Placeholder node \"{}\" was replaced with Const node \"{}\" with value \"{}\"".format(
87                 name, new_node.name, value))