提交 fa26d01c 编写于 作者: J jiangjiajun

modify code format

上级 73830eb2
- repo: local - repo: https://github.com/PaddlePaddle/mirrors-yapf.git
sha: 0d79c0c469bab64f7229c9aca2b1186ef47f0e37
hooks: hooks:
- id: yapf - id: yapf
name: yapf
entry: yapf
language: system
args: [-i, --style .style.yapf]
files: \.py$ files: \.py$
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
sha: a11d9314b22d8f8c7556443875b731ef05965464 sha: a11d9314b22d8f8c7556443875b731ef05965464
hooks: hooks:
...@@ -18,6 +14,7 @@ ...@@ -18,6 +14,7 @@
- id: check-symlinks - id: check-symlinks
- id: check-added-large-files - id: check-added-large-files
- repo: local - repo: local
hooks: hooks:
- id: copyright_checker - id: copyright_checker
name: copyright_checker name: copyright_checker
......
...@@ -11,8 +11,7 @@ setuptools.setup( ...@@ -11,8 +11,7 @@ setuptools.setup(
version=x2paddle.__version__, version=x2paddle.__version__,
author="dltp-sz", author="dltp-sz",
author_email="dltp-sz@baidu.com", author_email="dltp-sz@baidu.com",
description= description="a toolkit for converting trained model to PaddlePaddle from other deep learning frameworks.",
"a toolkit for converting trained model to PaddlePaddle from other deep learning frameworks.",
long_description=long_description, long_description=long_description,
long_description_content_type="text/plain", long_description_content_type="text/plain",
url="https://github.com/PaddlePaddle/x2paddle", url="https://github.com/PaddlePaddle/x2paddle",
...@@ -23,6 +22,4 @@ setuptools.setup( ...@@ -23,6 +22,4 @@ setuptools.setup(
"Operating System :: OS Independent", "Operating System :: OS Independent",
], ],
license='Apache 2.0', license='Apache 2.0',
entry_points={'console_scripts': [ entry_points={'console_scripts': ['x2paddle=x2paddle.convert:main', ]})
'x2paddle=x2paddle.convert:main',
]})
...@@ -48,8 +48,7 @@ def arg_parser(): ...@@ -48,8 +48,7 @@ def arg_parser():
"-f", "-f",
type=_text_type, type=_text_type,
default=None, default=None,
help= help="define which deeplearning framework(tensorflow/caffe/onnx/paddle2onnx)"
"define which deeplearning framework(tensorflow/caffe/onnx/paddle2onnx)"
) )
parser.add_argument( parser.add_argument(
"--caffe_proto", "--caffe_proto",
...@@ -126,7 +125,6 @@ def tf2paddle(model_path, ...@@ -126,7 +125,6 @@ def tf2paddle(model_path,
optimizer.merge_bias() optimizer.merge_bias()
optimizer.optimize_sub_graph() optimizer.optimize_sub_graph()
# optimizer.merge_batch_norm() # optimizer.merge_batch_norm()
# optimizer.merge_prelu() # optimizer.merge_prelu()
else: else:
......
...@@ -46,8 +46,9 @@ class Layer(object): ...@@ -46,8 +46,9 @@ class Layer(object):
for input in self.inputs: for input in self.inputs:
if isinstance(input, GraphNode): if isinstance(input, GraphNode):
if hasattr(input, "index"): if hasattr(input, "index"):
in_list += (input.layer_name + "[{}]".format( in_list += (
input.index) + ", ") input.layer_name + "[{}]".format(input.index) + ", "
)
else: else:
in_list += (input.layer_name + ", ") in_list += (input.layer_name + ", ")
elif isinstance(input, six.string_types): elif isinstance(input, six.string_types):
......
...@@ -34,8 +34,8 @@ class CaffeResolver(object): ...@@ -34,8 +34,8 @@ class CaffeResolver(object):
if not os.path.isfile(self.caffe_proto): if not os.path.isfile(self.caffe_proto):
raise Exception( raise Exception(
"The .py file compiled by caffe.proto is not exist.") "The .py file compiled by caffe.proto is not exist.")
(filepath, tempfilename) = os.path.split( (filepath,
os.path.abspath(self.caffe_proto)) tempfilename) = os.path.split(os.path.abspath(self.caffe_proto))
(filename, extension) = os.path.splitext(tempfilename) (filename, extension) = os.path.splitext(tempfilename)
sys.path.append(filepath) sys.path.append(filepath)
out = __import__(filename) out = __import__(filename)
...@@ -50,12 +50,10 @@ class CaffeGraphNode(GraphNode): ...@@ -50,12 +50,10 @@ class CaffeGraphNode(GraphNode):
def __init__(self, layer, type_str, layer_name=None): def __init__(self, layer, type_str, layer_name=None):
if layer_name is None: if layer_name is None:
super(CaffeGraphNode, self).__init__( super(CaffeGraphNode, self).__init__(
layer, layer, layer.name.replace('/', '_').replace('-', '_'))
layer.name.replace('/', '_').replace('-', '_'))
else: else:
super(CaffeGraphNode, self).__init__( super(CaffeGraphNode, self).__init__(
layer, layer, layer_name.replace('/', '_').replace('-', '_'))
layer_name.replace('/', '_').replace('-', '_'))
self.layer_type = type_str self.layer_type = type_str
self.fluid_code = FluidCode() self.fluid_code = FluidCode()
self.data = None self.data = None
......
此差异已折叠。
...@@ -492,8 +492,8 @@ class ONNXDecoder(object): ...@@ -492,8 +492,8 @@ class ONNXDecoder(object):
sess = rt.InferenceSession(model_path) sess = rt.InferenceSession(model_path)
for ipt in sess.get_inputs(): for ipt in sess.get_inputs():
datatype = datatype_map[ipt.type] datatype = datatype_map[ipt.type]
input_dict[ipt.name] = np.random.random( input_dict[ipt.name] = np.random.random(ipt.shape).astype(
ipt.shape).astype(datatype) datatype)
res = sess.run(None, input_feed=input_dict) res = sess.run(None, input_feed=input_dict)
except: except:
......
...@@ -120,8 +120,8 @@ def convolutiondepthwise_layer(inputs, ...@@ -120,8 +120,8 @@ def convolutiondepthwise_layer(inputs,
dila_len) dila_len)
c_in = input_shape[0][1] c_in = input_shape[0][1]
c_out = num_output if num_output is not None else input_shape[0][1] c_out = num_output if num_output is not None else input_shape[0][1]
group = int(c_in / (c_in / c_out)) if c_in > c_out else int( group = int(c_in / (c_in / c_out)) if c_in > c_out else int(c_in /
c_in / (c_out / c_in)) (c_out / c_in))
out = fluid.layers.conv2d( out = fluid.layers.conv2d(
input, input,
dilation=[dila_h, dila_w], dilation=[dila_h, dila_w],
......
...@@ -23,8 +23,7 @@ def register(kind, shape, layer, weights): ...@@ -23,8 +23,7 @@ def register(kind, shape, layer, weights):
kind = [kind] kind = [kind]
else: else:
assert type( assert type(
kind kind) is list, 'invalid param "kind" for register, not a list or str'
) is list, 'invalid param "kind" for register, not a list or str'
for k in kind: for k in kind:
assert type( assert type(
......
...@@ -144,8 +144,8 @@ class CaffeOpMapper(OpMapper): ...@@ -144,8 +144,8 @@ class CaffeOpMapper(OpMapper):
[s_h, s_w] = [params.stride] * 2 [s_h, s_w] = [params.stride] * 2
elif len(params.stride) > 0: elif len(params.stride) > 0:
s_h = params.stride_h if params.stride_h > 0 else params.stride[0] s_h = params.stride_h if params.stride_h > 0 else params.stride[0]
s_w = params.stride_w if params.stride_w > 0 else params.stride[ s_w = params.stride_w if params.stride_w > 0 else params.stride[len(
len(params.stride) - 1] params.stride) - 1]
elif params.stride_h > 0 or params.stride_w > 0: elif params.stride_h > 0 or params.stride_w > 0:
s_h = params.stride_h s_h = params.stride_h
s_w = params.stride_w s_w = params.stride_w
...@@ -154,8 +154,8 @@ class CaffeOpMapper(OpMapper): ...@@ -154,8 +154,8 @@ class CaffeOpMapper(OpMapper):
[p_h, p_w] = [params.pad] * 2 [p_h, p_w] = [params.pad] * 2
elif len(params.pad) > 0: elif len(params.pad) > 0:
p_h = params.pad_h if params.pad_h > 0 else params.pad[0] p_h = params.pad_h if params.pad_h > 0 else params.pad[0]
p_w = params.pad_w if params.pad_w > 0 else params.pad[ p_w = params.pad_w if params.pad_w > 0 else params.pad[len(
len(params.pad) - 1] params.pad) - 1]
elif params.pad_h > 0 or params.pad_w > 0: elif params.pad_h > 0 or params.pad_w > 0:
p_h = params.pad_h p_h = params.pad_h
p_w = params.pad_w p_w = params.pad_w
...@@ -225,11 +225,9 @@ class CaffeOpMapper(OpMapper): ...@@ -225,11 +225,9 @@ class CaffeOpMapper(OpMapper):
input_c = node.input_shape[0][1] input_c = node.input_shape[0][1]
output_c = channel output_c = channel
data.append( data.append(
np.zeros([output_c, input_c, kernel[0], np.zeros([output_c, input_c, kernel[0], kernel[1]]).astype(
kernel[1]]).astype('float32')) 'float32'))
data.append(np.zeros([ data.append(np.zeros([output_c, ])).astype('float32')
output_c,
])).astype('float32')
else: else:
data = self.adjust_parameters(node) data = self.adjust_parameters(node)
self.weights[node.layer_name + '_weights'] = data[0] self.weights[node.layer_name + '_weights'] = data[0]
...@@ -240,24 +238,16 @@ class CaffeOpMapper(OpMapper): ...@@ -240,24 +238,16 @@ class CaffeOpMapper(OpMapper):
input = self.graph.get_bottom_node(node, idx=0, copy=True) input = self.graph.get_bottom_node(node, idx=0, copy=True)
attr = { attr = {
'filter_size': 'filter_size': kernel,
kernel, 'num_filters': channel,
'num_filters': 'stride': stride,
channel, 'padding': pad,
'stride': 'dilation': dilation,
stride, 'groups': group,
'padding': 'name': string(node.layer_name),
pad, 'param_attr': string(node.layer_name + '_weights'),
'dilation': 'bias_attr': False
dilation, if len(data) == 1 else string(node.layer_name + '_bias'),
'groups':
group,
'name':
string(node.layer_name),
'param_attr':
string(node.layer_name + '_weights'),
'bias_attr':
False if len(data) == 1 else string(node.layer_name + '_bias'),
} }
node.fluid_code.add_layer( node.fluid_code.add_layer(
"conv2d", inputs=input, output=node, param_attr=attr) "conv2d", inputs=input, output=node, param_attr=attr)
...@@ -275,11 +265,9 @@ class CaffeOpMapper(OpMapper): ...@@ -275,11 +265,9 @@ class CaffeOpMapper(OpMapper):
input_c = node.input_shape[0][1] input_c = node.input_shape[0][1]
output_c = channel output_c = channel
data.append( data.append(
np.zeros([output_c, input_c, kernel[0], np.zeros([output_c, input_c, kernel[0], kernel[1]]).astype(
kernel[1]]).astype('float32')) 'float32'))
data.append(np.zeros([ data.append(np.zeros([output_c, ]).astype('float32'))
output_c,
]).astype('float32'))
else: else:
data = self.adjust_parameters(node) data = self.adjust_parameters(node)
self.weights[node.layer_name + '_weights'] = data[0] self.weights[node.layer_name + '_weights'] = data[0]
...@@ -289,26 +277,17 @@ class CaffeOpMapper(OpMapper): ...@@ -289,26 +277,17 @@ class CaffeOpMapper(OpMapper):
) == 1, 'The count of Deconvolution node\'s input is not 1.' ) == 1, 'The count of Deconvolution node\'s input is not 1.'
input = self.graph.get_bottom_node(node, idx=0, copy=True) input = self.graph.get_bottom_node(node, idx=0, copy=True)
attr = { attr = {
'output_size': 'output_size': None,
None, 'filter_size': kernel,
'filter_size': 'num_filters': channel,
kernel, 'stride': stride,
'num_filters': 'padding': pad,
channel, 'dilation': dilation,
'stride': 'groups': group,
stride, 'name': string(node.layer_name),
'padding': 'param_attr': string(node.layer_name + '_weights'),
pad, 'bias_attr': False
'dilation': if len(data) == 1 else string(node.layer_name + '_bias')
dilation,
'groups':
group,
'name':
string(node.layer_name),
'param_attr':
string(node.layer_name + '_weights'),
'bias_attr':
False if len(data) == 1 else string(node.layer_name + '_bias')
} }
node.fluid_code.add_layer( node.fluid_code.add_layer(
"conv2d_transpose", inputs=input, output=node, param_attr=attr) "conv2d_transpose", inputs=input, output=node, param_attr=attr)
...@@ -372,8 +351,8 @@ class CaffeOpMapper(OpMapper): ...@@ -372,8 +351,8 @@ class CaffeOpMapper(OpMapper):
output_c = params.num_output output_c = params.num_output
data = [] data = []
data.append( data.append(
np.zeros([input_c, np.zeros([input_c, output_c]).astype('float32').astype(
output_c]).astype('float32').astype('float32')) 'float32'))
data.append( data.append(
np.zeros([output_c]).astype('float32').astype('float32')) np.zeros([output_c]).astype('float32').astype('float32'))
else: else:
...@@ -397,16 +376,12 @@ class CaffeOpMapper(OpMapper): ...@@ -397,16 +376,12 @@ class CaffeOpMapper(OpMapper):
assert params.bias_term == True assert params.bias_term == True
input = self.graph.get_bottom_node(node, idx=0, copy=True) input = self.graph.get_bottom_node(node, idx=0, copy=True)
attr = { attr = {
'size': 'size': params.num_output,
params.num_output, 'name': string(node.layer_name),
'name': 'act': None,
string(node.layer_name), 'param_attr': string(node.layer_name + '_weights'),
'act': 'bias_attr': False
None, if len(data) == 1 else string(node.layer_name + '_bias')
'param_attr':
string(node.layer_name + '_weights'),
'bias_attr':
False if len(data) == 1 else string(node.layer_name + '_bias')
} }
node.fluid_code.add_layer( node.fluid_code.add_layer(
"fc", inputs=input, output=node, param_attr=attr) "fc", inputs=input, output=node, param_attr=attr)
...@@ -607,12 +582,8 @@ class CaffeOpMapper(OpMapper): ...@@ -607,12 +582,8 @@ class CaffeOpMapper(OpMapper):
'The parameter of {} (type is {}) is not set. So we set the parameters as 0' 'The parameter of {} (type is {}) is not set. So we set the parameters as 0'
.format(node.layer_name, node.layer_type)) .format(node.layer_name, node.layer_type))
input_c = node.input_shape[0][1] input_c = node.input_shape[0][1]
mean = np.zeros([ mean = np.zeros([input_c, ]).astype('float32')
input_c, variance = np.zeros([input_c, ]).astype('float32')
]).astype('float32')
variance = np.zeros([
input_c,
]).astype('float32')
scale = 0 scale = 0
else: else:
...@@ -649,10 +620,10 @@ class CaffeOpMapper(OpMapper): ...@@ -649,10 +620,10 @@ class CaffeOpMapper(OpMapper):
input_c, input_c,
]).astype('float32') ]).astype('float32')
else: else:
self.weights[node.layer_name + '_scale'] = np.squeeze( self.weights[node.layer_name + '_scale'] = np.squeeze(node.data[
node.data[0]).astype('float32') 0]).astype('float32')
self.weights[node.layer_name + '_offset'] = np.squeeze( self.weights[node.layer_name + '_offset'] = np.squeeze(node.data[
node.data[1]).astype('float32') 1]).astype('float32')
params = node.layer.scale_param params = node.layer.scale_param
axis = params.axis axis = params.axis
num_axes = params.num_axes num_axes = params.num_axes
...@@ -750,8 +721,8 @@ class CaffeOpMapper(OpMapper): ...@@ -750,8 +721,8 @@ class CaffeOpMapper(OpMapper):
node.fluid_code.add_layer( node.fluid_code.add_layer(
"topk", "topk",
inputs=input, inputs=input,
output='{}_topk_var, {}_index_var'.format( output='{}_topk_var, {}_index_var'.format(node.layer_name,
node.layer_name, node.layer_name), node.layer_name),
param_attr=attr) param_attr=attr)
attr = {'dtype': '{}_topk_var.dtype'.format(node.layer_name)} attr = {'dtype': '{}_topk_var.dtype'.format(node.layer_name)}
node.fluid_code.add_layer( node.fluid_code.add_layer(
...@@ -762,8 +733,8 @@ class CaffeOpMapper(OpMapper): ...@@ -762,8 +733,8 @@ class CaffeOpMapper(OpMapper):
attr = {'axis': axis, 'name': string(node.layer_name)} attr = {'axis': axis, 'name': string(node.layer_name)}
node.fluid_code.add_layer( node.fluid_code.add_layer(
"concat", "concat",
inputs='{}_topk_var, {}_index_var'.format( inputs='{}_topk_var, {}_index_var'.format(node.layer_name,
node.layer_name, node.layer_name), node.layer_name),
output=node, output=node,
param_attr=attr) param_attr=attr)
else: else:
...@@ -787,23 +758,22 @@ class CaffeOpMapper(OpMapper): ...@@ -787,23 +758,22 @@ class CaffeOpMapper(OpMapper):
offset_real = [0] * len(input_shape) offset_real = [0] * len(input_shape)
if hasattr(params, "offset") and len(params.offset) > 0: if hasattr(params, "offset") and len(params.offset) > 0:
offset = list(params.offset) offset = list(params.offset)
assert (len(input_shape) - axis) == len( assert (len(input_shape) - axis
offset), "invalid offset[%s] in crop layer" % (str(offset)) ) == len(offset), "invalid offset[%s] in crop layer" % (
str(offset))
offset_real = [0] * axis + offset offset_real = [0] * axis + offset
attr = {'offsets': list(offset_real), 'name': string(node.layer_name)} attr = {'offsets': list(offset_real), 'name': string(node.layer_name)}
node.fluid_code.add_layer( node.fluid_code.add_layer(
"crop", "crop",
inputs={ inputs={'x': input,
'x': input, 'shape': node.input_shape[1]},
'shape': node.input_shape[1]
},
output=node, output=node,
param_attr=attr) param_attr=attr)
def Flatten(self, node): def Flatten(self, node):
assert len( assert len(
node.inputs node.
) == 1, 'The count of DetectionOutput node\'s input is not 1.' inputs) == 1, 'The count of DetectionOutput node\'s input is not 1.'
input = self.graph.get_bottom_node(node, idx=0, copy=True) input = self.graph.get_bottom_node(node, idx=0, copy=True)
shape = node.output_shape[0] shape = node.output_shape[0]
attr = {'shape': shape, 'name': string(node.layer_name)} attr = {'shape': shape, 'name': string(node.layer_name)}
......
...@@ -33,8 +33,8 @@ def get_kernel_parameters(params): ...@@ -33,8 +33,8 @@ def get_kernel_parameters(params):
[s_h, s_w] = [params.stride] * 2 [s_h, s_w] = [params.stride] * 2
elif len(params.stride) > 0: elif len(params.stride) > 0:
s_h = params.stride_h if params.stride_h > 0 else params.stride[0] s_h = params.stride_h if params.stride_h > 0 else params.stride[0]
s_w = params.stride_w if params.stride_w > 0 else params.stride[ s_w = params.stride_w if params.stride_w > 0 else params.stride[len(
len(params.stride) - 1] params.stride) - 1]
elif params.stride_h > 0 or params.stride_w > 0: elif params.stride_h > 0 or params.stride_w > 0:
s_h = params.stride_h s_h = params.stride_h
s_w = params.stride_w s_w = params.stride_w
...@@ -67,10 +67,10 @@ def get_strided_kernel_output_shape(params, input_shape, round_func): ...@@ -67,10 +67,10 @@ def get_strided_kernel_output_shape(params, input_shape, round_func):
i_w = input_shape[3] i_w = input_shape[3]
dila_h, dila_w, pad_h, pad_w, kernel_h, kernel_w, stride_h, stride_w = get_kernel_parameters( dila_h, dila_w, pad_h, pad_w, kernel_h, kernel_w, stride_h, stride_w = get_kernel_parameters(
params) params)
o_h = (i_h + 2 * pad_h - o_h = (i_h + 2 * pad_h - (dila_h *
(dila_h * (kernel_h - 1) + 1)) / float(stride_h) + 1 (kernel_h - 1) + 1)) / float(stride_h) + 1
o_w = (i_w + 2 * pad_w - o_w = (i_w + 2 * pad_w - (dila_w *
(dila_w * (kernel_w - 1) + 1)) / float(stride_w) + 1 (kernel_w - 1) + 1)) / float(stride_w) + 1
o_h = int(round_func(o_h)) o_h = int(round_func(o_h))
o_w = int(round_func(o_w)) o_w = int(round_func(o_w))
has_c_o = hasattr(params, 'num_output') has_c_o = hasattr(params, 'num_output')
......
...@@ -36,8 +36,7 @@ def register(kind, shape, layer, child_func, weights): ...@@ -36,8 +36,7 @@ def register(kind, shape, layer, child_func, weights):
kind = [kind] kind = [kind]
else: else:
assert type( assert type(
kind kind) is list, 'invalid param "kind" for register, not a list or str'
) is list, 'invalid param "kind" for register, not a list or str'
for k in kind: for k in kind:
assert type( assert type(
......
...@@ -28,60 +28,49 @@ default_op_mapping_field_values['FILL_NAME_FIELD'] = True ...@@ -28,60 +28,49 @@ default_op_mapping_field_values['FILL_NAME_FIELD'] = True
default_op_mapping = { default_op_mapping = {
'Shape': ['shape', ['X'], ['Out']], 'Shape': ['shape', ['X'], ['Out']],
'Clip': [ 'Clip': [
'clip', ['X'], ['Out'], 'clip', ['X'], ['Out'], dict(), dict(
dict(), min=(_np.asarray(
dict( [255, 255, 127, 255], dtype=_np.uint8).view(_np.float32)[0]),
min=(_np.asarray([255, 255, 127, 255], max=(_np.asarray(
dtype=_np.uint8).view(_np.float32)[0]), [255, 255, 127, 127], dtype=_np.uint8).view(_np.float32)[0]), )
max=(_np.asarray([255, 255, 127, 127],
dtype=_np.uint8).view(_np.float32)[0]),
)
], ],
'Erf': ['erf', ['X'], ['Out']], 'Erf': ['erf', ['X'], ['Out']],
'Ceil': ['ceil', ['X'], ['Out']], 'Ceil': ['ceil', ['X'], ['Out']],
'ReduceMean': [ 'ReduceMean': [
'reduce_mean', ['X'], ['Out'], 'reduce_mean', ['X'], ['Out'], dict(
dict(axes='dim', keepdims='keep_dim'), axes='dim', keepdims='keep_dim'), dict(keep_dim=1)
dict(keep_dim=1)
], ],
'ReduceSum': [ 'ReduceSum': [
'reduce_sum', ['X'], ['Out'], 'reduce_sum', ['X'], ['Out'], dict(
dict(axes='dim', keepdims='keep_dim'), axes='dim', keepdims='keep_dim'), dict(keep_dim=1)
dict(keep_dim=1)
], ],
'ReduceMin': [ 'ReduceMin': [
'reduce_min', ['X'], ['Out'], 'reduce_min', ['X'], ['Out'], dict(
dict(axes='dim', keepdims='keep_dim'), axes='dim', keepdims='keep_dim'), dict(keep_dim=1)
dict(keep_dim=1)
], ],
'ReduceMax': [ 'ReduceMax': [
'reduce_max', ['X'], ['Out'], 'reduce_max', ['X'], ['Out'], dict(
dict(axes='dim', keepdims='keep_dim'), axes='dim', keepdims='keep_dim'), dict(keep_dim=1)
dict(keep_dim=1)
], ],
#active function #active function
'Relu': ['relu', ['X'], ['Out']], 'Relu': ['relu', ['X'], ['Out']],
'LeakyRelu': ['leaky_relu', ['X'], ['Out'], 'LeakyRelu': ['leaky_relu', ['X'], ['Out'], dict(), dict(alpha=.01)],
dict(), dict(alpha=.01)], 'Elu': ['elu', ['X'], ['Out'], dict(), dict(alpha=1.)],
'Elu': ['elu', ['X'], ['Out'],
dict(), dict(alpha=1.)],
'ThresholdedRelu': [ 'ThresholdedRelu': [
'thresholded_relu', ['X'], ['Out'], 'thresholded_relu', ['X'], ['Out'], dict(alpha='threshold'),
dict(alpha='threshold'),
dict(alpha=1.) dict(alpha=1.)
], ],
'Tanh': ['tanh', ['X'], ['Out']], 'Tanh': ['tanh', ['X'], ['Out']],
'Sigmoid': ['sigmoid', ['X'], ['Out']], 'Sigmoid': ['sigmoid', ['X'], ['Out']],
'HardSigmoid': [ 'HardSigmoid': [
'hard_sigmoid', ['X'], ['Out'], 'hard_sigmoid', ['X'], ['Out'], dict(
dict(alpha='slope', beta='offset'), alpha='slope', beta='offset'), dict(
dict(slope=.2, offset=.5) slope=.2, offset=.5)
], ],
'Softsign': ['softsign', ['X'], ['Out']], 'Softsign': ['softsign', ['X'], ['Out']],
'Softplus': ['softplus', ['X'], ['Out']], 'Softplus': ['softplus', ['X'], ['Out']],
'Exp': ['exp', ['X'], ['Out']], 'Exp': ['exp', ['X'], ['Out']],
'Softmax': ['softmax', ['X'], ['Out'], 'Softmax': ['softmax', ['X'], ['Out'], dict(), dict(axis=1)],
dict(), dict(axis=1)],
'Sqrt': ['sqrt', ['X'], ['Out']], 'Sqrt': ['sqrt', ['X'], ['Out']],
'Floor': ['floor', ['X'], ['Out']], 'Floor': ['floor', ['X'], ['Out']],
'Abs': ['abs', ['X'], ['Out']], 'Abs': ['abs', ['X'], ['Out']],
......
...@@ -140,8 +140,8 @@ class ONNXOpMapper(OpMapper): ...@@ -140,8 +140,8 @@ class ONNXOpMapper(OpMapper):
model.graph.ClearField('output') model.graph.ClearField('output')
model.graph.output.MergeFrom(model.graph.value_info) model.graph.output.MergeFrom(model.graph.value_info)
onnx.save(model, os.path.join(self.tmp_data_dir, onnx.save(model,
'onnx_model_infer.onnx')) os.path.join(self.tmp_data_dir, 'onnx_model_infer.onnx'))
sess = rt.InferenceSession( sess = rt.InferenceSession(
os.path.join(self.tmp_data_dir, 'onnx_model_infer.onnx')) os.path.join(self.tmp_data_dir, 'onnx_model_infer.onnx'))
res = sess.run(None, input_feed=inputs_dict) res = sess.run(None, input_feed=inputs_dict)
...@@ -217,8 +217,7 @@ class ONNXOpMapper(OpMapper): ...@@ -217,8 +217,7 @@ class ONNXOpMapper(OpMapper):
default_attrs, default_attrs,
input_perm, input_perm,
output_perm, output_perm,
fill_name_field, fill_name_field, ) = info
) = info
if fluid_op in default_ioa_constraint: if fluid_op in default_ioa_constraint:
for predicate, message in default_ioa_constraint[fluid_op]: for predicate, message in default_ioa_constraint[fluid_op]:
...@@ -429,10 +428,8 @@ class ONNXOpMapper(OpMapper): ...@@ -429,10 +428,8 @@ class ONNXOpMapper(OpMapper):
} }
node.fluid_code.add_layer( node.fluid_code.add_layer(
'roi_align', 'roi_align',
inputs={ inputs={'input': val_x,
'input': val_x, 'rois': val_rois},
'rois': val_rois
},
output=node, output=node,
param_attr=attr) param_attr=attr)
...@@ -449,10 +446,8 @@ class ONNXOpMapper(OpMapper): ...@@ -449,10 +446,8 @@ class ONNXOpMapper(OpMapper):
} }
node.fluid_code.add_layer( node.fluid_code.add_layer(
'roi_pool', 'roi_pool',
inputs={ inputs={'input': val_x,
'input': val_x, 'rois': val_rois},
'rois': val_rois
},
output=node, output=node,
param_attr=attr) param_attr=attr)
...@@ -527,10 +522,8 @@ class ONNXOpMapper(OpMapper): ...@@ -527,10 +522,8 @@ class ONNXOpMapper(OpMapper):
val_y = self.graph.get_input_node(node, idx=1, copy=True) val_y = self.graph.get_input_node(node, idx=1, copy=True)
node.fluid_code.add_layer( node.fluid_code.add_layer(
'greater_than', 'greater_than',
inputs={ inputs={'x': val_x,
'x': val_x, 'y': val_y},
'y': val_y
},
output=node, output=node,
param_attr=None) param_attr=None)
...@@ -549,8 +542,7 @@ class ONNXOpMapper(OpMapper): ...@@ -549,8 +542,7 @@ class ONNXOpMapper(OpMapper):
shape = val_output.out_shapes[0] shape = val_output.out_shapes[0]
if shape is None: if shape is None:
shape = list(value.shape) shape = list(value.shape)
_logger.warning( _logger.warning('in (Constant -> %s): '
'in (Constant -> %s): '
'attribute "shape" of %s not inferred, ' 'attribute "shape" of %s not inferred, '
'using value as 1-D tensor may lead to fails', 'using value as 1-D tensor may lead to fails',
val_output.layer_name, val_output.layer_name) val_output.layer_name, val_output.layer_name)
...@@ -616,10 +608,8 @@ class ONNXOpMapper(OpMapper): ...@@ -616,10 +608,8 @@ class ONNXOpMapper(OpMapper):
if axis == 0 and len(indices_shape) <= 1: if axis == 0 and len(indices_shape) <= 1:
node.fluid_code.add_layer( node.fluid_code.add_layer(
'gather', 'gather',
inputs={ inputs={'input': val_x,
'input': val_x, 'index': indices},
'index': indices
},
output=node, output=node,
param_attr=None) param_attr=None)
elif axis > 0 and len(indices_shape) <= 1: elif axis > 0 and len(indices_shape) <= 1:
...@@ -634,10 +624,8 @@ class ONNXOpMapper(OpMapper): ...@@ -634,10 +624,8 @@ class ONNXOpMapper(OpMapper):
param_attr=attr_trans) param_attr=attr_trans)
node.fluid_code.add_layer( node.fluid_code.add_layer(
'gather', 'gather',
inputs={ inputs={'input': name_trans,
'input': name_trans, 'index': indices},
'index': indices
},
output=node, output=node,
param_attr=None) param_attr=None)
node.fluid_code.add_layer( node.fluid_code.add_layer(
...@@ -649,9 +637,7 @@ class ONNXOpMapper(OpMapper): ...@@ -649,9 +637,7 @@ class ONNXOpMapper(OpMapper):
'reshape', 'reshape',
inputs=indices, inputs=indices,
output=indices, output=indices,
param_attr={'shape': [ param_attr={'shape': [reshape_shape, ]})
reshape_shape,
]})
perm = list(range(len(val_x.out_shapes[0]))) perm = list(range(len(val_x.out_shapes[0])))
perm = [axis] + perm[:axis] + perm[axis + 1:] perm = [axis] + perm[:axis] + perm[axis + 1:]
...@@ -664,10 +650,8 @@ class ONNXOpMapper(OpMapper): ...@@ -664,10 +650,8 @@ class ONNXOpMapper(OpMapper):
param_attr=attr_trans) param_attr=attr_trans)
node.fluid_code.add_layer( node.fluid_code.add_layer(
'gather', 'gather',
inputs={ inputs={'input': name_trans,
'input': name_trans, 'index': indices},
'index': indices
},
output=node, output=node,
param_attr=None) param_attr=None)
node.fluid_code.add_layer( node.fluid_code.add_layer(
...@@ -926,8 +910,10 @@ class ONNXOpMapper(OpMapper): ...@@ -926,8 +910,10 @@ class ONNXOpMapper(OpMapper):
def Sum(self, node): def Sum(self, node):
val_inps = node.layer.input val_inps = node.layer.input
inputs = { inputs = {
"x": self.graph.get_input_node(node, idx=0, copy=True), "x": self.graph.get_input_node(
"y": self.graph.get_input_node(node, idx=1, copy=True), node, idx=0, copy=True),
"y": self.graph.get_input_node(
node, idx=1, copy=True),
} }
node.fluid_code.add_layer("elementwise_add", inputs=inputs, output=node) node.fluid_code.add_layer("elementwise_add", inputs=inputs, output=node)
...@@ -1022,10 +1008,8 @@ class ONNXOpMapper(OpMapper): ...@@ -1022,10 +1008,8 @@ class ONNXOpMapper(OpMapper):
val_y = self.graph.get_input_node(node, idx=1, copy=True) val_y = self.graph.get_input_node(node, idx=1, copy=True)
node.fluid_code.add_layer( node.fluid_code.add_layer(
"equal", "equal",
inputs={ inputs={'x': val_x,
'x': val_x, 'y': val_y},
'y': val_y
},
output=node, output=node,
param_attr=None) param_attr=None)
...@@ -1055,29 +1039,23 @@ class ONNXOpMapper(OpMapper): ...@@ -1055,29 +1039,23 @@ class ONNXOpMapper(OpMapper):
mul_val_x = val_x.layer_name + '_mul' mul_val_x = val_x.layer_name + '_mul'
node.fluid_code.add_layer( node.fluid_code.add_layer(
"elementwise_mul", "elementwise_mul",
inputs={ inputs={'x': val_x,
'x': val_x, 'y': cast_condition},
'y': cast_condition
},
output=mul_val_x, output=mul_val_x,
param_attr=None) param_attr=None)
mul_val_y = val_y.layer_name + '_mul' mul_val_y = val_y.layer_name + '_mul'
node.fluid_code.add_layer( node.fluid_code.add_layer(
"elementwise_mul", "elementwise_mul",
inputs={ inputs={'x': val_y,
'x': val_y, 'y': cast_not_condition},
'y': cast_not_condition
},
output=mul_val_y, output=mul_val_y,
param_attr=None) param_attr=None)
node.fluid_code.add_layer( node.fluid_code.add_layer(
"elementwise_add", "elementwise_add",
inputs={ inputs={'x': mul_val_x,
'x': mul_val_x, 'y': mul_val_y},
'y': mul_val_y
},
output=node, output=node,
param_attr=None) param_attr=None)
...@@ -1106,7 +1084,8 @@ class ONNXOpMapper(OpMapper): ...@@ -1106,7 +1084,8 @@ class ONNXOpMapper(OpMapper):
output=flatten_name, output=flatten_name,
param_attr={'axis': 0}) param_attr={'axis': 0})
node.fluid_code.add_layer( node.fluid_code.add_layer(
"concat", inputs=flatten_names, output=node, param_attr={'axis': 0}) "concat", inputs=flatten_names, output=node,
param_attr={'axis': 0})
def Identity(self, node): def Identity(self, node):
val_x = self.graph.get_input_node(node, idx=0, copy=True) val_x = self.graph.get_input_node(node, idx=0, copy=True)
...@@ -1280,11 +1259,11 @@ class ONNXOpMapper(OpMapper): ...@@ -1280,11 +1259,11 @@ class ONNXOpMapper(OpMapper):
output_size = [0, 0] output_size = [0, 0]
output_size[0] = (val_x.out_shapes[0][2] - output_size[0] = (val_x.out_shapes[0][2] - 1
1) * strides[0] - 2 * paddings[0] + dilations[0] * ( ) * strides[0] - 2 * paddings[0] + dilations[0] * (
kernel_shape[0] - 1) + 1 + out_padding[0] kernel_shape[0] - 1) + 1 + out_padding[0]
output_size[1] = (val_x.out_shapes[0][3] - output_size[1] = (val_x.out_shapes[0][3] - 1
1) * strides[1] - 2 * paddings[1] + dilations[1] * ( ) * strides[1] - 2 * paddings[1] + dilations[1] * (
kernel_shape[1] - 1) + 1 + out_padding[1] kernel_shape[1] - 1) + 1 + out_padding[1]
attr = { attr = {
'num_filters': num_out_channels, 'num_filters': num_out_channels,
...@@ -1367,29 +1346,23 @@ class ONNXOpMapper(OpMapper): ...@@ -1367,29 +1346,23 @@ class ONNXOpMapper(OpMapper):
'squeeze', 'squeeze',
inputs=val_x, inputs=val_x,
output=var_x0, output=var_x0,
param_attr={ param_attr={'axes': [1],
'axes': [1], 'name': string(var_x0)})
'name': string(var_x0)
})
var_w0 = node.layer_name + '_w0' var_w0 = node.layer_name + '_w0'
node.fluid_code.add_layer( node.fluid_code.add_layer(
'squeeze', 'squeeze',
inputs=val_w, inputs=val_w,
output=var_w0, output=var_w0,
param_attr={ param_attr={'axes': [0],
'axes': [0], 'name': string(var_w0)})
'name': string(var_w0)
})
var_fc = node.layer_name + '_fc' var_fc = node.layer_name + '_fc'
var_mm = (node.layer_name + '_mm') if val_b else var_fc var_mm = (node.layer_name + '_mm') if val_b else var_fc
node.fluid_code.add_layer( node.fluid_code.add_layer(
'matmul', 'matmul',
inputs={ inputs={'x': var_x0,
'x': var_x0, 'y': var_w0},
'y': var_w0
},
output=var_mm, output=var_mm,
param_attr={ param_attr={
'transpose_x': 0, 'transpose_x': 0,
...@@ -1402,10 +1375,8 @@ class ONNXOpMapper(OpMapper): ...@@ -1402,10 +1375,8 @@ class ONNXOpMapper(OpMapper):
'squeeze', 'squeeze',
inputs=val_r, inputs=val_r,
output=var_r0, output=var_r0,
param_attr={ param_attr={'axes': [0],
'axes': [0], 'name': string(var_r0)})
'name': string(var_r0)
})
var_r0t = node.layer_name + '_r0t' var_r0t = node.layer_name + '_r0t'
...@@ -1413,10 +1384,8 @@ class ONNXOpMapper(OpMapper): ...@@ -1413,10 +1384,8 @@ class ONNXOpMapper(OpMapper):
'transpose', 'transpose',
inputs=var_r0, inputs=var_r0,
output=var_r0t, output=var_r0t,
param_attr={ param_attr={'perm': [1, 0],
'perm': [1, 0], 'name': string(var_r0t)})
'name': string(var_r0t)
})
if val_b: if val_b:
var_bi = node.layer_name + '_bi' var_bi = node.layer_name + '_bi'
var_bh = node.layer_name + '_bh' var_bh = node.layer_name + '_bh'
...@@ -1434,10 +1403,8 @@ class ONNXOpMapper(OpMapper): ...@@ -1434,10 +1403,8 @@ class ONNXOpMapper(OpMapper):
'squeeze', 'squeeze',
inputs=var_bi, inputs=var_bi,
output=var_bi0, output=var_bi0,
param_attr={ param_attr={'axes': [0],
'axes': [0], 'name': string(var_bi0)})
'name': string(var_bi0)
})
node.fluid_code.add_layer( node.fluid_code.add_layer(
'elmentwise_add', 'elmentwise_add',
...@@ -1454,10 +1421,8 @@ class ONNXOpMapper(OpMapper): ...@@ -1454,10 +1421,8 @@ class ONNXOpMapper(OpMapper):
'squeeze', 'squeeze',
inputs=val_xh, inputs=val_xh,
output=var_xh0, output=var_xh0,
param_attr={ param_attr={'axes': [1],
'axes': [1], 'name': string(var_xh0)})
'name': string(var_xh0)
})
var_y00 = node.layer_name + '_y00' var_y00 = node.layer_name + '_y00'
attr = { attr = {
......
...@@ -30,8 +30,8 @@ def im2sequence(op, block): ...@@ -30,8 +30,8 @@ def im2sequence(op, block):
slice_blocks = list() slice_blocks = list()
for i in range(out_h): for i in range(out_h):
for j in range(out_w): for j in range(out_w):
starts_name = "im2sequence.starts.{}.{}.{}".format( starts_name = "im2sequence.starts.{}.{}.{}".format(im2seq_counter,
im2seq_counter, i, j) i, j)
starts_tensor = helper.make_tensor( starts_tensor = helper.make_tensor(
name=starts_name, name=starts_name,
data_type=onnx_pb.TensorProto.INT64, data_type=onnx_pb.TensorProto.INT64,
......
...@@ -44,8 +44,7 @@ def multiclass_nms(op, block): ...@@ -44,8 +44,7 @@ def multiclass_nms(op, block):
if normalized == False: if normalized == False:
warnings.warn( warnings.warn(
'The parameter normalized of multiclass_nms OP of Paddle is False, which has diff with ONNX. \ 'The parameter normalized of multiclass_nms OP of Paddle is False, which has diff with ONNX. \
Please set normalized=True in multiclass_nms of Paddle' Please set normalized=True in multiclass_nms of Paddle')
)
#convert the paddle attribute to onnx tensor #convert the paddle attribute to onnx tensor
name_score_threshold = [outputs['Out'][0] + "@score_threshold"] name_score_threshold = [outputs['Out'][0] + "@score_threshold"]
...@@ -353,7 +352,8 @@ def multiclass_nms(op, block): ...@@ -353,7 +352,8 @@ def multiclass_nms(op, block):
outputs_gather_topk_class = [result_name + "@gather_topk_class"] outputs_gather_topk_class = [result_name + "@gather_topk_class"]
node_gather_topk_class = onnx.helper.make_node( node_gather_topk_class = onnx.helper.make_node(
'Gather', 'Gather',
inputs=outputs_gather_1_nonzero + [outputs_topk_select_topk_indices[1]], inputs=outputs_gather_1_nonzero +
[outputs_topk_select_topk_indices[1]],
outputs=outputs_gather_topk_class, outputs=outputs_gather_topk_class,
axis=1) axis=1)
node_list.append(node_gather_topk_class) node_list.append(node_gather_topk_class)
...@@ -362,7 +362,8 @@ def multiclass_nms(op, block): ...@@ -362,7 +362,8 @@ def multiclass_nms(op, block):
outputs_gather_topk_boxes_id = [result_name + "@gather_topk_boxes_id"] outputs_gather_topk_boxes_id = [result_name + "@gather_topk_boxes_id"]
node_gather_topk_boxes_id = onnx.helper.make_node( node_gather_topk_boxes_id = onnx.helper.make_node(
'Gather', 'Gather',
inputs=outputs_gather_2_nonzero + [outputs_topk_select_topk_indices[1]], inputs=outputs_gather_2_nonzero +
[outputs_topk_select_topk_indices[1]],
outputs=outputs_gather_topk_boxes_id, outputs=outputs_gather_topk_boxes_id,
axis=1) axis=1)
node_list.append(node_gather_topk_boxes_id) node_list.append(node_gather_topk_boxes_id)
......
...@@ -38,8 +38,8 @@ def yolo_box(op, block): ...@@ -38,8 +38,8 @@ def yolo_box(op, block):
downsample_ratio = attrs['downsample_ratio'] downsample_ratio = attrs['downsample_ratio']
input_size = input_height * downsample_ratio input_size = input_height * downsample_ratio
conf_thresh = attrs['conf_thresh'] conf_thresh = attrs['conf_thresh']
conf_thresh_mat = np.ones([num_anchors * input_height * input_width conf_thresh_mat = np.ones([num_anchors * input_height *
]) * conf_thresh input_width]) * conf_thresh
node_list = [] node_list = []
im_outputs = [] im_outputs = []
......
...@@ -250,8 +250,7 @@ class PaddleOpMapper(object): ...@@ -250,8 +250,7 @@ class PaddleOpMapper(object):
node = helper.make_node( node = helper.make_node(
pool_type[op.attr('pooling_type')][1], pool_type[op.attr('pooling_type')][1],
inputs=op.input('X'), inputs=op.input('X'),
outputs=op.output('Out'), outputs=op.output('Out'), )
)
else: else:
input_shape = block.var(op.input('X')[0]).shape input_shape = block.var(op.input('X')[0]).shape
k_size = op.attr('ksize') k_size = op.attr('ksize')
...@@ -407,8 +406,7 @@ class PaddleOpMapper(object): ...@@ -407,8 +406,7 @@ class PaddleOpMapper(object):
node = helper.make_node( node = helper.make_node(
'Clip', 'Clip',
inputs=[op.input('X')[0], min_name, max_name], inputs=[op.input('X')[0], min_name, max_name],
outputs=op.output('Out'), outputs=op.output('Out'), )
)
return [min_node, max_node, node] return [min_node, max_node, node]
def shape(self, op, block): def shape(self, op, block):
...@@ -450,8 +448,7 @@ class PaddleOpMapper(object): ...@@ -450,8 +448,7 @@ class PaddleOpMapper(object):
node = helper.make_node( node = helper.make_node(
"Slice", "Slice",
inputs=[op.input('Input')[0], starts_name, ends_name, axes_name], inputs=[op.input('Input')[0], starts_name, ends_name, axes_name],
outputs=op.output('Out'), outputs=op.output('Out'), )
)
return [starts_node, ends_node, axes_node, node] return [starts_node, ends_node, axes_node, node]
def fill_constant(self, op, block): def fill_constant(self, op, block):
...@@ -551,8 +548,8 @@ class PaddleOpMapper(object): ...@@ -551,8 +548,8 @@ class PaddleOpMapper(object):
if op.attr('align_corners'): if op.attr('align_corners'):
coordinate_transformation_mode = 'align_corners' coordinate_transformation_mode = 'align_corners'
if ('OutSize' in input_names and len(op.input('OutSize')) > 0) or ( if ('OutSize' in input_names and len(op.input('OutSize')) > 0) or (
'SizeTensor' in input_names 'SizeTensor' in input_names and
and len(op.input('SizeTensor')) > 0): len(op.input('SizeTensor')) > 0):
node_list = list() node_list = list()
roi_node = self.make_constant_node( roi_node = self.make_constant_node(
self.get_name(op.type, 'roi'), onnx_pb.TensorProto.FLOAT, self.get_name(op.type, 'roi'), onnx_pb.TensorProto.FLOAT,
...@@ -631,8 +628,7 @@ class PaddleOpMapper(object): ...@@ -631,8 +628,7 @@ class PaddleOpMapper(object):
elif 'Scale' in input_names and len(op.input('Scale')) > 0: elif 'Scale' in input_names and len(op.input('Scale')) > 0:
node = helper.make_node( node = helper.make_node(
'Resize', 'Resize',
inputs=[op.input('X')[0], inputs=[op.input('X')[0], op.input('Scale')[0]],
op.input('Scale')[0]],
outputs=op.output('Out'), outputs=op.output('Out'),
mode='linear', mode='linear',
coordinate_transformation_mode=coordinate_transformation_mode) coordinate_transformation_mode=coordinate_transformation_mode)
...@@ -641,8 +637,9 @@ class PaddleOpMapper(object): ...@@ -641,8 +637,9 @@ class PaddleOpMapper(object):
scale = op.attr('scale') scale = op.attr('scale')
if out_shape.count(-1) > 0: if out_shape.count(-1) > 0:
scale_name = self.get_name(op.type, 'scale') scale_name = self.get_name(op.type, 'scale')
scale_node = self.make_constant_node( scale_node = self.make_constant_node(scale_name,
scale_name, onnx_pb.TensorProto.FLOAT, [1, 1, scale, scale]) onnx_pb.TensorProto.FLOAT,
[1, 1, scale, scale])
roi_name = self.get_name(op.type, 'roi') roi_name = self.get_name(op.type, 'roi')
roi_node = self.make_constant_node(roi_name, roi_node = self.make_constant_node(roi_name,
onnx_pb.TensorProto.FLOAT, onnx_pb.TensorProto.FLOAT,
...@@ -667,16 +664,14 @@ class PaddleOpMapper(object): ...@@ -667,16 +664,14 @@ class PaddleOpMapper(object):
if 'OutSize' in input_names and len(op.input('OutSize')) > 0: if 'OutSize' in input_names and len(op.input('OutSize')) > 0:
node = helper.make_node( node = helper.make_node(
'Resize', 'Resize',
inputs=[op.input('X')[0], '', inputs=[op.input('X')[0], '', op.input('OutSize')[0]],
op.input('OutSize')[0]],
outputs=op.output('Out'), outputs=op.output('Out'),
mode='nearest', mode='nearest',
coordinate_transformation_mode=coordinate_transformation_mode) coordinate_transformation_mode=coordinate_transformation_mode)
elif 'Scale' in input_names and len(op.input('Scale')) > 0: elif 'Scale' in input_names and len(op.input('Scale')) > 0:
node = helper.make_node( node = helper.make_node(
'Resize', 'Resize',
inputs=[op.input('X')[0], inputs=[op.input('X')[0], op.input('Scale')[0]],
op.input('Scale')[0]],
outputs=op.output('Out'), outputs=op.output('Out'),
mode='nearest', mode='nearest',
coordinate_transformation_mode=coordinate_transformation_mode) coordinate_transformation_mode=coordinate_transformation_mode)
...@@ -685,8 +680,9 @@ class PaddleOpMapper(object): ...@@ -685,8 +680,9 @@ class PaddleOpMapper(object):
scale = op.attr('scale') scale = op.attr('scale')
if out_shape.count(-1) > 0: if out_shape.count(-1) > 0:
scale_name = self.get_name(op.type, 'scale') scale_name = self.get_name(op.type, 'scale')
scale_node = self.make_constant_node( scale_node = self.make_constant_node(scale_name,
scale_name, onnx_pb.TensorProto.FLOAT, [1, 1, scale, scale]) onnx_pb.TensorProto.FLOAT,
[1, 1, scale, scale])
roi_name = self.get_name(op.type, 'roi') roi_name = self.get_name(op.type, 'roi')
roi_node = self.make_constant_node(roi_name, roi_node = self.make_constant_node(roi_name,
onnx_pb.TensorProto.FLOAT, onnx_pb.TensorProto.FLOAT,
...@@ -737,8 +733,7 @@ class PaddleOpMapper(object): ...@@ -737,8 +733,7 @@ class PaddleOpMapper(object):
node1 = helper.make_node( node1 = helper.make_node(
'Clip', 'Clip',
inputs=[name0, min_name, max_name], inputs=[name0, min_name, max_name],
outputs=[name1], outputs=[name1], )
)
name2 = self.get_name(op.type, 'mul') name2 = self.get_name(op.type, 'mul')
node2 = helper.make_node( node2 = helper.make_node(
'Mul', inputs=[op.input('X')[0], name1], outputs=[name2]) 'Mul', inputs=[op.input('X')[0], name1], outputs=[name2])
......
...@@ -114,9 +114,8 @@ class TFOpMapper(OpMapper): ...@@ -114,9 +114,8 @@ class TFOpMapper(OpMapper):
else: else:
unsupported_ops.add(op) unsupported_ops.add(op)
if len(unsupported_ops) > 0: if len(unsupported_ops) > 0:
sys.stderr.write( sys.stderr.write("=========={} Ops are not supported yet======\n".
"=========={} Ops are not supported yet======\n".format( format(len(unsupported_ops)))
len(unsupported_ops)))
for op in unsupported_ops: for op in unsupported_ops:
sys.stderr.write("========== {} ==========\n".format(op)) sys.stderr.write("========== {} ==========\n".format(op))
sys.exit(-1) sys.exit(-1)
...@@ -296,8 +295,8 @@ class TFOpMapper(OpMapper): ...@@ -296,8 +295,8 @@ class TFOpMapper(OpMapper):
shape = [shape[i] for i in [0, 3, 1, 2]] shape = [shape[i] for i in [0, 3, 1, 2]]
if len(shape) == 3: if len(shape) == 3:
shape = [shape[i] for i in [2, 0, 1]] shape = [shape[i] for i in [2, 0, 1]]
self.weights[node.layer_name] = numpy.transpose( self.weights[node.layer_name] = numpy.transpose(node.value,
node.value, (2, 0, 1)) (2, 0, 1))
elif node.tf_data_format == "NCHW": elif node.tf_data_format == "NCHW":
if len(shape) == 4: if len(shape) == 4:
self.graph.data_format_propagation(node) self.graph.data_format_propagation(node)
...@@ -534,8 +533,8 @@ class TFOpMapper(OpMapper): ...@@ -534,8 +533,8 @@ class TFOpMapper(OpMapper):
attr = {"shape": shape} attr = {"shape": shape}
self.add_omit_nodes(param.layer_name, node.layer_name) self.add_omit_nodes(param.layer_name, node.layer_name)
else: else:
assert len(param.out_shapes[0] assert len(param.out_shapes[
) == 1, "Unexpected situation of shape parameter" 0]) == 1, "Unexpected situation of shape parameter"
attr = {"shape": [-1]} attr = {"shape": [-1]}
node.fluid_code.add_layer( node.fluid_code.add_layer(
"reshape", "reshape",
...@@ -647,15 +646,15 @@ class TFOpMapper(OpMapper): ...@@ -647,15 +646,15 @@ class TFOpMapper(OpMapper):
def ConcatV2(self, node): def ConcatV2(self, node):
inputs = [ inputs = [
self.graph.get_node(name, copy=True) self.graph.get_node(
for name in node.layer.input[:-1] name, copy=True) for name in node.layer.input[:-1]
] ]
axis = self.graph.get_node(node.layer.input[-1], copy=True) axis = self.graph.get_node(node.layer.input[-1], copy=True)
assert axis.layer_type == "Const" assert axis.layer_type == "Const"
self.add_omit_nodes(axis.layer_name, node.layer_name) self.add_omit_nodes(axis.layer_name, node.layer_name)
axis = axis.value axis = axis.value
if inputs[0].tf_data_format == "NHWC" and len( if inputs[0].tf_data_format == "NHWC" and len(inputs[0].out_shapes[
inputs[0].out_shapes[0]) == 4: 0]) == 4:
axis = nhwc_dim_to_nchw(inputs[0], axis) axis = nhwc_dim_to_nchw(inputs[0], axis)
attr = {"axis": axis} attr = {"axis": axis}
node.fluid_code.add_layer( node.fluid_code.add_layer(
...@@ -684,11 +683,12 @@ class TFOpMapper(OpMapper): ...@@ -684,11 +683,12 @@ class TFOpMapper(OpMapper):
def Pack(self, node): def Pack(self, node):
inputs = [ inputs = [
self.graph.get_node(name, copy=True) for name in node.layer.input self.graph.get_node(
name, copy=True) for name in node.layer.input
] ]
axis = node.get_attr("axis") axis = node.get_attr("axis")
if inputs[0].tf_data_format == "NHWC" and len( if inputs[0].tf_data_format == "NHWC" and len(inputs[0].out_shapes[
inputs[0].out_shapes[0]) == 4: 0]) == 4:
tf_data_format = list(inputs[0].tf_data_format) tf_data_format = list(inputs[0].tf_data_format)
tf_data_format.insert(axis, str(len(tf_data_format))) tf_data_format.insert(axis, str(len(tf_data_format)))
axis = nhwc_dim_to_nchw(inputs[0], axis) axis = nhwc_dim_to_nchw(inputs[0], axis)
...@@ -1010,8 +1010,8 @@ class TFOpMapper(OpMapper): ...@@ -1010,8 +1010,8 @@ class TFOpMapper(OpMapper):
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
else: else:
resize_shape = self.decoder.infer_shape_tensor( resize_shape = self.decoder.infer_shape_tensor(resize_shape,
resize_shape, node.out_shapes[0]) node.out_shapes[0])
align_corners = node.get_attr("align_corners") align_corners = node.get_attr("align_corners")
attr = {"align_corners": align_corners, "out_shape": resize_shape} attr = {"align_corners": align_corners, "out_shape": resize_shape}
node.fluid_code.add_layer( node.fluid_code.add_layer(
...@@ -1024,8 +1024,8 @@ class TFOpMapper(OpMapper): ...@@ -1024,8 +1024,8 @@ class TFOpMapper(OpMapper):
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
else: else:
resize_shape = self.decoder.infer_shape_tensor( resize_shape = self.decoder.infer_shape_tensor(resize_shape,
resize_shape, node.out_shapes[0]) node.out_shapes[0])
align_corners = node.get_attr("align_corners") align_corners = node.get_attr("align_corners")
attr = { attr = {
"align_corners": align_corners, "align_corners": align_corners,
......
...@@ -486,8 +486,8 @@ class TFOpMapperNHWC(OpMapper): ...@@ -486,8 +486,8 @@ class TFOpMapperNHWC(OpMapper):
attr = {"shape": shape} attr = {"shape": shape}
self.add_omit_nodes(param.layer_name, node.layer_name) self.add_omit_nodes(param.layer_name, node.layer_name)
else: else:
assert len(param.out_shapes[0] assert len(param.out_shapes[
) == 1, "Unexpected situation of shape parameter" 0]) == 1, "Unexpected situation of shape parameter"
attr = {"shape": [-1]} attr = {"shape": [-1]}
node.fluid_code.add_layer( node.fluid_code.add_layer(
"reshape", "reshape",
...@@ -577,8 +577,8 @@ class TFOpMapperNHWC(OpMapper): ...@@ -577,8 +577,8 @@ class TFOpMapperNHWC(OpMapper):
def ConcatV2(self, node): def ConcatV2(self, node):
inputs = [ inputs = [
self.graph.get_node(name, copy=True) self.graph.get_node(
for name in node.layer.input[:-1] name, copy=True) for name in node.layer.input[:-1]
] ]
axis = self.graph.get_node(node.layer.input[-1], copy=True) axis = self.graph.get_node(node.layer.input[-1], copy=True)
assert axis.layer_type == "Const" assert axis.layer_type == "Const"
...@@ -608,7 +608,8 @@ class TFOpMapperNHWC(OpMapper): ...@@ -608,7 +608,8 @@ class TFOpMapperNHWC(OpMapper):
def Pack(self, node): def Pack(self, node):
inputs = [ inputs = [
self.graph.get_node(name, copy=True) for name in node.layer.input self.graph.get_node(
name, copy=True) for name in node.layer.input
] ]
axis = node.get_attr("axis") axis = node.get_attr("axis")
attr = {"axis": axis} attr = {"axis": axis}
...@@ -949,8 +950,8 @@ class TFOpMapperNHWC(OpMapper): ...@@ -949,8 +950,8 @@ class TFOpMapperNHWC(OpMapper):
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
else: else:
resize_shape = self.decoder.infer_shape_tensor( resize_shape = self.decoder.infer_shape_tensor(resize_shape,
resize_shape, node.out_shapes[0]) node.out_shapes[0])
align_corners = node.get_attr("align_corners") align_corners = node.get_attr("align_corners")
attr = {"perm": [0, 3, 1, 2]} attr = {"perm": [0, 3, 1, 2]}
node.fluid_code.add_layer( node.fluid_code.add_layer(
...@@ -969,8 +970,8 @@ class TFOpMapperNHWC(OpMapper): ...@@ -969,8 +970,8 @@ class TFOpMapperNHWC(OpMapper):
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
else: else:
resize_shape = self.decoder.infer_shape_tensor( resize_shape = self.decoder.infer_shape_tensor(resize_shape,
resize_shape, node.out_shapes[0]) node.out_shapes[0])
align_corners = node.get_attr("align_corners") align_corners = node.get_attr("align_corners")
attr = {"perm": [0, 3, 1, 2]} attr = {"perm": [0, 3, 1, 2]}
node.fluid_code.add_layer( node.fluid_code.add_layer(
......
...@@ -768,8 +768,8 @@ class TFOptimizer(object): ...@@ -768,8 +768,8 @@ class TFOptimizer(object):
is_prelu = False is_prelu = False
continue continue
if len(in_nodes0[0].outputs) != 1 or len( if len(in_nodes0[0].outputs) != 1 or len(in_nodes0[1]
in_nodes0[1].outputs) != 1: .outputs) != 1:
is_prelu = False is_prelu = False
continue continue
...@@ -778,8 +778,8 @@ class TFOptimizer(object): ...@@ -778,8 +778,8 @@ class TFOptimizer(object):
self.graph.get_node(in_name) self.graph.get_node(in_name)
for in_name in in_nodes0[1].inputs for in_name in in_nodes0[1].inputs
] ]
if in_nodes2[1].layer_type != "Const" or numpy.fabs( if in_nodes2[1].layer_type != "Const" or numpy.fabs(in_nodes2[
in_nodes2[1].value - 0.5) > 1e-06: 1].value - 0.5) > 1e-06:
is_prelu = False is_prelu = False
continue continue
if in_nodes2[0].layer_type != "Mul": if in_nodes2[0].layer_type != "Mul":
...@@ -788,8 +788,8 @@ class TFOptimizer(object): ...@@ -788,8 +788,8 @@ class TFOptimizer(object):
if exist_act(in_nodes2[0]): if exist_act(in_nodes2[0]):
is_prelu = False is_prelu = False
continue continue
if len(in_nodes2[1].outputs) != 1 or len( if len(in_nodes2[1].outputs) != 1 or len(in_nodes2[0]
in_nodes2[0].outputs) != 1: .outputs) != 1:
is_prelu = False is_prelu = False
continue continue
...@@ -804,8 +804,8 @@ class TFOptimizer(object): ...@@ -804,8 +804,8 @@ class TFOptimizer(object):
if exist_act(in_nodes3[1]): if exist_act(in_nodes3[1]):
is_prelu = False is_prelu = False
continue continue
if len(in_nodes3[0].outputs) != 1 or len( if len(in_nodes3[0].outputs) != 1 or len(in_nodes3[1]
in_nodes3[1].outputs) != 1: .outputs) != 1:
is_prelu = False is_prelu = False
continue continue
...@@ -857,12 +857,12 @@ class TFOptimizer(object): ...@@ -857,12 +857,12 @@ class TFOptimizer(object):
mode = "element" mode = "element"
elif len(in_nodes3[0].value.shape) == 0: elif len(in_nodes3[0].value.shape) == 0:
mode = "all" mode = "all"
elif len(in_nodes3[0].value.shape elif len(in_nodes3[0].value.shape) == 1 and in_nodes3[
) == 1 and in_nodes3[0].value.shape[0] == 1: 0].value.shape[0] == 1:
mode = "all" mode = "all"
elif len(in_shape) == 4 and len( elif len(in_shape) == 4 and len(in_nodes3[
in_nodes3[0].value.shape 0].value.shape) == 1 and in_nodes3[0].value.shape[
) == 1 and in_nodes3[0].value.shape[0] == in_shape[-1]: 0] == in_shape[-1]:
mode = "channel" mode = "channel"
weight = self.op_mapper.weights[in_nodes3[0].layer_name] weight = self.op_mapper.weights[in_nodes3[0].layer_name]
weight = numpy.expand_dims(weight, 0) weight = numpy.expand_dims(weight, 0)
...@@ -917,14 +917,15 @@ class TFOptimizer(object): ...@@ -917,14 +917,15 @@ class TFOptimizer(object):
self.graph.get_node(in_name) for in_name in node.inputs self.graph.get_node(in_name) for in_name in node.inputs
] ]
if in_nodes0[0].layer_type != "Mul" or in_nodes0[ if in_nodes0[0].layer_type != "Mul" or in_nodes0[
1].layer_type != "Const" or in_nodes0[1].value.size != 1: 1].layer_type != "Const" or in_nodes0[
1].value.size != 1:
is_scale = False is_scale = False
continue continue
if exist_act(in_nodes0[0]): if exist_act(in_nodes0[0]):
is_scale = False is_scale = False
continue continue
if len(in_nodes0[0].outputs) != 1 or len( if len(in_nodes0[0].outputs) != 1 or len(in_nodes0[1]
in_nodes0[1].outputs) != 1: .outputs) != 1:
is_scale = False is_scale = False
continue continue
...@@ -940,8 +941,8 @@ class TFOptimizer(object): ...@@ -940,8 +941,8 @@ class TFOptimizer(object):
if exist_act(in_nodes1[1]): if exist_act(in_nodes1[1]):
is_scale = False is_scale = False
continue continue
if len(in_nodes1[0].outputs) != 1 or len( if len(in_nodes1[0].outputs) != 1 or len(in_nodes1[1]
in_nodes1[1].outputs) != 1: .outputs) != 1:
is_scale = False is_scale = False
continue continue
...@@ -963,8 +964,8 @@ class TFOptimizer(object): ...@@ -963,8 +964,8 @@ class TFOptimizer(object):
scale = 1.0 / in_nodes2[1].value * in_nodes1[0].value scale = 1.0 / in_nodes2[1].value * in_nodes1[0].value
act = None act = None
if node.fluid_code.layers[0].param_attr is not None: if node.fluid_code.layers[0].param_attr is not None:
act = node.fluid_code.layers[0].param_attr.get( act = node.fluid_code.layers[0].param_attr.get("act",
"act", None) None)
node.fluid_code.clear() node.fluid_code.clear()
attr = { attr = {
...@@ -1003,17 +1004,17 @@ class TFOptimizer(object): ...@@ -1003,17 +1004,17 @@ class TFOptimizer(object):
if exist_act(in_nodes0[0]): if exist_act(in_nodes0[0]):
is_affine_channel = False is_affine_channel = False
continue continue
if len(in_nodes0[0].outputs) != 1 or len( if len(in_nodes0[0].outputs) != 1 or len(in_nodes0[1]
in_nodes0[1].outputs) != 1: .outputs) != 1:
is_affine_channel = False is_affine_channel = False
continue continue
in_nodes1 = [ in_nodes1 = [
self.graph.get_node(in_name) self.graph.get_node(in_name)
for in_name in in_nodes0[0].inputs for in_name in in_nodes0[0].inputs
] ]
if len(in_nodes1[0].out_shapes[0] if len(in_nodes1[0].out_shapes[0]) != 4 or in_nodes1[
) != 4 or in_nodes1[1].layer_type != "Const" or len( 1].layer_type != "Const" or len(in_nodes1[1]
in_nodes1[1].value.shape) != 3: .value.shape) != 3:
is_affine_channel = False is_affine_channel = False
continue continue
if len(in_nodes1[1].outputs) != 1: if len(in_nodes1[1].outputs) != 1:
...@@ -1036,8 +1037,8 @@ class TFOptimizer(object): ...@@ -1036,8 +1037,8 @@ class TFOptimizer(object):
node.layer_type = "AffineChannel" node.layer_type = "AffineChannel"
node.inputs = [in_node.layer_name] node.inputs = [in_node.layer_name]
scale = 1.0 / in_nodes0[1].value.flatten() scale = 1.0 / in_nodes0[1].value.flatten()
bias = in_nodes1[1].value.flatten( bias = in_nodes1[1].value.flatten() / in_nodes0[
) / in_nodes0[1].value.flatten() 1].value.flatten()
if not bias_add: if not bias_add:
bias *= -1.0 bias *= -1.0
self.op_mapper.weights[node.layer_name + "_scale"] = scale self.op_mapper.weights[node.layer_name + "_scale"] = scale
...@@ -1045,8 +1046,8 @@ class TFOptimizer(object): ...@@ -1045,8 +1046,8 @@ class TFOptimizer(object):
act = None act = None
if node.fluid_code.layers[0].param_attr is not None: if node.fluid_code.layers[0].param_attr is not None:
act = node.fluid_code.layers[0].param_attr.get( act = node.fluid_code.layers[0].param_attr.get("act",
"act", None) None)
node.fluid_code.clear() node.fluid_code.clear()
attr = { attr = {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册