Publishing R3
[platform/upstream/dldt.git] / model-optimizer / mo / front / kaldi / extractor.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 from mo.graph.graph import Node
18 from mo.front.common.partial_infer.elemental import copy_shape_infer, single_output_infer
19 from mo.utils.error import Error
20 from mo.utils.utils import refer_to_faq_msg
21
22
23 def node_pb_arg(pb_extractor):
24     return lambda node: pb_extractor(node.pb)
25
26
27 kaldi_type_extractors = {
28     # Data Layers
29     'globalinput': node_pb_arg(lambda x: dict(op='Placeholder', type='Input',
30                                               infer=lambda node: single_output_infer(node, lambda n: n.shape))),
31
32     # Utility Layers
33     'softmax': node_pb_arg(lambda _: dict(op='SoftMax', type='SoftMax', infer=copy_shape_infer)),
34 }
35
36
37 def common_kaldi_fields(node: Node) -> dict:
38     pb = node.pb if node.pb else node
39     layer_type = pb.type
40     return {
41         'kind': 'op',
42         'name': pb.name,
43         'type': layer_type,
44         'op': layer_type,
45         # generic code relies on op; it should be overridden by specific op extractor
46         'infer': None,
47         'precision': 'FP32'  # TODO use real precision derived from the model
48     }
49
50
51 def kaldi_extractor(node: Node) -> (bool, dict):
52     if node.has_valid('op') and node.op == 'Identity':
53         return True, {}
54     result = common_kaldi_fields(node)
55
56     layer_type = result['type'].lower()
57     if layer_type not in kaldi_type_extractors:
58         raise Error('Found unsupported layer {}. '.format(node.id) +
59                     'Model Optimizer does not support this layer type: {}. '.format(layer_type) +
60                     'Please, implement extension. ' +
61                     refer_to_faq_msg(45))
62
63     result.update(kaldi_type_extractors[layer_type](node))
64     supported = True
65
66     return supported, result