tf_op_mapper.py 60.5 KB
Newer Older
S
SunAhong1993 已提交
1
# Copyright (c) 2020  PaddlePaddle Authors. All Rights Reserved.
S
SunAhong1993 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

S
SunAhong1993 已提交
15
from x2paddle.decoder.tf_decoder import TFGraph, TFGraphNode
16
from x2paddle.core.program import PaddleGraph
S
SunAhong1993 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
from x2paddle.core.util import *
import traceback
import math
import inspect
import numpy
import sys

name_counter = dict()


def gen_name(op_name, var_name):
    name = "{}_{}".format(op_name, var_name)
    if name not in name_counter:
        name_counter[name] = 0
    else:
        name_counter[name] += 1
    name = name + '_' + str(name_counter[name])
    return name


# compute padding size for SAME mode
def get_same_padding(in_size, kernel_size, stride):
    new_size = int(math.ceil(in_size * 1.0 / stride))
    pad_size = (new_size - 1) * stride + kernel_size - in_size
    if pad_size < 0:
        pad_size = 0
    pad0 = int(pad_size / 2)
    pad1 = pad_size - pad0
    return [pad0, pad1]


S
SunAhong1993 已提交
48
class TFOpMapper():
S
SunAhong1993 已提交
49 50 51 52 53 54 55 56 57 58 59
    directly_map_ops = {
        'Relu': ['paddle.nn.ReLU'],
        'Relu6': ['paddle.nn.ReLU6'],
        'Abs': ['paddle.abs'],
        'Sigmoid': ['paddle.nn.Sigmoid'],
        'Exp': ['paddle.exp'],
        'Rsqrt': ['paddle.rsqrt'],
        'Sqrt': ['paddle.sqrt'],
        'swish_f32': ['paddle.nn.Swish'],
        'Tanh': ['paddle.nn.Tanh'],
        'Softplus': ['paddle.nn.Softplus'],
60
        'LeakyRelu': ['paddle.nn.LeakyReLU', dict(alpha='negative_slope')],
S
SunAhong1993 已提交
61
        'Softmax': ['paddle.nn.Softmax'],
S
SunAhong1993 已提交
62 63 64 65 66 67 68 69
        'Floor': ['paddle.floor'],
        'Erf': ['paddle.erf'],
        'Square': ['paddle.square']
    }
    elementwise_ops = {
        'Add': 'paddle.add',
        'AddV2': 'paddle.add',
        'RealDiv': 'paddle.divide',
S
SunAhong1993 已提交
70
        'DivNoNan': 'paddle.divide',
S
SunAhong1993 已提交
71
        'Sub': 'paddle.subtract',
S
SunAhong1993 已提交
72 73
        'Maximum': 'paddle.maximum',
        'Minimum': 'paddle.minimum',
S
SunAhong1993 已提交
74 75 76 77 78 79
        'Mul': 'paddle.multiply',
        'FloorDiv': 'paddle.floor_divide',
        'FloorMod': 'paddle.floor_mod',
        'LogicalAnd': 'logical_and',
    }
    bool_ops = {
S
SunAhong1993 已提交
80 81
        'LessEqual': 'paddle.less_equal',
        'GreaterEqual': 'paddle.greater_equal',
S
SunAhong1993 已提交
82 83 84
        'Greater': 'paddle.greater_than',
        'NotEqual': 'paddle.not_equal',
        'Equal': 'paddle.equal',
S
SunAhong1993 已提交
85 86 87 88 89
    }

    def __init__(self, decoder):
        self.decoder = decoder
        self.graph = decoder.tf_graph
S
SunAhong1993 已提交
90 91
        if not self.op_checker():
            raise Exception("Model is not supported yet.")
S
SunAhong1993 已提交
92 93 94
        self.params = dict()
        self.nn_name2id = dict()
        self.inputs_info = dict()
S
SunAhong1993 已提交
95
        self.paddle_graph = PaddleGraph(parent_layer=None, source_type="tf")
S
SunAhong1993 已提交
96
        self.paddle_graph.outputs = self.graph.output_nodes
S
SunAhong1993 已提交
97 98 99 100 101 102 103 104 105 106 107

        not_placeholder = list()
        for name in self.graph.input_nodes:
            if self.graph.get_node(
                    name).layer_type != "Placeholder" and self.graph.get_node(
                        name
                    ).layer_type != "OneShotIterator" and self.graph.get_node(
                        name).layer_type != "IteratorV2":
                not_placeholder.append(name)
        for name in not_placeholder:
            idx = self.graph.input_nodes.index(name)
108
            del self.graph.input_nodes[idx]
S
SunAhong1993 已提交
109 110 111 112 113 114 115

        print("Total nodes: {}".format(
            sum([
                isinstance(node, TFGraphNode)
                for name, node in self.graph.node_map.items()
            ])))
        print("Nodes converting ...")
S
SunAhong1993 已提交
116 117 118 119 120 121 122 123
        for i, node_name in enumerate(self.graph.topo_sort):
            sys.stderr.write("\rConverting node {} ...     ".format(i + 1))
            node = self.graph.get_node(node_name)
            op = node.layer_type
            if op in self.directly_map_ops:
                self.directly_map(node)
            elif op in self.elementwise_ops:
                self.elementwise_map(node)
S
SunAhong1993 已提交
124 125
            elif op in self.bool_ops:
                self.bool_map(node)
S
SunAhong1993 已提交
126 127
            elif hasattr(self, op):
                func = getattr(self, op)
S
SunAhong1993 已提交
128 129
                func(node)
        print("\nNodes converted.")
S
SunAhong1993 已提交
130 131 132
        self.paddle_graph.set_name(self.graph.graph_name)
        self.paddle_graph.set_parameters(self.params)
        self.paddle_graph.set_inputs_info(self.inputs_info)
133

S
SunAhong1993 已提交
134 135 136 137 138 139 140
    def op_checker(self):
        unsupported_ops = set()
        for node_name in self.graph.topo_sort:
            node = self.graph.get_node(node_name)
            op = node.layer_type
            if not hasattr(self, op) and \
                op not in self.directly_map_ops and \
S
SunAhong1993 已提交
141 142
                op not in self.elementwise_ops and \
                op not in self.bool_ops:
S
SunAhong1993 已提交
143 144 145 146 147
                unsupported_ops.add(op)
        if len(unsupported_ops) == 0:
            return True
        else:
            if len(unsupported_ops) > 0:
148 149
                print("\n========= {} OPs are not supported yet ===========".
                      format(len(unsupported_ops)))
S
SunAhong1993 已提交
150 151
            for op in unsupported_ops:
                print("========== {} ============".format(op))
152
            return False
S
SunAhong1993 已提交
153 154

    def directly_map(self, node):
S
SunAhong1993 已提交
155 156
        inputs = node.layer.input
        assert len(inputs) == 1, 'directly_map error with multi inputs'
S
SunAhong1993 已提交
157
        op_info = self.directly_map_ops[node.layer_type]
S
SunAhong1993 已提交
158 159
        input = self.graph.get_input_node(node, 0)
        paddle_op = op_info[0]
S
SunAhong1993 已提交
160
        layer_attrs = dict()
S
SunAhong1993 已提交
161 162
        if len(op_info) > 1:
            attrs_name_map_dict = op_info[1]
S
fix  
SunAhong1993 已提交
163
            for tf_attr_name, pd_attr_name in attrs_name_map_dict.items():
S
SunAhong1993 已提交
164 165 166
                layer_attrs[pd_attr_name] = node.get_attr(tf_attr_name)
        if paddle_op.startswith("paddle.nn"):
            op_name = paddle_op[10:].lower()
