caffe_decoder.py 10.5 KB
Newer Older
J
jiangjiajun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
#   Copyright (c) 2019  PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
S
SunAhong1993 已提交
14 15 16 17 18 19

import os
import sys
from google.protobuf import text_format
import numpy as np
from x2paddle.core.graph import GraphNode, Graph
S
SunAhong1993 已提交
20
from x2paddle.core.fluid_code import FluidCode
S
SunAhong1993 已提交
21
from x2paddle.op_mapper import caffe_shape
S
SunAhong1993 已提交
22 23 24


class CaffeResolver(object):
S
SunAhong1993 已提交
25 26
    def __init__(self, caffe_proto):
        self.proto_path = caffe_proto
S
SunAhong1993 已提交
27
        if self.proto_path is None:
S
SunAhong1993 已提交
28 29 30
            self.use_default = True
        else:
            self.use_default = False
S
SunAhong1993 已提交
31 32 33
        self.import_caffe()

    def import_caffepb(self):
S
SunAhong1993 已提交
34 35 36 37 38 39
        (filepath,
         tempfilename) = os.path.split(os.path.abspath(self.proto_path))
        (filename, extension) = os.path.splitext(tempfilename)
        sys.path.append(filepath)
        out = __import__(filename)
        return out
S
SunAhong1993 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

    def import_caffe(self):
        self.caffe = None
        self.caffepb = None
        if self.use_default:
            try:
                # Try to import PyCaffe first
                import caffe
                self.caffe = caffe
            except ImportError:
                # Fall back to the protobuf implementation
                self.caffepb = self.import_caffepb()
        else:
            self.caffepb = self.import_caffepb()
        if self.caffe:
            # Use the protobuf code from the imported distribution.
            # This way, Caffe variants with custom layers will work.
            self.caffepb = self.caffe.proto.caffe_pb2
        self.NetParameter = self.caffepb.NetParameter

    def has_pycaffe(self):
        return self.caffe is not None


class CaffeGraphNode(GraphNode):
    def __init__(self, layer, layer_name=None):
        if layer_name is None:
S
SunAhong1993 已提交
67 68 69
            super(CaffeGraphNode,
                  self).__init__(layer,
                                 layer.name.replace('/', '_').replace('-', '_'))
S
SunAhong1993 已提交
70
        else:
S
SunAhong1993 已提交
71 72 73
            super(CaffeGraphNode,
                  self).__init__(layer,
                                 layer_name.replace('/', '_').replace('-', '_'))
S
SunAhong1993 已提交
74
        self.layer_type = layer.type
S
SunAhong1993 已提交
75
        self.fluid_code = FluidCode()
S
SunAhong1993 已提交
76
        self.data = None
S
SunAhong1993 已提交
77 78 79 80

    def set_params(self, params):
        self.data = params

S
SunAhong1993 已提交
81
    def set_output_shape(self, input_shape, is_input=True):
S
SunAhong1993 已提交
82
        func_name = 'shape_' + self.layer_type.lower()
S
SunAhong1993 已提交
83 84 85 86 87
        if is_input:
            self.output_shape = getattr(caffe_shape, func_name)(self.layer,
                                                                input_shape)
        else:
            self.output_shape = input_shape
S
SunAhong1993 已提交
88 89 90 91

    def set_input_shape(self, input_shape):
        self.input_shape = input_shape

S
SunAhong1993 已提交
92 93

class CaffeGraph(Graph):
S
SunAhong1993 已提交
94
    def __init__(self, model, params):
