onnx_decoder.py 22.1 KB
Newer Older
C
update  
channingss 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   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
16
from x2paddle.decoder.onnx_shape_inference import SymbolicShapeInference
C
update  
channingss 已提交
17 18
from onnx.checker import ValidationError
from onnx.checker import check_model
C
Channingss 已提交
19
from onnx import helper, shape_inference
C
update  
channingss 已提交
20 21 22 23
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 已提交
24
from onnx import AttributeProto, TensorProto, GraphProto
C
update  
channingss 已提交
25 26
from collections import OrderedDict as Dict
import onnx
C
channingss 已提交
27
from onnx.helper import ValueInfoProto
C
update  
channingss 已提交
28 29
import numpy as np
from copy import deepcopy
C
channingss 已提交
30
import logging as _logging
C
channingss 已提交
31
import os
S
SunAhong1993 已提交
32
import copy
C
update  
channingss 已提交
33 34

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


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.attr_map = self.get_attr_map()
C
channingss 已提交
46
        self.out_shapes = list()
C
update  
channingss 已提交
47
        self.dtype = None
C
channingss 已提交
48
        self.which_child = {}
C
update  
channingss 已提交
49

Y
yeliang2258 已提交
50 51 52 53 54 55 56 57 58 59 60 61
    def get_input_index(self, input_name):
        """
        get the index of input_name in layer.input
        -1 means input_name is not in the input
        """
        index = -1
        for i in range(len(self.layer.input)):
            if input_name == self.layer.input[i]:
                index = i
                break
        return index

C
update  
channingss 已提交
62 63 64 65 66
    def get_attr_map(self):
        """
        convert ONNX node attributes to dict
        """
        return {
67
            attr.name: self.get_attribute_value(attr)
C
update  
channingss 已提交
68 69 70 71 72
            for attr in self.layer.attribute
        }

    @property
    def value(self):
C
channingss 已提交
73 74 75
        assert 'Constant' in self.layer_type, "Only Constant | ConstantOfShape node has value."
        if 'value' not in self.attr_map:
            return None
C
channingss 已提交
76
        return self.attr_map['value']
S
SunAhong1993 已提交
77

S
SunAhong1993 已提交
78 79 80 81 82
    @property
    def name(self):
        if hasattr(self, 'index'):
            return "{}_p{}".format(self.layer_name, self.index)
        return self.layer_name
C
update  
channingss 已提交
83

84
    def get_attribute_value(self, attr):