S
SunAhong1993 已提交
167 168 169 170
            op_name = name_generator(op_name, self.nn_name2id)
            output_name = node.name
            layer_outputs = [op_name, output_name]
            self.paddle_graph.add_layer(
S
SunAhong1993 已提交
171
                kernel=paddle_op,
S
SunAhong1993 已提交
172 173 174 175 176
                inputs={"x": input.name},
                outputs=layer_outputs,
                **layer_attrs)
        else:
            self.paddle_graph.add_layer(
S
SunAhong1993 已提交
177
                kernel=paddle_op,
S
SunAhong1993 已提交
178 179 180 181
                inputs={"x": input.name},
                outputs=[node.name],
                **layer_attrs)

S
SunAhong1993 已提交
182 183 184 185
    def elementwise_map(self, node, op_type=None):
        if op_type is None:
            assert node.layer_type in self.elementwise_ops
            op_type = self.elementwise_ops[node.layer_type]
S
SunAhong1993 已提交
186 187
        x = self.graph.get_input_node(node, 0)
        y = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
188 189
        x_shape = x.out_shapes[0]
        y_shape = y.out_shapes[0]
S
SunAhong1993 已提交
190
        layer_id = self.paddle_graph.add_layer(
S
SunAhong1993 已提交
191 192 193 194
            kernel=op_type,
            inputs={"x": x.name,
                    "y": y.name},
            outputs=[node.name])
195 196 197 198 199
        self.paddle_graph.layers[layer_id].input_shapes = {
            "x": x_shape,
            "y": y_shape
        }

S
SunAhong1993 已提交
200 201 202 203
    def bool_map(self, node):
        op_type = self.bool_ops[node.layer_type]
        self.elementwise_map(node, op_type)
        node.set_dtype("bool")
S
SunAhong1993 已提交
204 205 206 207 208 209

    def Placeholder(self, node):
        shape = node.out_shapes[0]
        assert len(shape) != 0, "Unknown shape of input nodes[{}].".format(
            node.layer_name)
        dtype = node.dtype
210

S
SunAhong1993 已提交
211 212 213 214
        self.paddle_graph.add_layer(
            kernel="paddle.to_tensor",
            inputs={},
            outputs=[node.name],
S
SunAhong1993 已提交
215 216
            data=node.name)
        self.inputs_info[node.name] = [shape, node.dtype]
S
SunAhong1993 已提交
217 218 219 220 221 222 223 224 225 226

    def Const(self, node):
        shape = node.out_shapes[0]
        dtype = node.dtype
        value = node.value
        if len(shape) == 0:
            assert value.size == 1, "Unexpected situation happend"
            if value == float('inf'):
                value = "float('inf')"
            self.paddle_graph.add_layer(
227 228
                "paddle.full",
                inputs={},
S
SunAhong1993 已提交
229 230 231 232 233 234
                outputs=[node.name],
                dtype=string(dtype),
                shape=[1],
                fill_value=value)
            return
        self.params[node.name] = node.value
235

S
SunAhong1993 已提交
236
        if 0 not in shape:
S
SunAhong1993 已提交
237
            self.paddle_graph.add_layer(
S
SunAhong1993 已提交
238 239 240 241
                "self.create_parameter",
                inputs={},
                outputs=[node.name],
                shape=shape,
S
SunAhong1993 已提交
242 243 244
                attr=string(node.name),
                dtype=string(dtype),
                default_initializer="paddle.nn.initializer.Constant(value=0.0)")
245

S
SunAhong1993 已提交
246
    def Transpose(self, node):
S
SunAhong1993 已提交
247 248
        input = self.graph.get_input_node(node, 0)
        perm = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
249 250 251
        if perm.layer_type == "Const":
            perm = perm.value.tolist()
        else:
252 253 254
            perm = self.decoder.infer_tensor(
                perm, use_diff_inputs=False).tolist()

S
SunAhong1993 已提交
255 256 257 258 259
        self.paddle_graph.add_layer(
            "paddle.transpose",
            inputs={"x": input.name},
            outputs=[node.name],
            perm=perm)
260

S
SunAhong1993 已提交
261 262 263 264
    def Where(self, node):
        if len(node.layer.input) == 1:
            cond = self.graph.get_input_node(node, 0)
            self.paddle_graph.add_layer(
265
                "paddle.nonzero", inputs={"x": cond.name}, outputs=[node.name])
S
SunAhong1993 已提交
266 267 268 269 270 271 272 273 274 275
        else:
            cond = self.graph.get_input_node(node, 0)
            x = self.graph.get_input_node(node, 1)
            y = self.graph.get_input_node(node, 2)
            self.paddle_graph.add_layer(
                "paddle.where",
                inputs={"condition": cond.name,
                        "x": x.name,
                        "y": y.name},
                outputs=[node.name])
276

S
add beg  
SunAhong1993 已提交
277 278
    def Neg(self, node):
        input = self.graph.get_input_node(node, 0)
279

S
add beg  
SunAhong1993 已提交
280 281 282 283 284
        self.paddle_graph.add_layer(
            "paddle.scale",
            inputs={"x": input.name},
            outputs=[node.name],
            scale=-1)
S
SunAhong1993 已提交
285 286

    def Fill(self, node):
S
SunAhong1993 已提交
287 288
        dims = self.graph.get_input_node(node, 0)
        input_value = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
289 290 291 292 293 294 295 296
        inputs = dict()
        layer_attrs = dict()
        assert input_value.layer_type == "Const", "Value of fill OP should be Const"
        if dims.layer_type == "Const":
            layer_attrs["shape"] = dims.value.tolist()
        else:
            inputs["shape"] = dims.name
        layer_attrs["dtype"] = string(input_value.dtype)
S
SunAhong1993 已提交
297
        layer_attrs["fill_value"] = input_value.value
S
SunAhong1993 已提交
298 299

        self.paddle_graph.add_layer(
300
            "paddle.full", inputs=inputs, outputs=[node.name], **layer_attrs)
S
SunAhong1993 已提交
301 302

    def DepthToSpace(self, node):