S
SunAhong1993 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        self.params = params
        super(CaffeGraph, self).__init__(model)

    def filter_layers(self, layers):
        '''Filter out layers based on the current phase.'''
        phase_map = {0: 'train', 1: 'test'}
        filtered_layer_names = set()
        filtered_layers = []
        for layer in layers:
            phase = 'test'
            if len(layer.include):
                phase = phase_map[layer.include[0].phase]
            if len(layer.exclude):
                phase = phase_map[1 - layer.include[0].phase]
            exclude = (phase != 'test')
            # Dropout layers appear in a fair number of Caffe
            # test-time networks. These are just ignored. We'll
            # filter them out here.
            if (not exclude) and (phase == 'test'):
                exclude = (layer.type == 'Dropout')
            if not exclude:
                filtered_layers.append(layer)
                # Guard against dupes.
                assert layer.name not in filtered_layer_names
                filtered_layer_names.add(layer.name)
            else:
S
SunAhong1993 已提交
121
                print('The filter layer:' + layer.name)
S
SunAhong1993 已提交
122 123 124 125 126 127 128 129 130
        return filtered_layers

    def build(self):
        layers = self.model.layers or self.model.layer
        layers = self.filter_layers(layers)

        inputs_num = len(self.model.input)
        if inputs_num != 0:
            input_dims_num = len(self.model.input_dim)
S
SunAhong1993 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144
            if input_dims_num != 0:
                if input_dims_num > 0 and input_dims_num != inputs_num * 4:
                    raise Error('invalid input_dim[%d] param in prototxt' %
                                (input_dims_num))
                for i in range(inputs_num):
                    dims = self.model.input_dim[i * 4:(i + 1) * 4]
                    data = self.model.layer.add()
                    try:
                        from caffe import layers as L
                        data.CopyFrom(
                            L.Input(input_param=dict(shape=dict(
                                dim=[dims[0], dims[1], dims[2], dims[3]
                                     ]))).to_proto().layer[0])
                    except:
S
SunAhong1993 已提交
145
                        print(
S
SunAhong1993 已提交
146
                            "The .py file compiled by .proto file does not work for the old style prototxt. "
S
SunAhong1993 已提交
147
                        )
S
SunAhong1993 已提交
148 149
                        print("There are 2 solutions for you as below:")
                        print(
S
SunAhong1993 已提交
150 151
                            "1. install caffe and don\'t set \'--caffe_proto\'."
                        )
S
SunAhong1993 已提交
152 153 154 155
                        print(
                            "2. modify your .prototxt from the old style to the new style."
                        )
                        sys.exit(-1)
S
SunAhong1993 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168
                    data.name = self.model.input[i]
                    data.top[0] = self.model.input[i]
            else:
                for i in range(inputs_num):
                    dims = self.model.input_shape[i].dim[0:4]
                    data = self.model.layer.add()
                    try:
                        from caffe import layers as L
                        data.CopyFrom(
                            L.Input(input_param=dict(shape=dict(
                                dim=[dims[0], dims[1], dims[2], dims[3]
                                     ]))).to_proto().layer[0])
                    except:
S
SunAhong1993 已提交
169
                        print(
S
SunAhong1993 已提交
170
                            "The .py file compiled by .proto file does not work for the old style prototxt. "
S
SunAhong1993 已提交
171 172 173
                        )
                        print("There are 2 solutions for you as below:")
                        print(
S
SunAhong1993 已提交
174 175
                            "1. install caffe and don\'t set \'--caffe_proto\'."
                        )
S
SunAhong1993 已提交
176 177
                        print(
                            "2. modify your .prototxt from the old style to the new style."
S
SunAhong1993 已提交
178
                        )
S
SunAhong1993 已提交
179
                        sys.exit(-1)
S
SunAhong1993 已提交
180 181 182
                    data.name = self.model.input[i]
                    data.top[0] = self.model.input[i]
            layers = [data] + layers
S
SunAhong1993 已提交
183

S
SunAhong1993 已提交
184
        top_layer = {}
S
SunAhong1993 已提交
185 186
        for layer in layers:
            self.node_map[layer.name] = CaffeGraphNode(layer)
S
SunAhong1993 已提交
187 188 189
            for in_name in layer.bottom:
                if in_name in top_layer:
                    self.connect(top_layer[in_name][-1], layer.name)