C
update  
channingss 已提交
85 86 87 88 89 90
        """
        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
91 92
            value = np.frombuffer(
                data, dtype=dtype, count=(len(data) // dtype.itemsize))
C
update  
channingss 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
        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]

C
Channingss 已提交
108
    def output(self, index=0):
S
SunAhong1993 已提交
109 110 111 112
        if index > 0 and len(self.layer.output) <= index:
            raise IndexError(
                'Output numbers of Node:{} is {} <= index:{}'.format(
                    self.layer_name, len(self.layer.output), index))
113
        return self.layer.output[index]
C
Channingss 已提交
114

C
update  
channingss 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128

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.weight = None
        self.embeded_as = None
C
channingss 已提交
129
        self.which_child = {}
C
update  
channingss 已提交
130 131 132

    @property
    def out_shapes(self):
C
channingss 已提交
133 134 135
        if isinstance(self.layer, ValueInfoProto):
            values = self.layer.type.tensor_type.shape.dim
            out_shapes = list()
S
SunAhong1993 已提交
136 137 138 139 140 141 142
            shape = list()
            for dim in values:
                if dim.dim_value == 0:
                    shape.append(-1)
                else:
                    shape.append(dim.dim_value)
            out_shapes.append(shape)
C
channingss 已提交
143
            return out_shapes
S
SunAhong1993 已提交
144 145 146 147 148 149 150 151 152 153 154
        elif isinstance(self.layer, TensorProto):
            values = self.layer.dims
            out_shapes = list()
            shape = list()
            for dim in values:
                if dim == 0:
                    shape.append(-1)
                else:
                    shape.append(dim)
            out_shapes.append(shape)
            return out_shapes
C
channingss 已提交
155 156 157 158 159
        else:
            values = self.layer.dims
            out_shapes = list()
            out_shapes.append(values)
            return out_shapes
S
SunAhong1993 已提交
160

S
SunAhong1993 已提交
161 162 163
    @property
    def name(self):
        return self.layer_name
C
update  
channingss 已提交
164 165 166

    @property
    def dtype(self):
C
channingss 已提交
167 168 169 170 171 172
        if isinstance(self.layer, ValueInfoProto):
            dtype = self.layer.type.tensor_type.elem_type
            return TENSOR_TYPE_TO_NP_TYPE[dtype]
        else:
            dtype = self.layer.data_type
            return TENSOR_TYPE_TO_NP_TYPE[dtype]
C
update  
channingss 已提交
173 174 175


class ONNXGraph(Graph):
C
channingss 已提交
176
    def __init__(self, onnx_model):
177 178
        super(ONNXGraph, self).__init__(onnx_model)
        self.fixed_input_shape = {}
C
update  
channingss 已提交
179 180
        self.initializer = {}
        self.place_holder_nodes = list()
181 182
        self.value_infos = {}
        self.graph = onnx_model.graph
C
update  
channingss 已提交
183
        self.get_place_holder_nodes()
184 185 186
        print("shape inferencing ...")
        self.graph = SymbolicShapeInference.infer_shapes(
            onnx_model, fixed_input_shape=self.fixed_input_shape)
C
Channingss 已提交
187 188 189
        if self.graph is None:
            print('[WARNING] Shape inference by ONNX offical interface.')
            onnx_model = shape_inference.infer_shapes(onnx_model)
S
SunAhong1993 已提交
190
            self.graph = onnx_model.graph
191 192 193 194
        print("shape inferenced.")
        self.build()
        self.collect_value_infos()
        self.allocate_shapes()
S
SunAhong1993 已提交
195
        self.graph_name = "ONNXModel"
C
update  
channingss 已提交
196 197 198 199 200 201

    def get_inner_nodes(self):
        """
        generate inner node of ONNX model
        """
        inner_nodes = []
202
        if not isinstance(self.graph, onnx.GraphProto):
C
update  
channingss 已提交
203 204
            logger.error('graph is not a GraphProto instance')
            return
205
        for initializer in self.graph.initializer:
C
update  
channingss 已提交
206 207 208 209
            name = initializer.name
            inner_nodes.append(name)
        return inner_nodes

210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    def get_symbolic_shape(self, dims):
        shape = []
        for dim in dims:
            if dim.HasField('dim_param'):
                shape.append(dim.dim_param)
            else:
                shape.append(dim.dim_value)
        return shape

    def check_input_shape(self, vi):
        if vi.type.HasField('tensor_type'):
            for dim in vi.type.tensor_type.shape.dim:
                if dim.HasField(
                        'dim_param') and vi.name not in self.fixed_input_shape:
                    shape = self.get_symbolic_shape(
                        vi.type.tensor_type.shape.dim)
                    print(
                        "Unknown shape for input tensor[tensor name: '{}'] -> shape: {}, Please define shape of input here,\nNote:you can use visualization tools like Netron to check input shape."
                        .format(vi.name, shape))
                    right_shape_been_input = False
                    while not right_shape_been_input:
                        try:
                            shape = raw_input(
                                "Shape of Input(e.g. -1,3,224,224), enter 'N' to skip: "
                            )
S
fix  
SunAhong1993 已提交
235
                        except NameError:
236 237 238 239 240 241 242 243 244 245 246 247 248 249
                            shape = input(
                                "Shape of Input(e.g. -1,3,224,224), enter 'N' to skip: "
                            )
                        if shape.count("-1") > 1:
                            print("Only 1 dimension can be -1, type again:)")
                        else:
                            right_shape_been_input = True
                    if shape == 'N':
                        break
                    shape = [int(dim) for dim in shape.strip().split(',')]
                    assert shape.count(-1) <= 1, "Only one dimension can be -1"
                    self.fixed_input_shape[vi.name] = shape
                    break

C
update  
channingss 已提交
250 251 252 253 254
    def get_place_holder_nodes(self):
        """
        generate place_holder node of ONNX model
        """
        inner_nodes = self.get_inner_nodes()
255 256 257 258
        for ipt_vi in self.graph.input:
            if ipt_vi.name not in inner_nodes:
                self.check_input_shape(ipt_vi)
                self.place_holder_nodes.append(ipt_vi.name)
C
update  
channingss 已提交
259

C
channingss 已提交
260 261 262 263
    def get_output_nodes(self):
        """
        generate output_nodes node of ONNX model
        """
C
Channingss 已提交
264
        self.output_nodes = [value.name for value in self.graph.output]
C
channingss 已提交
265

C
update  
channingss 已提交
266 267 268 269 270 271 272 273 274 275 276 277
    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
        """