S
SunAhong1993 已提交
303
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

        block_size = node.get_attr("block_size")
        data_format = node.get_attr("data_format").decode()
        if data_format == "NHWC":
            n, h, w, c = input.out_shapes[0]
        else:
            n, c, h, w = input.out_shapes[0]

        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("depth_to_space", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

        shape = [0, block_size * block_size, -1, h, w]
        reshape_name = gen_name("depth_to_space", "reshape")
        self.paddle_graph.add_layer(
            kernel="paddle.reshape",
            inputs={"x": input_name},
            outputs=[reshape_name],
            shape=shape)

        transpose_name = gen_name("depth_to_space", "transpose")
        self.paddle_graph.add_layer(
            kernel="paddle.transpose",
            inputs={"x": reshape_name},
            outputs=[transpose_name],
            perm=[0, 2, 1, 3, 4])

        reshape_name = gen_name("depth_to_space", "reshape")
        self.paddle_graph.add_layer(
            kernel="paddle.reshape",
            inputs={"x": transpose_name},
            outputs=[reshape_name],
            shape=[0, c, h, w])

        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
345
            kernel="paddle.nn.functional.pixel_shuffle",
S
SunAhong1993 已提交
346 347 348 349 350 351 352 353 354 355 356 357
            inputs={"x": reshape_name},
            outputs=[node.name],
            upscale_factor=block_size)

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def MaxPool(self, node):
S
SunAhong1993 已提交
358
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

        k_size = node.get_attr("ksize")
        strides = node.get_attr("strides")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()

        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("max_pool", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            strides = [strides[i] for i in [0, 3, 1, 2]]
            k_size = [k_size[i] for i in [0, 3, 1, 2]]
            input_name = transpose_name

        op_name = name_generator("pool", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
S
SunAhong1993 已提交
380

S
SunAhong1993 已提交
381
        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
382
            kernel="paddle.nn.MaxPool2D",
S
SunAhong1993 已提交
383 384
            inputs={"input": input_name},
            outputs=layer_outputs,
S
SunAhong1993 已提交
385 386 387
            kernel_size=k_size[2:4],
            stride=strides[2:4],
            padding=string(pad_mode))
S
SunAhong1993 已提交
388 389 390 391 392 393 394 395 396 397 398 399

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def Conv2D(self, node):
        op_name = name_generator("conv", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
S
SunAhong1993 已提交
400 401
        input = self.graph.get_input_node(node, 0)
        kernel = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415

        k_size = kernel.out_shapes[0]
        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()
        if data_format == "NHWC":
            n, h, w, c = input.out_shapes[0]
        else:
            n, c, h, w = input.out_shapes[0]

        if kernel.layer_type == 'Const':
            kernel_value = kernel.value
        else:
416 417
            kernel_value = self.decoder.infer_tensor(
                kernel, use_diff_inputs=False)
S
SunAhong1993 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        kernel_weight_name = op_name + ".weight"
        self.params[kernel_weight_name] = numpy.transpose(kernel_value,
                                                          (3, 2, 0, 1))

        input_name = input.name
        if data_format == "NHWC":
            strides = [strides[i] for i in [0, 3, 1, 2]]
            dilations = [dilations[i] for i in [0, 3, 1, 2]]
            transpose_name = gen_name("conv2d", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

        if c == -1:
            attr = {"shape": [0, k_size[2], 0, 0]}
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": input_name},
                outputs=[input_name],
                shape=[0, k_size[2], 0, 0])

        self.paddle_graph.add_layer(
            kernel="paddle.nn.Conv2D",
            inputs={"input": input_name},
            outputs=layer_outputs,
            weight_attr=string(kernel_weight_name),
            bias_attr=False,
            in_channels=k_size[2],
            out_channels=k_size[3],
            kernel_size=k_size[0:2],
            stride=strides[2:4],
            dilation=dilations[2:4],
            padding=string(pad_mode))

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
461

S
SunAhong1993 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
    def Conv3D(self, node):
        op_name = name_generator("conv", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
        input = self.graph.get_input_node(node, 0)
        kernel = self.graph.get_input_node(node, 1)

        k_size = kernel.out_shapes[0]
        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()
        if data_format == "NDHWC":
            n, d, h, w, c = input.out_shapes[0]
        else:
            n, c, d, h, w = input.out_shapes[0]

        if kernel.layer_type == 'Const':
            kernel_value = kernel.value
        else:
482 483
            kernel_value = self.decoder.infer_tensor(
                kernel, use_diff_inputs=False)
S
SunAhong1993 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
        kernel_weight_name = op_name + ".weight"
        self.params[kernel_weight_name] = numpy.transpose(kernel_value,
                                                          (4, 3, 0, 1, 2))

        input_name = input.name
        if data_format == "NDHWC":
            strides = [strides[i] for i in [0, 4, 1, 2, 3]]
            dilations = [dilations[i] for i in [0, 4, 1, 2, 3]]
            transpose_name = gen_name("conv3d", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 4, 1, 2, 3])
            input_name = transpose_name

        if c == -1:
            attr = {"shape": [0, k_size[2], 0, 0, 0]}
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": input_name},
                outputs=[input_name],
                shape=[0, k_size[2], 0, 0, 0])

        self.paddle_graph.add_layer(
            kernel="paddle.nn.Conv3D",
            inputs={"input": input_name},
            outputs=layer_outputs,
            weight_attr=string(kernel_weight_name),
            bias_attr=False,
            in_channels=k_size[3],
            out_channels=k_size[4],
            kernel_size=k_size[0:3],
            stride=strides[2:5],
            dilation=dilations[2:5],
            padding=string(pad_mode))

        if data_format == "NDHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 4, 1])
S
SunAhong1993 已提交
527 528

    def BiasAdd(self, node):
S
SunAhong1993 已提交
529 530
        input = self.graph.get_input_node(node, 0)
        bias = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
531 532 533 534 535 536 537 538 539 540
        self.paddle_graph.add_layer(
            kernel="paddle.add",
            inputs={"x": input.name,
                    "y": bias.name},
            outputs=[node.name])

    def FusedBatchNorm(self, node):
        op_name = name_generator("bn", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
S
SunAhong1993 已提交
541
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
542

S
SunAhong1993 已提交
543 544 545 546
        gamma = self.graph.get_input_node(node, 1)
        beta = self.graph.get_input_node(node, 2)
        moving_mean = self.graph.get_input_node(node, 3)
        moving_var = self.graph.get_input_node(node, 4)
S
SunAhong1993 已提交
547 548 549 550 551 552 553
        data_format = node.get_attr("data_format").decode()

        assert gamma.layer_type == "Const"
        assert beta.layer_type == "Const"
        assert moving_mean.layer_type == "Const"
        assert moving_var.layer_type == "Const"

554
        input_name = input.name
S
SunAhong1993 已提交
555 556 557 558 559 560 561 562
        if data_format == "NHWC":
            transpose_name = gen_name("batch_norm", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name
S
SunAhong1993 已提交
563 564
            n, h, w, c = input.out_shapes[0]
        else:
565
            n, c, h, w = input.out_shapes[0]
S
SunAhong1993 已提交
566

567 568 569 570 571 572 573 574
        self.params["{}_{}".format(node.name, gamma.name)] = self.params[
            gamma.name]
        self.params["{}_{}".format(node.name, beta.name)] = self.params[
            beta.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]
S
SunAhong1993 已提交
575 576 577 578
        self.paddle_graph.add_layer(
            kernel="paddle.nn.BatchNorm",
            inputs={"input": input_name},
            outputs=layer_outputs,
S
SunAhong1993 已提交
579
            num_channels=c,
S
SunAhong1993 已提交
580
            epsilon=node.get_attr("epsilon"),
S
SunAhong1993 已提交
581 582
            param_attr=string("{}_{}".format(node.name, gamma.name)),
            bias_attr=string("{}_{}".format(node.name, beta.name)),
583 584 585 586
            moving_mean_name=string("{}_{}".format(node.name,
                                                   moving_mean.name)),
            moving_variance_name=string("{}_{}".format(node.name,
                                                       moving_var.name)),
S
SunAhong1993 已提交
587 588 589 590 591 592 593 594
            is_test=True)

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
595

S
SunAhong1993 已提交
596 597
    def FusedBatchNormV3(self, node):
        self.FusedBatchNorm(node)
S
SunAhong1993 已提交
598 599

    def Mean(self, node):
S
SunAhong1993 已提交
600 601
        input = self.graph.get_input_node(node, 0)
        reduce_idx = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
602 603 604 605 606 607 608 609 610 611 612 613
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        dims = reduce_idx.value.tolist()
        keep_dims = node.get_attr("keep_dims")

        self.paddle_graph.add_layer(
            kernel="paddle.mean",
            inputs={"x": input.name},
            outputs=[node.name],
            axis=dims,
            keepdim=keep_dims)

    def Reshape(self, node):
S
SunAhong1993 已提交
614 615
        input = self.graph.get_input_node(node, 0)
        param = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

        input_name = input.name

        if param.layer_type == "Const":
            shape = param.value.tolist()
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": input_name},
                outputs=[node.name],
                shape=shape)
        else:
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": input_name,
                        "shape": param.name},
                outputs=[node.name])
        if param.layer_type != "Const":
            out_shape = numpy.array(node.out_shapes[0])
            if (out_shape > 0).any():
                out_shape[out_shape < 0] = 0
                self.paddle_graph.add_layer(
                    kernel="paddle.reshape",
                    inputs={"x": node.name},
                    outputs=[node.name],
                    shape=out_shape.tolist())

    def Pad(self, node):
