onnx_converter.py 55.7 KB
Newer Older
L
Liangliang He 已提交
1
# Copyright 2018 The MACE Authors. All Rights Reserved.
L
liutuo 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# 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.


import sys
from enum import Enum
import six
L
liutuo 已提交
19

L
liyin 已提交
20 21 22
from py_proto import mace_pb2
from transform import base_converter
from transform.base_converter import ActivationType
23 24
from transform.base_converter import ConverterUtil
from transform.base_converter import DataFormat
L
liyin 已提交
25 26 27 28
from transform.base_converter import EltwiseType
from transform.base_converter import FrameworkType
from transform.base_converter import MaceOp
from transform.base_converter import MaceKeyword
29 30 31 32 33 34
from transform.base_converter import PoolingType
from transform.base_converter import PaddingMode
from transform.base_converter import PadType
from transform.base_converter import ReduceType
from transform.base_converter import RoundMode

L
liyin 已提交
35 36 37
from utils.util import mace_check

import numpy as np
38

L
liutuo 已提交
39 40
import onnx
import onnx.utils
41
from onnx import mapping, numpy_helper, TensorProto
L
liyin 已提交
42
from numbers import Number
L
liutuo 已提交
43

44
IS_PYTHON3 = sys.version_info > (3,)
L
liutuo 已提交
45

L
liutuo 已提交
46 47 48 49 50 51 52 53 54

class AttributeType(Enum):
    INT = 100
    FLOAT = 101
    INTS = 102
    FLOATS = 103
    BOOL = 104


L
liutuo 已提交
55 56 57 58 59
OnnxSupportedOps = [
    'Abs',
    # 'Acos',
    # 'Acosh',
    'Add',
60
    'Affine',
L
liutuo 已提交
61
    # 'And',
62
    'Append',
L
liutuo 已提交
63 64 65 66 67 68 69 70
    'ArgMax',
    'ArgMin',
    # 'Asin',
    # 'Asinh',
    # 'Atan',
    # 'Atanh',
    'AveragePool',
    'BatchNormalization',
L
liutuo 已提交
71
    'BatchNorm',
L
liutuo 已提交
72 73
    'Cast',
    # 'Ceil',
L
liutuo 已提交
74
    'Clip',
L
liutuo 已提交
75 76
    # 'Compress',
    'Concat',
77
    'Constant',
L
liutuo 已提交
78 79 80 81 82 83
    # 'ConstantLike',
    'Conv',
    'ConvTranspose',
    # 'Cos',
    # 'Cosh',
    'DepthToSpace',
84
    'DimRange',
L
liutuo 已提交
85 86
    'Div',
    'Dropout',
L
liutuo 已提交
87
    'DynamicLSTM',
L
luxuhui 已提交
88
    # 'Elu',
L
liutuo 已提交
89 90 91
    'Equal',
    # 'Exp',
    # 'Expand',
L
liutuo 已提交
92
    'ExtractPooling',
L
liutuo 已提交
93
    # 'EyeLike',
M
mi-pc 已提交
94
    'Flatten',
L
liutuo 已提交
95 96 97 98 99 100 101 102 103 104 105 106
    # 'Floor',
    # 'GRU',
    'Gather',
    'Gemm',
    'GlobalAveragePool',
    # 'GlobalLpPool',
    'GlobalMaxPool',
    # 'Greater',
    # 'HardSigmoid',
    # 'Hardmax',
    'Identity',
    # 'If',
L
liutuo 已提交
107
    'IfDefined',
L
liutuo 已提交
108 109 110
    'ImageScaler',
    # 'InstanceNormalization',
    # 'LRN',
111
    'LSTM',
L
liutuo 已提交
112
    'LstmNonlinear',
L
liutuo 已提交
113 114 115
    'LeakyRelu',
    # 'Less',
    # 'Log',
L
liutuo 已提交
116
    'LogSoftmax',
L
liutuo 已提交
117
    # 'Loop',
118
    'LpNormalization',
L
liutuo 已提交
119 120 121 122 123 124
    # 'LpPool',
    'MatMul',
    'Max',
    'MaxPool',
    # 'MaxRoiPool',
    # 'MaxUnpool',
L
luxuhui 已提交
125
    # 'Mean',
L
liutuo 已提交
126 127 128 129
    'Min',
    'Mul',
    # 'Multinomial',
    'Neg',
130
    'Normalize',
L
liutuo 已提交
131
    # 'Not',
132
    'Offset',
L
liutuo 已提交
133 134 135
    # 'OneHot',
    # 'Or',
    'PRelu',
L
liutuo 已提交
136
    'Pad',
L
liutuo 已提交
137
    'PadContext',
138
    'PNorm',
L
liutuo 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    'Pow',
    # 'RNN',
    # 'RandomNormal',
    # 'RandonNormalLike',
    # 'RandonUniform',
    # 'RandonUniformLike',
    'Reciprocal',
    # 'ReduceL1',
    # 'ReduceL2',
    # 'ReduceLogSum',
    # 'ReduceLogSumExp',
    'ReduceMax',
    'ReduceMean',
    'ReduceMin',
    'ReduceProd',
    # 'ReduceSum',
    # 'ReduceSumSquare',
    'Relu',
L
liutuo 已提交
157
    'ReplaceIndex',
L
liutuo 已提交
158
    'Reshape',
L
liutuo 已提交
159
    'Round',
160
    'Scale',
L
liutuo 已提交
161 162 163 164 165 166 167
    # 'Scan',
    # 'Selu',
    'Shape',
    'Sigmoid',
    # 'Sin',
    # 'Sinh',
    # 'Size',
168
    'Slice',
L
liutuo 已提交
169 170 171 172
    'Softmax',
    # 'Softplus',
    # 'Softsign',
    'SpaceToDepth',
173
    'Splice',
L
liutuo 已提交
174 175 176 177
    'Split',
    'Sqrt',
    'Squeeze',
    'Sub',
L
liutuo 已提交
178
    'Subsample',
L
liutuo 已提交
179
    'Sum',
180
    'SumGroup',
L
liutuo 已提交
181 182
    # 'Tan',
    'Tanh',
183
    'TargetRMSNorm',
L
liutuo 已提交
184 185 186
    # 'Tile',
    # 'TopK',
    'Transpose',
187
    'Unsqueeze',
188
    'Upsample',
L
liutuo 已提交
189 190 191 192 193 194 195 196 197 198
    # 'Xor',
]

OnnxOpType = Enum('OnnxOpType',
                  [(op, op) for op in OnnxSupportedOps],
                  type=str)

onnx_attr_translator = {
    "axis": lambda x: int(x),
    "axes": lambda x: [int(a) for a in x],
L
liutuo 已提交
199
    "dtype": lambda x: onnx_dtype(x),
L
liutuo 已提交
200
    "keepdims": lambda x: bool(x),
L
liutuo 已提交
201
    "to": lambda x: onnx_dtype(x),
L
liutuo 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
}


def translate_onnx(key, val):
    return onnx_attr_translator.get(key, lambda x: x)(val)


def convert_onnx(attr):
    return convert_onnx_attribute_proto(attr)


def convert_onnx_attribute_proto(attr_proto):
    if attr_proto.HasField('f'):
        return attr_proto.f
    elif attr_proto.HasField('i'):
        return attr_proto.i
    elif attr_proto.HasField('s'):
        return str(attr_proto.s, 'utf-8')\
220
            if IS_PYTHON3 else attr_proto.s
L
liutuo 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    elif attr_proto.HasField('t'):
        return attr_proto.t  # this is a proto!
    elif attr_proto.floats:
        return list(attr_proto.floats)
    elif attr_proto.ints:
        return list(attr_proto.ints)
    elif attr_proto.strings:
        str_list = list(attr_proto.strings)
        if IS_PYTHON3:
            str_list = map(lambda x: str(x, 'utf-8'), str_list)
        return str_list
    else:
        raise ValueError("Unsupported ONNX attribute: {}".format(attr_proto))