278
        for layer in self.graph.node:
C
channingss 已提交
279 280
            node = ONNXGraphNode(layer)
            self.node_map[layer.name] = node
C
update  
channingss 已提交
281

282
        for layer in self.graph.input:
C
update  
channingss 已提交
283 284 285 286 287 288
            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 已提交
289

C
update  
channingss 已提交
290
        #set data node's weight
291
        for initializer in self.graph.initializer:
C
channingss 已提交
292 293
            name = initializer.name
            weight = to_array(initializer)
C
update  
channingss 已提交
294 295 296 297
            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 = []
C
channingss 已提交
298
            else:
299 300
                self.node_map[name] = ONNXGraphDataNode(
                    initializer, layer_name=name, is_global_input=False)
C
channingss 已提交
301 302
                self.node_map[name].weight = weight
                self.node_map[name].embeded_as = []
C
update  
channingss 已提交
303 304 305 306

        #generate connection between nodes for topo
        for layer_name, node in self.node_map.items():
            if isinstance(node, ONNXGraphNode):
307
                self.build_connection(layer_name, node)
C
channingss 已提交
308
        #generate topo
C
update  
channingss 已提交
309 310
        super(ONNXGraph, self).build()

S
SunAhong1993 已提交
311
        self.input_nodes = copy.deepcopy(self.place_holder_nodes)
C
update  
channingss 已提交
312

313 314 315 316 317 318 319 320 321
    def build_connection(self, layer_name, node):
        """
        find connection for nodes
        """
        for idx, in_node in enumerate(node.layer.input):
            if in_node == '':
                continue
            if in_node not in self.node_map:
                flag = 0
322
                for nd in self.graph.node:
323 324 325 326
                    for idx, opt in enumerate(nd.output):
                        if opt == in_node:
                            self.connect(nd.name, layer_name)
                            flag = 1
S
fix  
SunAhong1993 已提交
327 328 329 330 331
                            if nd.name in node.which_child:
                                for n_i, n_ipt in enumerate(node.inputs):
                                    if first_i == n_i:
                                        continue
                                    if n_ipt == nd.name:
S
SunAhong1993 已提交
332 333
                                        new_nd_name = "{}/{}".format(nd.name,
                                                                     n_i)
S
fix  
SunAhong1993 已提交
334 335 336 337 338 339
                                        if new_nd_name not in node.which_child:
                                            node.which_child[new_nd_name] = idx
                                            break
                            else:
                                first_i = node.inputs.index(nd.name)
                                node.which_child[nd.name] = idx
340 341 342 343 344 345 346 347 348 349 350
                            self.node_map[nd.name].index = 0
                            break
                    if flag == 1:
                        break
                if flag == 0:
                    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 已提交
351 352
    def get_input_node(self, node, idx=0, copy=False):
        if len(node.which_child) == 0:
C
channingss 已提交
353 354
            ipt_node = super(ONNXGraph, self).get_node(node.inputs[idx], copy)
            return ipt_node
C
channingss 已提交
355 356
        else:
            ipt_node = super(ONNXGraph, self).get_node(node.inputs[idx], copy)
S
fix  
SunAhong1993 已提交
357 358 359 360 361 362
            new_ipt_name = "{}/{}".format(ipt_node.layer_name, idx)
            if new_ipt_name in node.which_child:
                ipt_node.index = node.which_child[new_ipt_name]
            else:
                if ipt_node.layer_name in node.which_child:
                    ipt_node.index = node.which_child[ipt_node.layer_name]
