提交 13aeafee 编写于 作者: S SunAhong1993

release

上级 6e035473
...@@ -33,7 +33,7 @@ X2Paddle的架构设计着重考虑了对多深度学习框架的的支持以及 ...@@ -33,7 +33,7 @@ X2Paddle的架构设计着重考虑了对多深度学习框架的的支持以及
- pytorch:torch >=1.5.0 (script方式暂不支持1.7.0) - pytorch:torch >=1.5.0 (script方式暂不支持1.7.0)
## 安装 ## 安装
### 方式一:源码安装 ### 方式一:源码安装(推荐)
``` ```
git clone https://github.com/PaddlePaddle/X2Paddle.git git clone https://github.com/PaddlePaddle/X2Paddle.git
cd X2Paddle cd X2Paddle
...@@ -41,7 +41,7 @@ git checkout develop ...@@ -41,7 +41,7 @@ git checkout develop
python setup.py install python setup.py install
``` ```
### 方式二:pip安装(推荐) ### 方式二:pip安装
我们会定期更新pip源上的x2paddle版本 我们会定期更新pip源上的x2paddle版本
``` ```
pip install x2paddle --index https://pypi.python.org/simple/ pip install x2paddle --index https://pypi.python.org/simple/
...@@ -95,8 +95,10 @@ X2Paddle提供了工具解决如下问题,详见[tools/README.md](tools/README ...@@ -95,8 +95,10 @@ X2Paddle提供了工具解决如下问题,详见[tools/README.md](tools/README
4. [X2Paddle添加内置的Caffe自定义层](./docs/user_guides/add_caffe_custom_layer.md) 4. [X2Paddle添加内置的Caffe自定义层](./docs/user_guides/add_caffe_custom_layer.md)
5. [转换后PaddlePaddle预测模型简介](./docs/user_guides/pd_folder_introduction.py) 5. [转换后PaddlePaddle预测模型简介](./docs/user_guides/pd_folder_introduction.py)
6. [Paddle到ONNX的转换](https://github.com/PaddlePaddle/Paddle2ONNX) 6. [Paddle到ONNX的转换](https://github.com/PaddlePaddle/Paddle2ONNX)
7. [X2Paddle测试模型库](./docs/introduction/x2paddle_model_zoo.md)
8. [X2Paddle支持的op列表](./docs/introduction/op_list.md) ## 支持列表文档
1. [X2Paddle测试模型库](./docs/introduction/x2paddle_model_zoo.md)
2. [X2Paddle支持的op列表](./docs/introduction/op_list.md)
## 转换教程 ## 转换教程
...@@ -109,16 +111,9 @@ X2Paddle提供了工具解决如下问题,详见[tools/README.md](tools/README ...@@ -109,16 +111,9 @@ X2Paddle提供了工具解决如下问题,详见[tools/README.md](tools/README
方式一:trace方式,转换后的代码有模块划分,每个模块的功能与PyTorch相同。 方式一:trace方式,转换后的代码有模块划分,每个模块的功能与PyTorch相同。
方式二:script方式,转换后的代码按执行顺序逐行出现。 方式二:script方式,转换后的代码按执行顺序逐行出现。
2. 新增Caffe/ONNX/Tensorflow到Paddle动态图的转换。 2. 新增Caffe/ONNX/Tensorflow到Paddle动态图的转换。
3. 新增TensorFlow op映射(14个):Neg、Greater、FloorMod、LogicalAdd、Prd、Equal、Conv3D、Ceil、AddN、DivNoNan、Where、MirrorPad、Size、TopKv2。 3. 新增TensorFlow op(14个):Neg、Greater、FloorMod、LogicalAdd、Prd、Equal、Conv3D、Ceil、AddN、DivNoNan、Where、MirrorPad、Size、TopKv2
4. 新增Optimizer模块,主要包括op融合、op消除功能,转换后的代码可读性更强,进行预测时耗时更短。 4. 新增Optimizer模块,主要包括op融合、op消除功能,转换后的代码可读性更强,进行预测时耗时更短。
2021.04.30
1. 新增支持转换的模型:[SwinTransformer](https://github.com/microsoft/Swin-Transformer/)[BASNet](https://github.com/xuebinqin/BASNet)[DBFace](https://github.com/dlunion/DBFace)[EasyOCR](https://github.com/JaidedAI/EasyOCR)[CifarNet](https://github.com/tensorflow/models/blob/master/research/slim/nets/cifarnet.py)等。
2. 支持Windows上使用本工具。
3. 新增TensorFlow op映射(4个):SplitV、ReverseV2、BatchToSpaceND、SpaceToBatchND。
4. 新增PyTorch op映射(11个):aten::index、aten::roll、aten::adaptive_avg_pool1d、aten::reflection_pad2d、aten::reflection_pad1d、aten::instance_norm、aten::gru、aten::norm、aten::clamp_min、aten:prelu、aten:split_with_sizes。
5. 新增ONNX op映射(1个):DepthToSpace。
6. 新增Caffe op映射(1个):op:MemoryData。
## 贡献代码 ## 贡献代码
......
__version__ = "1.1.0" __version__ = "1.0.2"
from .core.program import PaddleGraph from .core.program import PaddleGraph
......
...@@ -41,6 +41,7 @@ def arg_parser(): ...@@ -41,6 +41,7 @@ def arg_parser():
parser.add_argument( parser.add_argument(
"--save_dir", "--save_dir",
"-s", "-s",
required=True,
type=_text_type, type=_text_type,
default=None, default=None,
help="path to save translated model") help="path to save translated model")
...@@ -220,8 +221,6 @@ def main(): ...@@ -220,8 +221,6 @@ def main():
x2paddle.__version__)) x2paddle.__version__))
return return
assert args.save_dir is not None, "--save_dir is not defined"
try: try:
import platform import platform
v0, v1, v2 = platform.python_version().split('.') v0, v1, v2 = platform.python_version().split('.')
......
...@@ -58,7 +58,8 @@ class TFOpMapper(OpMapper): ...@@ -58,7 +58,8 @@ class TFOpMapper(OpMapper):
'swish_f32': ['paddle.nn.Swish'], 'swish_f32': ['paddle.nn.Swish'],
'Tanh': ['paddle.nn.Tanh'], 'Tanh': ['paddle.nn.Tanh'],
'Softplus': ['paddle.nn.Softplus'], 'Softplus': ['paddle.nn.Softplus'],
'LeakyRelu': ['paddle.nn.LeakyReLU', dict(alpha='negative_slope')], 'LeakyRelu': ['paddle.nn.LeakyReLU',
dict(alpha='negative_slope')],
'Softmax': ['paddle.nn.Softmax'], 'Softmax': ['paddle.nn.Softmax'],
'Floor': ['paddle.floor'], 'Floor': ['paddle.floor'],
'Erf': ['paddle.erf'], 'Erf': ['paddle.erf'],
...@@ -95,8 +96,7 @@ class TFOpMapper(OpMapper): ...@@ -95,8 +96,7 @@ class TFOpMapper(OpMapper):
self.nn_name2id = dict() self.nn_name2id = dict()
self.input_index = 0 self.input_index = 0
self.inputs_info = dict() self.inputs_info = dict()
self.paddle_graph = PaddleGraph( self.paddle_graph = PaddleGraph(parent_layer=None, graph_type="dygraph", source_type="tf")
parent_layer=None, graph_type="dygraph", source_type="tf")
self.paddle_graph.outputs = self.graph.output_nodes self.paddle_graph.outputs = self.graph.output_nodes
not_placeholder = list() not_placeholder = list()
...@@ -149,8 +149,8 @@ class TFOpMapper(OpMapper): ...@@ -149,8 +149,8 @@ class TFOpMapper(OpMapper):
return True return True
else: else:
if len(unsupported_ops) > 0: if len(unsupported_ops) > 0:
print("\n========= {} OPs are not supported yet ===========". print("\n========= {} OPs are not supported yet ===========".format(
format(len(unsupported_ops))) len(unsupported_ops)))
for op in unsupported_ops: for op in unsupported_ops:
print("========== {} ============".format(op)) print("========== {} ============".format(op))
return False return False
...@@ -196,10 +196,7 @@ class TFOpMapper(OpMapper): ...@@ -196,10 +196,7 @@ class TFOpMapper(OpMapper):
inputs={"x": x.name, inputs={"x": x.name,
"y": y.name}, "y": y.name},
outputs=[node.name]) outputs=[node.name])
self.paddle_graph.layers[layer_id].input_shapes = { self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
"x": x_shape,
"y": y_shape
}
def bool_map(self, node): def bool_map(self, node):
op_type = self.bool_ops[node.layer_type] op_type = self.bool_ops[node.layer_type]
...@@ -254,8 +251,7 @@ class TFOpMapper(OpMapper): ...@@ -254,8 +251,7 @@ class TFOpMapper(OpMapper):
if perm.layer_type == "Const": if perm.layer_type == "Const":
perm = perm.value.tolist() perm = perm.value.tolist()
else: else:
perm = self.decoder.infer_tensor( perm = self.decoder.infer_tensor(perm, use_diff_inputs=False).tolist()
perm, use_diff_inputs=False).tolist()
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.transpose", "paddle.transpose",
...@@ -267,7 +263,9 @@ class TFOpMapper(OpMapper): ...@@ -267,7 +263,9 @@ class TFOpMapper(OpMapper):
if len(node.layer.input) == 1: if len(node.layer.input) == 1:
cond = self.graph.get_input_node(node, 0) cond = self.graph.get_input_node(node, 0)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.nonzero", inputs={"x": cond.name}, outputs=[node.name]) "paddle.nonzero",
inputs={"x": cond.name},
outputs=[node.name])
else: else:
cond = self.graph.get_input_node(node, 0) cond = self.graph.get_input_node(node, 0)
x = self.graph.get_input_node(node, 1) x = self.graph.get_input_node(node, 1)
...@@ -302,7 +300,10 @@ class TFOpMapper(OpMapper): ...@@ -302,7 +300,10 @@ class TFOpMapper(OpMapper):
layer_attrs["fill_value"] = input_value.value layer_attrs["fill_value"] = input_value.value
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.full", inputs=inputs, outputs=[node.name], **layer_attrs) "paddle.full",
inputs=inputs,
outputs=[node.name],
**layer_attrs)
def DepthToSpace(self, node): def DepthToSpace(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
...@@ -418,8 +419,7 @@ class TFOpMapper(OpMapper): ...@@ -418,8 +419,7 @@ class TFOpMapper(OpMapper):
if kernel.layer_type == 'Const': if kernel.layer_type == 'Const':
kernel_value = kernel.value kernel_value = kernel.value
else: else:
kernel_value = self.decoder.infer_tensor( kernel_value = self.decoder.infer_tensor(kernel, use_diff_inputs=False)
kernel, use_diff_inputs=False)
kernel_weight_name = op_name + ".weight" kernel_weight_name = op_name + ".weight"
self.params[kernel_weight_name] = numpy.transpose(kernel_value, self.params[kernel_weight_name] = numpy.transpose(kernel_value,
(3, 2, 0, 1)) (3, 2, 0, 1))
...@@ -444,6 +444,7 @@ class TFOpMapper(OpMapper): ...@@ -444,6 +444,7 @@ class TFOpMapper(OpMapper):
outputs=[input_name], outputs=[input_name],
shape=[0, k_size[2], 0, 0]) shape=[0, k_size[2], 0, 0])
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.Conv2D", kernel="paddle.nn.Conv2D",
inputs={"input": input_name}, inputs={"input": input_name},
...@@ -484,8 +485,7 @@ class TFOpMapper(OpMapper): ...@@ -484,8 +485,7 @@ class TFOpMapper(OpMapper):
if kernel.layer_type == 'Const': if kernel.layer_type == 'Const':
kernel_value = kernel.value kernel_value = kernel.value
else: else:
kernel_value = self.decoder.infer_tensor( kernel_value = self.decoder.infer_tensor(kernel, use_diff_inputs=False)
kernel, use_diff_inputs=False)
kernel_weight_name = op_name + ".weight" kernel_weight_name = op_name + ".weight"
self.params[kernel_weight_name] = numpy.transpose(kernel_value, self.params[kernel_weight_name] = numpy.transpose(kernel_value,
(4, 3, 0, 1, 2)) (4, 3, 0, 1, 2))
...@@ -569,14 +569,10 @@ class TFOpMapper(OpMapper): ...@@ -569,14 +569,10 @@ class TFOpMapper(OpMapper):
else: else:
n, c, h, w = input.out_shapes[0] n, c, h, w = input.out_shapes[0]
self.params["{}_{}".format(node.name, gamma.name)] = self.params[ self.params["{}_{}".format(node.name, gamma.name)] = self.params[gamma.name]
gamma.name] self.params["{}_{}".format(node.name, beta.name)] = self.params[beta.name]
self.params["{}_{}".format(node.name, beta.name)] = self.params[ self.params["{}_{}".format(node.name, moving_mean.name)] = self.params[moving_mean.name]
beta.name] self.params["{}_{}".format(node.name, moving_var.name)] = self.params[moving_var.name]
self.params["{}_{}".format(node.name, moving_mean.name)] = self.params[
moving_mean.name]
self.params["{}_{}".format(node.name, moving_var.name)] = self.params[
moving_var.name]
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.BatchNorm", kernel="paddle.nn.BatchNorm",
inputs={"input": input_name}, inputs={"input": input_name},
...@@ -585,10 +581,8 @@ class TFOpMapper(OpMapper): ...@@ -585,10 +581,8 @@ class TFOpMapper(OpMapper):
epsilon=node.get_attr("epsilon"), epsilon=node.get_attr("epsilon"),
param_attr=string("{}_{}".format(node.name, gamma.name)), param_attr=string("{}_{}".format(node.name, gamma.name)),
bias_attr=string("{}_{}".format(node.name, beta.name)), bias_attr=string("{}_{}".format(node.name, beta.name)),
moving_mean_name=string("{}_{}".format(node.name, moving_mean_name=string("{}_{}".format(node.name, moving_mean.name)),
moving_mean.name)), moving_variance_name=string("{}_{}".format(node.name, moving_var.name)),
moving_variance_name=string("{}_{}".format(node.name,
moving_var.name)),
is_test=True) is_test=True)
if data_format == "NHWC": if data_format == "NHWC":
...@@ -665,6 +659,7 @@ class TFOpMapper(OpMapper): ...@@ -665,6 +659,7 @@ class TFOpMapper(OpMapper):
def MirrorPad(self, node): def MirrorPad(self, node):
self.Pad(node) self.Pad(node)
def PadV2(self, node): def PadV2(self, node):
self.Pad(node) self.Pad(node)
...@@ -693,12 +688,15 @@ class TFOpMapper(OpMapper): ...@@ -693,12 +688,15 @@ class TFOpMapper(OpMapper):
inputs={"input": input_name}, inputs={"input": input_name},
outputs=[node.name]) outputs=[node.name])
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.prod", inputs={"x": node.name}, outputs=[node.name]) kernel="paddle.prod",
inputs={"x": node.name},
outputs=[node.name])
def Ceil(self, node): def Ceil(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.ceil", inputs={"x": input.name}, kernel="paddle.ceil",
inputs={"x": input.name},
outputs=[node.name]) outputs=[node.name])
def ArgMax(self, node): def ArgMax(self, node):
...@@ -767,6 +765,7 @@ class TFOpMapper(OpMapper): ...@@ -767,6 +765,7 @@ class TFOpMapper(OpMapper):
self.params[kernel_weight_name] = numpy.transpose(kernel.value, self.params[kernel_weight_name] = numpy.transpose(kernel.value,
(2, 3, 0, 1)) (2, 3, 0, 1))
input_name = input.name input_name = input.name
if data_format == "NHWC": if data_format == "NHWC":
in_shape = [in_shape[i] for i in [0, 3, 1, 2]] in_shape = [in_shape[i] for i in [0, 3, 1, 2]]
...@@ -834,6 +833,15 @@ class TFOpMapper(OpMapper): ...@@ -834,6 +833,15 @@ class TFOpMapper(OpMapper):
stride=strides[2:4], stride=strides[2:4],
padding=string(pad_mode)) padding=string(pad_mode))
# self.paddle_graph.add_layer(
# kernel="fluid.layers.pool2d",
# inputs={"input": input_name},
# outputs=[node.name],
# pool_size=k_size[2:4],
# pool_type=string("avg"),
# pool_stride=strides[2:4],
# pool_padding=string(pad_mode))
if data_format == "NHWC": if data_format == "NHWC":
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.transpose", kernel="paddle.transpose",
...@@ -876,9 +884,7 @@ class TFOpMapper(OpMapper): ...@@ -876,9 +884,7 @@ class TFOpMapper(OpMapper):
axis = 1 axis = 1
else: else:
raise Exception("Unexpected situation happend in Unpack OP") raise Exception("Unexpected situation happend in Unpack OP")
layer_outputs = [ layer_outputs = ["{}_p{}".format(node.layer_name, i) for i in range(num)]
"{}_p{}".format(node.layer_name, i) for i in range(num)
]
if len(layer_outputs) == 1: if len(layer_outputs) == 1:
layer_outputs[0] = "[{}]".format(node.layer_name) layer_outputs[0] = "[{}]".format(node.layer_name)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
...@@ -1081,8 +1087,7 @@ class TFOpMapper(OpMapper): ...@@ -1081,8 +1087,7 @@ class TFOpMapper(OpMapper):
kernel="paddle.split", kernel="paddle.split",
inputs={"x": input.name}, inputs={"x": input.name},
outputs=[ outputs=[
"{}_p{}".format(node.layer_name, i) "{}_p{}".format(node.layer_name, i) for i in range(len(size_splits))
for i in range(len(size_splits))
], ],
num_or_sections=size_splits, num_or_sections=size_splits,
axis=dim) axis=dim)
...@@ -1098,8 +1103,7 @@ class TFOpMapper(OpMapper): ...@@ -1098,8 +1103,7 @@ class TFOpMapper(OpMapper):
begin = begin.value.tolist() begin = begin.value.tolist()
attrs['offsets'] = begin attrs['offsets'] = begin
else: else:
begin = self.decoder.infer_tensor( begin = self.decoder.infer_tensor(begin, use_diff_inputs=False).tolist()
begin, use_diff_inputs=False).tolist()
attrs['offsets'] = begin attrs['offsets'] = begin
if size.layer_type == "Const": if size.layer_type == "Const":
size = size.value.tolist() size = size.value.tolist()
...@@ -1114,18 +1118,19 @@ class TFOpMapper(OpMapper): ...@@ -1114,18 +1118,19 @@ class TFOpMapper(OpMapper):
shape=shape) shape=shape)
inputs['shape'] = reshape_name inputs['shape'] = reshape_name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.crop", inputs=inputs, outputs=[node.name], **attrs) kernel="paddle.crop",
inputs=inputs,
outputs=[node.name],
**attrs)
def ResizeNearestNeighbor(self, node): def ResizeNearestNeighbor(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
resize_shape = self.graph.get_input_node(node, 1) resize_shape = self.graph.get_input_node(node, 1)
data_format = "NHWC" data_format = "NHWC"
inputs = {"x": input.name} inputs = {"x": input.name}
attrs = { attrs = {"align_corners": node.get_attr("align_corners"),
"align_corners": node.get_attr("align_corners"),
"mode": string("nearest"), "mode": string("nearest"),
"align_mode": 1 "align_mode": 1}
}
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
...@@ -1167,11 +1172,9 @@ class TFOpMapper(OpMapper): ...@@ -1167,11 +1172,9 @@ class TFOpMapper(OpMapper):
resize_shape = self.graph.get_input_node(node, 1) resize_shape = self.graph.get_input_node(node, 1)
data_format = "NHWC" data_format = "NHWC"
inputs = {"x": input.name} inputs = {"x": input.name}
attrs = { attrs = {"align_corners": node.get_attr("align_corners"),
"align_corners": node.get_attr("align_corners"),
"mode": string("bilinear"), "mode": string("bilinear"),
"align_mode": 1 "align_mode": 1}
}
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
...@@ -1276,17 +1279,15 @@ class TFOpMapper(OpMapper): ...@@ -1276,17 +1279,15 @@ class TFOpMapper(OpMapper):
if out_shape.layer_type == "Const": if out_shape.layer_type == "Const":
out_shape = out_shape.value.tolist() out_shape = out_shape.value.tolist()
else: else:
out_shape = self.decoder.infer_tensor( out_shape = self.decoder.infer_tensor(out_shape,
out_shape, out_shape=node.out_shapes[0]) out_shape=node.out_shapes[0])
in_shape = input.out_shapes[0] in_shape = input.out_shapes[0]
if in_shape.count(-1) > 2: if in_shape.count(-1) > 2:
in_shape = self.decoder.infer_tensor( in_shape = self.decoder.infer_tensor(input, use_diff_inputs=False).shape
input, use_diff_inputs=False).shape
k_size = kernel.out_shapes[0] k_size = kernel.out_shapes[0]
if k_size.count(-1) > 2: if k_size.count(-1) > 2:
k_size = self.decoder.infer_tensor( k_size = self.decoder.infer_tensor(kernel, use_diff_inputs=False).shape
kernel, use_diff_inputs=False).shape
pad_mode = node.get_attr("padding").decode() pad_mode = node.get_attr("padding").decode()
strides = node.get_attr("strides") strides = node.get_attr("strides")
...@@ -1309,6 +1310,19 @@ class TFOpMapper(OpMapper): ...@@ -1309,6 +1310,19 @@ class TFOpMapper(OpMapper):
perm=[0, 3, 1, 2]) perm=[0, 3, 1, 2])
input_name = transpose_name input_name = transpose_name
# TODO(syf): The output_size is not set.
# self.paddle_graph.add_layer(
# kernel="paddle.nn.Conv2DTranspose",
# inputs={"input": input_name},
# outputs=layer_outputs,
# weight_attr=string(kernel_name),
# bias_attr=False,
# in_channels=k_size[3],
# out_channels=k_size[2],
# kernel_size=k_size[0:2],
# stride=strides[2:4],
# dilation=dilations[2:4],
# padding=string(pad_mode))
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"self.create_parameter", "self.create_parameter",
inputs={}, inputs={},
...@@ -1318,11 +1332,8 @@ class TFOpMapper(OpMapper): ...@@ -1318,11 +1332,8 @@ class TFOpMapper(OpMapper):
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.functional.conv2d_transpose", kernel="paddle.nn.functional.conv2d_transpose",
inputs={ inputs={"x": input_name,
"x": input_name, "weight": "{}_{}".format(node.name, kernel_name).replace(".", "_")},
"weight":
"{}_{}".format(node.name, kernel_name).replace(".", "_")
},
outputs=[node.name], outputs=[node.name],
bias=None, bias=None,
stride=strides[2:4], stride=strides[2:4],
...@@ -1350,7 +1361,10 @@ class TFOpMapper(OpMapper): ...@@ -1350,7 +1361,10 @@ class TFOpMapper(OpMapper):
inputs["repeat_times"] = repeat_times.name inputs["repeat_times"] = repeat_times.name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.tile", inputs=inputs, outputs=[node.name], **attr) kernel="paddle.tile",
inputs=inputs,
outputs=[node.name],
**attr)
def Range(self, node): def Range(self, node):
start = self.graph.get_input_node(node, 0) start = self.graph.get_input_node(node, 0)
...@@ -1383,7 +1397,10 @@ class TFOpMapper(OpMapper): ...@@ -1383,7 +1397,10 @@ class TFOpMapper(OpMapper):
attr["dtype"] = string(node.dtype) attr["dtype"] = string(node.dtype)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.arange", inputs=inputs, outputs=[node.name], **attr) kernel="paddle.arange",
inputs=inputs,
outputs=[node.name],
**attr)
def SquaredDifference(self, node): def SquaredDifference(self, node):
x = self.graph.get_input_node(node, 0) x = self.graph.get_input_node(node, 0)
...@@ -1394,20 +1411,14 @@ class TFOpMapper(OpMapper): ...@@ -1394,20 +1411,14 @@ class TFOpMapper(OpMapper):
# TODO(syf) # TODO(syf)
layer_id = self.paddle_graph.add_layer( layer_id = self.paddle_graph.add_layer(
"paddle.subtract", inputs=inputs, outputs=[node.name]) "paddle.subtract", inputs=inputs, outputs=[node.name])
self.paddle_graph.layers[layer_id].input_shapes = { self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
"x": x_shape,
"y": y_shape
}
inputs = {"x": node.name, "y": node.name} inputs = {"x": node.name, "y": node.name}
x_shape = node.out_shapes[0] x_shape = node.out_shapes[0]
y_shape = node.out_shapes[0] y_shape = node.out_shapes[0]
layer_id = self.paddle_graph.add_layer( layer_id = self.paddle_graph.add_layer(
"paddle.multiply", inputs=inputs, outputs=[node.name]) "paddle.multiply", inputs=inputs, outputs=[node.name])
self.paddle_graph.layers[layer_id].input_shapes = { self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
"x": x_shape,
"y": y_shape
}
def OneHot(self, node): def OneHot(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
...@@ -1461,7 +1472,10 @@ class TFOpMapper(OpMapper): ...@@ -1461,7 +1472,10 @@ class TFOpMapper(OpMapper):
outputs=[input_name], outputs=[input_name],
dtype=string("bool")) dtype=string("bool"))
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.all", inputs={"x": input_name}, outputs=[node.name], **attr) "paddle.all",
inputs={"x": input_name},
outputs=[node.name],
**attr)
node.layer.attr['dtype'].type = 10 node.layer.attr['dtype'].type = 10
...@@ -1482,7 +1496,10 @@ class TFOpMapper(OpMapper): ...@@ -1482,7 +1496,10 @@ class TFOpMapper(OpMapper):
shape=[-1]) shape=[-1])
inputs = {'x': embeddings.name, 'index': index_name} inputs = {'x': embeddings.name, 'index': index_name}
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.gather", inputs=inputs, outputs=[node.name], axis=axis) "paddle.gather",
inputs=inputs,
outputs=[node.name],
axis=axis)
if len(index.out_shapes[0]) != 1: if len(index.out_shapes[0]) != 1:
out_shape = node.out_shapes[0] out_shape = node.out_shapes[0]
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
...@@ -1496,7 +1513,9 @@ class TFOpMapper(OpMapper): ...@@ -1496,7 +1513,9 @@ class TFOpMapper(OpMapper):
index = self.graph.get_input_node(node, 1) index = self.graph.get_input_node(node, 1)
inputs = {'x': x.name, 'index': index.name} inputs = {'x': x.name, 'index': index.name}
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.gather_nd", inputs=inputs, outputs=[node.name]) "paddle.gather_nd",
inputs=inputs,
outputs=[node.name])
def ExpandDims(self, node): def ExpandDims(self, node):
x = self.graph.get_input_node(node, 0, copy=True) x = self.graph.get_input_node(node, 0, copy=True)
...@@ -1511,7 +1530,10 @@ class TFOpMapper(OpMapper): ...@@ -1511,7 +1530,10 @@ class TFOpMapper(OpMapper):
else: else:
inputs['axis'] = y.name inputs['axis'] = y.name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.unsqueeze", inputs=inputs, outputs=[node.name], **attr) "paddle.unsqueeze",
inputs=inputs,
outputs=[node.name],
**attr)
def ReverseV2(self, node): def ReverseV2(self, node):
x = self.graph.get_input_node(node, 0) x = self.graph.get_input_node(node, 0)
...@@ -1526,114 +1548,7 @@ class TFOpMapper(OpMapper): ...@@ -1526,114 +1548,7 @@ class TFOpMapper(OpMapper):
else: else:
inputs['axis'] = axis.name inputs['axis'] = axis.name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.flip", inputs=inputs, outputs=[node.name], **attr) "paddle.flip",
inputs=inputs,
def BatchToSpaceND(self, node):
'''
reshape->transpose->reshape->crop
'''
x = self.graph.get_input_node(node, 0)
block_shape = self.graph.get_input_node(node, 1)
crops = self.graph.get_input_node(node, 2)
if block_shape.layer_type == "Const":
block_shape = block_shape.value.tolist()
if crops.layer_type == "Const":
crops = crops.value.tolist()
data_format = x.get_attr("data_format").decode()
if data_format == "NHWC":
n, h, w, c = x.out_shapes[0]
else:
n, c, h, w = x.out_shapes[0]
input_name = x.name
#reshape
shape = block_shape + [-1, h, w, c]
reshape_name = gen_name("batch_to_space", "reshape")
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": input_name},
outputs=[reshape_name],
shape=shape)
#transpose
perm = [len(block_shape)] + list(j for i in range(len(block_shape)) for j in (i + len(block_shape) + 1, i)) +\
list(i + 2*len(block_shape) + 1 for i in range(len(x.out_shapes[0]) - len(block_shape) - 1))
transpose_name = gen_name("batch_to_space", "transpose")
self.paddle_graph.add_layer(
kernel="paddle.transpose",
inputs={"x": reshape_name},
outputs=[transpose_name],
perm=perm)
#reshape
shape = [-1] + list(i * j
for i, j in zip(block_shape, x.out_shapes[0][
1:])) + x.out_shapes[0][1 + len(block_shape):]
reshape_name = gen_name("batch_to_space", "reshape")
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": transpose_name},
outputs=[reshape_name],
shape=shape)
#crop
attrs = {}
crop_shape = shape
crop_offsets = [0] * len(shape)
for i in range(len(crops)):
crop_shape[i + 1] = crop_shape[i + 1] - crops[i][0] - crops[i][1]
crop_offsets[i + 1] = crops[i][0]
attrs['shape'] = crop_shape
attrs['offsets'] = crop_offsets
self.paddle_graph.add_layer(
kernel="paddle.crop",
inputs={"x": reshape_name},
outputs=[node.name],
**attrs)
def SpaceToBatchND(self, node):
'''
zero-pad->reshape->transpose->reshape
'''
x = self.graph.get_input_node(node, 0)
block_shape = self.graph.get_input_node(node, 1)
paddings = self.graph.get_input_node(node, 2)
if block_shape.layer_type == "Const":
block_shape = block_shape.value.tolist()
if paddings.layer_type == "Const":
paddings = paddings.value.flatten().tolist()
input_name = x.name
#zero-pad
constant_values = 0
pad_name = gen_name("space_to_batch", "pad")
paddings = [0, 0] + paddings + [0, 0]
self.paddle_graph.add_layer(
kernel="paddle.nn.functional.pad",
inputs={"x": input_name},
outputs=[pad_name],
pad=paddings,
value=constant_values)
#reshape
n, h, w, c = x.out_shapes[0]
h = h + paddings[2] + paddings[3]
w = w + paddings[4] + paddings[5]
shape = [
n, h // block_shape[0], block_shape[0], w // block_shape[1],
block_shape[1], c
]
reshape_name = gen_name("space_to_batch", "reshape")
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": pad_name},
outputs=[reshape_name],
shape=shape)
#transpose
transpose_name = gen_name("space_to_batch", "transpose")
self.paddle_graph.add_layer(
kernel="paddle.transpose",
inputs={"x": reshape_name},
outputs=[transpose_name],
perm=[2, 4, 0, 1, 3, 5])
#reshape
shape = [-1, h // block_shape[0], w // block_shape[1], c]
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": transpose_name},
outputs=[node.name], outputs=[node.name],
shape=shape) **attr)
...@@ -60,8 +60,8 @@ class TFOpMapper(OpMapper): ...@@ -60,8 +60,8 @@ class TFOpMapper(OpMapper):
'swish_f32': ['paddle.nn.functional.swish'], 'swish_f32': ['paddle.nn.functional.swish'],
'Tanh': ['paddle.tanh'], 'Tanh': ['paddle.tanh'],
'Softplus': ['paddle.nn.functional.softplus'], 'Softplus': ['paddle.nn.functional.softplus'],
'LeakyRelu': 'LeakyRelu': ['paddle.nn.functional.leaky_relu',
['paddle.nn.functional.leaky_relu', dict(alpha='negative_slope')], dict(alpha='negative_slope')],
'Floor': ['paddle.floor'], 'Floor': ['paddle.floor'],
'Erf': ['paddle.erf'], 'Erf': ['paddle.erf'],
'Square': ['paddle.square'] 'Square': ['paddle.square']
...@@ -95,8 +95,7 @@ class TFOpMapper(OpMapper): ...@@ -95,8 +95,7 @@ class TFOpMapper(OpMapper):
if not self.op_checker(): if not self.op_checker():
raise Exception("Model is not supported yet.") raise Exception("Model is not supported yet.")
self.params = dict() self.params = dict()
self.paddle_graph = PaddleGraph( self.paddle_graph = PaddleGraph(parent_layer=None, graph_type="static", source_type="tf")
parent_layer=None, graph_type="static", source_type="tf")
self.params_output2id = dict() self.params_output2id = dict()
not_placeholder = list() not_placeholder = list()
...@@ -151,8 +150,8 @@ class TFOpMapper(OpMapper): ...@@ -151,8 +150,8 @@ class TFOpMapper(OpMapper):
return True return True
else: else:
if len(unsupported_ops) > 0: if len(unsupported_ops) > 0:
print("\n========= {} OPs are not supported yet ===========". print("\n========= {} OPs are not supported yet ===========".format(
format(len(unsupported_ops))) len(unsupported_ops)))
for op in unsupported_ops: for op in unsupported_ops:
print("========== {} ============".format(op)) print("========== {} ============".format(op))
return False return False
...@@ -187,10 +186,7 @@ class TFOpMapper(OpMapper): ...@@ -187,10 +186,7 @@ class TFOpMapper(OpMapper):
inputs={"x": x.name, inputs={"x": x.name,
"y": y.name}, "y": y.name},
outputs=[node.name]) outputs=[node.name])
self.paddle_graph.layers[layer_id].input_shapes = { self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
"x": x_shape,
"y": y_shape
}
def bool_map(self, node): def bool_map(self, node):
op_type = self.bool_ops[node.layer_type] op_type = self.bool_ops[node.layer_type]
...@@ -245,8 +241,7 @@ class TFOpMapper(OpMapper): ...@@ -245,8 +241,7 @@ class TFOpMapper(OpMapper):
if perm.layer_type == "Const": if perm.layer_type == "Const":
perm = perm.value.tolist() perm = perm.value.tolist()
else: else:
perm = self.decoder.infer_tensor( perm = self.decoder.infer_tensor(perm, use_diff_inputs=False).tolist()
perm, use_diff_inputs=False).tolist()
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.transpose", kernel="paddle.transpose",
...@@ -268,7 +263,10 @@ class TFOpMapper(OpMapper): ...@@ -268,7 +263,10 @@ class TFOpMapper(OpMapper):
attr["fill_value"] = input_value.value attr["fill_value"] = input_value.value
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.full", inputs=inputs, outputs=[node.name], **attr) "paddle.full",
inputs=inputs,
outputs=[node.name],
**attr)
if dims.layer_type != "Const": if dims.layer_type != "Const":
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.reshape", "paddle.reshape",
...@@ -335,7 +333,9 @@ class TFOpMapper(OpMapper): ...@@ -335,7 +333,9 @@ class TFOpMapper(OpMapper):
if len(node.layer.input) == 1: if len(node.layer.input) == 1:
cond = self.graph.get_input_node(node, 0) cond = self.graph.get_input_node(node, 0)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.nonzero", inputs={"x": cond.name}, outputs=[node.name]) "paddle.nonzero",
inputs={"x": cond.name},
outputs=[node.name])
else: else:
cond = self.graph.get_input_node(node, 0) cond = self.graph.get_input_node(node, 0)
x = self.graph.get_input_node(node, 1) x = self.graph.get_input_node(node, 1)
...@@ -409,8 +409,7 @@ class TFOpMapper(OpMapper): ...@@ -409,8 +409,7 @@ class TFOpMapper(OpMapper):
kernel_value = kernel.value kernel_value = kernel.value
kernel_weight_name = kernel.name.replace('/', '_') kernel_weight_name = kernel.name.replace('/', '_')
else: else:
kernel_value = self.decoder.infer_tensor( kernel_value = self.decoder.infer_tensor(kernel, use_diff_inputs=False)
kernel, use_diff_inputs=False)
if kernel.layer_type == 'Split': if kernel.layer_type == 'Split':
kernel_weight_name = "{}_{}_kernel".format(node.name, kernel_weight_name = "{}_{}_kernel".format(node.name,
kernel.name) kernel.name)
...@@ -448,8 +447,7 @@ class TFOpMapper(OpMapper): ...@@ -448,8 +447,7 @@ class TFOpMapper(OpMapper):
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.functional.conv2d", kernel="paddle.nn.functional.conv2d",
inputs={"x": input_name, inputs={"x": input_name, "weight": kernel_weight_name},
"weight": kernel_weight_name},
outputs=[node.name], outputs=[node.name],
bias=None, bias=None,
stride=strides[2:4], stride=strides[2:4],
...@@ -481,8 +479,7 @@ class TFOpMapper(OpMapper): ...@@ -481,8 +479,7 @@ class TFOpMapper(OpMapper):
kernel_value = kernel.value kernel_value = kernel.value
kernel_weight_name = kernel.name.replace('/', '_') kernel_weight_name = kernel.name.replace('/', '_')
else: else:
kernel_value = self.decoder.infer_tensor( kernel_value = self.decoder.infer_tensor(kernel, use_diff_inputs=False)
kernel, use_diff_inputs=False)
if kernel.layer_type == 'Split': if kernel.layer_type == 'Split':
kernel_weight_name = "{}_{}_kernel".format(node.name, kernel_weight_name = "{}_{}_kernel".format(node.name,
kernel.name) kernel.name)
...@@ -520,8 +517,7 @@ class TFOpMapper(OpMapper): ...@@ -520,8 +517,7 @@ class TFOpMapper(OpMapper):
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.functional.conv3d", kernel="paddle.nn.functional.conv3d",
inputs={"x": input_name, inputs={"x": input_name, "weight": kernel_weight_name},
"weight": kernel_weight_name},
outputs=[node.name], outputs=[node.name],
bias=None, bias=None,
stride=strides[2:5], stride=strides[2:5],
...@@ -569,13 +565,11 @@ class TFOpMapper(OpMapper): ...@@ -569,13 +565,11 @@ class TFOpMapper(OpMapper):
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.functional.batch_norm", kernel="paddle.nn.functional.batch_norm",
inputs={ inputs={"x": input_name,
"x": input_name,
"running_mean": moving_mean.name, "running_mean": moving_mean.name,
"running_var": moving_var.name, "running_var": moving_var.name,
"weight": gamma.name, "weight": gamma.name,
"bias": beta.name "bias": beta.name},
},
outputs=[node.name], outputs=[node.name],
epsilon=node.get_attr("epsilon")) epsilon=node.get_attr("epsilon"))
...@@ -653,6 +647,7 @@ class TFOpMapper(OpMapper): ...@@ -653,6 +647,7 @@ class TFOpMapper(OpMapper):
def MirrorPad(self, node): def MirrorPad(self, node):
self.Pad(node) self.Pad(node)
def PadV2(self, node): def PadV2(self, node):
self.Pad(node) self.Pad(node)
...@@ -681,12 +676,15 @@ class TFOpMapper(OpMapper): ...@@ -681,12 +676,15 @@ class TFOpMapper(OpMapper):
inputs={"input": input_name}, inputs={"input": input_name},
outputs=[node.name]) outputs=[node.name])
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.prod", inputs={"x": node.name}, outputs=[node.name]) kernel="paddle.prod",
inputs={"x": node.name},
outputs=[node.name])
def Ceil(self, node): def Ceil(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.ceil", inputs={"x": input.name}, kernel="paddle.ceil",
inputs={"x": input.name},
outputs=[node.name]) outputs=[node.name])
def ArgMax(self, node): def ArgMax(self, node):
...@@ -863,9 +861,7 @@ class TFOpMapper(OpMapper): ...@@ -863,9 +861,7 @@ class TFOpMapper(OpMapper):
axis = 1 axis = 1
else: else:
raise Exception("Unexpected situation happend in Unpack OP") raise Exception("Unexpected situation happend in Unpack OP")
layer_outputs = [ layer_outputs = ["{}_p{}".format(node.layer_name, i) for i in range(num)]
"{}_p{}".format(node.layer_name, i) for i in range(num)
]
if len(layer_outputs) == 1: if len(layer_outputs) == 1:
layer_outputs[0] = "[{}]".format(node.layer_name) layer_outputs[0] = "[{}]".format(node.layer_name)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
...@@ -1068,8 +1064,7 @@ class TFOpMapper(OpMapper): ...@@ -1068,8 +1064,7 @@ class TFOpMapper(OpMapper):
kernel="paddle.split", kernel="paddle.split",
inputs={"x": input.name}, inputs={"x": input.name},
outputs=[ outputs=[
"{}_p{}".format(node.layer_name, i) "{}_p{}".format(node.layer_name, i) for i in range(len(size_splits))
for i in range(len(size_splits))
], ],
num_or_sections=size_splits, num_or_sections=size_splits,
axis=dim) axis=dim)
...@@ -1085,8 +1080,15 @@ class TFOpMapper(OpMapper): ...@@ -1085,8 +1080,15 @@ class TFOpMapper(OpMapper):
begin = begin.value.tolist() begin = begin.value.tolist()
attrs['offsets'] = begin attrs['offsets'] = begin
else: else:
begin = self.decoder.infer_tensor( # shape = begin.out_shapes[0]
begin, use_diff_inputs=False).tolist() # reshape_name = gen_name("slice", "reshape")
# self.paddle_graph.add_layer(
# kernel="fluid.layers.reshape",
# inputs={"x": begin.name},
# outputs=[reshape_name],
# shape=shape)
# inputs['offsets'] = reshape_name
begin = self.decoder.infer_tensor(begin, use_diff_inputs=False).tolist()
attrs['offsets'] = begin attrs['offsets'] = begin
if size.layer_type == "Const": if size.layer_type == "Const":
size = size.value.tolist() size = size.value.tolist()
...@@ -1101,18 +1103,19 @@ class TFOpMapper(OpMapper): ...@@ -1101,18 +1103,19 @@ class TFOpMapper(OpMapper):
shape=shape) shape=shape)
inputs['shape'] = reshape_name inputs['shape'] = reshape_name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.crop", inputs=inputs, outputs=[node.name], **attrs) kernel="paddle.crop",
inputs=inputs,
outputs=[node.name],
**attrs)
def ResizeNearestNeighbor(self, node): def ResizeNearestNeighbor(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
resize_shape = self.graph.get_input_node(node, 1) resize_shape = self.graph.get_input_node(node, 1)
data_format = "NHWC" data_format = "NHWC"
inputs = {"x": input.name} inputs = {"x": input.name}
attrs = { attrs = {"align_corners": node.get_attr("align_corners"),
"align_corners": node.get_attr("align_corners"),
"mode": string("nearest"), "mode": string("nearest"),
"align_mode": 1 "align_mode": 1}
}
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
...@@ -1154,11 +1157,9 @@ class TFOpMapper(OpMapper): ...@@ -1154,11 +1157,9 @@ class TFOpMapper(OpMapper):
resize_shape = self.graph.get_input_node(node, 1) resize_shape = self.graph.get_input_node(node, 1)
data_format = "NHWC" data_format = "NHWC"
inputs = {"x": input.name} inputs = {"x": input.name}
attrs = { attrs = {"align_corners": node.get_attr("align_corners"),
"align_corners": node.get_attr("align_corners"),
"mode": string("bilinear"), "mode": string("bilinear"),
"align_mode": 1 "align_mode": 1}
}
if resize_shape.layer_type == "Const": if resize_shape.layer_type == "Const":
resize_shape = resize_shape.value.tolist() resize_shape = resize_shape.value.tolist()
...@@ -1260,17 +1261,15 @@ class TFOpMapper(OpMapper): ...@@ -1260,17 +1261,15 @@ class TFOpMapper(OpMapper):
if out_shape.layer_type == "Const": if out_shape.layer_type == "Const":
out_shape = out_shape.value.tolist() out_shape = out_shape.value.tolist()
else: else:
out_shape = self.decoder.infer_tensor( out_shape = self.decoder.infer_tensor(out_shape,
out_shape, out_shape=node.out_shapes[0]) out_shape=node.out_shapes[0])
in_shape = input.out_shapes[0] in_shape = input.out_shapes[0]
if in_shape.count(-1) > 2: if in_shape.count(-1) > 2:
in_shape = self.decoder.infer_tensor( in_shape = self.decoder.infer_tensor(input, use_diff_inputs=False).shape
input, use_diff_inputs=False).shape
k_size = kernel.out_shapes[0] k_size = kernel.out_shapes[0]
if k_size.count(-1) > 2: if k_size.count(-1) > 2:
k_size = self.decoder.infer_tensor( k_size = self.decoder.infer_tensor(kernel, use_diff_inputs=False).shape
kernel, use_diff_inputs=False).shape
pad_mode = node.get_attr("padding").decode() pad_mode = node.get_attr("padding").decode()
strides = node.get_attr("strides") strides = node.get_attr("strides")
...@@ -1303,11 +1302,8 @@ class TFOpMapper(OpMapper): ...@@ -1303,11 +1302,8 @@ class TFOpMapper(OpMapper):
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.nn.functional.conv2d_transpose", kernel="paddle.nn.functional.conv2d_transpose",
inputs={ inputs={"x": input_name,
"x": input_name, "weight": "{}_{}".format(node.name, kernel_name).replace(".", "_")},
"weight":
"{}_{}".format(node.name, kernel_name).replace(".", "_")
},
outputs=[node.name], outputs=[node.name],
bias=None, bias=None,
stride=strides[2:4], stride=strides[2:4],
...@@ -1334,10 +1330,12 @@ class TFOpMapper(OpMapper): ...@@ -1334,10 +1330,12 @@ class TFOpMapper(OpMapper):
inputs["repeat_times"] = repeat_times.name inputs["repeat_times"] = repeat_times.name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.tile", inputs=inputs, outputs=[node.name], **attr) kernel="paddle.tile",
inputs=inputs,
outputs=[node.name],
**attr)
if not isinstance(repeat_times, if not isinstance(repeat_times, list) and repeat_times.layer_type != "Const":
list) and repeat_times.layer_type != "Const":
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.reshape", kernel="paddle.reshape",
inputs={"x": node.name}, inputs={"x": node.name},
...@@ -1374,7 +1372,10 @@ class TFOpMapper(OpMapper): ...@@ -1374,7 +1372,10 @@ class TFOpMapper(OpMapper):
attr["dtype"] = string(node.dtype) attr["dtype"] = string(node.dtype)
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
kernel="paddle.arange", inputs=inputs, outputs=[node.name], **attr) kernel="paddle.arange",
inputs=inputs,
outputs=[node.name],
**attr)
if start.layer_type != "Const" or \ if start.layer_type != "Const" or \
limit.layer_type != "Const" or \ limit.layer_type != "Const" or \
delta.layer_type != "Const": delta.layer_type != "Const":
...@@ -1393,20 +1394,14 @@ class TFOpMapper(OpMapper): ...@@ -1393,20 +1394,14 @@ class TFOpMapper(OpMapper):
# TODO(syf) # TODO(syf)
layer_id = self.paddle_graph.add_layer( layer_id = self.paddle_graph.add_layer(
"paddle.subtract", inputs=inputs, outputs=[node.name]) "paddle.subtract", inputs=inputs, outputs=[node.name])
self.paddle_graph.layers[layer_id].input_shapes = { self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
"x": x_shape,
"y": y_shape
}
inputs = {"x": node.name, "y": node.name} inputs = {"x": node.name, "y": node.name}
x_shape = node.out_shapes[0] x_shape = node.out_shapes[0]
y_shape = node.out_shapes[0] y_shape = node.out_shapes[0]
layer_id = self.paddle_graph.add_layer( layer_id = self.paddle_graph.add_layer(
"paddle.multiply", inputs=inputs, outputs=[node.name]) "paddle.multiply", inputs=inputs, outputs=[node.name])
self.paddle_graph.layers[layer_id].input_shapes = { self.paddle_graph.layers[layer_id].input_shapes = {"x": x_shape, "y": y_shape}
"x": x_shape,
"y": y_shape
}
def OneHot(self, node): def OneHot(self, node):
input = self.graph.get_input_node(node, 0) input = self.graph.get_input_node(node, 0)
...@@ -1460,7 +1455,10 @@ class TFOpMapper(OpMapper): ...@@ -1460,7 +1455,10 @@ class TFOpMapper(OpMapper):
outputs=[input_name], outputs=[input_name],
dtype=string("bool")) dtype=string("bool"))
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.all", inputs={"x": input_name}, outputs=[node.name], **attr) "paddle.all",
inputs={"x": input_name},
outputs=[node.name],
**attr)
node.layer.attr['dtype'].type = 10 node.layer.attr['dtype'].type = 10
...@@ -1481,7 +1479,10 @@ class TFOpMapper(OpMapper): ...@@ -1481,7 +1479,10 @@ class TFOpMapper(OpMapper):
shape=[-1]) shape=[-1])
inputs = {'x': embeddings.name, 'index': index_name} inputs = {'x': embeddings.name, 'index': index_name}
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.gather", inputs=inputs, outputs=[node.name], axis=axis) "paddle.gather",
inputs=inputs,
outputs=[node.name],
axis=axis)
if len(index.out_shapes[0]) != 1: if len(index.out_shapes[0]) != 1:
out_shape = node.out_shapes[0] out_shape = node.out_shapes[0]
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
...@@ -1495,7 +1496,9 @@ class TFOpMapper(OpMapper): ...@@ -1495,7 +1496,9 @@ class TFOpMapper(OpMapper):
index = self.graph.get_input_node(node, 1) index = self.graph.get_input_node(node, 1)
inputs = {'x': x.name, 'index': index.name} inputs = {'x': x.name, 'index': index.name}
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.gather_nd", inputs=inputs, outputs=[node.name]) "paddle.gather_nd",
inputs=inputs,
outputs=[node.name])
def ExpandDims(self, node): def ExpandDims(self, node):
x = self.graph.get_input_node(node, 0, copy=True) x = self.graph.get_input_node(node, 0, copy=True)
...@@ -1510,7 +1513,10 @@ class TFOpMapper(OpMapper): ...@@ -1510,7 +1513,10 @@ class TFOpMapper(OpMapper):
else: else:
inputs['axis'] = y.name inputs['axis'] = y.name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.unsqueeze", inputs=inputs, outputs=[node.name], **attr) "paddle.unsqueeze",
inputs=inputs,
outputs=[node.name],
**attr)
def ReverseV2(self, node): def ReverseV2(self, node):
x = self.graph.get_input_node(node, 0) x = self.graph.get_input_node(node, 0)
...@@ -1525,114 +1531,8 @@ class TFOpMapper(OpMapper): ...@@ -1525,114 +1531,8 @@ class TFOpMapper(OpMapper):
else: else:
inputs['axis'] = axis.name inputs['axis'] = axis.name
self.paddle_graph.add_layer( self.paddle_graph.add_layer(
"paddle.flip", inputs=inputs, outputs=[node.name], **attr) "paddle.flip",
inputs=inputs,
def BatchToSpaceND(self, node):
'''
reshape->transpose->reshape->crop
'''
x = self.graph.get_input_node(node, 0)
block_shape = self.graph.get_input_node(node, 1)
crops = self.graph.get_input_node(node, 2)
if block_shape.layer_type == "Const":
block_shape = block_shape.value.tolist()
if crops.layer_type == "Const":
crops = crops.value.tolist()
data_format = x.get_attr("data_format").decode()
if data_format == "NHWC":
n, h, w, c = x.out_shapes[0]
else:
n, c, h, w = x.out_shapes[0]
input_name = x.name
#reshape
shape = block_shape + [-1, h, w, c]
reshape_name = gen_name("batch_to_space", "reshape")
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": input_name},
outputs=[reshape_name],
shape=shape)
#transpose
perm = [len(block_shape)] + list(j for i in range(len(block_shape)) for j in (i + len(block_shape) + 1, i)) +\
list(i + 2*len(block_shape) + 1 for i in range(len(x.out_shapes[0]) - len(block_shape) - 1))
transpose_name = gen_name("batch_to_space", "transpose")
self.paddle_graph.add_layer(
kernel="paddle.transpose",
inputs={"x": reshape_name},
outputs=[transpose_name],
perm=perm)
#reshape
shape = [-1] + list(i * j
for i, j in zip(block_shape, x.out_shapes[0][
1:])) + x.out_shapes[0][1 + len(block_shape):]
reshape_name = gen_name("batch_to_space", "reshape")
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": transpose_name},
outputs=[reshape_name],
shape=shape)
#crop
attrs = {}
crop_shape = shape
crop_offsets = [0] * len(shape)
for i in range(len(crops)):
crop_shape[i + 1] = crop_shape[i + 1] - crops[i][0] - crops[i][1]
crop_offsets[i + 1] = crops[i][0]
attrs['shape'] = crop_shape
attrs['offsets'] = crop_offsets
self.paddle_graph.add_layer(
kernel="paddle.crop",
inputs={"x": reshape_name},
outputs=[node.name], outputs=[node.name],
**attrs) **attr)
def SpaceToBatchND(self, node):
'''
zero-pad->reshape->transpose->reshape
'''
x = self.graph.get_input_node(node, 0)
block_shape = self.graph.get_input_node(node, 1)
paddings = self.graph.get_input_node(node, 2)
if block_shape.layer_type == "Const":
block_shape = block_shape.value.tolist()
if paddings.layer_type == "Const":
paddings = paddings.value.flatten().tolist()
input_name = x.name
#zero-pad
constant_values = 0
pad_name = gen_name("space_to_batch", "pad")
paddings = [0, 0] + paddings + [0, 0]
self.paddle_graph.add_layer(
kernel="paddle.nn.functional.pad",
inputs={"x": input_name},
outputs=[pad_name],
pad=paddings,
value=constant_values)
#reshape
n, h, w, c = x.out_shapes[0]
h = h + paddings[2] + paddings[3]
w = w + paddings[4] + paddings[5]
shape = [
n, h // block_shape[0], block_shape[0], w // block_shape[1],
block_shape[1], c
]
reshape_name = gen_name("space_to_batch", "reshape")
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": pad_name},
outputs=[reshape_name],
shape=shape)
#transpose
transpose_name = gen_name("space_to_batch", "transpose")
self.paddle_graph.add_layer(
kernel="paddle.transpose",
inputs={"x": reshape_name},
outputs=[transpose_name],
perm=[2, 4, 0, 1, 3, 5])
#reshape
shape = [-1, h // block_shape[0], w // block_shape[1], c]
self.paddle_graph.add_layer(
kernel="paddle.reshape",
inputs={"x": transpose_name},
outputs=[node.name],
shape=shape)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册