onnx_decoder.py 19.8 KB
Newer Older
C
update  
channingss 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#   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.

from x2paddle.core.graph import GraphNode, Graph
from x2paddle.core.fluid_code import FluidCode
from onnx.checker import ValidationError
from onnx.checker import check_model
from onnx.utils import polish_model
from onnx.version_converter import convert_version
from onnx import helper
from onnx.helper import get_attribute_value, make_attribute
from onnx.shape_inference import infer_shapes
from onnx.mapping import TENSOR_TYPE_TO_NP_TYPE
from onnx.numpy_helper import to_array
C
channingss 已提交
26
from onnx import AttributeProto, TensorProto, GraphProto
C
update  
channingss 已提交
27 28 29 30
from collections import OrderedDict as Dict
import onnx
import numpy as np
from copy import deepcopy
C
channingss 已提交
31
import logging as _logging
C
update  
channingss 已提交
32 33

default_op_domain = 'ai.onnx'
C
channingss 已提交
34
_logger = _logging.getLogger(__name__)
C
update  
channingss 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47


class ONNXGraphNode(GraphNode):
    def __init__(self, layer, layer_name=None):
        if layer_name is None:
            super(ONNXGraphNode, self).__init__(layer, layer.name)
        else:
            super(ONNXGraphNode, self).__init__(layer, layer_name)
        self.layer_type = layer.op_type
        self.fluid_code = FluidCode()
        self.attr_map = self.get_attr_map()
        self.dtype_map = {1: "float32", 3: "int32", 9: "int64"}
        self.weight_inputs = list()
C
channingss 已提交
48
        self.out_shapes = list()
C
update  
channingss 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61
        self.dtype = None

    def get_attr_map(self):
        """
        convert ONNX node attributes to dict
        """
        return {
            attr.name: self.get_attribute_value2(attr)
            for attr in self.layer.attribute
        }

    @property
    def value(self):
C
channingss 已提交
62 63 64 65
        assert 'Constant' in self.layer_type, "Only Constant | ConstantOfShape node has value."
        attr = self.layer.attribute['value']
        if 'value' not in self.attr_map:
            return None
