Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / caffe / extractors / native_caffe.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 from mo.front.caffe.extractors.utils import embed_input
20 from mo.front.common.partial_infer.caffe_fallback import caffe_native_node_infer
21
22
23 def blob_name(i):
24     """
25     Implements legacy schema for blobs naming:
26         0-th blob is called 'weights'
27         1-th blob is called 'biases'
28     then, next blobs are called according to the new default schema
29     with 'custom_' prefix: custom_2, custom_3 and so on.
30     """
31     predefined_names = ['weights', 'biases']
32     if i < len(predefined_names):
33         return predefined_names[i]
34     else:
35         return 'custom_{}'.format(i)
36
37
38 def extract_custom_blobs(node):
39     """
40     Enumerate all blobs in node.model_pb, for each blob
41     creates a new embedded input of name 'custom_X', where X is an index >= 0 according
42     to the order blobs appear in node.model_pb. The order is also enforced by input port index.
43     So the order of blobs is preserved in the final IR generation.
44     Order is important because they can be accessed by indices (in addition to names).
45     Update node attributes in-place.
46     """
47     base_port = len(node.in_nodes())
48     if not hasattr(node.model_pb, 'blobs'):
49         return
50     for i, blob in enumerate(node.model_pb.blobs):
51         port = base_port + i
52         internal_name = '_custom_blob_' + str(i)
53         log.debug("Found new custom blob of length {} for node {}. ".format(
54             len(blob.data),
55             node.name if node.has_valid('name') else '<UNKNOWN>'
56         ) +
57                   "It will appear as input {} and internal attribute {}.".format(
58                       port,
59                       internal_name))
60         embed_input(node.graph.node[node.id], port, internal_name, blob.data, blob_name(i))
61
62
63 def native_caffe_node_extractor(node):
64     extract_custom_blobs(node)
65     return dict(infer=caffe_native_node_infer, top=list(node.pb.top)[0])