S
SunAhong1993 已提交
643 644
        input = self.graph.get_input_node(node, 0)
        paddings = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
645 646
        assert paddings.layer_type == "Const", "Padding should be Const"
        paddings = paddings.value.flatten().tolist()
S
SunAhong1993 已提交
647

S
SunAhong1993 已提交
648 649 650 651 652
        constant_values = 0
        if len(node.layer.input) > 2:
            constant_values = self.graph.get_input_node(node, 2)
            assert constant_values.layer_type == "Const", "Padding should be Const"
            constant_values = constant_values.value
S
SunAhong1993 已提交
653

S
SunAhong1993 已提交
654 655
        if len(paddings) == 8 and sum(paddings[:2]) == 0 \
            and sum(paddings[-2:]) == 0:
S
SunAhong1993 已提交
656
            paddings = paddings[2:-2]
S
SunAhong1993 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670
            self.paddle_graph.add_layer(
                kernel="paddle.nn.functional.pad",
                inputs={"x": input.name},
                outputs=[node.name],
                pad=paddings,
                value=constant_values,
                data_format=string('NHWC'))
        else:
            self.paddle_graph.add_layer(
                kernel="paddle.nn.functional.pad",
                inputs={"x": input.name},
                outputs=[node.name],
                pad=paddings,
                value=constant_values)
671

S
SunAhong1993 已提交
672
    def MirrorPad(self, node):
S
SunAhong1993 已提交
673
        self.Pad(node)
674

S
SunAhong1993 已提交
675 676
    def PadV2(self, node):
        self.Pad(node)
S
SunAhong1993 已提交
677 678

    def Squeeze(self, node):
S
SunAhong1993 已提交
679
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
680
        squeeze_dims = node.get_attr('squeeze_dims')
681 682 683
        axis = node.get_attr('axis')
        if squeeze_dims != None and axis == None:
            axis = squeeze_dims
S
SunAhong1993 已提交
684 685 686 687
        self.paddle_graph.add_layer(
            kernel="paddle.squeeze",
            inputs={"x": input.name},
            outputs=[node.name],
688
            axis=axis)
S
SunAhong1993 已提交
689 690

    def Shape(self, node):
S
SunAhong1993 已提交
691
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
692 693 694 695 696
        input_name = input.name
        self.paddle_graph.add_layer(
            kernel="paddle.shape",
            inputs={"input": input_name},
            outputs=[node.name])
697

S
SunAhong1993 已提交
698 699 700 701 702 703 704 705
    def Size(self, node):
        input = self.graph.get_input_node(node, 0)
        input_name = input.name
        self.paddle_graph.add_layer(
            kernel="paddle.shape",
            inputs={"input": input_name},
            outputs=[node.name])
        self.paddle_graph.add_layer(
706 707
            kernel="paddle.prod", inputs={"x": node.name}, outputs=[node.name])

S
SunAhong1993 已提交
708 709 710
    def Ceil(self, node):
        input = self.graph.get_input_node(node, 0)
        self.paddle_graph.add_layer(
711
            kernel="paddle.ceil", inputs={"x": input.name},
S
SunAhong1993 已提交
712
            outputs=[node.name])
S
SunAhong1993 已提交
713 714

    def ArgMax(self, node):
S
SunAhong1993 已提交
715 716
        input = self.graph.get_input_node(node, 0)
        axis = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
717 718 719 720 721 722 723
        assert axis.layer_type == "Const", "ArgMax only support Const parameter"
        axis = axis.value
        self.paddle_graph.add_layer(
            kernel="paddle.argmax",
            inputs={"x": input.name},
            outputs=[node.name],
            axis=axis)
724

S
SunAhong1993 已提交
725 726 727 728 729 730 731 732 733 734 735 736
    def TopKV2(self, node):
        input = self.graph.get_input_node(node, 0)
        k = self.graph.get_input_node(node, 1)
        assert k.layer_type == "Const", "ArgMax only support Const parameter"
        k = k.value
        sort = node.get_attr('sorted')
        self.paddle_graph.add_layer(
            kernel="paddle.topk",
            inputs={"x": input.name},
            outputs=[node.name],
            k=k,
            sorted=sort)
S
SunAhong1993 已提交
737 738

    def MatMul(self, node):