C
update  
channingss 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        return self.attr_map[name]

    def get_attribute_value2(self, attr):
        """
        get_attribute_value enhanced
        """
        if attr.type == onnx.AttributeProto.TENSOR:
            dtype = np.dtype(TENSOR_TYPE_TO_NP_TYPE[attr.t.data_type])
            data = attr.t.raw_data
            value = np.frombuffer(data,
                                  dtype=dtype,
                                  count=(len(data) // dtype.itemsize))
        elif attr.type == onnx.AttributeProto.STRING:
            value = attr.s
            value = value.decode() if isinstance(value, bytes) else value
        else:
            value = get_attribute_value(attr)
        return value

    def get_attr(self, name, default=None):
        """
        get_attribute_value from attr_map
        """
        if name not in self.attr_map:
            return default
        return self.attr_map[name]


class ONNXGraphDataNode(GraphNode):
    def __init__(self, layer, layer_name=None, is_global_input=False):
        if layer_name is None:
            super(ONNXGraphDataNode, self).__init__(layer, layer.name)
        else:
            super(ONNXGraphDataNode, self).__init__(layer, layer_name)
        if is_global_input:
            self.layer_type = 'place_holder'
        else:
            self.layer_type = 'create_parameter'
        self.layer_name = layer_name
        self.fluid_code = FluidCode()
        self.weight = None
        self.embeded_as = None

    @property
    def out_shapes(self):
        values = self.layer.type.tensor_type.shape.dim
        out_shapes = list()
C
channingss 已提交
113
        out_shapes.append([dim.dim_value for dim in values])
C
update  
channingss 已提交
114 115 116 117 118 119 120 121 122
        return out_shapes

    @property
    def dtype(self):
        dtype = self.layer.type.tensor_type.elem_type
        return TENSOR_TYPE_TO_NP_TYPE[dtype]


class ONNXGraph(Graph):
C
channingss 已提交
123 124 125
    def __init__(self, graph, onnx_model):
        super(ONNXGraph, self).__init__(graph)
        self.onnx_model = onnx_model
C
update  
channingss 已提交
126 127 128
        self.initializer = {}
        self.place_holder_nodes = list()
        self.get_place_holder_nodes()
C
channingss 已提交
129 130 131

        self.value_infos = self.inferred_model_value_info(graph)
        self.results_of_inference = dict()
C
update  
channingss 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

    def get_inner_nodes(self):
        """
        generate inner node of ONNX model
        """
        inner_nodes = []
        if not isinstance(self.model, onnx.GraphProto):
            logger.error('graph is not a GraphProto instance')
            return
        for initializer in self.model.initializer:
            name = initializer.name
            inner_nodes.append(name)
        return inner_nodes

    def get_place_holder_nodes(self):
        """
        generate place_holder node of ONNX model
        """
        inner_nodes = self.get_inner_nodes()
        input_nodes = [value.name for value in self.model.input]
        for ipt_data in input_nodes:
            if ipt_data not in inner_nodes:
                self.place_holder_nodes.append(ipt_data)

    def is_place_holder_nodes(self, layer):
        """
        return layer is or not place_holder node
        """
        if layer in self.place_holder_nodes:
            return True
        return False

    def build(self):
        """
        build topo_sort of ONNX model
        """
C
channingss 已提交
168 169 170 171
        data_node = self.place_holder_nodes[0]
        value_info = self.value_infos[data_node]
        input_shape = value_info['shape']
        self.get_results_of_inference(self.onnx_model, input_shape)
C
update  
channingss 已提交
172
        for layer in self.model.node:
C
channingss 已提交
173 174 175
            node = ONNXGraphNode(layer)
            self.node_map[layer.name] = node
            for opt in layer.output:
C
channingss 已提交
176 177 178 179 180 181 182 183
                if opt in self.value_infos:
                    value_info = self.value_infos[opt]
                    node.dtype = value_info['dtype']
                    node.out_shapes.append(value_info['shape'])
                else:
                    _, dtype, shape = self.get_dynamic_shape(opt)
                    node.dtype = dtype
                    node.out_shapes.append(shape)
C
update  
channingss 已提交
184 185 186 187 188 189 190 191

        for layer in self.model.input:
            if layer.name not in self.node_map:
                is_place_holder = self.is_place_holder_nodes(layer.name)
                self.node_map[layer.name] = ONNXGraphDataNode(
                    layer,
                    layer_name=layer.name,
                    is_global_input=is_place_holder)
C
channingss 已提交
192

C
update  
channingss 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        #set data node's weight
        for name, weight in self.graph_weights(self.model):
            if name in self.node_map:
                if isinstance(self.node_map[name], ONNXGraphDataNode):
                    self.node_map[name].weight = weight
                    self.node_map[name].embeded_as = []

        #generate connection between nodes for topo
        for layer_name, node in self.node_map.items():
            if isinstance(node, ONNXGraphNode):
                for idx, in_node in enumerate(node.layer.input):
                    if in_node not in self.node_map:
                        raise Exception(
                            'input[{}] of node[{}] does not exist in node_map'.
                            format(in_node, layer_name))
                    else:
                        self.connect(in_node, layer_name)
C
channingss 已提交
210
        #generate topo
C
update  
channingss 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        super(ONNXGraph, self).build()

        self.input_nodes = self.place_holder_nodes

    def get_nodes(self, names, copy=False):
        """
        get nodes by more than one name
        """
        nodes = []
        for name in names:
            nodes.add(self.get_node(name, copy=copy))

    def graph_weights(self, graph):
        """
        generator for weights
        """

        if not isinstance(graph, onnx.GraphProto):
            logger.error('graph is not a GraphProto instance')
            return

        for initializer in graph.initializer:
            name = initializer.name
            weight = to_array(initializer)
            yield name, weight

C
channingss 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    def inferred_model_value_info(self, graph):
        """
        collect value/type info for an ONNX model
        """
        assert isinstance(graph,
                          onnx.GraphProto), 'model is not a ModelProto instance'

        value_info = Dict()
        for item in graph.value_info:
            value_info[item.name] = {
                'dtype':
                TENSOR_TYPE_TO_NP_TYPE[item.type.tensor_type.elem_type],
                'shape':
                [dim.dim_value for dim in item.type.tensor_type.shape.dim],
                'external': False
            }
        for item in graph.input:
            assert item.name not in value_info
            value_info[item.name] = {
                'dtype':
                TENSOR_TYPE_TO_NP_TYPE[item.type.tensor_type.elem_type],
                'shape':
                [dim.dim_value for dim in item.type.tensor_type.shape.dim],
                'external': True
            }
        for item in graph.output:
C
channingss 已提交
263
            assert item.name not in value_info
C
channingss 已提交
264 265 266 267 268 269 270 271 272
            value_info[item.name] = {
                'dtype':
                TENSOR_TYPE_TO_NP_TYPE[item.type.tensor_type.elem_type],
                'shape':
                [dim.dim_value for dim in item.type.tensor_type.shape.dim],
                'external': True
            }
        return value_info

C
channingss 已提交
273
    def get_results_of_inference(self, model, shape):
C
channingss 已提交
274 275 276 277 278 279 280 281 282 283 284
        try:
            import torch
            version = torch.__version__
            if '1.1.0' not in version:
                print("your model have dynamic graph, torch==1.1.0 is required")
                return
        except:
            print(
                "your model have dynamic graph, we use caff2 to inference graph, please use \"pip install torch==1.1.0\"."
            )
            return
C
channingss 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
        from x2paddle.decoder.onnx_backend import prepare

        np_images = np.random.rand(shape[0], shape[1], shape[2],
                                   shape[3]).astype('float32')

        outputs = []
        for node in model.graph.node:
            value_info = helper.make_tensor_value_info(node.name,
                                                       TensorProto.UNDEFINED,
                                                       [])
            outputs.append(value_info)

        while len(outputs) > 0:
            tmp_outputs = outputs[:254]
            model.graph.ClearField('output')
            model.graph.output.MergeFrom(tmp_outputs)
            prepared_backend = prepare(model,
                                       device='CPU',
                                       no_check_UNSAFE=True)
            res = prepared_backend.run(inputs=np_images)
            for idx, info in enumerate(tmp_outputs):
                self.results_of_inference[info.name] = res[idx]
            outputs = outputs[254:]
        return

    def get_dynamic_shape(self, layer):
        """
        get dynamic shape from caffe2.backend
        """
        output = self.results_of_inference[layer]
        return output.tolist(), output.dtype, output.shape

C
update  
channingss 已提交
317 318 319 320 321

class ONNXDecoder(object):
    def __init__(self, onnx_model):
        model = onnx.load(onnx_model)
        print('model ir_version: {}, op version: {}'.format(
C
channingss 已提交
322 323 324 325 326 327 328
            model.ir_version, model.opset_import[0].version))
        if model.opset_import[0].version < 9:
            _logger.warning(
                'Now, onnx2paddle main support convert onnx model opset_verison == 9,'
                'opset_verison of your onnx model is %d < 9,'
                'some operator may cannot convert.',
                model.opset_import[0].version)
C
update  
channingss 已提交
329

C
channingss 已提交
330 331
        check_model(model)
        model = onnx.shape_inference.infer_shapes(model)
C
update  
channingss 已提交
332 333 334 335 336 337
        model = self.optimize_model_skip_op_for_inference(model)
        model = self.optimize_model_strip_initializer(model)
        self.standardize_variable_name(model.graph)

        self.model = model
        graph_def = model.graph
C
channingss 已提交
338
        self.onnx_graph = ONNXGraph(graph_def, model)
C
update  
channingss 已提交
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
        self.onnx_graph.build()

    def build_value_refs(self, nodes):
        """
        build op reference of inputs and outputs
        """
        input_refs = Dict()
        output_refs = Dict()
        for idx, node in enumerate(nodes):
            for val_name in node.input:
                input_refs.setdefault(val_name, set()).add(idx)
            for val_name in node.output:
                output_refs.setdefault(val_name, set()).add(idx)
        return input_refs, output_refs

    def skip_node_forward(self, nodes, src_output_name, dst_input_name,
                          input_refs):
        """
        skip nodes between src_output_name -> dst_input_name and connect this pair
        """
        processed = 0
        for next_idx in input_refs[src_output_name]:
            next_node = nodes[next_idx]
            for val_idx, next_input_name in enumerate(next_node.input):
                if next_input_name == src_output_name:
                    next_node.input[val_idx] = dst_input_name
                    processed += 1
        return processed

    def skip_node_backward(self, nodes, src_input_name, dst_output_name,
                           output_refs):
        """
        skip nodes between dst_output_name -> src_input_name and connect this pair
        """
        processed = 0
        for prev_idx in output_refs[src_input_name]:
            prev_node = nodes[prev_idx]
            for val_idx, prev_output_name in enumerate(prev_node.output):
                if prev_output_name == src_input_name:
                    prev_node.output[val_idx] = dst_output_name
                    processed += 1
        return processed

    def optimize_model_skip_op_for_inference(self, model, op_list=None):
        """
        skip ops can be bypassed for inference
        """
        if op_list is None:
            op_list = ['Dropout']

        nodes = model.graph.node
        input_refs, output_refs = self.build_value_refs(nodes)
        ret = type(model)()
        ret.CopyFrom(model)
        ret_nodes = ret.graph.node
        nodes_to_remove = []
        for node_idx, node in enumerate(nodes):
            if not (node.domain == default_op_domain or node.domain == ''):
                continue
            op_type = node.op_type
            if not (op_type in op_list):
                continue
            if op_type in ['Dropout']:
                input_name = node.input[0]
                output_name = node.output[0]
            elif not (len(node.input) == 1 and len(node.output) == 1):
                print(
                    'currently only 1-input-1-output op supported, skip required %d: %s',
                    node_idx, node.op_type)
                continue
            else:
                input_name = node.input[0]
                output_name = node.output[0]

            if output_name in input_refs:
                processed = self.skip_node_forward(ret_nodes, output_name,
                                                   input_name, input_refs)
            elif input_name in output_refs:
                processed = self.skip_node_backward(ret_nodes, input_name,
                                                    output_name, output_refs)
            else:
                processed = -1
            if processed > 0:
                nodes_to_remove.append(node_idx)
C
channingss 已提交
423 424 425 426 427
                for value_info in ret.graph.value_info:
                    for output in node.output:
                        if value_info.name == output:
                            ret.graph.value_info.remove(value_info)

C
update  
channingss 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
                print('skip op {}: {} -> {} -> {}'.format(
                    node_idx, input_name, node.op_type, output_name))
            elif processed == 0:
                print('weird, no node processed')
            else:
                print('standalone op {}: {} -> {} -> {} not skipped'.format(
                    node_idx, input_name, node.op_type, output_name))

        nodes_to_remove.sort(reverse=True)
        for node_idx in nodes_to_remove:
            ret_nodes.pop(node_idx)
        return ret

    def optimize_model_strip_initializer(self, model, keep_input_only=True):
        """
        strip weights for inference
        """
        nodes = model.graph.node
        input_refs, output_refs = self.build_value_refs(nodes)
        out_names = [val.name for val in model.graph.output]

        ret = type(model)()
        ret.CopyFrom(model)
        # strip initializers
        ret.graph.ClearField('initializer')
        ret_initializers = ret.graph.initializer
        for initializer in model.graph.initializer:
            name = initializer.name
            if name in input_refs:
                ret_initializers.add().CopyFrom(initializer)
            elif not keep_input_only and name in output_refs:
                ret_initializers.add().CopyFrom(initializer)
            else:
                dtype = TENSOR_TYPE_TO_NP_TYPE[initializer.data_type]

        # strip inputs
        ret.graph.ClearField('input')
        ret_inputs = ret.graph.input
        for item in model.graph.input:
            name = item.name
            if name in input_refs or name in out_names:
                ret_inputs.add().CopyFrom(item)
        return ret

    def make_variable_name(self, name):
        """
        make a valid code name for ParamAttr
        """

        if name == '':
            raise ValueError('name should not be empty')
        for s in ' .*?\\/-:':  #
            name = name.replace(s, '_')
        return '_' + name

    def standardize_variable_name(self, graph):
        """
        standardize variable name for paddle's code
        """
        for initializer in graph.initializer:
            initializer.name = self.make_variable_name(initializer.name)
        for ipt in graph.input:
            ipt.name = self.make_variable_name(ipt.name)
        for output in graph.output:
            output.name = self.make_variable_name(output.name)
        for item in graph.value_info:
            item.name = self.make_variable_name(item.name)
        for node in graph.node:
C
channingss 已提交
496
            node.name = node.output[0]
C
update  
channingss 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
            node.name = self.make_variable_name(node.name)
            for i in range(len(node.input)):
                node.input[i] = self.make_variable_name(node.input[i])
            for i in range(len(node.output)):
                node.output[i] = self.make_variable_name(node.output[i])

    def split_model(self, model, outputs=None):
        """
        Takes a model and changes its outputs.
        """
        if outputs is None:
            raise RuntimeError("outputs is None")
        if outputs == model.graph.output[0].name:
            return model
        nodes = model.graph.node
        keep_nodes = []

        # all the nodes we need to keep.
        for node in nodes:
            if outputs in node.output:
                keep_nodes.append(node)
                break
            keep_nodes.append(node)

        infer_shapes = onnx.shape_inference.infer_shapes(model)

        var_out = []
        for value_info in infer_shapes.graph.value_info:
            if value_info.name == outputs:
                var_out.append(value_info)
                break

        graph = helper.make_graph(keep_nodes, model.graph.name,
                                  model.graph.input, var_out,
                                  model.graph.initializer)

        onnx_model = helper.make_model(graph)
        onnx_model.ir_version = model.ir_version
        onnx_model.producer_name = model.producer_name
        onnx_model.producer_version = model.producer_version
        onnx_model.domain = model.domain
        onnx_model.model_version = model.model_version
        onnx_model.doc_string = model.doc_string

        if len(onnx_model.graph.input) != len(model.graph.input):
            raise RuntimeError("Input mismatch {} != {}".format(
                len(onnx_model.input), len(model.input)))
        return onnx_model