def onnx_dtype(dtype):
    if isinstance(dtype, Number):
        onnx_dtype = dtype
    elif isinstance(dtype, str):
        onnx_dtype = TensorProto.DataType.Value(dtype)
    else:
        raise RuntimeError("dtype should be number or str.")
    return mapping.TENSOR_TYPE_TO_NP_TYPE[onnx_dtype]


class OnnxNode(object):
    def __init__(self, node):
        self.name = str(node.name)
Y
yytdfc 已提交
249
        if self.name == '':
250
            self.name = str(node.output)
L
liutuo 已提交
251 252 253 254 255 256 257 258 259 260
        self.op_type = str(node.op_type)
        self.domain = str(node.domain)
        self.attrs = dict([(attr.name,
                            translate_onnx(attr.name, convert_onnx(attr)))
                           for attr in node.attribute])
        self.inputs = list(node.input)
        self.outputs = list(node.output)
        self.node_proto = node

    def print_info(self):
261 262 263 264 265 266
        print("node: ", self.name)
        print("    type: ", self.op_type)
        print("    domain: ", self.domain)
        print("    inputs: ", self.inputs)
        print("    outputs: ", self.outputs)
        print("    attrs:")
L
liutuo 已提交
267
        for arg in self.attrs:
268
            print("        %s: %s" % (arg, self.attrs[arg]))
L
liutuo 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306


class OnnxTensor(object):
    def __init__(self, name, value, shape, dtype):
        self._name = name
        self._tensor_data = value
        self._shape = shape
        self._dtype = dtype


class OnnxConverter(base_converter.ConverterInterface):
    pooling_type_mode = {
        OnnxOpType.AveragePool.name: PoolingType.AVG,
        OnnxOpType.MaxPool.name: PoolingType.MAX
    }

    auto_pad_mode = {
        'NOTSET': PaddingMode.NA,
        'SAME_UPPER': PaddingMode.SAME,
        'SAME_LOWER': PaddingMode.SAME,
        'VALID': PaddingMode.VALID,
    }
    auto_pad_mode = {six.b(k): v for k, v in six.iteritems(auto_pad_mode)}

    eltwise_type = {
        OnnxOpType.Mul.name: EltwiseType.PROD,
        OnnxOpType.Add.name: EltwiseType.SUM,
        OnnxOpType.Max.name: EltwiseType.MAX,
        OnnxOpType.Min.name: EltwiseType.MIN,
        OnnxOpType.Abs.name: EltwiseType.ABS,
        OnnxOpType.Pow.name: EltwiseType.POW,
        OnnxOpType.Sub.name: EltwiseType.SUB,
        OnnxOpType.Div.name: EltwiseType.DIV,
        OnnxOpType.Neg.name: EltwiseType.NEG,
        OnnxOpType.Sum.name: EltwiseType.SUM,
        OnnxOpType.Equal.name: EltwiseType.EQUAL,
        OnnxOpType.Sqrt.name: EltwiseType.POW,
        OnnxOpType.Reciprocal.name: EltwiseType.POW,
307
        OnnxOpType.Scale.name: EltwiseType.PROD,
L
liutuo 已提交
308
        OnnxOpType.Clip.name: EltwiseType.CLIP,
L
liutuo 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321
    }

    reduce_type = {
        OnnxOpType.GlobalAveragePool.name: ReduceType.MEAN,
        OnnxOpType.GlobalMaxPool.name: ReduceType.MAX,
        OnnxOpType.ReduceMax.name: ReduceType.MAX,
        OnnxOpType.ReduceMean.name: ReduceType.MEAN,
        OnnxOpType.ReduceMin.name: ReduceType.MIN,
        OnnxOpType.ReduceProd.name: ReduceType.PROD,
    }

    activation_type = {
        OnnxOpType.Relu.name: ActivationType.RELU,
Y
yejianwu 已提交
322
        OnnxOpType.LeakyRelu.name: ActivationType.LEAKYRELU,
L
liutuo 已提交
323 324 325 326 327 328 329 330 331
        OnnxOpType.PRelu.name: ActivationType.PRELU,
        OnnxOpType.Tanh.name: ActivationType.TANH,
        OnnxOpType.Sigmoid.name: ActivationType.SIGMOID,
    }

    def __init__(self, option, src_model_file):
        self._op_converters = {
            OnnxOpType.Abs.name: self.convert_eltwise,
            OnnxOpType.Add.name: self.convert_eltwise,
332 333
            OnnxOpType.Affine.name: self.convert_affine,
            OnnxOpType.Append.name: self.convert_concat,
L
liutuo 已提交
334 335 336 337
            OnnxOpType.ArgMax.name: self.convert_argmax,
            OnnxOpType.ArgMin.name: self.convert_argmax,
            OnnxOpType.AveragePool.name: self.convert_pooling,
            OnnxOpType.BatchNormalization.name: self.convert_fused_batchnorm,
L
liutuo 已提交
338
            OnnxOpType.BatchNorm.name: self.convert_fused_batchnorm,
L
liutuo 已提交
339
            OnnxOpType.Cast.name: self.convert_cast,
L
liutuo 已提交
340
            OnnxOpType.Clip.name: self.convert_clip,
L
liutuo 已提交
341 342 343
            OnnxOpType.Concat.name: self.convert_concat,
            OnnxOpType.Conv.name: self.convert_conv2d,
            OnnxOpType.ConvTranspose.name: self.convert_deconv,
344
            OnnxOpType.Constant.name: self.convert_constant,
L
liutuo 已提交
345
            OnnxOpType.DepthToSpace.name: self.convert_depth_space,
L
liutuo 已提交
346
            OnnxOpType.Dropout.name: self.convert_dropout,
347
            OnnxOpType.DimRange.name: self.convert_dim_range,
L
liutuo 已提交
348 349
            OnnxOpType.Div.name: self.convert_eltwise,
            OnnxOpType.Equal.name: self.convert_eltwise,
L
liutuo 已提交
350
            OnnxOpType.ExtractPooling.name: self.convert_extract_pooling,
M
mi-pc 已提交
351
            OnnxOpType.Flatten.name: self.convert_flatten,
L
liutuo 已提交
352
            OnnxOpType.Gather.name: self.convert_gather,
L
liutuo 已提交
353
            OnnxOpType.Gemm.name: self.convert_gemm,
L
liutuo 已提交
354 355 356
            OnnxOpType.GlobalAveragePool.name: self.convert_reduce,
            OnnxOpType.GlobalMaxPool.name: self.convert_reduce,
            OnnxOpType.Identity.name: self.convert_identity,
L
liutuo 已提交
357
            OnnxOpType.IfDefined.name: self.convert_ifdefined,
L
liutuo 已提交
358 359
            OnnxOpType.ImageScaler.name: self.convert_imagescaler,
            OnnxOpType.LeakyRelu.name: self.convert_activation,
L
liutuo 已提交
360
            OnnxOpType.LogSoftmax.name: self.convert_softmax,
361
            OnnxOpType.LpNormalization: self.convert_lpnormalization,
L
liutuo 已提交
362
            OnnxOpType.LstmNonlinear.name: self.convert_lstm_nonlinear,
L
liutuo 已提交
363
            OnnxOpType.DynamicLSTM.name: self.convert_dynamic_lstm,
L
liutuo 已提交
364 365 366 367 368 369
            OnnxOpType.Max.name: self.convert_eltwise,
            OnnxOpType.MaxPool.name: self.convert_pooling,
            OnnxOpType.MatMul.name: self.convert_matmul,
            OnnxOpType.Min.name: self.convert_eltwise,
            OnnxOpType.Mul.name: self.convert_eltwise,
            OnnxOpType.Neg.name: self.convert_eltwise,
370
            OnnxOpType.Normalize: self.convert_normalize,
L
liutuo 已提交
371
            OnnxOpType.Offset.name: self.convert_subsample,
L
liutuo 已提交
372
            OnnxOpType.Pad.name: self.convert_pad,
L
liutuo 已提交
373
            OnnxOpType.PadContext.name: self.convert_pad_context,
374
            OnnxOpType.PNorm.name: self.convert_pnorm,
L
liutuo 已提交
375 376 377 378 379
            OnnxOpType.Pow.name: self.convert_eltwise,
            OnnxOpType.PRelu.name: self.convert_activation,
            OnnxOpType.Relu.name: self.convert_activation,
            OnnxOpType.Reshape.name: self.convert_reshape,
            OnnxOpType.Reciprocal.name: self.convert_eltwise,
L
luxuhui 已提交
380
            OnnxOpType.ReduceMax.name: self.convert_reduce,
L
liutuo 已提交
381
            OnnxOpType.ReduceMean.name: self.convert_reduce,
L
luxuhui 已提交
382 383
            OnnxOpType.ReduceMin.name: self.convert_reduce,
            OnnxOpType.ReduceProd.name: self.convert_reduce,
L
liutuo 已提交
384 385
            OnnxOpType.ReplaceIndex.name: self.convert_replaceindex,
            OnnxOpType.Round.name: self.convert_replaceindex,
386
            OnnxOpType.Scale.name: self.convert_eltwise,
387
            OnnxOpType.Shape.name: self.convert_shape,
L
liutuo 已提交
388
            OnnxOpType.Sigmoid.name: self.convert_activation,
389
            OnnxOpType.Slice.name: self.convert_slice,
L
liutuo 已提交
390 391
            OnnxOpType.Softmax.name: self.convert_softmax,
            OnnxOpType.SpaceToDepth.name: self.convert_depth_space,
392
            OnnxOpType.Splice.name: self.convert_splice,
L
liutuo 已提交
393 394 395 396
            OnnxOpType.Split.name: self.convert_split,
            OnnxOpType.Sqrt.name: self.convert_eltwise,
            OnnxOpType.Squeeze.name: self.convert_squeeze,
            OnnxOpType.Sub.name: self.convert_eltwise,
L
liutuo 已提交
397
            OnnxOpType.Subsample.name: self.convert_subsample,
L
liutuo 已提交
398
            OnnxOpType.Sum.name: self.convert_eltwise,
399
            OnnxOpType.SumGroup.name: self.convert_sum_group,
L
liutuo 已提交
400
            OnnxOpType.Tanh.name: self.convert_activation,
401
            OnnxOpType.TargetRMSNorm: self.convert_target_rms_norm,
L
liutuo 已提交
402
            OnnxOpType.Transpose.name: self.convert_transpose,
403
            OnnxOpType.Unsqueeze.name: self.convert_unsqueeze,
404
            OnnxOpType.Upsample.name: self.convert_upsample
L
liutuo 已提交
405 406 407
        }
        self._option = option
        self._mace_net_def = mace_pb2.NetDef()