S
SunAhong1993 已提交
739 740
        x = self.graph.get_input_node(node, 0)
        y = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
        transpose_a = node.get_attr('transpose_a')
        transpose_b = node.get_attr('transpose_b')
        if transpose_a is None:
            transpose_a = node.get_attr('adj_x')
        if transpose_b is None:
            transpose_b = node.get_attr('adj_y')
        self.paddle_graph.add_layer(
            kernel="paddle.matmul",
            inputs={"x": x.name,
                    "y": y.name},
            outputs=[node.name],
            transpose_x=transpose_a,
            transpose_y=transpose_b)

    def BatchMatMul(self, node):
        return self.MatMul(node)

    def BatchMatMulV2(self, node):
        return self.MatMul(node)

    def DepthwiseConv2dNative(self, node):
        op_name = name_generator("conv", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
S
SunAhong1993 已提交
765 766
        input = self.graph.get_input_node(node, 0)
        kernel = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
        assert kernel.layer_type == "Const", "Kernel of DepthwiseConv2DNative should be Const"

        in_shape = input.out_shapes[0]
        k_size = kernel.out_shapes[0]
        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()

        kernel_weight_name = op_name + ".weight"
        self.params[kernel_weight_name] = numpy.transpose(kernel.value,
                                                          (2, 3, 0, 1))

        input_name = input.name
        if data_format == "NHWC":
            in_shape = [in_shape[i] for i in [0, 3, 1, 2]]
            strides = [strides[i] for i in [0, 3, 1, 2]]
            dilations = [dilations[i] for i in [0, 3, 1, 2]]
            transpose_name = gen_name('depthwise_conv2d', 'transpose')
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

        self.paddle_graph.add_layer(
            kernel="paddle.nn.Conv2D",
            inputs={"input": input_name},
            outputs=layer_outputs,
            weight_attr=string(kernel_weight_name),
            bias_attr=False,
            in_channels=in_shape[1],
            out_channels=k_size[2],
            kernel_size=k_size[0:2],
            stride=strides[2:4],
            dilation=dilations[2:4],
            groups=k_size[3] * in_shape[1],
            padding=string(pad_mode))

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def AvgPool(self, node):
S
SunAhong1993 已提交
815
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

        k_size = node.get_attr("ksize")
        strides = node.get_attr("strides")
        data_format = node.get_attr("data_format").decode()
        pad_mode = node.get_attr("padding").decode()

        input_name = input.name
        if data_format == "NHWC":
            transpose_name = gen_name("avg_pool", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            strides = [strides[i] for i in [0, 3, 1, 2]]
            k_size = [k_size[i] for i in [0, 3, 1, 2]]
            input_name = transpose_name

        op_name = name_generator("pool", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
837

S
SunAhong1993 已提交
838
        # TODO(syf): The op has diff.
S
SunAhong1993 已提交
839
        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
840
            kernel="paddle.nn.AvgPool2D",
S
SunAhong1993 已提交
841
            inputs={"input": input_name},
S
SunAhong1993 已提交
842 843 844 845 846
            outputs=layer_outputs,
            kernel_size=k_size[2:4],
            stride=strides[2:4],
            padding=string(pad_mode))

S
SunAhong1993 已提交
847 848 849 850 851 852 853 854
        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def Pack(self, node):
S
SunAhong1993 已提交
855 856 857 858
        inputs_list = list()
        for i in range(len(node.inputs)):
            inputs_list.append(self.graph.get_input_node(node, i))
        input_names = [i.name for i in inputs_list]
S
SunAhong1993 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872
        axis = node.get_attr("axis")
        self.paddle_graph.add_layer(
            kernel="paddle.stack",
            inputs={"x": input_names},
            outputs=[node.name],
            axis=axis)
        if len(node.out_shapes[0]) == 1:
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": node.name},
                outputs=[node.name],
                shape=[-1])

    def Unpack(self, node):
S
SunAhong1993 已提交
873
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
        axis = node.get_attr("axis")
        num = node.get_attr("num")
        shape = input.out_shapes[0]
        input_name = input.name
        if len(shape) == 1:
            if shape[0] > 0 and num == shape[0]:
                self.paddle_graph.add_layer(
                    kernel="paddle.unsqueeze",
                    inputs={"x": input.name},
                    outputs=[node.name],
                    axis=[0])
                input_name = node.name
                axis = 1
            else:
                raise Exception("Unexpected situation happend in Unpack OP")
889 890 891
        layer_outputs = [
            "{}_p{}".format(node.layer_name, i) for i in range(num)
        ]
S
SunAhong1993 已提交
892 893
        if len(layer_outputs) == 1:
            layer_outputs[0] = "[{}]".format(node.layer_name)
S
SunAhong1993 已提交
894 895 896
        self.paddle_graph.add_layer(
            kernel="paddle.unstack",
            inputs={"x": input_name},
S
SunAhong1993 已提交
897
            outputs=layer_outputs,
S
SunAhong1993 已提交
898 899 900 901
            axis=axis,
            num=num)

    def ConcatV2(self, node):
S
SunAhong1993 已提交
902 903 904 905
        inputs_list = list()
        for i in range(len(node.inputs) - 1):
            inputs_list.append(self.graph.get_input_node(node, i))
        axis = self.graph.get_input_node(node, -1)
S
SunAhong1993 已提交
906 907 908
        assert axis.layer_type == "Const", "axis for ConcatV2 must be type Const"
        axis = axis.value
        if axis < 0:
S
fix  
SunAhong1993 已提交
909
            axis += len(inputs_list[0].out_shapes[0])
S
SunAhong1993 已提交
910

S
SunAhong1993 已提交
911
        input_names = [i.name for i in inputs_list]
S
SunAhong1993 已提交
912 913
        self.paddle_graph.add_layer(
            kernel="paddle.concat",
S
SunAhong1993 已提交
914
            inputs={"x": input_names},
S
SunAhong1993 已提交
915 916
            outputs=[node.name],
            axis=axis)
917

S
SunAhong1993 已提交
918 919 920 921 922 923 924 925 926
    def Concat(self, node):
        inputs_list = list()
        for i in range(1, len(node.inputs)):
            inputs_list.append(self.graph.get_input_node(node, i))
        axis = self.graph.get_input_node(node, 0)
        assert axis.layer_type == "Const", "axis for ConcatV2 must be type Const"
        axis = axis.value
        if axis < 0:
            axis += len(inputs_list[0].out_shapes[0])
927

S
SunAhong1993 已提交
928 929 930 931 932 933
        input_names = [i.name for i in inputs_list]
        self.paddle_graph.add_layer(
            kernel="paddle.concat",
            inputs={"x": input_names},
            outputs=[node.name],
            axis=axis)
934

S
SunAhong1993 已提交
935 936 937 938 939 940 941 942 943 944
    def AddN(self, node):
        inputs_list = list()
        for i in range(len(node.inputs) - 1):
            inputs_list.append(self.graph.get_input_node(node, i))

        input_names = [i.name for i in inputs_list]
        self.paddle_graph.add_layer(
            kernel="paddle.add_n",
            inputs={"inputs": input_names},
            outputs=[node.name])
S
SunAhong1993 已提交
945 946

    def StridedSlice(self, node):
S
SunAhong1993 已提交
947 948 949 950
        input = self.graph.get_input_node(node, 0)
        begin = self.graph.get_input_node(node, 1)
        end = self.graph.get_input_node(node, 2)
        strides = self.graph.get_input_node(node, 3)
S
SunAhong1993 已提交
951 952 953 954

        if strides.layer_type == "Const":
            strides = strides.value.tolist()
        else:
S
SunAhong1993 已提交
955
            strides = self.decoder.infer_tensor(strides)
S
SunAhong1993 已提交
956 957 958
        if begin.layer_type == "Const":
            begin = begin.value.tolist()
        else:
S
SunAhong1993 已提交
959
            begin = self.decoder.infer_tensor(begin)
S
SunAhong1993 已提交
960 961 962
        if end.layer_type == "Const":
            end = end.value.tolist()
        else:
S
SunAhong1993 已提交
963
            end = self.decoder.infer_tensor(end)
S
SunAhong1993 已提交
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

        assert len(set(strides)) == 1 and strides[
            0] == 1, "Only support strides be 1 in StridedSlice OP"

        if len(begin) < len(input.out_shapes[0]):
            begin = begin + [0] * (len(input.out_shapes[0]) - len(begin))
        if len(end) < len(input.out_shapes[0]):
            end = end + [0] * (len(input.out_shapes[0]) - len(end))
        for i in range(len(end)):
            if end[i] == 0:
                end[i] = 999999

        begin_mask = node.get_attr('begin_mask')
        end_mask = node.get_attr('end_mask')
        ellipsis_mask = node.get_attr('ellipsis_mask')
        new_axis_mask = node.get_attr('new_axis_mask')
        shrink_axis_mask = node.get_attr('shrink_axis_mask')

        assert ellipsis_mask == 0, "(OP:{} Name:{})Only support ellipsis_mask be 0[now: {}] n StridedSlice OP".format(
            node.layer_type, node.layer.name, ellipsis_mask)

        # TODO codes without validation
        # Use it carefully
        new_begin = list()
        new_end = list()
        new_axes = list()
        shrink_axes = list()
        for i, item in enumerate(begin):
            mask = (new_axis_mask >> i) & 1
            if mask != 0:
                new_axes.append(i)
                continue

            mask = (shrink_axis_mask >> i) & 1
            if mask != 0:
                shrink_axes.append(i)

            mask = (begin_mask >> i) & 1
            if mask != 0:
                new_begin.append(0)
            else:
                new_begin.append(item)

            mask = (end_mask >> i) & 1
            if mask != 0:
                new_end.append(999999)
            else:
                new_end.append(end[i])
1012

S
fix  
SunAhong1993 已提交
1013 1014 1015 1016 1017 1018
        if input.dtype == "bool":
            self.paddle_graph.add_layer(
                "paddle.cast",
                inputs={"x": input.name},
                outputs=[input.name],
                dtype=string("int32"))
S
SunAhong1993 已提交
1019 1020 1021 1022 1023 1024 1025 1026

        self.paddle_graph.add_layer(
            kernel="paddle.slice",
            inputs={"input": input.name},
            outputs=[node.name],
            axes=[i for i in range(len(new_begin))],
            starts=new_begin,
            ends=new_end)
1027

S
fix  
SunAhong1993 已提交
1028 1029 1030 1031 1032 1033 1034
        if input.dtype == "bool":
            self.paddle_graph.add_layer(
                "paddle.cast",
                inputs={"x": node.name},
                outputs=[node.name],
                dtype=string("bool"))

S
SunAhong1993 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        if len(new_axes) > 0:
            self.paddle_graph.add_layer(
                kernel="paddle.unsqueeze",
                inputs={"x": node.name},
                outputs=[node.name],
                axis=new_axes)
        if len(shrink_axes) > 0:
            if len(input.out_shapes[0]) + len(new_axes) <= 1:
                pass
            else:
                self.paddle_graph.add_layer(
                    kernel="paddle.squeeze",
                    inputs={"x": node.name},
                    outputs=[node.name],
                    axis=shrink_axes)
1050

S
SunAhong1993 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    def Prod(self, node):
        input = self.graph.get_input_node(node, 0)
        reduction_indices = self.graph.get_input_node(node, 1)
        assert reduction_indices.layer_type == "Const"
        keep_dims = node.get_attr('keep_dims')
        axis = reduction_indices.value

        self.paddle_graph.add_layer(
            kernel="paddle.prod",
            inputs={"x": input.name},
            outputs=[node.layer_name],
            keepdim=keep_dims,
            axis=axis)
S
SunAhong1993 已提交
1064 1065

    def Split(self, node):
S
SunAhong1993 已提交
1066 1067
        dim = self.graph.get_input_node(node, 0)
        input = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1068 1069 1070 1071 1072 1073
        assert dim.layer_type == "Const"
        num_split = node.get_attr('num_split')
        dim = dim.value

        self.paddle_graph.add_layer(
            kernel="paddle.split",
S
SunAhong1993 已提交
1074
            inputs={"x": input.name},
S
SunAhong1993 已提交
1075 1076 1077 1078
            outputs=[
                "{}_p{}".format(node.layer_name, i) for i in range(num_split)
            ],
            num_or_sections=num_split,
S
SunAhong1993 已提交
1079
            axis=dim)
1080

S
SunAhong1993 已提交
1081 1082 1083 1084 1085 1086 1087 1088
    def SplitV(self, node):
        input = self.graph.get_input_node(node, 0)
        size_splits = self.graph.get_input_node(node, 1)
        assert size_splits.layer_type == "Const", "size_splits of SplitV OP should be Const"
        size_splits = size_splits.value.tolist()
        dim = self.graph.get_input_node(node, 2)
        assert dim.layer_type == "Const", "dim of SplitV OP should be Const"
        dim = dim.value
1089

S
SunAhong1993 已提交
1090 1091 1092 1093
        self.paddle_graph.add_layer(
            kernel="paddle.split",
            inputs={"x": input.name},
            outputs=[
1094 1095
                "{}_p{}".format(node.layer_name, i)
                for i in range(len(size_splits))
S
SunAhong1993 已提交
1096 1097 1098
            ],
            num_or_sections=size_splits,
            axis=dim)
S
SunAhong1993 已提交
1099 1100

    def Slice(self, node):
S
SunAhong1993 已提交
1101 1102 1103
        input = self.graph.get_input_node(node, 0)
        begin = self.graph.get_input_node(node, 1)
        size = self.graph.get_input_node(node, 2)
S
SunAhong1993 已提交
1104 1105 1106 1107 1108 1109 1110

        inputs = {"x": input.name}
        attrs = {}
        if begin.layer_type == "Const":
            begin = begin.value.tolist()
            attrs['offsets'] = begin
        else:
1111 1112
            begin = self.decoder.infer_tensor(
                begin, use_diff_inputs=False).tolist()
S
SunAhong1993 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
            attrs['offsets'] = begin
        if size.layer_type == "Const":
            size = size.value.tolist()
            attrs['shape'] = size
        else:
            shape = size.out_shapes[0]
            reshape_name = gen_name("slice", "reshape")
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": size.name},
                outputs=[reshape_name],
                shape=shape)
            inputs['shape'] = reshape_name
        self.paddle_graph.add_layer(
1127
            kernel="paddle.crop", inputs=inputs, outputs=[node.name], **attrs)