S
SunAhong1993 已提交
363

C
channingss 已提交
364
            return ipt_node
C
update  
channingss 已提交
365

366
    def graph_weights(self):
C
update  
channingss 已提交
367 368 369 370
        """
        generator for weights
        """

371
        if not isinstance(self.graph, onnx.GraphProto):
C
update  
channingss 已提交
372 373 374
            logger.error('graph is not a GraphProto instance')
            return

375
        for initializer in self.graph.initializer:
C
update  
channingss 已提交
376 377 378 379
            name = initializer.name
            weight = to_array(initializer)
            yield name, weight

380
    def collect_value_infos(self):
C
channingss 已提交
381 382 383
        """
        collect value/type info for an ONNX model
        """
384
        assert isinstance(self.graph,
C
channingss 已提交
385 386
                          onnx.GraphProto), 'model is not a ModelProto instance'

387 388
        for item in self.graph.value_info:
            self.value_infos[item.name] = {
C
channingss 已提交
389 390 391 392 393 394
                '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
            }
395 396 397 398 399 400 401 402 403 404 405 406 407

    def allocate_shapes(self):
        """
        run shape inference
        """
        for layer in self.graph.node:
            node = self.node_map[layer.name]
            for opt in layer.output:
                if opt in self.value_infos:
                    value_info = self.value_infos[opt]
                    #if len(value_info['shape']) == 0 or value_info[
                    #        'dtype'] is None or 0 in value_info['shape']:
                    #    #TODO add node shape inference
408 409 410 411 412
                    shape = value_info['shape']
                    for idx in range(len(shape)):
                        if shape[idx] == 0:
                            shape[idx] = -1
                    node.out_shapes.append(shape)
413 414 415
                    node.dtype = value_info['dtype']
                else:
                    node.out_shapes.append([])
C
channingss 已提交
416

C
update  
channingss 已提交
417 418

class ONNXDecoder(object):
C
channingss 已提交
419
    def __init__(self, onnx_model):
420
        onnx_model = onnx.load(onnx_model)
C
update  
channingss 已提交
421
        print('model ir_version: {}, op version: {}'.format(
422 423 424 425 426 427 428 429
            onnx_model.ir_version, onnx_model.opset_import[0].version))
        self.op_set = onnx_model.opset_import[0].version

        check_model(onnx_model)

        onnx_model = self.optimize_model_skip_op(onnx_model)
        onnx_model = self.optimize_node_name(onnx_model)
        self.graph = ONNXGraph(onnx_model)
C
update  
channingss 已提交
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

    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

472
    def optimize_model_skip_op(self, model, op_list=None):
C
update  
channingss 已提交
473 474 475
        """
        skip ops can be bypassed for inference
        """
476
        nodes = model.graph.node
C
update  
channingss 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
        if op_list is None:
            op_list = ['Dropout']
        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 已提交
512 513 514 515 516
                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 已提交
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 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
                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')
W
WJJ1995 已提交
567
        for s in ' .*?\\/-:;':
C
update  
channingss 已提交
568
            name = name.replace(s, '_')
569 570
        return 'x2paddle_' + name

571
    def optimize_node_name(self, model):
C
update  
channingss 已提交
572 573 574
        """
        standardize variable name for paddle's code
        """
575
        graph = model.graph
C
update  
channingss 已提交
576 577 578 579 580 581 582 583 584
        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 已提交
585
            node.name = node.output[0]
W
wjj19950828 已提交
586 587
            if ":" in node.name and len(
                    node.output) > 1 and node.op_type != "LSTM":
W
WJJ1995 已提交
588
                node.name = node.name.split(':')[0]
C
update  
channingss 已提交
589 590
            node.name = self.make_variable_name(node.name)
            for i in range(len(node.input)):
591 592 593 594
                if node.input[i] == '':
                    continue
                else:
                    node.input[i] = self.make_variable_name(node.input[i])
C
update  
channingss 已提交
595 596
            for i in range(len(node.output)):
                node.output[i] = self.make_variable_name(node.output[i])
S
fix  
SunAhong1993 已提交
597
        return model