408
        self._data_format = DataFormat.NCHW
409
        ConverterUtil.set_filter_format(self._mace_net_def, DataFormat.OIHW)
410 411
        ConverterUtil.add_data_format_arg(self._mace_net_def,
                                          self._data_format)
L
liutuo 已提交
412 413
        onnx_model = onnx.load(src_model_file)

414 415 416
        ir_version = onnx_model.ir_version
        opset_imp = onnx_model.opset_import

L
liutuo 已提交
417 418
        onnx.checker.check_model(onnx_model)

L
liutuo 已提交
419 420
        self._isKaldi = False

421
        polish_available = True
422
        print("onnx model IR version: ", ir_version)
423 424 425
        for imp in opset_imp:
            domain = imp.domain
            version = imp.version
426
            print("constains ops domain: ", domain, "version:", version)
L
liutuo 已提交
427
            if 'kaldi' in domain:
428
                polish_available = False
429
                self._data_format = DataFormat.NONE
L
liutuo 已提交
430
                self._isKaldi = True
431 432 433 434
        if polish_available:
            onnx_model = onnx.utils.polish_model(onnx_model)

        self._onnx_model = onnx_model
L
liutuo 已提交
435 436 437 438
        self._graph_shapes_dict = {}
        self._consts = {}
        self._replace_tensors = {}

439 440
    @staticmethod
    def print_graph_info(graph):
L
liutuo 已提交
441
        for value_info in graph.value_info:
442
            print("value info:", value_info)
L
liutuo 已提交
443
        for value_info in graph.input:
444
            print("inputs info:", value_info)
L
liutuo 已提交
445
        for value_info in graph.output:
446
            print("outputs info:", value_info)
L
liutuo 已提交
447 448 449 450 451 452 453 454

    def extract_shape_info(self, graph):
        def extract_value_info(shape_dict, value_info):
            t = tuple([int(dim.dim_value)
                       for dim in value_info.type.tensor_type.shape.dim])
            if t:
                shape_dict[value_info.name] = t

455 456 457 458 459 460
        for vi in graph.value_info:
            extract_value_info(self._graph_shapes_dict, vi)
        for vi in graph.input:
            extract_value_info(self._graph_shapes_dict, vi)
        for vi in graph.output:
            extract_value_info(self._graph_shapes_dict, vi)
L
liutuo 已提交
461 462 463 464 465 466

    def add_tensor(self, name, shape, data_type, value):
        tensor = self._mace_net_def.tensors.add()
        tensor.name = name
        tensor.dims.extend(list(shape))
        tensor.data_type = data_type
467 468 469 470 471 472 473

        if tensor.data_type == mace_pb2.DT_INT32:
            tensor.int32_data.extend(value.astype(np.int32).flat)
        elif tensor.data_type == mace_pb2.DT_FLOAT:
            tensor.float_data.extend(value.astype(np.float32).flat)
        else:
            mace_check(False, "Not supported tensor type: %s" % name)
L
liutuo 已提交
474 475 476 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

    def run(self):
        graph_def = self._onnx_model.graph
        self.extract_shape_info(graph_def)
        self.convert_tensors(graph_def)
        self.convert_ops(graph_def)
        return self._mace_net_def

    def add_stride_pad_kernel_arg(self, attrs, op_def):
        if 'strides' in attrs:
            strides = attrs['strides']
            mace_check(len(strides) == 2, "strides should has 2 values.")
            stride = [strides[0], strides[1]]
        else:
            stride = [1, 1]

        strides_arg = op_def.arg.add()
        strides_arg.name = MaceKeyword.mace_strides_str
        strides_arg.ints.extend(stride)

        if 'kernel_shape' in attrs:
            kernel_shape = attrs['kernel_shape']
            mace_check(len(kernel_shape) == 2,
                       "kernel shape should has 2 values.")
            kernel = [kernel_shape[0], kernel_shape[1]]
            kernels_arg = op_def.arg.add()
            kernels_arg.name = MaceKeyword.mace_kernel_str
            kernels_arg.ints.extend(kernel)

L
liutuo 已提交
503
        # TODO: Does not support AutoPad yet.
L
liutuo 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
        if 'pads' in attrs:
            pads = attrs['pads']
            if len(pads) == 4:
                pad = [pads[0] + pads[2], pads[1] + pads[3]]
            else:
                pad = [0, 0]
            padding_arg = op_def.arg.add()
            padding_arg.name = MaceKeyword.mace_padding_values_str
            padding_arg.ints.extend(pad)
        elif 'auto_pad' in attrs:
            auto_pad_arg = op_def.arg.add()
            auto_pad_arg.name = MaceKeyword.mace_padding_str
            auto_pad_arg.i = self.auto_pad_mode[attrs['auto_pad']].value
        else:
            pad = [0, 0]
            padding_arg = op_def.arg.add()
            padding_arg.name = MaceKeyword.mace_padding_values_str
            padding_arg.ints.extend(pad)

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
    def remove_node(self, node):
        input_name = node.inputs[0]
        output_name = node.outputs[0]
        self._replace_tensors[output_name] = input_name

    @staticmethod
    def squeeze_shape(shape, axis):
        new_shape = []
        if len(axis) > 0:
            for i in range(len(shape)):
                if i not in axis:
                    new_shape.append(shape[i])
        else:
            new_shape = shape
        return new_shape