S
SunAhong1993 已提交
1128 1129

    def ResizeNearestNeighbor(self, node):
S
SunAhong1993 已提交
1130 1131
        input = self.graph.get_input_node(node, 0)
        resize_shape = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1132
        data_format = "NHWC"
S
SunAhong1993 已提交
1133
        inputs = {"x": input.name}
1134 1135 1136 1137 1138
        attrs = {
            "align_corners": node.get_attr("align_corners"),
            "mode": string("nearest"),
            "align_mode": 1
        }
S
SunAhong1993 已提交
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150

        if resize_shape.layer_type == "Const":
            resize_shape = resize_shape.value.tolist()
            attrs["size"] = resize_shape
        else:
            shape = resize_shape.out_shapes[0]
            reshape_name = gen_name("resize_nearest", "reshape")
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": resize_shape.name},
                outputs=[reshape_name],
                shape=shape)
S
SunAhong1993 已提交
1151
            inputs["size"] = reshape_name
S
SunAhong1993 已提交
1152 1153 1154 1155 1156 1157 1158 1159

        if data_format == "NHWC":
            transpose_name = gen_name("resize_nearest", "reshape")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
S
SunAhong1993 已提交
1160
            inputs["x"] = transpose_name
S
SunAhong1993 已提交
1161 1162

        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
1163
            kernel="paddle.nn.functional.interpolate",
S
SunAhong1993 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
            inputs=inputs,
            outputs=[node.name],
            **attrs)

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])
1174

S
SunAhong1993 已提交
1175
    def ResizeBilinear(self, node):
S
SunAhong1993 已提交
1176 1177
        input = self.graph.get_input_node(node, 0)
        resize_shape = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1178
        data_format = "NHWC"
S
SunAhong1993 已提交
1179
        inputs = {"x": input.name}
1180 1181 1182 1183 1184
        attrs = {
            "align_corners": node.get_attr("align_corners"),
            "mode": string("bilinear"),
            "align_mode": 1
        }
S
SunAhong1993 已提交
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196

        if resize_shape.layer_type == "Const":
            resize_shape = resize_shape.value.tolist()
            attrs["size"] = resize_shape
        else:
            shape = resize_shape.out_shapes[0]
            reshape_name = gen_name("resize_bilinear", "reshape")
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": resize_shape.name},
                outputs=[reshape_name],
                shape=shape)
S
SunAhong1993 已提交
1197
            inputs["size"] = reshape_name
S
SunAhong1993 已提交
1198 1199 1200 1201 1202 1203 1204 1205

        if data_format == "NHWC":
            transpose_name = gen_name("resize_bilinear", "reshape")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
S
SunAhong1993 已提交
1206
            inputs["x"] = transpose_name
S
SunAhong1993 已提交
1207 1208

        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
1209
            kernel="paddle.nn.functional.interpolate",
S
SunAhong1993 已提交
1210 1211 1212 1213 1214 1215
            inputs=inputs,
            outputs=[node.name],
            **attrs)

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
S
rename  
SunAhong1993 已提交
1216
                kernel="paddle.transpose",
S
SunAhong1993 已提交
1217 1218 1219 1220 1221
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def Cast(self, node):
S
SunAhong1993 已提交
1222
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
1223 1224 1225 1226 1227 1228 1229 1230
        dtype = node.dtype
        self.paddle_graph.add_layer(
            kernel="paddle.cast",
            inputs={"x": input.name},
            outputs=[node.name],
            dtype=string(dtype))

    def Sum(self, node):