S
SunAhong1993 已提交
190 191 192
                else:
                    raise Exception(
                        'input[{}] of node[{}] does not exist in node_map'.
S
SunAhong1993 已提交
193 194 195 196 197 198
                        format(in_name, layer.name))
            for out_name in layer.top:
                if out_name not in top_layer:
                    top_layer[out_name] = [layer.name]
                else:
                    top_layer[out_name].append(layer.name)
S
SunAhong1993 已提交
199 200 201 202

        for layer_name, data in self.params:
            if layer_name in self.node_map:
                node = self.node_map[layer_name]
S
SunAhong1993 已提交
203
                node.set_params(data)
S
SunAhong1993 已提交
204
            else:
S
SunAhong1993 已提交
205 206
                raise Exception('Ignoring parameters for non-existent layer: %s' % \
                       layer_name)
S
SunAhong1993 已提交
207

S
SunAhong1993 已提交
208 209
        super(CaffeGraph, self).build()

S
SunAhong1993 已提交
210 211 212 213 214 215
    def get_bottom_node(self, node, idx=0, copy=False):
        input_node_name = node.inputs[idx]
        assert input_node_name in self.node_map, 'The {} isn\'t a valid node'.format(
            name)
        input_node = self.node_map[input_node_name]
        if len(input_node.layer.top) > 1:
S
SunAhong1993 已提交
216 217
            need_idx = list(input_node.layer.top).index(node.layer.bottom[idx])
            name = input_node_name + ':' + str(need_idx)
S
SunAhong1993 已提交
218 219 220 221
        else:
            name = input_node_name
        return self.get_node(name, copy=copy)

S
SunAhong1993 已提交
222

J
jiangjiajun 已提交
223
class CaffeDecoder(object):
S
SunAhong1993 已提交
224
    def __init__(self, proto_path, model_path, caffe_proto=None):
S
SunAhong1993 已提交
225 226 227
        self.proto_path = proto_path
        self.model_path = model_path

S
SunAhong1993 已提交
228
        self.resolver = CaffeResolver(caffe_proto=caffe_proto)
S
SunAhong1993 已提交
229 230 231 232 233 234
        self.net = self.resolver.NetParameter()
        with open(proto_path, 'rb') as proto_file:
            proto_str = proto_file.read()
            text_format.Merge(proto_str, self.net)

        self.load()
S
SunAhong1993 已提交
235
        self.caffe_graph = CaffeGraph(self.net, self.params)
S
SunAhong1993 已提交
236 237 238 239 240 241 242 243 244 245 246
        self.caffe_graph.build()

    def load(self):
        if self.resolver.has_pycaffe():
            self.load_using_caffe()
        else:
            self.load_using_pb()

    def load_using_caffe(self):
        caffe = self.resolver.caffe
        caffe.set_mode_cpu()
S
SunAhong1993 已提交
247 248
        print(self.proto_path)
        print(self.model_path)
S
SunAhong1993 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        net = caffe.Net(self.proto_path, self.model_path, caffe.TEST)
        data = lambda blob: blob.data
        self.params = [(k, list(map(data, v))) for k, v in net.params.items()]

    def load_using_pb(self):
        data = self.resolver.NetParameter()
        data.MergeFromString(open(self.model_path, 'rb').read())
        pair = lambda layer: (layer.name, self.normalize_pb_data(layer))
        layers = data.layers or data.layer
        self.params = [pair(layer) for layer in layers if layer.blobs]

    def normalize_pb_data(self, layer):
        transformed = []
        for blob in layer.blobs:
            if len(blob.shape.dim):
                dims = blob.shape.dim
                c_o, c_i, h, w = map(int, [1] * (4 - len(dims)) + list(dims))
            else:
                c_o = blob.num
                c_i = blob.channels
                h = blob.height
                w = blob.width
            data = np.array(blob.data, dtype=np.float32).reshape(c_o, c_i, h, w)
            transformed.append(data)
        return transformed