539 540 541 542 543 544 545
    @staticmethod
    def unsqueeze_shape(shape, axis):
        new_shape = [n for n in shape]
        for n in axis:
            new_shape.insert(n, 1)
        return new_shape

546 547 548 549 550 551 552 553 554 555
    @staticmethod
    def transpose_const(tensor):
        shape = tensor.dims
        mace_check(len(shape) == 2, "gemm only supports 2-dim input.")
        tensor_data = np.array(tensor.float_data).reshape(
            shape[0], shape[1])
        tensor_data = tensor_data.transpose(1, 0)
        tensor.float_data[:] = tensor_data.flat
        tensor.dims[:] = tensor_data.shape

L
liutuo 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    def convert_ops(self, graph_def):
        for n in graph_def.node:
            node = OnnxNode(n)
            mace_check(node.op_type in self._op_converters,
                       "Mace does not support onnx op type %s yet"
                       % node.op_type)
            self._op_converters[node.op_type](node)

    def convert_tensors(self, graph_def):
        initializer = graph_def.initializer
        if initializer:
            for init in initializer:
                tensor = self._mace_net_def.tensors.add()
                tensor.name = init.name

                onnx_tensor = numpy_helper.to_array(init)
                tensor.dims.extend(list(init.dims))
                data_type = onnx_dtype(init.data_type)

                if data_type == np.float32 or data_type == np.float64:
                    tensor.data_type = mace_pb2.DT_FLOAT
                    tensor.float_data.extend(
                        onnx_tensor.astype(np.float32).flat)
L
liutuo 已提交
579
                elif data_type == np.int64 or data_type == np.int32:
L
liutuo 已提交
580 581 582 583 584 585 586 587
                    tensor.data_type = mace_pb2.DT_INT32
                    tensor.int32_data.extend(
                        onnx_tensor.astype(np.int32).flat)
                else:
                    mace_check(False,
                               "Not supported tensor type: %s" % data_type)
                self._consts[tensor.name] = tensor

588
    def convert_general_op(self, node, with_shape=True):
L
liutuo 已提交
589 590 591 592 593 594 595 596 597
        op = self._mace_net_def.op.add()
        op.name = node.name

        for input in node.inputs:
            if input in self._replace_tensors:
                input = self._replace_tensors[input]
            op.input.append(input)
        for output in node.outputs:
            op.output.append(output)
598 599 600 601 602
            if with_shape:
                if output in self._graph_shapes_dict:
                    output_shape = op.output_shape.add()
                    shape_info = self._graph_shapes_dict[output]
                    output_shape.dims.extend(shape_info)
L
liutuo 已提交
603 604 605 606 607 608 609 610 611

        data_type_arg = op.arg.add()
        data_type_arg.name = 'T'
        data_type_arg.i = self._option.data_type

        framework_type_arg = op.arg.add()
        framework_type_arg.name = MaceKeyword.mace_framework_type_str
        framework_type_arg.i = FrameworkType.ONNX.value

612
        ConverterUtil.add_data_format_arg(op, self._data_format)