S
SunAhong1993 已提交
1231 1232
        input = self.graph.get_input_node(node, 0)
        reduce_idx = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1233 1234 1235 1236 1237 1238
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        keep_dims = node.get_attr("keep_dims")
        dim = reduce_idx.value.tolist()

        self.paddle_graph.add_layer(
            kernel="paddle.sum",
S
SunAhong1993 已提交
1239
            inputs={"x": input.name},
S
SunAhong1993 已提交
1240 1241 1242 1243 1244
            outputs=[node.name],
            axis=dim,
            keepdim=keep_dims)

    def Max(self, node):
S
SunAhong1993 已提交
1245 1246
        input = self.graph.get_input_node(node, 0)
        reduce_idx = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1247 1248 1249 1250 1251
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        keep_dims = node.get_attr("keep_dims")
        dim = reduce_idx.value.tolist()
        self.paddle_graph.add_layer(
            kernel="paddle.max",
S
SunAhong1993 已提交
1252
            inputs={"x": input.name},
S
SunAhong1993 已提交
1253 1254 1255 1256 1257
            outputs=[node.name],
            axis=dim,
            keepdim=keep_dims)

    def RandomUniform(self, node):
S
SunAhong1993 已提交
1258
        shape = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        if shape.layer_type == "Const":
            shape = shape.value.tolist()
            self.paddle_graph.add_layer(
                kernel="paddle.uniform",
                inputs={},
                outputs=[node.name],
                shape=shape,
                min=0.0,
                max=0.9999)
        else:
            self.paddle_graph.add_layer(
                kernel="paddle.uniform",
                inputs={'shape': shape.name},
                outputs=[node.name],
                min=0.0,
                max=0.9999)

    def Conv2DBackpropInput(self, node):
        op_name = name_generator("conv", self.nn_name2id)
        output_name = node.name
        layer_outputs = [op_name, output_name]
S
SunAhong1993 已提交
1280 1281 1282
        out_shape = self.graph.get_input_node(node, 0)
        kernel = self.graph.get_input_node(node, 1)
        input = self.graph.get_input_node(node, 2)
S
SunAhong1993 已提交
1283 1284 1285 1286 1287 1288

        assert kernel.layer_type == "Const", "Kernel of Conv2DBackpropInput should be Const"

        if out_shape.layer_type == "Const":
            out_shape = out_shape.value.tolist()
        else:
1289 1290
            out_shape = self.decoder.infer_tensor(
                out_shape, out_shape=node.out_shapes[0])
S
SunAhong1993 已提交
1291 1292 1293

        in_shape = input.out_shapes[0]
        if in_shape.count(-1) > 2:
1294 1295
            in_shape = self.decoder.infer_tensor(
                input, use_diff_inputs=False).shape
S
SunAhong1993 已提交
1296 1297
        k_size = kernel.out_shapes[0]
        if k_size.count(-1) > 2:
1298 1299
            k_size = self.decoder.infer_tensor(
                kernel, use_diff_inputs=False).shape
S
SunAhong1993 已提交
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322

        pad_mode = node.get_attr("padding").decode()
        strides = node.get_attr("strides")
        dilations = node.get_attr("dilations")
        data_format = node.get_attr("data_format").decode()

        kernel_name = op_name + ".weight"
        self.params[kernel_name] = numpy.transpose(kernel.value, (3, 2, 0, 1))

        input_name = input.name
        if data_format == "NHWC":
            in_shape = [in_shape[i] for i in [0, 3, 1, 2]]
            strides = [strides[i] for i in [0, 3, 1, 2]]
            dilations = [dilations[i] for i in [0, 3, 1, 2]]
            transpose_name = gen_name("conv2dbackpropinput", "transpose")
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": input.name},
                outputs=[transpose_name],
                perm=[0, 3, 1, 2])
            input_name = transpose_name

        self.paddle_graph.add_layer(
S
SunAhong1993 已提交
1323 1324 1325 1326 1327
            "self.create_parameter",
            inputs={},
            outputs=["{}_{}".format(node.name, kernel_name).replace(".", "_")],
            shape=self.params[kernel_name].shape,
            attr=string(kernel_name))
1328

S
SunAhong1993 已提交
1329 1330
        self.paddle_graph.add_layer(
            kernel="paddle.nn.functional.conv2d_transpose",
1331 1332 1333 1334 1335
            inputs={
                "x": input_name,
                "weight":
                "{}_{}".format(node.name, kernel_name).replace(".", "_")
            },
S
SunAhong1993 已提交
1336 1337
            outputs=[node.name],
            bias=None,
S
SunAhong1993 已提交
1338 1339
            stride=strides[2:4],
            dilation=dilations[2:4],
S
SunAhong1993 已提交
1340 1341
            padding=string(pad_mode),
            output_size=out_shape[1:3])
S
SunAhong1993 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350

        if data_format == "NHWC":
            self.paddle_graph.add_layer(
                kernel="paddle.transpose",
                inputs={"x": node.name},
                outputs=[node.name],
                perm=[0, 2, 3, 1])

    def Tile(self, node):
S
SunAhong1993 已提交
1351
        input = self.graph.get_input_node(node, 0)
S
SunAhong1993 已提交
1352
        repeat_times = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1353 1354 1355
        inputs = {"x": input.name}
        attr = dict()
        in_shape = input.out_shapes[0]
S
SunAhong1993 已提交
1356 1357 1358
        if repeat_times.layer_type == "Const":
            repeat_times = repeat_times.value.tolist()
            attr["repeat_times"] = repeat_times
S
SunAhong1993 已提交
1359
        else:
S
SunAhong1993 已提交
1360
            inputs["repeat_times"] = repeat_times.name
S
SunAhong1993 已提交
1361 1362

        self.paddle_graph.add_layer(
1363
            kernel="paddle.tile", inputs=inputs, outputs=[node.name], **attr)
S
SunAhong1993 已提交
1364 1365

    def Range(self, node):
S
SunAhong1993 已提交
1366 1367 1368
        start = self.graph.get_input_node(node, 0)
        limit = self.graph.get_input_node(node, 1)
        delta = self.graph.get_input_node(node, 2)
S
SunAhong1993 已提交
1369 1370 1371 1372 1373 1374 1375 1376 1377
        inputs = dict()
        attr = dict()

        dtype = 'int32'
        if start.dtype.startswith('float'):
            dtype = start.dtype
        if start.layer_type == "Const":
            attr["start"] = start.value
        else:
1378

S
SunAhong1993 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
            inputs["start"] = start.name
        if limit.dtype.startswith('float'):
            dtype = limit.dtype
        if limit.layer_type == "Const":
            attr["end"] = limit.value
        else:
            inputs["end"] = limit.name
        if delta.dtype.startswith('float'):
            dtype = delta.dtype
        if delta.layer_type == "Const":
            attr["step"] = delta.value
        else:
            inputs["step"] = delta.name
        node.set_dtype(dtype)
        attr["dtype"] = string(node.dtype)

        self.paddle_graph.add_layer(
1396
            kernel="paddle.arange", inputs=inputs, outputs=[node.name], **attr)
S
SunAhong1993 已提交
1397 1398

    def SquaredDifference(self, node):
S
SunAhong1993 已提交
1399 1400
        x = self.graph.get_input_node(node, 0)
        y = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1401 1402 1403
        inputs = {"x": x.name, "y": y.name}
        x_shape = x.out_shapes[0]
        y_shape = y.out_shapes[0]
