Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / middle / passes / convert_data_type.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 import numpy as np
19
20 from mo.graph.graph import Node, Graph
21 from mo.utils.error import Error
22 from mo.utils.utils import refer_to_faq_msg
23
24 SUPPORTED_DATA_TYPES = {
25     'float': (np.float32, 'FP32'),
26     'half': (np.float16, 'FP16'),
27     'FP32': (np.float32, 'FP32'),
28     'FP16': (np.float16, 'FP16'),
29     'I32': (np.int32, 'I32'),
30     'uint8': (np.uint8, 'UI8'),
31 }
32
33
34 def data_type_str_to_np(data_type_str: str):
35     return SUPPORTED_DATA_TYPES[data_type_str][0] if data_type_str in SUPPORTED_DATA_TYPES else None
36
37
38 def data_type_str_to_precision(data_type_str: str):
39     return SUPPORTED_DATA_TYPES[data_type_str][1] if data_type_str in SUPPORTED_DATA_TYPES else None
40
41
42 def convert_blob(graph: Graph, node: Node, data_type: type):
43     out_edges = graph.out_edges(node.node, data=True)
44
45     # if the data.value is used as binary weights
46     if any('bin' in d for _, __, d in out_edges):
47         blob = node.value
48         if blob.dtype != data_type:
49             new_blob = blob.astype(dtype=data_type, casting="same_kind")
50             consumers = [x.name if x.has_valid('name') else '<NO NAME>' for x in node.out_nodes()]
51             log.debug(
52                 'Blob was converted to {} while dumping to the bin file. This blob is an input for {} nodes.'.format(
53                     data_type, consumers))
54             finite_match = (np.isfinite(blob) != np.isfinite(new_blob))
55             zero_match = ((blob == 0) != (new_blob == 0))
56             finite_match_count = np.count_nonzero(finite_match)
57             zero_match_count = np.count_nonzero(zero_match)
58             if finite_match_count:
59                 log.error(
60                     ("{} elements of {} were clipped to infinity while converting a blob for " \
61                      "node [{}] to {}. " +
62                      refer_to_faq_msg(76)).format(
63                         finite_match_count, blob.size, consumers, data_type))
64             if zero_match_count:
65                 log.warning(
66                     ("{} elements of {} were clipped to zero while converting a blob for node " \
67                      " [{}] to {}. " +
68                      refer_to_faq_msg(77)).format(
69                         zero_match_count, blob.size, consumers, data_type))
70             node.value = new_blob
71
72
73 def convert(graph: Graph, data_type_str: str):
74     for node_name, node_attrs in graph.nodes(data=True):
75         node = Node(graph, node_name)
76         # if the data type is forcibly set then use it
77         if node.has_valid('force_precision'):
78             real_data_type_str = node_attrs['force_precision']
79         else:
80             real_data_type_str = data_type_str
81         node_attrs['precision'] = data_type_str_to_precision(real_data_type_str)
82         if node.kind == 'data' and node.value is not None:
83             try:
84                 convert_blob(graph, node, data_type_str_to_np(real_data_type_str))
85             except Exception as e:
86                 raise Error('Coudn\'t convert blob {}, details: {}', node.soft_get('name'), e) from e