L
liutuo 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625
        return op

    def convert_activation(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Activation.name

        type_arg = op.arg.add()
        type_arg.name = MaceKeyword.mace_activation_type_str
        type_arg.s = six.b(self.activation_type[node.op_type].name)

        if "alpha" in node.attrs:
            alpha_value = node.attrs["alpha"]
        else:
L
liutuo 已提交
626 627 628 629
            if node.op_type == OnnxOpType.LeakyRelu.name:
                alpha_value = 0.01
            else:
                alpha_value = 0
L
liutuo 已提交
630
        alpha_arg = op.arg.add()
631
        alpha_arg.name = MaceKeyword.mace_activation_leakyrelu_coefficient_str
L
liutuo 已提交
632 633
        alpha_arg.f = alpha_value

634
    def convert_affine(self, node):
L
liutuo 已提交
635 636
        op = self.convert_general_op(node)
        op.type = MaceOp.MatMul.name
637 638 639
        transpose_b_arg = op.arg.add()
        transpose_b_arg.name = MaceKeyword.mace_transpose_b_str
        transpose_b_arg.i = 1
L
liutuo 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665

    def convert_argmax(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.ArgMax.name

        if 'axis' in node.attrs:
            axis_value = node.attrs['axis']
        else:
            axis_value = 0
        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
        axis_arg.i = axis_value

        if 'keepdims' in node.attrs:
            keepdims = node.attrs['keepdims']
        else:
            keepdims = 1
        keep_dims_arg = op.arg.add()
        keep_dims_arg.name = MaceKeyword.mace_keepdims_str
        keep_dims_arg.i = keepdims

        if node.op_type == OnnxOpType.ArgMin.name:
            min_arg = op.arg.add()
            min_arg.name = MaceKeyword.mace_argmin_str
            min_arg.i = 1

666 667 668 669
    def convert_biasadd(self, node):
        self.convert_general_op(node)
        op.type = MaceOp.BiasAdd.name

L
liutuo 已提交
670 671 672 673 674 675
    def convert_cast(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Cast.name

        if 'to' in node.attrs:
            dtype = node.attrs['to']
L
liutuo 已提交
676
            if dtype == np.float32 or dtype == np.float64:
L
liutuo 已提交
677
                op.output_type.extend([self._option.data_type])
L
liutuo 已提交
678
            elif dtype == np.int64 or dtype == np.int32:
L
liutuo 已提交
679 680 681 682 683 684
                op.output_type.extend([mace_pb2.DT_INT32])
            else:
                mace_check(False, "data type %s not supported" % dtype)
        else:
            op.output_type.extend([self._option.data_type])

685
    def convert_concat(self, node):
L
liutuo 已提交
686
        op = self.convert_general_op(node)
687
        op.type = MaceOp.Concat.name
L
liutuo 已提交
688
        if self._isKaldi is False:
689 690 691
            mace_check('axis' in node.attrs,
                       'Concat op should have axis attribute.')
            axis_value = node.attrs['axis']
L
liutuo 已提交
692
        else:
L
liutuo 已提交
693
            axis_value = -1
694 695
        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
L
liutuo 已提交
696
        axis_arg.i = axis_value
L
liutuo 已提交
697

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    def convert_constant(self, node):
        output_name = node.outputs[0]
        tensor = self._mace_net_def.tensors.add()
        tensor.name = output_name
        onnx_tensor = node.attrs['value']
        tensor_value = numpy_helper.to_array(onnx_tensor)
        tensor.dims.extend(list(onnx_tensor.dims))
        data_type = onnx_dtype(onnx_tensor.data_type)

        if data_type == np.float32 or data_type == np.float64:
            tensor.data_type = mace_pb2.DT_FLOAT
            tensor.float_data.extend(
                tensor_value.astype(np.float32).flat)
        elif data_type == np.int32 or data_type == np.int64:
            tensor.data_type = mace_pb2.DT_INT32
            tensor.int32_data.extend(
                tensor_value.astype(np.int32).flat)
        else:
            mace_check(False,
                       "Not supported tensor type: %s" % data_type)
        self._consts[tensor.name] = tensor

720
    def convert_conv2d(self, node):
L
liutuo 已提交
721 722
        op = self.convert_general_op(node)
        self.add_stride_pad_kernel_arg(node.attrs, op)
723 724
        group_arg = op.arg.add()
        group_arg.name = MaceKeyword.mace_group_str
L
liutuo 已提交
725 726 727 728
        if 'group' in node.attrs:
            group_val = node.attrs["group"]
        else:
            group_val = 1
729 730 731
        group_arg.i = group_val

        is_depthwise = False
L
liutuo 已提交
732 733
        if group_val > 1:
            filter_shape = self._graph_shapes_dict[node.inputs[1]]
734 735 736
            mace_check(group_val == filter_shape[0] and
                       filter_shape[1] == 1,
                       "Mace does not support group convolution yet")
L
liutuo 已提交
737 738 739 740 741
            filter_tensor = self._consts[node.inputs[1]]
            new_shape = [filter_shape[1], filter_shape[0],
                         filter_shape[2], filter_shape[3]]
            del filter_tensor.dims[:]
            filter_tensor.dims.extend(new_shape)
742 743 744
            is_depthwise = True
        if is_depthwise:
            op.type = MaceOp.DepthwiseConv2d.name
L
liutuo 已提交
745
        else:
746
            op.type = MaceOp.Conv2D.name
747 748
            mace_check(op.input[1] in self._consts,
                       "Mace does not support non-const filter convolution.")
L
liutuo 已提交
749 750 751 752 753 754 755 756 757

        dilation_arg = op.arg.add()
        dilation_arg.name = MaceKeyword.mace_dilations_str
        if 'dilations' in node.attrs:
            dilation_val = node.attrs["dilations"]
        else:
            dilation_val = [1, 1]
        dilation_arg.ints.extend(dilation_val)

758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    def convert_deconv(self, node):
        op = self.convert_general_op(node)

        self.add_stride_pad_kernel_arg(node.attrs, op)

        if 'group' in node.attrs:
            group_val = node.attrs["group"]
        else:
            group_val = 1
        if group_val > 1:
            op.type = MaceOp.DepthwiseDeconv2d.name
            filter_shape = self._graph_shapes_dict[node.inputs[1]]
            filter_tensor = self._consts[node.inputs[1]]
            new_shape = [filter_shape[1], filter_shape[0],
                         filter_shape[2], filter_shape[3]]
            del filter_tensor.dims[:]
            filter_tensor.dims.extend(new_shape)
        else:
            op.type = MaceOp.Deconv2D.name
        group_arg = op.arg.add()
        group_arg.name = MaceKeyword.mace_group_str
        group_arg.i = group_val

        dilation_arg = op.arg.add()
        dilation_arg.name = MaceKeyword.mace_dilations_str
        if 'dilations' in node.attrs:
            dilation_val = node.attrs["dilations"]
        else:
            dilation_val = [1, 1]
        dilation_arg.ints.extend(dilation_val)
        mace_check(dilation_val == [1, 1],
                   "not support convtranspose with dilation != 1 yet.")

        mace_check('output_padding' not in node.attrs,
                   "not support convtranspose with output_padding yet.")
        mace_check('output_shape' not in node.attrs,
                   "not support convtranspose with output_shape yet.")
        # TODO: if output shape specified, calculate padding value
        # if 'output_padding' in node.attrs:
        #     output_padding = node.attrs['output_padding']
L
liutuo 已提交
798 799 800 801 802 803 804 805 806
        #     output_padding_arg = op.arg.add()
        #     output_padding_arg.name = MaceKeyword.mace_output_padding_str
        #     output_padding_arg.ints.extend(output_padding)
        # if 'output_shape' in node.attrs:
        #     output_shape = node.attrs['output_shape']
        #     output_shape_arg = op.arg.add()
        #     output_shape_arg.name = MaceKeyword.mace_output_shape_str
        #     output_shape_arg.ints.extend(output_shape)

807 808 809 810 811 812 813 814 815 816 817 818
    def convert_depth_space(self, node):
        op = self.convert_general_op(node)
        if op.type == OnnxOpType.DepthToSpace.name:
            op.type = MaceOp.DepthToSpace.name
        else:
            op.type = MaceOp.SpaceToDepth.name
        mace_check(('block_size' in node.attrs),
                   "depth to space op should have block size attribute.")
        block_size = node.attrs['block_size']
        size_arg = op.arg.add()
        size_arg.name = MaceKeyword.mace_space_depth_block_size_str
        size_arg.i = block_size
L
liutuo 已提交
819

820
    def convert_dim_range(self, node):
L
liutuo 已提交
821
        op = self.convert_general_op(node)
822 823 824 825 826 827 828 829 830
        op.type = MaceOp.Slice.name

        mace_check('offset' in node.attrs,
                   "Attribute dim required!")
        mace_check('output_dim' in node.attrs,
                   "Attribute output_dim required!")
        offset = node.attrs['offset']
        starts_arg = op.arg.add()
        starts_arg.name = 'starts'
L
liutuo 已提交
831
        starts_arg.ints.extend([offset])
832 833
        output_dim = node.attrs['output_dim']
        ends_arg = op.arg.add()
L
liutuo 已提交
834 835
        ends_arg.name = 'ends'
        ends_arg.ints.extend([output_dim + offset])
836 837
        axes_arg = op.arg.add()
        axes_arg.name = 'axes'
L
liutuo 已提交
838 839
        axes_arg.ints.extend([-1])

L
liutuo 已提交
840 841 842 843 844 845
    def convert_dropout(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Identity.name
        del op.output[1:]
        del op.output_shape[1:]

L
liutuo 已提交
846 847 848 849
    def convert_dynamic_lstm(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.DynamicLSTM.name

L
liutuo 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
        self.copy_node_attr(op, node, 'prev_out_delay',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'prev_cell_delay',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'prev_out_offset',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'prev_out_dim',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'prev_cell_dim',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'bias_a',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'bias_b',
                            AttributeType.INT)
        self.copy_node_attr(op, node, 'scale',
                            AttributeType.FLOAT)
        self.copy_node_attr(op, node, 'subsample_factor',
                            AttributeType.INT, default=1)
        self.copy_node_attr(op, node, 'cell_cache_indexes',
                            AttributeType.INTS, default=[])
        self.copy_node_attr(op, node, 'out_cache_indexes',
                            AttributeType.INTS, default=[])
        self.copy_node_attr(op, node, 'forward_indexes',
                            AttributeType.INTS)
L
liutuo 已提交
874

L
liutuo 已提交
875
    def convert_clip(self, node):
M
mi-pc 已提交
876 877 878
        #  If clip's min value is zero,
        #  convert clip to activation(ReLU or ReLUX)
        #  so it can be fused into convolution.
L
liutuo 已提交
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        is_relux = False
        if 'min' in node.attrs:
            min_value = node.attrs['min']
            if min_value == 0:
                is_relux = True
        if is_relux:
            op = self.convert_general_op(node)
            op.type = MaceOp.Activation.name

            type_arg = op.arg.add()
            type_arg.name = MaceKeyword.mace_activation_type_str
            if "max" in node.attrs:
                max_value = node.attrs["max"]
                type_arg.s = six.b(ActivationType.RELUX.name)
                alpha_arg = op.arg.add()
                alpha_arg.name = MaceKeyword.mace_activation_max_limit_str
                alpha_arg.f = max_value
            else:
                type_arg.s = six.b(ActivationType.RELU.name)
        else:
            self.convert_eltwise(node)

901
    def convert_eltwise(self, node):
L
liutuo 已提交
902
        op = self.convert_general_op(node)
903 904 905 906
        op.type = MaceOp.Eltwise.name
        type_arg = op.arg.add()
        type_arg.name = MaceKeyword.mace_element_type_str
        type_arg.i = self.eltwise_type[node.op_type].value
L
liutuo 已提交
907

908 909 910 911 912 913 914 915 916 917 918 919 920
        if node.op_type == OnnxOpType.Sqrt.name:
            value_arg = op.arg.add()
            value_arg.name = MaceKeyword.mace_scalar_input_str
            value_arg.f = 0.5
        elif node.op_type == OnnxOpType.Reciprocal.name:
            value_arg = op.arg.add()
            value_arg.name = MaceKeyword.mace_scalar_input_str
            value_arg.f = -1
        elif node.op_type == OnnxOpType.Scale.name and 'scale' in node.attrs:
            value = node.attrs['scale']
            value_arg = op.arg.add()
            value_arg.name = MaceKeyword.mace_scalar_input_str
            value_arg.f = value
L
liutuo 已提交
921 922 923 924 925 926 927 928 929 930 931 932
        elif node.op_type == OnnxOpType.Clip.name:
            if 'min' in node.attrs:
                min_value = node.attrs['min']
            else:
                min_value = np.finfo(np.float32).min
            if 'max' in node.attrs:
                max_value = node.attrs['max']
            else:
                max_value = np.finfo(np.float32).max
            coeff_arg = op.arg.add()
            coeff_arg.name = MaceKeyword.mace_coeff_str
            coeff_arg.floats.extend([min_value, max_value])
L
liutuo 已提交
933 934 935 936 937 938 939 940
        elif len(node.inputs) == 2:
            if node.inputs[1] in self._consts and \
                    node.inputs[0] not in self._consts:
                const_name = node.inputs[1]
                const_tensor = self._consts[const_name]
                if len(const_tensor.dims) == 0:
                    value_arg = op.arg.add()
                    value_arg.name = MaceKeyword.mace_scalar_input_str
L
liutuo 已提交
941 942 943 944 945 946 947 948
                    if const_tensor.data_type == mace_pb2.DT_INT32:
                        value_arg.f = float(const_tensor.int32_data[0])
                    elif const_tensor.data_type == mace_pb2.DT_FLOAT:
                        value_arg.f = const_tensor.float_data[0]
                    else:
                        mace_check(False,
                                   "Does not support param's data type %s"
                                   % const_tensor.data_type)
L
liutuo 已提交
949 950 951 952 953 954 955 956 957 958 959 960
                    value_index_arg = op.arg.add()
                    value_index_arg.name = \
                        MaceKeyword.mace_scalar_input_index_str
                    value_index_arg.i = 1
                    del op.input[1]
            elif node.inputs[0] in self._consts and \
                    node.inputs[1] not in self._consts:
                const_name = node.inputs[0]
                const_tensor = self._consts[const_name]
                if len(const_tensor.dims) == 0:
                    value_arg = op.arg.add()
                    value_arg.name = MaceKeyword.mace_scalar_input_str
L
liutuo 已提交
961 962 963 964 965 966 967 968
                    if const_tensor.data_type == mace_pb2.DT_INT32:
                        value_arg.f = float(const_tensor.int32_data[0])
                    elif const_tensor.data_type == mace_pb2.DT_FLOAT:
                        value_arg.f = const_tensor.float_data[0]
                    else:
                        mace_check(False,
                                   "Does not support param's data type %s"
                                   % const_tensor.data_type)
L
liutuo 已提交
969 970 971 972 973
                    value_index_arg = op.arg.add()
                    value_index_arg.name = \
                        MaceKeyword.mace_scalar_input_index_str
                    value_index_arg.i = 0
                    del op.input[0]
L
liutuo 已提交
974

L
liutuo 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
    @staticmethod
    def copy_node_attr(op, node, attr_name, dtype=AttributeType.INT,
                       default=None):
        if attr_name in node.attrs or default is not None:
            if attr_name in node.attrs:
                value = node.attrs[attr_name]
            else:
                value = default
            new_arg = op.arg.add()
            new_arg.name = attr_name
            if dtype == AttributeType.INT:
                new_arg.i = int(value)
            elif dtype == AttributeType.FLOAT:
                new_arg.f = float(value)
            elif dtype == AttributeType.INTS:
                new_arg.ints.extend(value)
            elif dtype == AttributeType.FLOATS:
                new_arg.floats.extend(value)
            return value
        else:
            return default

    def convert_extract_pooling(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.ExtractPooling.name

        self.copy_node_attr(op, node, 'include_variance', AttributeType.INT)
        self.copy_node_attr(op, node, 'num_log_count', AttributeType.INT)
        self.copy_node_attr(op, node, 'variance_floor', AttributeType.FLOAT)
L
liutuo 已提交
1004 1005
        self.copy_node_attr(op, node, 'counts', AttributeType.FLOATS)
        self.copy_node_attr(op, node, 'forward_indexes', AttributeType.INTS)
L
liutuo 已提交
1006

1007 1008 1009
    def convert_flatten(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Reshape.name
M
mi-pc 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
        axis_arg.i = 1
        if 'axis' in node.attrs:
            axis_arg.i = node.attrs['axis']
        axis_arg.i = 4 + axis_arg.i if axis_arg.i < 0 else axis_arg.i

        end_axis_arg = op.arg.add()
        end_axis_arg.name = MaceKeyword.mace_end_axis_str
        end_axis_arg.i = -1
L
liutuo 已提交
1020

L
liutuo 已提交
1021 1022 1023
    def convert_kaldi_batchnorm(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.KaldiBatchNorm.name
L
liutuo 已提交
1024 1025
        dim = self.copy_node_attr(op, node, 'dim', AttributeType.INT, -1)
        block_dim = self.copy_node_attr(op, node, 'block_dim',
L
liutuo 已提交
1026
                                        AttributeType.INT, -1)
L
liutuo 已提交
1027
        epsilon = self.copy_node_attr(op, node, 'epsilon',
L
liutuo 已提交
1028
                                      AttributeType.FLOAT, 1e-3)
L
liutuo 已提交
1029
        target_rms = self.copy_node_attr(op, node, 'target_rms',
L
liutuo 已提交
1030
                                         AttributeType.FLOAT, 1.0)
L
liutuo 已提交
1031
        test_mode = self.copy_node_attr(op, node, 'test_mode',
L
liutuo 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
                                        AttributeType.INT, 0)
        mace_check(block_dim > 0 and
                   dim % block_dim == 0 and
                   epsilon > 0 and
                   target_rms > 0, "attributes invalid.")

        if test_mode > 0:
            mace_check(len(node.inputs) == 3,
                       "Kaldi's BatchNorm should have 3 inputs.")
            stats_mean = np.array(self._consts[node.inputs[1]].float_data)
            stats_var = np.array(self._consts[node.inputs[2]].float_data)
            offset_value = -1.0 * stats_mean
            scale_value = stats_var
            scale_value[scale_value < 0] = 0
            scale_value = np.power(scale_value + epsilon, -0.5) * target_rms
            offset_value = offset_value * scale_value
            scale_name = node.name + '_scale'
            offset_name = node.name + '_offset'
            self.add_tensor(scale_name, scale_value.shape,
                            mace_pb2.DT_FLOAT, scale_value)
            self.add_tensor(offset_name, offset_value.shape,
                            mace_pb2.DT_FLOAT, offset_value)
            del op.input[1:]
            op.input.extend([scale_name, offset_name])
            del op.output[1:]
            del op.output_shape[1:]

1059
    def convert_fused_batchnorm(self, node):
L
liutuo 已提交
1060 1061 1062
        if self._isKaldi:
            self.convert_kaldi_batchnorm(node)
            return
L
liutuo 已提交
1063
        op = self.convert_general_op(node)
1064
        op.type = MaceOp.BatchNorm.name
L
liutuo 已提交
1065

1066 1067
        if "epsilon" in node.attrs:
            epsilon_value = node.attrs["epsilon"]
L
liutuo 已提交
1068
        else:
1069
            epsilon_value = 1e-5
L
liutuo 已提交
1070

1071 1072 1073 1074 1075 1076 1077 1078 1079
        mace_check(len(node.inputs) == 5, "batch norm should have 5 inputs.")

        gamma_value = np.array(self._consts[node.inputs[1]].float_data)
        beta_value = np.array(self._consts[node.inputs[2]].float_data)
        mean_value = np.array(self._consts[node.inputs[3]].float_data)
        var_value = np.array(self._consts[node.inputs[4]].float_data)

        scale_name = node.name + 'scale'
        offset_name = node.name + 'offset'
L
liutuo 已提交
1080
        scale_value = ((1.0 / np.sqrt(
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
                    var_value + epsilon_value)) * gamma_value)
        offset_value = (-mean_value * scale_value) + beta_value
        self.add_tensor(scale_name, scale_value.shape, mace_pb2.DT_FLOAT,
                        scale_value)
        self.add_tensor(offset_name, offset_value.shape, mace_pb2.DT_FLOAT,
                        offset_value)
        del op.input[1:]
        op.input.extend([scale_name, offset_name])
        del op.output[1:]
        del op.output_shape[1:]

    def convert_gather(self, node):
L
liutuo 已提交
1093
        op = self.convert_general_op(node)
1094
        op.type = MaceOp.Gather.name
L
liutuo 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103

        if 'axis' in node.attrs:
            value = node.attrs['axis']
        else:
            value = 0
        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
        axis_arg.i = value

L
liutuo 已提交
1104
    def convert_gemm(self, node):
L
liutuo 已提交
1105 1106 1107
        if self._isKaldi:
            self.convert_affine(node)
            return
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123

        mace_check(len(node.inputs) >= 2,
                   "Gemm should have at least two inputs.")
        if 'alpha' in node.attrs:
            alpha = node.attrs['alpha']
            if alpha != 1.0 and node.inputs[1] in self._consts:
                weights = self._consts[node.inputs[1]]
                for idx in six.moves.range(self.get_tensor_len(weights)):
                    weights.float_data[idx] *= alpha
        if 'beta' in node.attrs:
            beta = node.attrs['beta']
            if beta != 1.0 and len(node.inputs) == 3 and\
                    node.inputs[2] in self._consts:
                bias = self._consts[node.inputs[2]]
                for idx in six.moves.range(self.get_tensor_len(bias)):
                    bias.float_data[idx] *= beta
L
liutuo 已提交
1124 1125
        trans_a = node.attrs['transA'] if 'transA' in node.attrs else 0
        trans_b = node.attrs['transB'] if 'transB' in node.attrs else 0
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
        is_fc = False
        if trans_a == 0 and trans_b == 1 and\
            node.inputs[0] in self._graph_shapes_dict and\
                node.inputs[1] in self._graph_shapes_dict and \
                node.inputs[1] in self._consts:
            shape_a = self._graph_shapes_dict[node.inputs[0]]
            shape_b = self._graph_shapes_dict[node.inputs[1]]
            if len(shape_a) == 4 and len(shape_b) == 2:
                tensor_b = self._consts[node.inputs[1]]
                tensor_data = np.array(tensor_b.float_data).reshape(
                    shape_b[0], shape_b[1], 1, 1)
                tensor_b.float_data[:] = tensor_data.flat
                tensor_b.dims[:] = tensor_data.shape
                is_fc = True
            elif len(shape_a) == 4 and\
                    len(shape_b) == 4 and list(shape_b[2:]) == [1, 1]:
                is_fc = True
        if is_fc:
            op = self.convert_general_op(node, with_shape=False)
            op.type = MaceOp.FullyConnected.name
            for output in node.outputs:
                output_shape = op.output_shape.add()
                shape_info = self._graph_shapes_dict[output]
                mace_check(len(shape_info) in [2, 4],
                           "gemm output shape should be 2 or 4 dims.")
                if len(shape_info) == 4:
                    mace_check(list(shape_info[2:]) == [1, 1],
                               "gemm's output shape should be [*, * , 1, 1]")
                else:
                    shape_info = [shape_info[0], shape_info[1], 1, 1]
                output_shape.dims.extend(shape_info)
L
liutuo 已提交
1157
        else:
1158 1159 1160 1161 1162 1163 1164 1165
            op = self.convert_general_op(node)
            op.type = MaceOp.MatMul.name
            trans_a_arg = op.arg.add()
            trans_a_arg.name = MaceKeyword.mace_transpose_a_str
            trans_a_arg.i = trans_a
            trans_b_arg = op.arg.add()
            trans_b_arg.name = MaceKeyword.mace_transpose_b_str
            trans_b_arg.i = trans_b
L
liutuo 已提交
1166

1167 1168 1169 1170
    def convert_identity(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Identity.name

L
liutuo 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
    def convert_ifdefined(self, node):
        op = self.convert_general_op(node)
        if 'offset' in node.attrs:
            offset = node.attrs['offset']
        else:
            offset = 0
        mace_check(offset <= 0, "IfDefined's offset should be <= 0.")
        if offset == 0:
            op.type = MaceOp.Identity.name
        else:
L
liutuo 已提交
1181 1182 1183 1184 1185
            op.type = MaceOp.IfDefined.name
            self.copy_node_attr(op, node, 'forward_indexes',
                                AttributeType.INTS)
            self.copy_node_attr(op, node, 'cache_forward_indexes',
                                AttributeType.INTS)
L
liutuo 已提交
1186

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    def convert_imagescaler(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.BatchNorm.name

        scale = node.attrs['scale']
        bias_value = np.array(node.attrs['bias'])
        scale_value = scale * np.ones_like(bias_value)

        scale_name = node.name + "_scale"
        bias_name = node.name + "_bias"
L
liutuo 已提交
1197 1198 1199 1200
        self.add_tensor(scale_name, scale_value.shape,
                        mace_pb2.DT_FLOAT, scale_value)
        self.add_tensor(bias_name, bias_value.shape,
                        mace_pb2.DT_FLOAT, bias_value)
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        op.input.extend([scale_name, bias_name])

    def convert_lstm(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.LSTMCell.name

    def convert_lstm_nonlinear(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.LstmNonlinear.name

    def convert_matmul(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.MatMul.name

    def convert_nop(self, node):
        pass

    def convert_normalize(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.BatchNorm.name

L
liutuo 已提交
1222 1223 1224 1225 1226 1227 1228 1229
    def convert_pad(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Pad.name
        if 'mode' in node.attrs:
            mode = node.attrs['mode']
            padding_type_arg = op.arg.add()
            padding_type_arg.name = MaceKeyword.mace_padding_type_str
            if mode == 'reflect':
1230
                padding_type_arg.i = PadType.REFLECT.value
L
liutuo 已提交
1231
            elif mode == 'edge':
1232
                padding_type_arg.i = PadType.SYMMETRIC.value
L
liutuo 已提交
1233
            else:
1234
                padding_type_arg.i = PadType.CONSTANT.value
L
liutuo 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
        if 'pads' in node.attrs:
            paddings_arg = op.arg.add()
            paddings_arg.name = MaceKeyword.mace_paddings_str
            paddings_value = node.attrs['pads']
            paddings_arg.ints.extend(paddings_value)
        if 'value' in node.attrs:
            constant_value_arg = op.arg.add()
            constant_value_arg.name = MaceKeyword.mace_constant_value_str
            constant_value_arg.f = node.attrs['value']

L
liutuo 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    def convert_pad_context(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.PadContext.name
        if 'left_context' in node.attrs:
            left_context_arg = op.arg.add()
            left_context_arg.name = 'left_context'
            left_context_arg.i = node.attrs['left_context']
        if 'right_context' in node.attrs:
            right_context_arg = op.arg.add()
            right_context_arg.name = 'right_context'
            right_context_arg.i = node.attrs['right_context']

1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    def convert_pnorm(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.PNorm.name
        if 'output_dim' in node.attrs:
            output_dim_arg = op.arg.add()
            output_dim_arg.name = 'output_dim'
            output_dim_arg.i = node.attrs['output_dim']
        if 'p' in node.attrs:
            p_value = node.attrs['p']
            mace_check((p_value >= 0) and (p_value <= 2),
                       "PNorm only supports p = 0, 1, 2")
            p_arg = op.arg.add()
            p_arg.name = 'p'
            p_arg.i = p_value

    def convert_pooling(self, node):
        op = self.convert_general_op(node)

        op.type = MaceOp.Pooling.name
        self.add_stride_pad_kernel_arg(node.attrs, op)
        pooling_type_arg = op.arg.add()
        pooling_type_arg.name = MaceKeyword.mace_pooling_type_str
        pooling_type_arg.i = self.pooling_type_mode[node.op_type].value

        round_mode_arg = op.arg.add()
        round_mode_arg.name = MaceKeyword.mace_round_mode_str
        round_mode_arg.i = RoundMode.FLOOR.value

    def convert_reduce(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Reduce.name

        reduce_type_arg = op.arg.add()
        reduce_type_arg.name = MaceKeyword.mace_reduce_type_str
        reduce_type_arg.i = self.reduce_type[node.op_type].value

        if node.op_type in [OnnxOpType.GlobalAveragePool.name,
                            OnnxOpType.GlobalMaxPool.name]:
            reduce_dims = [2, 3]
            keep_dims = 1
        else:
            if 'axes' in node.attrs:
                reduce_dims = node.attrs['axes']
            else:
                reduce_dims = []
            if 'keepdims' in node.attrs:
                keep_dims = node.attrs['keepdims']
            else:
                keep_dims = 1
        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
        axis_arg.ints.extend(reduce_dims)

        keep_dims_arg = op.arg.add()
        keep_dims_arg.name = MaceKeyword.mace_keepdims_str
        keep_dims_arg.i = keep_dims

L
liutuo 已提交
1314 1315 1316 1317 1318 1319
    def convert_replaceindex(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.ReplaceIndex.name
        self.copy_node_attr(op, node, 'forward_indexes',
                            AttributeType.INTS)

1320 1321 1322 1323
    def convert_reshape(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Reshape.name

1324 1325 1326 1327 1328
    def convert_shape(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Shape.name
        op.output_type.extend([mace_pb2.DT_INT32])

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
    def convert_slice(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Slice.name

        mace_check('starts' in node.attrs, "Attribute starts required!")
        mace_check('ends' in node.attrs, "Attribute ends required!")
        starts = node.attrs['starts']
        starts_arg = op.arg.add()
        starts_arg.name = 'starts'
        starts_arg.ints.extend(starts)
        ends = node.attrs['ends']
        ends_arg = op.arg.add()
        ends_arg.name = 'ends'
        ends_arg.ints.extend(ends)
        if 'axes' in node.attrs:
            axes = node.attrs['axes']
            axes_arg = op.arg.add()
            axes_arg.name = 'axes'
            axes_arg.ints.extend(axes)

    def convert_softmax(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Softmax.name
L
liutuo 已提交
1352 1353 1354 1355
        if node.op_type == OnnxOpType.LogSoftmax.name:
            use_log_arg = op.arg.add()
            use_log_arg.name = 'use_log'
            use_log_arg.i = 1
1356

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    def convert_lpnormalization(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.LpNorm.name

        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
        axis_arg.i = node.attrs.get('axis', -1)

        p_arg = op.arg.add()
        p_arg.name = MaceKeyword.mace_p_str
        p_arg.i = node.attrs.get('p', 2)

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    def convert_splice(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Splice.name
        if 'context' in node.attrs:
            context = node.attrs['context']
        else:
            context = [0]
        context_arg = op.arg.add()
        context_arg.name = 'context'
        context_arg.ints.extend(context)
        if 'const_component_dim' in node.attrs:
            const_dim = node.attrs['const_component_dim']
L
liutuo 已提交
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
            const_dim_arg = op.arg.add()
            const_dim_arg.name = 'const_component_dim'
            const_dim_arg.i = const_dim
            self.copy_node_attr(op, node,
                                'forward_const_indexes',
                                AttributeType.INTS)

        self.copy_node_attr(op, node, 'subsample_factor',
                            AttributeType.INT, default=1)
        self.copy_node_attr(op, node, 'forward_indexes',
                            AttributeType.INTS)
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418

    def convert_split(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Split.name

        if 'axis' in node.attrs:
            value = node.attrs['axis']
        else:
            value = 0
        axis_arg = op.arg.add()
        axis_arg.name = MaceKeyword.mace_axis_str
        axis_arg.i = value

    def convert_squeeze(self, node):
        axis_value = node.attrs['axes']
        if node.inputs[0] in self._consts:
            tensor = self._consts[node.inputs[0]]
            shape = tensor.dims
            new_shape = self.squeeze_shape(shape, axis_value)
            del tensor.dims[:]
            tensor.dims.extend(new_shape)
            self.remove_node(node)
        else:
            op = self.convert_general_op(node)
            op.type = MaceOp.Squeeze.name
            axis_arg = op.arg.add()
            axis_arg.name = MaceKeyword.mace_axis_str
Y
yejianwu 已提交
1419 1420
            if 'axes' in node.attrs:
                axis_value = node.attrs['axes']
1421 1422 1423 1424
            else:
                axis_value = []
            axis_arg.ints.extend(axis_value)

1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
    def convert_unsqueeze(self, node):
        mace_check('axes' in node.attrs,
                   "Unsqueeze op should have 'axes' attribute.")
        axis_value = node.attrs['axes']
        if node.inputs[0] in self._consts:
            tensor = self._consts[node.inputs[0]]
            shape = tensor.dims
            new_shape = self.unsqueeze_shape(shape, axis_value)
            del tensor.dims[:]
            tensor.dims.extend(new_shape)
            self.remove_node(node)
        else:
            op = self.convert_general_op(node)
            op.type = MaceOp.Unsqueeze.name
            axis_arg = op.arg.add()
            axis_arg.name = MaceKeyword.mace_axis_str
            axis_arg.ints.extend(axis_value)

L
liutuo 已提交
1443 1444 1445 1446 1447 1448
    def convert_subsample(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Subsample.name
        self.copy_node_attr(op, node, 'forward_indexes',
                            AttributeType.INTS)

1449 1450 1451 1452 1453 1454 1455 1456
    def convert_sum_group(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.SumGroup.name

    def convert_target_rms_norm(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.TargetRMSNorm.name

L
liutuo 已提交
1457 1458 1459 1460 1461 1462
        self.copy_node_attr(op, node, 'target_rms',
                            AttributeType.FLOAT)
        self.copy_node_attr(op, node, 'add_log_stddev',
                            AttributeType.INT, default=0)
        self.copy_node_attr(op, node, 'block_dim',
                            AttributeType.INT, default=0)
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488

    def convert_transpose(self, node):
        op = self.convert_general_op(node)
        op.type = MaceOp.Transpose.name

        if 'perm' in node.attrs:
            perm = node.attrs['perm']
            ordered_perm = np.sort(perm)
            if np.array_equal(perm, ordered_perm):
                op.type = MaceOp.Identity.name
                del op.input[1:]
            else:
                dims_arg = op.arg.add()
                dims_arg.name = MaceKeyword.mace_dims_str
                dims_arg.ints.extend(perm)

    def convert_timeoffset(self, node):
        op = self.convert_general_op(node)
        mace_check('offset' in node.attrs,
                   'Offset attribute required in Offset Node.')
        offset = node.attrs['offset']
        if offset == 0:
            op.type = MaceOp.Identity.name
        else:
            op.type = MaceOp.TimeOffset.name

L
liutuo 已提交
1489 1490 1491 1492 1493
        chunk_size = node.attrs['chunk_size']
        chunk_size_arg = op.arg.add()
        chunk_size_arg.name = 'chunk_size'
        chunk_size_arg.i = chunk_size

1494 1495 1496
        offset_arg = op.arg.add()
        offset_arg.name = 'offset'
        offset_arg.i = offset
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518

    def convert_upsample(self, node):
        op = self.convert_general_op(node)
        del op.input[1:]  # cut all unnecessary inputs (onnx>=1.5)

        output_size = self._graph_shapes_dict[op.output[0]]
        output_size = np.array(output_size[-2:]).astype(np.int32)
        if node.attrs['mode'] == 'nearest':
            op.type = MaceOp.ResizeNearestNeighbor.name
            size_tensor_name = op.name + ":size"
            self.add_tensor(size_tensor_name, output_size.shape,
                            mace_pb2.DT_INT32, output_size)
            op.input.append(size_tensor_name)
        else:
            op.type = MaceOp.ResizeBilinear.name
            size_arg = op.arg.add()
            size_arg.name = MaceKeyword.mace_resize_size_str
            size_arg.ints.extend(output_size.tolist())

        align_corners_arg = op.arg.add()
        align_corners_arg.name = MaceKeyword.mace_align_corners_str
        align_corners_arg.i = node.attrs.get('align_corners', 0)