S
SunAhong1993 已提交
1404
        # TODO(syf)
S
SunAhong1993 已提交
1405
        layer_id = self.paddle_graph.add_layer(
S
SunAhong1993 已提交
1406
            "paddle.subtract", inputs=inputs, outputs=[node.name])
1407 1408 1409 1410
        self.paddle_graph.layers[layer_id].input_shapes = {
            "x": x_shape,
            "y": y_shape
        }
S
SunAhong1993 已提交
1411 1412 1413 1414 1415 1416

        inputs = {"x": node.name, "y": node.name}
        x_shape = node.out_shapes[0]
        y_shape = node.out_shapes[0]
        layer_id = self.paddle_graph.add_layer(
            "paddle.multiply", inputs=inputs, outputs=[node.name])
1417 1418 1419 1420
        self.paddle_graph.layers[layer_id].input_shapes = {
            "x": x_shape,
            "y": y_shape
        }
S
SunAhong1993 已提交
1421 1422

    def OneHot(self, node):
S
SunAhong1993 已提交
1423 1424 1425 1426
        input = self.graph.get_input_node(node, 0)
        depth = self.graph.get_input_node(node, 1)
        on_value = self.graph.get_input_node(node, 2)
        off_value = self.graph.get_input_node(node, 3)
S
SunAhong1993 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
        assert depth.layer_type == 'Const', 'Parameter depth should be Const in OneHot'
        assert on_value.layer_type == 'Const', 'Parameter on_value should be Const in OneHot'
        assert off_value.layer_type == 'Const', 'Parameter off_value should be Const in OneHot'

        attr = {'depth': depth.value}
        on_value = on_value.value
        off_value = off_value.value
        assert math.fabs(on_value -
                         1.0) < 1e-06, "on_value should be 1 in OneHot"
        assert math.fabs(off_value -
                         0.0) < 1e-06, "off_value should be 0 in OneHot"

        self.paddle_graph.add_layer(
            "paddle.nn.functional.one_hot",
            inputs={"x": input.name},
            outputs=[node.name],
            num_classes=depth.value)

    def Pow(self, node):
S
SunAhong1993 已提交
1446 1447
        x = self.graph.get_input_node(node, 0)
        factor = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
        inputs = {"x": x.name}
        attr = dict()
        if factor.layer_type == 'Const':
            attr["y"] = factor.value.tolist()
        else:
            inputs["y"] = factor.name
        self.paddle_graph.add_layer(
            "paddle.pow", inputs=inputs, outputs=[node.name], **attr)

    def All(self, node):
S
SunAhong1993 已提交
1458 1459
        input = self.graph.get_input_node(node, 0)
        reduce_idx = self.graph.get_input_node(node, 1)
S
SunAhong1993 已提交
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
        assert reduce_idx.layer_type == "Const", "Only support Const parameter[reduce_idx]"
        attr = dict()
        attr["axis"] = reduce_idx.value.tolist()
        attr["keepdim"] = node.get_attr("keep_dims")

        input_name = input.name
        if input.dtype != "bool":
            input_name = gen_name("all", "cast")
            self.paddle_graph.add_layer(
                "paddle.cast",
                inputs={"x": input.name},
                outputs=[input_name],
                dtype=string("bool"))
        self.paddle_graph.add_layer(
1474
            "paddle.all", inputs={"x": input_name}, outputs=[node.name], **attr)
S
SunAhong1993 已提交
1475 1476 1477 1478

        node.layer.attr['dtype'].type = 10

    def GatherV2(self, node):
S
SunAhong1993 已提交
1479 1480 1481
        embeddings = self.graph.get_input_node(node, 0)
        index = self.graph.get_input_node(node, 1)
        axis = self.graph.get_input_node(node, 2)
S
SunAhong1993 已提交
1482
        assert axis.layer_type == 'Const', "Only support Const parameter[axis]"
S
SunAhong1993 已提交
1483
        axis = axis.value
S
SunAhong1993 已提交
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        index_name = index.name
        if len(index.out_shapes[0]) != 1:
            reshape_name = gen_name("gather", "reshape")
            index_name = reshape_name
            self.paddle_graph.add_layer(
                "paddle.reshape",
                inputs={"x": index.name},
                outputs=[reshape_name],
                shape=[-1])
        inputs = {'x': embeddings.name, 'index': index_name}
        self.paddle_graph.add_layer(
1495
            "paddle.gather", inputs=inputs, outputs=[node.name], axis=axis)
S
SunAhong1993 已提交
1496 1497 1498 1499 1500 1501 1502
        if len(index.out_shapes[0]) != 1:
            out_shape = node.out_shapes[0]
            self.paddle_graph.add_layer(
                kernel="paddle.reshape",
                inputs={"x": node.name},
                outputs=[node.name],
                shape=out_shape)
1503

S
SunAhong1993 已提交
1504 1505 1506 1507 1508
    def GatherNd(self, node):
        x = self.graph.get_input_node(node, 0)
        index = self.graph.get_input_node(node, 1)
        inputs = {'x': x.name, 'index': index.name}
        self.paddle_graph.add_layer(
1509
            "paddle.gather_nd", inputs=inputs, outputs=[node.name])
S
SunAhong1993 已提交
1510 1511

    def ExpandDims(self, node):
S
SunAhong1993 已提交
1512 1513
        x = self.graph.get_input_node(node, 0, copy=True)
        y = self.graph.get_input_node(node, 1, copy=True)
S
SunAhong1993 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522
        inputs = {"x": x.name}
        attr = dict()
        if y.layer_type == 'Const':
            dim = y.value.tolist()
            if not isinstance(dim, list):
                dim = [dim]
            attr['axis'] = dim
        else:
            inputs['axis'] = y.name
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
        if len(x.out_shapes[0]) == 0:
            value = self.decoder.infer_tensor(x, use_diff_inputs=False).tolist()
            self.paddle_graph.add_layer(
                "paddle.full",
                inputs={},
                outputs=[node.name],
                dtype=string(x.dtype),
                shape=[1],
                fill_value=value)
        else:
            self.paddle_graph.add_layer(
                "paddle.unsqueeze", inputs=inputs, outputs=[node.name], **attr)
1535

S
SunAhong1993 已提交
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
    def ReverseV2(self, node):
        x = self.graph.get_input_node(node, 0)
        axis = self.graph.get_input_node(node, 1)
        inputs = {"x": x.name}
        attr = dict()
        if axis.layer_type == 'Const':
            axis = axis.value.tolist()
            if not isinstance(axis, list):
                axis = [axis]
            attr['axis'] = axis
        else:
            inputs['axis'] = axis.name
        self.paddle_graph.add_layer(
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
            "paddle.flip", inputs=inputs, outputs=[node.name], **attr)

    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},
S
SunAhong1993 已提交
1658
            outputs=[node.name],
1659
            shape=shape)
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682

    def Sign(self, node):
        x = self.graph.get_input_node(node, 0)
        support_list = ["float16", "float32", "float64"]
        if x.dtype not in support_list:
            self.paddle_graph.add_layer(
                "paddle.cast",
                inputs={"x": x.name},
                outputs=[node.name],
                dtype=string("float32"))
            self.paddle_graph.add_layer(
                kernel="paddle.sign",
                inputs={"x": node.name},
                outputs=[node.name])
            self.paddle_graph.add_layer(
                "paddle.cast",
                inputs={"x": node.name},
                outputs=[node.name],
                dtype=string(x.dtype))
        else:
            self.paddle_graph.add_layer(
                kernel="paddle.sign", inputs={"x": x.name},
                outputs=[node.name])