ascend_parser.py 97.1 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# 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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle.fluid.core as core
import numpy as np
16 17
from functools import reduce

18 19
__all__ = []

20
registerd_op = {  # forwards
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 48 49 50 51 52 53 54 55 56 57 58
    "elementwise_add": "AddParser",
    "matmul": "MatMulParser",
    "mul": "MulParser",
    "relu": "ReluParser",
    "softmax_with_cross_entropy": "SoftmaxWithCrossEntropyParser",
    "shape": "ShapeParser",
    "fill_constant": "FillConstantParser",
    "reduce_sum": "ReduceSumParser",
    "elementwise_mul": "DotMulParser",
    "elementwise_div": "DotDivParser",
    "elementwise_pow": "DotPowParser",
    "elementwise_max": "MaxParser",
    "elementwise_min": "MinParser",
    "elementwise_sub": "DotSubParser",
    "pow": "PowParser",
    "gelu": "GeluParser",
    "sqrt": "SqrtParser",
    "log": "LogParser",
    "sum": "SumParser",
    "logical_not": "LogicalNotParser",
    "gather": "GatherParser",
    "scatter": "ScatterParser",
    "cast": "CastParser",
    "tanh": "TanhParser",
    "stack": "StackParser",
    "square": "SquareParser",
    "unsqueeze2": "UnSqueezeParser",
    "assign": "AssignParser",
    "softmax": "SoftMaxParser",
    "reshape2": "ReshapeParser",
    "transpose2": "TransposeParser",
    "layer_norm": "LayerNormParser",
    "less_than": "LessParser",
    "mean": "MeanParser",
    "scale": "ScaleParser",
    "slice": "SliceParser",
    "top_k": "TopkParser",
    "accuracy": "AccuracyParser",
59
    # "increment": "IncrementParser",
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
    "lookup_table": "LookupTableParser",
    "truncated_gaussian_random": "TruncatedNormalParser",
    "c_allgather": "AllGatherParser",
    "c_allreduce_sum": "AllReduceSumParser",
    "c_allreduce_max": "AllReduceMaxParser",
    "c_broadcast": "BroadcastParser",
    "c_reduce_scatter": "ReduceScatterParser",
    "c_send": "SendParser",
    "c_receive": "ReceiveParser",
    "uniform_random": "UniformRandomParser",
    "range": "RangeParser",
    "equal": "EqualParser",
    "expand": "ExpandParser",
    "squeeze2": "SqueezeParser",
    ## backwords
    "matmul_grad": "MatMulGradParser",
    "mul_grad": "MulGradParser",
    "relu_grad": "ReluGradParser",
    "reduce_sum_grad": "ReduceSumGradParser",
    "softmax_with_cross_entropy_grad": "SoftmaxWithCrossEntropyGradParser",
    "tanh_grad": "TanhGradParser",
    "log_grad": "LogGradParser",
    "pow_grad": "PowGradParser",
    "sqrt_grad": "SqrtGradParser",
    "gelu_grad": "GeluGradParser",
    "mean_grad": "MeanGradParser",
    'lookup_table_grad': "LookUpTableGradParser",
    "elementwise_mul_grad": "DotMulGradParser",
    "elementwise_add_grad": "DotAddGradParser",
    "elementwise_div_grad": "DotDivGradParser",
    "softmax_grad": "SoftmaxGradParser",
    "slice_grad": "SliceGradParser",
    "reshape2_grad": "ReshapeGradParser",
    "gather_grad": "GatherGradParser",
    "transpose2_grad": "TransposeGradParser",
    "layer_norm_grad": "LayerNormGradParser",
    ## opt
    "sgd": "SGDParser",
98
    # "adam": "AdamParser",
99
}
100 101 102 103 104 105 106 107 108 109 110 111 112
global_cnt = -1
global_input_cnt = -1


class AscendHelper(object):
    def __init__(self):
        self.dtype2ge_map = {
            0: core.GEDataType.DT_BOOL,
            1: core.GEDataType.DT_INT16,
            2: core.GEDataType.DT_INT32,
            3: core.GEDataType.DT_INT64,
            4: core.GEDataType.DT_FLOAT16,
            5: core.GEDataType.DT_FLOAT,
113
            6: core.GEDataType.DT_DOUBLE,
114 115 116 117 118 119 120 121
        }
        self.dtype2np_map = {
            0: "bool",
            1: "int16",
            2: "int32",
            3: "int64",
            4: "float16",
            5: "float32",
122
            6: "float64",
123
        }
124
        self.dtype2paddle_inv_map = {"VarType.FP32": 0, "VarType.FP16": 1}
125 126 127

    def dtype2ge(self, dtype):
        assert dtype in self.dtype2ge_map, "dtype[%d] is not supported %d" % (
128 129
            dtype
        )
130 131 132 133
        return self.dtype2ge_map[dtype]

    def dtype2np(self, index):
        assert index in self.dtype2np_map, "index[%d] is not supported %d" % (
134 135
            index
        )
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        return self.dtype2np_map[index]


class AscendParserFactory(object):
    def __init__(self, graph, var2geop):
        self.graph = graph
        self.var2geop = var2geop

    def create_parse(self, parser_class):
        try:
            parser = globals()[parser_class](self.graph, self.var2geop)
            return parser
        except:
            raise ValueError("parser class %s does not exist" % parser_class)


class AscendParserBase(object):
    def __init__(self, graph, var2geop):
        self.graph = graph
        self.var2geop = var2geop
        self.op = None
        self.ascend_helper = AscendHelper()

    def _get_ge_input(self, input_var_name):
        assert input_var_name in self.var2geop, "var %s not created before" % (
161 162
            input_var_name
        )
163 164 165 166
        return self.var2geop[input_var_name]

    def update_output(self, geop_list, index_list):
        output_num = len(self.op.output_names)
167 168 169 170
        assert output_num == len(index_list), (
            "Parser[%s]'s output number[%d] is not equal to parameters number[%d]"
            % (self.parser_name, len(index_list), output_num)
        )
171 172 173
        for output_id in range(output_num):
            arguments = self.op.output(self.op.output_names[output_id])
            if len(arguments) > 0:
174 175 176 177 178 179 180 181 182
                assert len(arguments) == len(index_list[output_id]), (
                    "Parser[%s]'s %dth argument number[%d] is not equal to paddle's number[%d]"
                    % (
                        self.parser_name,
                        output_id,
                        len(index_list[output_id]),
                        len(arguments),
                    )
                )
183
                for i in range(len(arguments)):
184
                    self.var2geop[arguments[i]] = geop_list[
185 186
                        index_list[output_id][i]
                    ]
187 188 189 190 191 192

        for geop in geop_list:
            self.graph.add_op(geop)

    def apply(self, op):
        self.op = op
193 194 195 196
        assert (
            self.op.type == self.parser_name
        ), "op [%s] != parser_name[%s]" % (self.op.type, self.parser_name)
        # print("begin to parse op %s" % (self.parser_name))
197 198 199 200 201 202 203 204 205 206 207
        geop_list, index_list = self._apply()
        self.update_output(geop_list, index_list)

    def _mark_as_input(self, ge_tensor):
        global global_input_cnt
        global_input_cnt += 1
        self.var2geop["geinput." + str(global_input_cnt)] = ge_tensor

    def _accumulated_op_id(self):
        global global_cnt
        global_cnt += 1
208 209
        name = "." + str(global_cnt)
        return name
210 211

    def _create_ge_tensor(self, shape, dtype, value):
212 213 214 215 216
        tensor_desc = core.GETensorDesc(
            core.GEShape(shape),
            core.GEFormat.FORMAT_ND,
            self.ascend_helper.dtype2ge(dtype),
        )
217 218
        tensor = core.GETensor(tensor_desc)

219 220 221 222 223
        data = (
            (value * np.ones((shape)))
            .reshape(shape)
            .astype(self.ascend_helper.dtype2np(dtype))
        )
224 225 226 227 228
        buf = data.tobytes()
        data_8 = np.frombuffer(buf, dtype=np.uint8)
        tensor.set_data(data_8)
        return tensor

229
    def _get_ge_tensor(self, shape, dtype, value_list):
230 231 232 233 234
        tensor_desc = core.GETensorDesc(
            core.GEShape(shape),
            core.GEFormat.FORMAT_ND,
            self.ascend_helper.dtype2ge(dtype),
        )
235 236
        tensor = core.GETensor(tensor_desc)

237 238 239 240 241
        data = (
            np.array(value_list)
            .reshape(shape)
            .astype(self.ascend_helper.dtype2np(dtype))
        )
242 243 244 245 246
        buf = data.tobytes()
        data_8 = np.frombuffer(buf, dtype=np.uint8)
        tensor.set_data(data_8)

        tensor_const = core.GEOperatorFactory.create_operator(
247 248
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)
249 250 251 252 253 254 255 256 257 258

        return tensor_const

    def _get_variable(self, shape, dtype, tensor):
        if dtype == "int32":
            type = core.GEDataType.DT_INT32
        elif dtype == "float32":
            type = core.GEDataType.DT_FLOAT

        var = core.GEOperatorFactory.create_operator(
259 260
            "variable" + self._accumulated_op_id(), "Variable"
        )
261 262
        var.update_output_desc(
            "y",
263 264 265 266 267 268 269 270 271 272 273
            core.GETensorDesc(
                core.GEShape(shape), core.GEFormat.FORMAT_ND, type
            ),
        )
        assign = (
            core.GEOperatorFactory.create_operator(
                "assign" + self._accumulated_op_id(), "Assign"
            )
            .set_input("value", tensor)
            .set_input("ref", var)
        )
274 275 276 277

        return assign

    def _create_shape_tensor(self):
278 279 280
        tensor_desc = core.GETensorDesc(
            core.GEShape([2]), core.GEFormat.FORMAT_ND, core.GEDataType.DT_INT32
        )
281 282 283 284 285 286 287 288 289 290 291
        tensor = core.GETensor(tensor_desc)

        data = np.ones((2)).astype("int32").reshape([2])
        data[0] = 64
        buf = data.tobytes()
        data_8 = np.frombuffer(buf, dtype=np.uint8)
        tensor.set_data(data_8)
        return tensor

    def _get_GEtensor_shape(self, tensor):
        tensor_shape = core.GEOperatorFactory.create_operator(
292 293 294 295 296 297 298 299 300
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", tensor)
        tensor_shape = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", tensor_shape)
            .set_attr_int32("dst_type", 0)
        )
301 302
        return tensor_shape

303 304 305

class AddParser(AscendParserBase):
    def __init__(self, graph, var2geop):
306
        super().__init__(graph, var2geop)
307 308 309 310 311
        self.parser_name = "elementwise_add"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
312 313 314 315 316 317 318
        add = (
            core.GEOperatorFactory.create_operator(
                "add" + self._accumulated_op_id(), "Add"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
319 320 321
        return [add], [[0]]


322
class DotSubParser(AscendParserBase):
323
    def __init__(self, graph, var2geop):
324
        super().__init__(graph, var2geop)
325
        self.parser_name = "elementwise_sub"
326 327 328

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
329
        y = self._get_ge_input(self.op.input_arg_names[1])
330 331 332 333 334 335 336
        sub = (
            core.GEOperatorFactory.create_operator(
                "sub" + self._accumulated_op_id(), "Sub"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
337
        return [sub], [[0]]
338 339


340
class DotMulParser(AscendParserBase):
341
    def __init__(self, graph, var2geop):
342
        super().__init__(graph, var2geop)
343
        self.parser_name = "elementwise_mul"
344 345 346

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
347
        y = self._get_ge_input(self.op.input_arg_names[1])
348 349 350 351 352 353 354
        mul = (
            core.GEOperatorFactory.create_operator(
                "dotmul" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
355
        return [mul], [[0]]
356 357


358 359
class DotDivParser(AscendParserBase):
    def __init__(self, graph, var2geop):
360
        super().__init__(graph, var2geop)
361 362 363 364 365
        self.parser_name = "elementwise_div"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
366 367 368 369 370 371 372
        div = (
            core.GEOperatorFactory.create_operator(
                "dotdiv" + self._accumulated_op_id(), "Div"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
373
        return [div], [[0]]
374 375


376
class DotPowParser(AscendParserBase):
377
    def __init__(self, graph, var2geop):
378
        super().__init__(graph, var2geop)
379
        self.parser_name = "elementwise_pow"
380 381

    def _apply(self):
382 383
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
384 385 386 387 388 389 390
        pow = (
            core.GEOperatorFactory.create_operator(
                "dotpow" + self._accumulated_op_id(), "Pow"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
391
        return [pow], [[0]]
392 393


394
class LessParser(AscendParserBase):
395
    def __init__(self, graph, var2geop):
396
        super().__init__(graph, var2geop)
397
        self.parser_name = "less_than"
398 399

    def _apply(self):
400 401
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
402 403 404 405 406 407 408
        less_than = (
            core.GEOperatorFactory.create_operator(
                "less_than" + self._accumulated_op_id(), "Less"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
409
        return [less_than], [[0]]
410 411


412 413
class MaxParser(AscendParserBase):
    def __init__(self, graph, var2geop):
414
        super().__init__(graph, var2geop)
415
        self.parser_name = "elementwise_max"
416

417 418 419
    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
420 421 422 423 424 425 426
        max_out = (
            core.GEOperatorFactory.create_operator(
                "max" + self._accumulated_op_id(), "Maximum"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
427 428 429 430
        return [max_out], [[0]]


class MinParser(AscendParserBase):
431
    def __init__(self, graph, var2geop):
432
        super().__init__(graph, var2geop)
433
        self.parser_name = "elementwise_min"
434 435

    def _apply(self):
436 437
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
438 439 440 441 442 443 444
        min_out = (
            core.GEOperatorFactory.create_operator(
                "min" + self._accumulated_op_id(), "Minimum"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
445
        return [min_out], [[0]]
446 447


448 449 450
## cal
class LogParser(AscendParserBase):
    def __init__(self, graph, var2geop):
451
        super().__init__(graph, var2geop)
452 453 454 455 456
        self.parser_name = "log"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        log = core.GEOperatorFactory.create_operator(
457 458
            "log" + self._accumulated_op_id(), "Log"
        ).set_input("x", x)
459 460 461 462 463
        return [log], [[0]]


class SqrtParser(AscendParserBase):
    def __init__(self, graph, var2geop):
464
        super().__init__(graph, var2geop)
465 466 467 468 469
        self.parser_name = "sqrt"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        sqrt = core.GEOperatorFactory.create_operator(
470 471
            "sqrt" + self._accumulated_op_id(), "Sqrt"
        ).set_input("x", x)
472 473 474 475 476
        return [sqrt], [[0]]


class PowParser(AscendParserBase):
    def __init__(self, graph, var2geop):
477
        super().__init__(graph, var2geop)
478 479 480 481 482
        self.parser_name = "pow"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        factor = self.op.attr("factor")
483 484 485 486 487 488 489 490 491
        pow_value = (
            core.GEOperatorFactory.create_operator(
                "pow" + self._accumulated_op_id(), "Power"
            )
            .set_input("x", x)
            .set_attr_float("power", factor)
            .set_attr_float("scale", 1.0)
            .set_attr_float("shift", 0.0)
        )
492 493 494 495 496
        return [pow_value], [[0]]


class SquareParser(AscendParserBase):
    def __init__(self, graph, var2geop):
497
        super().__init__(graph, var2geop)
498 499 500 501 502
        self.parser_name = "square"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        square = core.GEOperatorFactory.create_operator(
503 504
            "square" + self._accumulated_op_id(), "Square"
        ).set_input("x", x)
505 506 507 508 509
        return [square], [[0]]


class SumParser(AscendParserBase):
    def __init__(self, graph, var2geop):
510
        super().__init__(graph, var2geop)
511 512 513 514 515 516 517 518
        self.parser_name = "sum"

    def _apply(self):
        len_list = len(self.op.input_arg_names)
        if len_list < 2:
            assert False, "the size of input list must large or equal 2"
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
519 520 521 522 523 524 525
        sum = (
            core.GEOperatorFactory.create_operator(
                "sum" + self._accumulated_op_id(), "Add"
            )
            .set_input("x1", x)
            .set_input("x2", y)
        )
526 527
        for i in range(2, len_list):
            y = self._get_ge_input(self.op.input_arg_names[i])
528 529 530 531 532 533 534
            sum = (
                core.GEOperatorFactory.create_operator(
                    "sum" + self._accumulated_op_id(), "Add"
                )
                .set_input("x1", sum)
                .set_input("x2", y)
            )
535 536 537 538 539
        return [sum], [[0]]


class LogicalNotParser(AscendParserBase):
    def __init__(self, graph, var2geop):
540
        super().__init__(graph, var2geop)
541 542 543 544 545
        self.parser_name = "logical_not"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        logical_not = core.GEOperatorFactory.create_operator(
546 547
            "logical_not" + self._accumulated_op_id(), "LogicalNot"
        ).set_input("x", x)
548 549 550 551 552
        return [logical_not], [[0]]


class MeanParser(AscendParserBase):
    def __init__(self, graph, var2geop):
553
        super().__init__(graph, var2geop)
554 555 556 557
        self.parser_name = "mean"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
558 559 560 561 562 563 564 565
        mean = (
            core.GEOperatorFactory.create_operator(
                "mean" + self._accumulated_op_id(), "ReduceMeanD"
            )
            .set_input("x", x)
            .set_attr_bool("keep_dims", False)
            .set_attr_vec_int32("axes", [])
        )
566 567 568 569 570
        return [mean], [[0]]


class ReduceSumParser(AscendParserBase):
    def __init__(self, graph, var2geop):
571
        super().__init__(graph, var2geop)
572 573 574 575 576 577 578 579 580 581
        self.parser_name = "reduce_sum"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        axes = self.op.attr("dim")
        keep_dims = self.op.attr("keep_dim")
        reduce_all = self.op.attr("reduce_all")
        x_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        if reduce_all:
            axes = list(range(len(x_shape)))
582 583 584 585 586 587 588 589
        reduce_sum = (
            core.GEOperatorFactory.create_operator(
                "reduce_sum" + self._accumulated_op_id(), "ReduceSumD"
            )
            .set_input("x", x, 0)
            .set_attr_vec_int32("axes", axes)
            .set_attr_bool("keep_dims", keep_dims)
        )
590 591 592
        return [reduce_sum], [[0]]


593
# class IncrementParser(AscendParserBase):
594
#    def __init__(self, graph, var2geop):
595
#        super().__init__(graph, var2geop)
596 597
#        self.parser_name = "increment"
#
598
#    def _apply(self):
599 600 601
#        x = self._get_ge_input(self.op.input_arg_names[0])
#        step = self.op.attr("step") #self._get_ge_input(self.op.input_arg_names[1])
#        print("step: ", step)
602
#
603
#        increment = core.GEOperatorFactory.create_operator("adds" + self._accumulated_op_id(), "Adds").set_input("x", x).set_attr_float("value", step) #set_input("x2", bias)
604
#
605 606 607 608 609 610
#        return [increment]


## matrix cal
class MatMulParser(AscendParserBase):
    def __init__(self, graph, var2geop):
611
        super().__init__(graph, var2geop)
612 613 614 615 616 617 618 619 620 621 622 623
        self.parser_name = "matmul"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
        transpose_x = self.op.attr("transpose_X")
        transpose_y = self.op.attr("transpose_Y")

        x1_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        x2_shape = self.op.block.var(self.op.input_arg_names[1]).shape

        if len(x1_shape) > 2:
624 625 626 627 628 629 630 631 632
            matmul = (
                core.GEOperatorFactory.create_operator(
                    "matmul" + self._accumulated_op_id(), "BatchMatMul"
                )
                .set_input("x1", x)
                .set_input("x2", y)
                .set_attr_bool("adj_x1", transpose_x)
                .set_attr_bool("adj_x2", transpose_y)
            )
633
        elif len(x1_shape) == 2:
634 635 636 637 638 639 640 641 642
            matmul = (
                core.GEOperatorFactory.create_operator(
                    "matmul" + self._accumulated_op_id(), "MatMul"
                )
                .set_input("x1", x)
                .set_input("x2", y)
                .set_attr_bool("transpose_x1", transpose_x)
                .set_attr_bool("transpose_x2", transpose_y)
            )
643 644 645
        else:
            assert False, "not support"
        return [matmul], [[0]]
646 647 648 649


class MulParser(AscendParserBase):
    def __init__(self, graph, var2geop):
650
        super().__init__(graph, var2geop)
651 652 653 654 655
        self.parser_name = "mul"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        y = self._get_ge_input(self.op.input_arg_names[1])
656 657 658 659 660 661 662
        x_num_col_dims = self.op.attr("x_num_col_dims")
        y_num_col_dims = self.op.attr("y_num_col_dims")
        shape_x1 = self.op.block.var(self.op.input_arg_names[0]).shape
        shape_x2 = self.op.block.var(self.op.input_arg_names[1]).shape

        if x_num_col_dims == 1 and y_num_col_dims == 1:
            if len(shape_x1) == 2 and len(shape_x2) == 2:
663 664 665 666 667 668 669
                matmul = (
                    core.GEOperatorFactory.create_operator(
                        "mul" + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", x)
                    .set_input("x2", y)
                )
670 671
            elif len(shape_x1) == 3 and len(shape_x2) == 2:
                flatten_x1 = core.GEOperatorFactory.create_operator(
672 673 674 675 676 677 678 679 680
                    "flatten" + self._accumulated_op_id(), "Flatten"
                ).set_input("x", x)
                matmul = (
                    core.GEOperatorFactory.create_operator(
                        "mul" + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", flatten_x1, 0)
                    .set_input("x2", y, 0)
                )
681 682 683 684 685
            else:
                assert False, "not support"
        else:
            if len(shape_x1) == 3 and len(shape_x2) == 2:
                assert x_num_col_dims == 2, "only support 2"
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
                flatten_x1 = (
                    core.GEOperatorFactory.create_operator(
                        "flatten" + self._accumulated_op_id(), "FlattenV2"
                    )
                    .set_input("x", x)
                    .set_attr_int32("axis", 0)
                    .set_attr_int32("end_axis", 1)
                )
                matmul_m = (
                    core.GEOperatorFactory.create_operator(
                        "mul" + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", flatten_x1, 0)
                    .set_input("x2", y, 0)
                )
                matmul_transpose = (
                    core.GEOperatorFactory.create_operator(
                        "transpose" + self._accumulated_op_id(), "TransposeD"
                    )
                    .set_input("x", matmul_m)
                    .set_attr_vec_int32("perm", [1, 0])
                )
708
                tensor = self._create_ge_tensor(
709 710
                    [3], 2, [shape_x2[1], shape_x1[0], shape_x1[1]]
                )
711
                const_shape = core.GEOperatorFactory.create_operator(
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
                    "shape" + self._accumulated_op_id(), "Const"
                ).set_attr_tensor("value", tensor)
                reshape_matmul = (
                    core.GEOperatorFactory.create_operator(
                        "reshape" + self._accumulated_op_id(), "Reshape"
                    )
                    .set_input("x", matmul_transpose)
                    .set_input("shape", const_shape)
                    .set_attr_int32("axis", 0)
                )
                matmul = (
                    core.GEOperatorFactory.create_operator(
                        "transpose" + self._accumulated_op_id(), "TransposeD"
                    )
                    .set_input("x", reshape_matmul)
                    .set_attr_vec_int32("perm", [1, 2, 0])
                )
729 730
            else:
                assert False, "not support"
731 732 733 734

        return [matmul], [[0]]


735 736
class LayerNormParser(AscendParserBase):
    def __init__(self, graph, var2geop):
737
        super().__init__(graph, var2geop)
738 739 740 741 742 743 744 745 746 747 748
        self.parser_name = "layer_norm"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[2])
        scale = self._get_ge_input(self.op.input_arg_names[1])
        bias = self._get_ge_input(self.op.input_arg_names[0])
        epsilon = self.op.attr("epsilon")
        begin_norm_axis = self.op.attr("begin_norm_axis")
        x_dtype = self.op.block.var(self.op.input_arg_names[2]).dtype

        shape_tensor = core.GEOperatorFactory.create_operator(
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", x)
        scale_expand = (
            core.GEOperatorFactory.create_operator(
                "broadcast_to_d" + self._accumulated_op_id(), "BroadcastTo"
            )
            .set_input("x", scale)
            .set_input("shape", shape_tensor)
        )
        bias_expand = (
            core.GEOperatorFactory.create_operator(
                "broadcast_to_d" + self._accumulated_op_id(), "BroadcastTo"
            )
            .set_input("x", bias)
            .set_input("shape", shape_tensor)
        )
        layer_norm = (
            core.GEOperatorFactory.create_operator(
                "layer_norm" + self._accumulated_op_id(), "LayerNorm"
            )
            .set_input("x", x)
            .set_input("gamma", scale_expand)
            .set_input("beta", bias_expand)
            .set_attr_int32("begin_norm_axis", begin_norm_axis)
            .set_attr_int32("begin_params_axis", begin_norm_axis)
            .set_attr_float("epsilon", epsilon)
        )

        cast_dtype = (
            0
            if self.ascend_helper.dtype2paddle_inv_map[str(x_dtype)] == 0
            else 1
        )
        y = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", layer_norm, 0)
            .set_attr_int32("dst_type", cast_dtype)
        )
        mean = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", layer_norm, 1)
            .set_attr_int32("dst_type", cast_dtype)
        )
        variance = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", layer_norm, 2)
            .set_attr_int32("dst_type", cast_dtype)
        )
803 804 805 806
        return [y, mean, variance], [[1], [2], [0]]


## activate function
807 808
class ReluParser(AscendParserBase):
    def __init__(self, graph, var2geop):
809
        super().__init__(graph, var2geop)
810 811 812 813 814
        self.parser_name = "relu"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        relu = core.GEOperatorFactory.create_operator(
815 816
            "relu" + self._accumulated_op_id(), "Relu"
        ).set_input("x", x)
817 818 819
        return [relu], [[0]]


820
class GeluParser(AscendParserBase):
821
    def __init__(self, graph, var2geop):
822
        super().__init__(graph, var2geop)
823
        self.parser_name = "gelu"
824 825

    def _apply(self):
826 827
        x = self._get_ge_input(self.op.input_arg_names[0])
        gelu = core.GEOperatorFactory.create_operator(
828 829
            "gelu" + self._accumulated_op_id(), "Gelu"
        ).set_input("x", x)
830 831 832 833 834
        return [gelu], [[0]]


class TanhParser(AscendParserBase):
    def __init__(self, graph, var2geop):
835
        super().__init__(graph, var2geop)
836 837 838 839 840
        self.parser_name = "tanh"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        tanh = core.GEOperatorFactory.create_operator(
841 842
            "tanh" + self._accumulated_op_id(), "Tanh"
        ).set_input("x", x)
843
        return [tanh], [[0]]
844 845


846
## loss function
847 848
class SoftmaxWithCrossEntropyParser(AscendParserBase):
    def __init__(self, graph, var2geop):
849
        super().__init__(graph, var2geop)
850 851 852 853 854 855
        self.parser_name = "softmax_with_cross_entropy"

    def _apply(self):
        label = self._get_ge_input(self.op.input_arg_names[0])
        logits = self._get_ge_input(self.op.input_arg_names[1])
        cls_num = self.op.block.var(self.op.input_arg_names[1]).shape[1]
856

857
        softmax = core.GEOperatorFactory.create_operator(
858 859 860 861 862 863 864 865 866
            "softmax" + self._accumulated_op_id(), "SoftmaxV2"
        ).set_input("x", logits)
        label = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", label)
            .set_attr_int32("dst_type", 3)
        )
867 868

        tensoron = self._create_ge_tensor([1], 5, 1)
869
        on = core.GEOperatorFactory.create_operator(
870 871
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensoron)
872
        tensoroff = self._create_ge_tensor([1], 5, 0)
873
        off = core.GEOperatorFactory.create_operator(
874 875
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensoroff)
876 877
        self._mark_as_input(on)
        self._mark_as_input(off)
878 879 880 881 882 883 884 885 886
        onehot = (
            core.GEOperatorFactory.create_operator(
                "onehot" + self._accumulated_op_id(), "OneHotD"
            )
            .set_input("x", label)
            .set_input("on_value", on)
            .set_input("off_value", off)
            .set_attr_int32("depth", cls_num)
        )
887
        squeeze = core.GEOperatorFactory.create_operator(
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
            "mul" + self._accumulated_op_id(), "Squeeze"
        ).set_input("x", onehot)

        loss_all = (
            core.GEOperatorFactory.create_operator(
                "loss" + self._accumulated_op_id(),
                "SoftmaxCrossEntropyWithLogits",
            )
            .set_input("features", logits)
            .set_input("labels", squeeze)
        )
        loss = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", loss_all, 0)
            .set_attr_int32("dst_type", 0)
        )
        loss_expand = (
            core.GEOperatorFactory.create_operator(
                "unsqueeze" + self._accumulated_op_id(), "Unsqueeze"
            )
            .set_input("x", loss)
            .set_attr_vec_int32("axes", [1])
        )
913
        return [label, softmax, loss_expand], [[2], [1]]
914 915


916
class SoftMaxParser(AscendParserBase):
917
    def __init__(self, graph, var2geop):
918
        super().__init__(graph, var2geop)
919
        self.parser_name = "softmax"
920 921

    def _apply(self):
922 923
        logits = self._get_ge_input(self.op.input_arg_names[0])
        axes = self.op.attr("axis")
924

925 926 927 928 929 930 931
        softmax = (
            core.GEOperatorFactory.create_operator(
                "softmax" + self._accumulated_op_id(), "SoftmaxV2"
            )
            .set_input("x", logits)
            .set_attr_vec_int32("axes", [axes])
        )
932
        return [softmax], [[0]]
933 934


935
## general
936 937
class ShapeParser(AscendParserBase):
    def __init__(self, graph, var2geop):
938
        super().__init__(graph, var2geop)
939 940 941 942 943
        self.parser_name = "shape"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        shape = core.GEOperatorFactory.create_operator(
944 945
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", x)
946 947 948 949 950
        return [shape], [[0]]


class FillConstantParser(AscendParserBase):
    def __init__(self, graph, var2geop):
951
        super().__init__(graph, var2geop)
952 953 954 955 956 957
        self.parser_name = "fill_constant"

    def _apply(self):
        shape = self.op.attr("shape")
        dtype = self.op.attr("dtype")
        value = self.op.attr("value")
958

959 960
        tensor = self._create_ge_tensor(shape, dtype, value)
        const = core.GEOperatorFactory.create_operator(
961 962
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)
963 964
        self._mark_as_input(const)
        if self.op.block.var(self.op.output('Out')[0]).persistable:
965
            # print("%s is Persistable in fill_constant" %
966
            #      (self.op.output('Out')[0]))
967
            var = core.GEOperatorFactory.create_operator(
968 969
                self.op.output('Out')[0], "Variable"
            )
970 971
            var.update_output_desc(
                "y",
972 973 974 975 976 977 978 979 980 981 982 983 984
                core.GETensorDesc(
                    core.GEShape(shape),
                    core.GEFormat.FORMAT_ND,
                    core.GEDataType.DT_FLOAT,
                ),
            )
            assign = (
                core.GEOperatorFactory.create_operator(
                    "assign" + self._accumulated_op_id(), "Assign"
                )
                .set_input("value", const)
                .set_input("ref", var)
            )
985
            return [const], [[0]]
986
        return [const], [[0]]
987 988 989 990


class TruncatedNormalParser(AscendParserBase):
    def __init__(self, graph, var2geop):
991
        super().__init__(graph, var2geop)
992 993 994 995 996 997 998 999
        self.parser_name = "truncated_gaussian_random"

    def _apply(self):
        shape = self.op.attr("shape")
        dtype = self.op.attr("dtype")
        mean = self.op.attr("mean")
        std = self.op.attr("std")
        seed = self.op.attr("seed")
1000

1001 1002
        tensor1 = self._create_ge_tensor([len(shape)], 2, shape)
        shape_tensor = core.GEOperatorFactory.create_operator(
1003 1004
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor1)
1005 1006
        tensor2 = self._create_ge_tensor([1], dtype, mean)
        mean_tensor = core.GEOperatorFactory.create_operator(
1007 1008
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor2)
1009 1010
        tensor3 = self._create_ge_tensor([1], dtype, std)
        std_tensor = core.GEOperatorFactory.create_operator(
1011 1012
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor3)
1013 1014
        tensor4 = self._create_ge_tensor([1], dtype, mean - 2 * std)
        min_tensor = core.GEOperatorFactory.create_operator(
1015 1016
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor4)
1017 1018
        tensor5 = self._create_ge_tensor([1], dtype, mean + 2 * std)
        max_tensor = core.GEOperatorFactory.create_operator(
1019 1020
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor5)
1021 1022 1023 1024 1025 1026 1027

        self._mark_as_input(shape_tensor)
        self._mark_as_input(mean_tensor)
        self._mark_as_input(std_tensor)
        self._mark_as_input(min_tensor)
        self._mark_as_input(max_tensor)

1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        truncated_normal = (
            core.GEOperatorFactory.create_operator(
                "truncated_normal" + self._accumulated_op_id(),
                "ParameterizedTruncatedNormal",
            )
            .set_input("shape", shape_tensor)
            .set_input("means", mean_tensor)
            .set_input("stdevs", std_tensor)
            .set_input("min", min_tensor)
            .set_input("max", max_tensor)
            .set_attr_int32("seed", 0)
        )
1040 1041 1042

        ## wirte the output of truncatedNormal from startup_program to main_program
        if self.op.block.var(self.op.output('Out')[0]).persistable:
1043
            # print("%s is Persistable in truncated_normal" %
1044
            #      (self.op.output('Out')[0]))
1045
            var = core.GEOperatorFactory.create_operator(
1046 1047
                self.op.output('Out')[0], "Variable"
            )
1048 1049
            var.update_output_desc(
                "y",
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
                core.GETensorDesc(
                    core.GEShape(shape),
                    core.GEFormat.FORMAT_ND,
                    core.GEDataType.DT_FLOAT,
                ),
            )
            assign = (
                core.GEOperatorFactory.create_operator(
                    "assign" + self._accumulated_op_id(), "Assign"
                )
                .set_input("value", truncated_normal)
                .set_input("ref", var)
            )
1063
            return [
1064 1065 1066 1067 1068 1069
                shape_tensor,
                mean_tensor,
                std_tensor,
                min_tensor,
                max_tensor,
                truncated_normal,
1070
            ], [[-1]]
1071
        # else:
1072 1073 1074 1075
        #    print(
        #        "self.op.output('Out')[0] is not persistable in truncated_noraml"
        #    )
        return [truncated_normal], [[0]]
1076 1077


1078
class GatherParser(AscendParserBase):
1079
    def __init__(self, graph, var2geop):
1080
        super().__init__(graph, var2geop)
1081
        self.parser_name = "gather"
1082 1083

    def _apply(self):
1084 1085 1086 1087
        index = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])
        clo = self.op.block.var(self.op.input_arg_names[1]).shape[-1]

1088 1089 1090 1091 1092 1093 1094 1095
        gather = (
            core.GEOperatorFactory.create_operator(
                "gather" + self._accumulated_op_id(), "Gather"
            )
            .set_input("x", x)
            .set_input("indices", index)
            .set_attr_bool("validate_indices", True)
        )
1096 1097 1098 1099 1100
        return [gather], [[0]]


class ScatterParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1101
        super().__init__(graph, var2geop)
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        self.parser_name = "scatter"

    def _apply(self):
        index = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])
        updates = self._get_ge_input(self.op.input_arg_names[2])
        overwrite = self.op.attr("overwrite")
        index_shape = self.op.block.var(self.op.input_arg_names[0]).shape

        if len(index_shape) == 1:
1112 1113 1114 1115 1116 1117 1118
            index = (
                core.GEOperatorFactory.create_operator(
                    "unsqueeze" + self.getid(), "Unsqueeze"
                )
                .set_input("x", index)
                .set_attr_vec_int32("axes", [1])
            )
1119
        if not overwrite:
1120 1121 1122 1123 1124 1125 1126 1127
            scatter_value = (
                core.GEOperatorFactory.create_operator(
                    "scatter" + self._accumulated_op_id(), "TensorScatterAdd"
                )
                .set_input("x", x)
                .set_input("indices", index)
                .set_input("updates", updates)
            )
1128
        else:
1129 1130 1131 1132 1133 1134 1135 1136
            scatter_value = (
                core.GEOperatorFactory.create_operator(
                    "scatter" + self._accumulated_op_id(), "TensorScatterUpdate"
                )
                .set_input("x", x)
                .set_input("indices", index)
                .set_input("updates", updates)
            )
J
Jiangxinz 已提交
1137
        return [x, index, updates, scatter_value], [[-1]]
1138 1139 1140 1141


class CastParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1142
        super().__init__(graph, var2geop)
1143 1144 1145 1146 1147
        self.parser_name = "cast"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        dtype = self.op.attr("out_dtype")
1148 1149 1150 1151 1152 1153 1154
        cast = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", x)
            .set_attr_int32("dst_type", dtype)
        )
1155 1156 1157 1158 1159
        return [cast], [[0]]


class AssignParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1160
        super().__init__(graph, var2geop)
1161 1162 1163 1164 1165
        self.parser_name = "assign"

    def _apply(self):
        const = self._get_ge_input(self.op.input_arg_names[0])
        var = self._get_ge_input(self.op.input_arg_names[1])
1166 1167 1168 1169 1170 1171 1172
        assign = (
            core.GEOperatorFactory.create_operator(
                "assign" + self._accumulated_op_id(), "Assign"
            )
            .set_input("value", const)
            .set_input("ref", var)
        )
1173 1174 1175 1176 1177
        return [assign], [[0]]


class ScaleParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1178
        super().__init__(graph, var2geop)
1179 1180 1181 1182 1183 1184 1185 1186 1187
        self.parser_name = "scale"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        scale = self.op.attr("scale")
        bias = self.op.attr("bias")
        bias_after_scale = self.op.attr("bias_after_scale")

        if bias_after_scale:
1188 1189 1190 1191 1192 1193 1194 1195 1196
            scale_value = (
                core.GEOperatorFactory.create_operator(
                    "scale" + self._accumulated_op_id(), "Power"
                )
                .set_input("x", x)
                .set_attr_float("power", 1.0)
                .set_attr_float("scale", scale)
                .set_attr_float("shift", bias)
            )
1197
        else:
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
            x_add_bias = (
                core.GEOperatorFactory.create_operator(
                    "adds" + self._accumulated_op_id(), "Adds"
                )
                .set_input("x", x)
                .set_attr_float("value", bias)
            )
            scale_value = (
                core.GEOperatorFactory.create_operator(
                    "scale" + self._accumulated_op_id(), "Power"
                )
                .set_input("x", x_add_bias)
                .set_attr_float("power", 1.0)
                .set_attr_float("scale", scale)
                .set_attr_float("shift", 0.0)
            )
1214 1215 1216
        return [scale_value], [[0]]


1217 1218
class SliceParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1219
        super().__init__(graph, var2geop)
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
        self.parser_name = "slice"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        axes = self.op.attr("axes")
        starts = self.op.attr("starts")
        ends = self.op.attr("ends")

        x_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        len_shape = len(x_shape)
        axes_cor = list(range(len_shape))
        starts_cor, ends_cor = [], []
        cnt = 0
        for i in range(len_shape):
            starts_cor.append(starts[cnt] if i in axes else 0)
            if i in axes and ends[cnt] <= x_shape[i]:
                ends_cor.append(ends[cnt])
            else:
                ends_cor.append(x_shape[i])
            if i in axes:
                cnt += 1
        size = [ends_cor[i] - starts_cor[i] for i in range(len(axes_cor))]

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
        assert (
            len(axes_cor) == len(starts_cor) == len(ends_cor)
        ), "the three fields must have same size"
        slice_value = (
            core.GEOperatorFactory.create_operator(
                "slice" + self._accumulated_op_id(), "SliceD"
            )
            .set_input("x", x)
            .set_attr_vec_int32("offsets", starts_cor)
            .set_attr_vec_int32("size", size)
        )
1254 1255 1256 1257

        return [slice_value], [[0]]


1258 1259
class ReshapeParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1260
        super().__init__(graph, var2geop)
1261 1262 1263
        self.parser_name = "reshape2"

    def _apply(self):
1264 1265
        org_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        assert org_shape.count(-1) == 0, "do not allow the dim is -1"
1266
        shape = self.op.attr("shape")
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
        for cnt in range(len(shape)):
            if shape[cnt] == 0:
                shape[cnt] = org_shape[cnt]

        if -1 in shape:
            assert shape.count(-1) == 1, "only allow one dim is -1"
            mul_res_org = reduce(lambda x, y: x * y, org_shape)
            mul_res_refine = reduce(lambda x, y: x * y, shape) * -1
            idx = shape.index(-1)
            shape[idx] = mul_res_org // mul_res_refine

        x = self._get_ge_input(self.op.input_arg_names[0])
1279 1280
        tensor = self._create_ge_tensor([len(shape)], 2, shape)
        const_shape = core.GEOperatorFactory.create_operator(
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
            "shape" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)
        reshape = (
            core.GEOperatorFactory.create_operator(
                "reshape" + self._accumulated_op_id(), "Reshape"
            )
            .set_input("x", x)
            .set_input("shape", const_shape)
            .set_attr_int32("axis", 0)
        )
1291
        x_shape = core.GEOperatorFactory.create_operator(
1292 1293
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", x)
1294 1295 1296 1297 1298 1299

        return [x_shape, reshape], [[1], [0]]


class TransposeParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1300
        super().__init__(graph, var2geop)
1301 1302 1303 1304 1305
        self.parser_name = "transpose2"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        perm = self.op.attr("axis")
1306 1307 1308 1309 1310 1311 1312
        transpose = (
            core.GEOperatorFactory.create_operator(
                "transpose" + self._accumulated_op_id(), "TransposeD"
            )
            .set_input("x", x)
            .set_attr_vec_int32("perm", perm)
        )
1313
        x_shape = core.GEOperatorFactory.create_operator(
1314 1315
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", x)
1316 1317 1318 1319 1320 1321

        return [x_shape, transpose], [[1], [0]]


class AccuracyParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1322
        super().__init__(graph, var2geop)
1323 1324 1325 1326 1327 1328 1329
        self.parser_name = "accuracy"

    def _apply(self):
        pred = self._get_ge_input(self.op.input_arg_names[0])
        label = self._get_ge_input(self.op.input_arg_names[1])
        logits = self._get_ge_input(self.op.input_arg_names[2])

1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
        pred = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", pred)
            .set_attr_int32("dst_type", 3)
        )
        label = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", label)
            .set_attr_int32("dst_type", 3)
        )
        equal = (
            core.GEOperatorFactory.create_operator(
                "equal" + self._accumulated_op_id(), "Equal"
            )
            .set_input("x1", pred)
            .set_input("x2", label)
        )
        cast = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", equal)
            .set_attr_int32("dst_type", 0)
        )
        acc = (
            core.GEOperatorFactory.create_operator(
                "mean" + self._accumulated_op_id(), "ReduceMeanD"
            )
            .set_input("x", cast)
            .set_attr_bool("keep_dims", False)
            .set_attr_vec_int32("axes", [])
        )
        correct = (
            core.GEOperatorFactory.create_operator(
                "sum" + self._accumulated_op_id(), "ReduceSumD"
            )
            .set_input("x", cast)
            .set_attr_bool("keep_dims", False)
            .set_attr_vec_int32("axes", [])
        )
1374
        ones_tensor = core.GEOperatorFactory.create_operator(
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
            "oneslike" + self._accumulated_op_id(), "OnesLike"
        ).set_input("x", label)
        ones_tensor = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", ones_tensor)
            .set_attr_int32("dst_type", 0)
        )
        total = (
            core.GEOperatorFactory.create_operator(
                "sum" + self._accumulated_op_id(), "ReduceSumD"
            )
            .set_input("x", ones_tensor)
            .set_attr_bool("keep_dims", False)
            .set_attr_vec_int32("axes", [])
        )
1392 1393 1394 1395 1396 1397

        return [acc, correct, total], [[0], [1], [2]]


class TopkParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1398
        super().__init__(graph, var2geop)
1399 1400 1401 1402 1403 1404 1405 1406
        self.parser_name = "top_k"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        k = self.op.attr("k")

        tensor = self._create_ge_tensor([1], 2, k)
        const_k = core.GEOperatorFactory.create_operator(
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)
        cast_x = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", x)
            .set_attr_int32("dst_type", 1)
        )
        topk = (
            core.GEOperatorFactory.create_operator(
                "topk" + self._accumulated_op_id(), "TopK"
            )
            .set_input("x", cast_x)
            .set_input("k", const_k)
        )
        value = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", topk, 0)
            .set_attr_int32("dst_type", 0)
        )
        index = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", topk, 1)
            .set_attr_int32("dst_type", 0)
        )
1437 1438 1439 1440 1441
        return [value, index], [[1], [0]]


class LookupTableParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1442
        super().__init__(graph, var2geop)
1443 1444 1445 1446 1447 1448
        self.parser_name = "lookup_table"

    def _apply(self):
        ids = self._get_ge_input(self.op.input_arg_names[0])
        w = self._get_ge_input(self.op.input_arg_names[1])

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
        ids_squeeze = (
            core.GEOperatorFactory.create_operator(
                "squeeze" + self._accumulated_op_id(), "Squeeze"
            )
            .set_input("x", ids)
            .set_attr_vec_int32("axes", [-1])
        )
        out = (
            core.GEOperatorFactory.create_operator(
                "lookup" + self._accumulated_op_id(), "Gather"
            )
            .set_input("x", w)
            .set_input("indices", ids_squeeze)
        )
1463 1464 1465 1466 1467
        return [out], [[0]]


class StackParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1468
        super().__init__(graph, var2geop)
1469 1470 1471 1472 1473 1474
        self.parser_name = "stack"

    def _apply(self):
        tiles = len(self.op.input_arg_names)
        data_x_lst = []
        for index in range(tiles):
1475 1476 1477
            data_x_lst.append(
                self._get_ge_input(self.op.input_arg_names[index])
            )
1478 1479 1480 1481 1482
        axis = self.op.attr("axis")

        data_x = data_x_lst[0]
        tensor = self._create_ge_tensor([1], 2, axis)
        tensor_axis = core.GEOperatorFactory.create_operator(
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
            "axis" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)
        expand = (
            core.GEOperatorFactory.create_operator(
                "expand" + self._accumulated_op_id(), "ExpandDims"
            )
            .set_input("x", data_x)
            .set_input("axis", tensor_axis)
        )

        stack = (
            core.GEOperatorFactory.create_operator(
                "stack" + self._accumulated_op_id(), "TileWithAxis"
            )
            .set_input("x", expand)
            .set_attr_int32("axis", axis)
            .set_attr_int32("tiles", tiles)
        )
1501 1502 1503 1504 1505 1506

        return [stack], [[0]]


class UnSqueezeParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1507
        super().__init__(graph, var2geop)
1508 1509 1510 1511 1512 1513
        self.parser_name = "unsqueeze2"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        axes = self.op.attr('axes')

1514 1515 1516 1517 1518 1519 1520
        output = (
            core.GEOperatorFactory.create_operator(
                "unsqueeze" + self._accumulated_op_id(), "Unsqueeze"
            )
            .set_input("x", x)
            .set_attr_vec_int32("axes", axes)
        )
1521
        shape = core.GEOperatorFactory.create_operator(
1522 1523
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", output)
1524 1525 1526 1527 1528 1529
        return [shape, output], [[1], [0]]


## parallel
class AllGatherParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1530
        super().__init__(graph, var2geop)
1531 1532 1533 1534 1535 1536 1537
        self.parser_name = "c_allgather"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        rank_size = self.op.attr("rank_size")
        group = self.op.attr("group")

1538 1539 1540 1541 1542 1543 1544 1545
        allgather = (
            core.GEOperatorFactory.create_operator(
                "allgather" + self._accumulated_op_id(), "HcomAllGather"
            )
            .set_input("x", x)
            .set_attr_int32("rank_size", rank_size)
            .set_attr_string("group", group)
        )
1546 1547 1548 1549 1550
        return [allgather], [[0]]


class AllReduceParser(AscendParserBase):
    def __init__(self, graph, var2geop, reduction):
1551
        super().__init__(graph, var2geop)
1552 1553 1554 1555 1556 1557 1558 1559
        self.parser_name = "c_allreduce_" + reduction
        self.reduction = reduction

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        reduction = self.reduction
        ring_id = self.op.attr("ring_id")
        group = "hcom_group_" + str(ring_id)
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
        fusion = None  # self.op.attr("fusion")
        fusion_id = None  # self.op.attr("fusion_id")

        allreduce = (
            core.GEOperatorFactory.create_operator(
                "allreduce" + self._accumulated_op_id(), "HcomAllReduce"
            )
            .set_input("x", x)
            .set_attr_string("reduction", reduction)
            .set_attr_string("group", group)
        )
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
        if fusion is not None:
            allreduce.set_attr_int32("fusion", fusion)

        if fusion_id is not None:
            allreduce.set_attr_int32("fusion_id", fusion_id)
        return [allreduce], [[0]]


class AllReduceSumParser(AllReduceParser):
    def __init__(self, graph, var2geop):
1581
        super().__init__(graph, var2geop, 'sum')
1582 1583 1584 1585


class AllReduceMaxParser(AllReduceParser):
    def __init__(self, graph, var2geop):
1586
        super().__init__(graph, var2geop, 'max')
1587 1588 1589 1590


class BroadcastParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1591
        super().__init__(graph, var2geop)
1592 1593 1594 1595 1596 1597 1598
        self.parser_name = "c_broadcast"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        root_rank = self.op.attr("root_rank")
        group = self.op.attr("group")

1599 1600 1601 1602 1603 1604 1605 1606
        broadcast = (
            core.GEOperatorFactory.create_operator(
                "broadcast" + self._accumulated_op_id(), "HcomBroadcast"
            )
            .set_input("x", x)
            .set_attr_int32("root_rank", root_rank)
            .set_attr_string("group", group)
        )
1607 1608 1609 1610 1611
        return [broadcast], [[0]]


class ReduceScatterParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1612
        super().__init__(graph, var2geop)
1613 1614 1615 1616 1617 1618 1619 1620
        self.parser_name = "c_reduce_scatter"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        reduction = self.op.attr("reduction")
        group = self.op.attr("group")
        rank_size = self.op.attr("rank_size")

1621 1622 1623 1624 1625 1626 1627 1628 1629
        reduce_scatter = (
            core.GEOperatorFactory.create_operator(
                "reducescatter" + self._accumulated_op_id(), "HcomReduceScatter"
            )
            .set_input("x", x)
            .set_attr_string("reduction", reduction)
            .set_attr_string("group", group)
            .set_attr_int32("rank_size", rank_size)
        )
1630 1631 1632 1633 1634
        return [reduce_scatter], [[0]]


class SendParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1635
        super().__init__(graph, var2geop)
1636 1637 1638 1639 1640 1641 1642 1643
        self.parser_name = "c_send"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        sr_tag = self.op.attr("sr_tag")
        dest_rank = self.op.attr("dest_rank")
        group = self.op.attr("group")

1644 1645 1646 1647 1648 1649 1650 1651 1652
        send = (
            core.GEOperatorFactory.create_operator(
                "send" + self._accumulated_op_id(), "HcomSend"
            )
            .set_input("x", x)
            .set_attr_int32("sr_tag", sr_tag)
            .set_attr_int32("dest_rank", dest_rank)
            .set_attr_string("group", group)
        )
1653 1654 1655 1656 1657
        return [send], [[0]]


class ReceiveParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1658
        super().__init__(graph, var2geop)
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
        self.parser_name = "c_receive"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        sr_tag = self.op.attr("sr_tag")
        src_rank = self.op.attr("src_rank")
        group = self.op.attr("group")
        shape = self.op.attr("shape")
        dtype = self.op.attr("dtype")

1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
        receive = (
            core.GEOperatorFactory.create_operator(
                "receive" + self._accumulated_op_id(), "HcomReceive"
            )
            .set_input("x", x)
            .set_attr_int32("sr_tag", sr_tag)
            .set_attr_int32("src_rank", src_rank)
            .set_attr_string("group", group)
            .set_attr_vec_int32("shape", shape)
            .set_attr_int32("dtype", dtype)
        )
1680 1681 1682 1683 1684
        return [receive], [[0]]


class RangeParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1685
        super().__init__(graph, var2geop)
1686 1687 1688 1689 1690 1691 1692 1693
        self.parser_name = "range"

    def _apply(self):
        # TODO not support range type yet
        start = self._get_ge_input(self.op.input_arg_names[0])
        end = self._get_ge_input(self.op.input_arg_names[1])
        delta = self._get_ge_input(self.op.input_arg_names[2])

1694 1695 1696 1697 1698 1699 1700 1701
        ge_range = (
            core.GEOperatorFactory.create_operator(
                "range" + self._accumulated_op_id(), "Range"
            )
            .set_input("start", end)
            .set_input("limit", start)
            .set_input("delta", delta)
        )
1702 1703 1704 1705 1706 1707

        return [ge_range], [[0]]


class UniformRandomParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1708
        super().__init__(graph, var2geop)
1709 1710 1711 1712 1713 1714 1715 1716 1717
        self.parser_name = "uniform_random"

    def _apply(self):
        shape = self.op.attr("shape")

        min_v = self.op.attr("min")
        max_v = self.op.attr("max")
        seed = self.op.attr("seed")
        dtype = self.op.attr("dtype")
1718 1719 1720 1721
        assert max_v > min_v, (
            "assert max_v > min_v, but received "
            + "as max_v={}, min_v={} ".format(max_v, min_v)
        )
1722 1723 1724

        tensor1 = self._create_ge_tensor([len(shape)], 2, shape)
        shape_tensor = core.GEOperatorFactory.create_operator(
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor1)

        ge_ur = (
            core.GEOperatorFactory.create_operator(
                "uniform_random" + self._accumulated_op_id(), "RandomUniform"
            )
            .set_input("shape", shape_tensor)
            .set_attr_dtype("dtype", self.ascend_helper.dtype2ge(dtype))
            .set_attr_int32("seed", seed)
1735
            .set_attr_int32("seed2", seed)
1736
        )
1737 1738 1739

        scale = max_v - min_v

1740 1741 1742 1743 1744 1745 1746 1747 1748
        scale_value = (
            core.GEOperatorFactory.create_operator(
                "scale" + self._accumulated_op_id(), "Power"
            )
            .set_input("x", ge_ur)
            .set_attr_float("power", 1.0)
            .set_attr_float("scale", scale)
            .set_attr_float("shift", min_v)
        )
1749 1750 1751 1752 1753 1754

        return [scale_value], [[0]]


class EqualParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1755
        super().__init__(graph, var2geop)
1756 1757 1758 1759 1760
        self.parser_name = "equal"

    def _apply(self):
        data_x1 = self._get_ge_input(self.op.input_arg_names[0])
        data_x2 = self._get_ge_input(self.op.input_arg_names[1])
1761 1762 1763 1764 1765 1766 1767
        equal = (
            core.GEOperatorFactory.create_operator(
                "equal" + self._accumulated_op_id(), "Equal"
            )
            .set_input("x1", data_x1)
            .set_input("x2", data_x2)
        )
1768 1769 1770 1771 1772
        return [equal], [[0]]


class ExpandParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1773
        super().__init__(graph, var2geop)
1774 1775 1776 1777 1778 1779 1780
        self.parser_name = "expand"

    def _apply(self):
        data_x1_shape = self._get_ge_input(self.op.input_arg_names[0])
        expand_times = self.op.attr('expand_times')

        tensor = self._create_ge_tensor([len(expand_times)], 2, expand_times)
1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
        expand_tensor = core.GEOperatorFactory.create_operator(
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)

        assign = (
            core.GEOperatorFactory.create_operator(
                "tile" + self._accumulated_op_id(), "Tile"
            )
            .set_input("x", data_x1_shape)
            .set_input("multiples", expand_tensor)
        )
1792 1793 1794 1795 1796
        return [assign], [[0]]


class SqueezeParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1797
        super().__init__(graph, var2geop)
1798 1799 1800 1801 1802 1803
        self.parser_name = "squeeze2"

    def _apply(self):
        tensor = self._get_ge_input(self.op.input_arg_names[0])
        axes = self.op.attr("axes")

1804 1805 1806 1807 1808 1809 1810
        data_squeezed = (
            core.GEOperatorFactory.create_operator(
                "squeeze" + self._accumulated_op_id(), "Squeeze"
            )
            .set_input("x", tensor)
            .set_attr_vec_int32("axes", axes)
        )
1811
        shape = core.GEOperatorFactory.create_operator(
1812 1813
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", data_squeezed)
1814 1815 1816
        return [shape, data_squeezed], [[1], [0]]


1817 1818 1819 1820 1821 1822 1823
# ****************************************************************#
# ***************************            *************************#
# ***************************            *************************#
# *************************** GradParser *************************#
# ***************************            *************************#
# ***************************            *************************#
# ****************************************************************#
1824 1825 1826
## grad
class ReduceSumGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1827
        super().__init__(graph, var2geop)
1828 1829 1830 1831 1832 1833 1834
        self.parser_name = "reduce_sum_grad"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        input = self._get_ge_input(self.op.input_arg_names[1])

        shape_tensor = core.GEOperatorFactory.create_operator(
1835 1836
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", input, 0)
1837 1838
        tensoron = self._create_ge_tensor([1], 2, -1)
        const = core.GEOperatorFactory.create_operator(
1839 1840
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensoron)
1841 1842
        self._mark_as_input(const)

1843 1844 1845 1846 1847 1848 1849 1850
        reduce_sum = (
            core.GEOperatorFactory.create_operator(
                "broadcast_to_d" + self._accumulated_op_id(), "BroadcastTo"
            )
            .set_input("x", x)
            .set_input("shape", shape_tensor)
        )
        # reduce_sum = core.GEOperatorFactory.create_operator("expand" + self._accumulated_op_id(), "ExpandDims").set_input("x", reduce_sum).set_input("axis", const)
1851 1852 1853 1854 1855 1856

        return [reduce_sum], [[0]]


class MatMulGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1857
        super().__init__(graph, var2geop)
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
        self.parser_name = "matmul_grad"

    def _apply(self):
        out_grad = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])
        y = self._get_ge_input(self.op.input_arg_names[2])
        transpose_x = self.op.attr("transpose_X")
        transpose_y = self.op.attr("transpose_Y")

        out_grad_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        x_shape = self.op.block.var(self.op.input_arg_names[1]).shape
        y_shape = self.op.block.var(self.op.input_arg_names[2]).shape

        if len(x_shape) > 2:
            if transpose_y:
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "BatchMatMul",
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y)
                    .set_attr_bool("adj_x1", False)
                    .set_attr_bool("adj_x2", False)
                )
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "BatchMatMul",
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", x)
                    .set_attr_bool("adj_x1", True)
                    .set_attr_bool("adj_x2", False)
                )
1893
            else:
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "BatchMatMul",
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y)
                    .set_attr_bool("adj_x1", False)
                    .set_attr_bool("adj_x2", True)
                )
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "BatchMatMul",
                    )
                    .set_input("x1", x)
                    .set_input("x2", out_grad)
                    .set_attr_bool("adj_x1", True)
                    .set_attr_bool("adj_x2", False)
                )
1914 1915
        else:
            if transpose_y:
1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y)
                    .set_attr_bool("transpose_x1", False)
                    .set_attr_bool("transpose_x2", False)
                )
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", x)
                    .set_attr_bool("transpose_x1", True)
                    .set_attr_bool("transpose_x2", False)
                )
1934
            else:
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y)
                    .set_attr_bool("transpose_x1", False)
                    .set_attr_bool("transpose_x2", True)
                )
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", x)
                    .set_input("x2", out_grad)
                    .set_attr_bool("transpose_x1", True)
                    .set_attr_bool("transpose_x2", False)
                )
1953 1954 1955 1956 1957 1958

        return [x_grad, y_grad], [[0], [1]]


class MulGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
1959
        super().__init__(graph, var2geop)
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
        self.parser_name = "mul_grad"

    def _apply(self):
        out_grad = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])
        y = self._get_ge_input(self.op.input_arg_names[2])
        x_num_col_dims = self.op.attr("x_num_col_dims")
        y_num_col_dims = self.op.attr("y_num_col_dims")

        shape_out_grad = self.op.block.var(self.op.input_arg_names[0]).shape
        shape_x = self.op.block.var(self.op.input_arg_names[1]).shape
        shape_y = self.op.block.var(self.op.input_arg_names[2]).shape

        if x_num_col_dims == 1 and y_num_col_dims == 1:
            if len(shape_x) == 2 and len(shape_y) == 2:
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y)
                    .set_attr_bool("transpose_x1", False)
                    .set_attr_bool("transpose_x2", True)
                )
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", x)
                    .set_input("x2", out_grad)
                    .set_attr_bool("transpose_x1", True)
                    .set_attr_bool("transpose_x2", False)
                )
1993 1994
            elif len(shape_x) == 3 and len(shape_y) == 2:
                flatten_x = core.GEOperatorFactory.create_operator(
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
                    "flatten" + self._accumulated_op_id(), "Flatten"
                ).set_input("x", x)
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y)
                    .set_attr_bool("transpose_x1", False)
                    .set_attr_bool("transpose_x2", True)
                )
2006
                if len(shape_out_grad) == 2:
2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
                    x_grad = (
                        core.GEOperatorFactory.create_operator(
                            "unsqueeze" + self._accumulated_op_id(), "Unsqueeze"
                        )
                        .set_input("x", x_grad)
                        .set_attr_vec_int32("axes", [1])
                    )

                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", flatten_x)
                    .set_input("x2", out_grad)
                    .set_attr_bool("transpose_x1", True)
                    .set_attr_bool("transpose_x2", False)
                )
2024 2025 2026
        else:
            if len(shape_x) == 3 and len(shape_y) == 2:
                assert x_num_col_dims == 2, "only support 2"
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
                flatten_x = (
                    core.GEOperatorFactory.create_operator(
                        "flatten" + self._accumulated_op_id(), "FlattenV2"
                    )
                    .set_input("x", x)
                    .set_attr_int32("axis", 0)
                    .set_attr_int32("end_axis", 1)
                )
                flatten_out_grad = (
                    core.GEOperatorFactory.create_operator(
                        "flatten" + self._accumulated_op_id(), "FlattenV2"
                    )
                    .set_input("x", out_grad)
                    .set_attr_int32("axis", 0)
                    .set_attr_int32("end_axis", 1)
                )

                y_unsqueeze = (
                    core.GEOperatorFactory.create_operator(
                        "unsqueeze" + self._accumulated_op_id(), "Unsqueeze"
                    )
                    .set_input("x", y)
                    .set_attr_vec_int32("axes", [0])
                )
                y_stack = (
                    core.GEOperatorFactory.create_operator(
                        "stack" + self._accumulated_op_id(), "TileWithAxis"
                    )
                    .set_input("x", y_unsqueeze)
                    .set_attr_int32("axis", 0)
                    .set_attr_int32("tiles", shape_out_grad[0])
                )
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "BatchMatMul",
                    )
                    .set_input("x1", out_grad)
                    .set_input("x2", y_stack)
                    .set_attr_bool("adj_x1", False)
                    .set_attr_bool("adj_x2", True)
                )
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(), "MatMul"
                    )
                    .set_input("x1", flatten_x)
                    .set_input("x2", flatten_out_grad)
                    .set_attr_bool("transpose_x1", True)
                    .set_attr_bool("transpose_x2", False)
                )
2078 2079 2080 2081 2082 2083

        return [x_grad, y_grad], [[0], [1]]


class ReluGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2084
        super().__init__(graph, var2geop)
2085 2086 2087 2088 2089
        self.parser_name = "relu_grad"

    def _apply(self):
        out = self._get_ge_input(self.op.input_arg_names[0])
        out_grad = self._get_ge_input(self.op.input_arg_names[1])
2090 2091 2092 2093 2094 2095 2096
        relu_grad = (
            core.GEOperatorFactory.create_operator(
                self.parser_name + self._accumulated_op_id(), "ReluGrad"
            )
            .set_input("gradients", out_grad)
            .set_input("features", out)
        )
2097 2098 2099 2100 2101
        return [relu_grad], [[0]]


class SoftmaxWithCrossEntropyGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2102
        super().__init__(graph, var2geop)
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
        self.parser_name = "softmax_with_cross_entropy_grad"

    def _apply(self):
        label = self._get_ge_input(self.op.input_arg_names[0])
        loss_grad = self._get_ge_input(self.op.input_arg_names[1])
        softmax = self._get_ge_input(self.op.input_arg_names[2])
        cls_num = self.op.block.var(self.op.input_arg_names[2]).shape[1]

        label_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        loss_grad_shape = self.op.block.var(self.op.input_arg_names[1]).shape
        softmax_shape = self.op.block.var(self.op.input_arg_names[2]).shape

        tensoron = self._create_ge_tensor([1], 5, 1)
        on = core.GEOperatorFactory.create_operator(
2117 2118
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensoron)
2119 2120
        tensoroff = self._create_ge_tensor([1], 5, 0)
        off = core.GEOperatorFactory.create_operator(
2121 2122
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensoroff)
2123 2124 2125
        self._mark_as_input(on)
        self._mark_as_input(off)

2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
        label = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", label)
            .set_attr_int32("dst_type", 3)
        )
        onehot = (
            core.GEOperatorFactory.create_operator(
                "onehot" + self._accumulated_op_id(), "OneHotD"
            )
            .set_input("x", label)
            .set_input("on_value", on)
            .set_input("off_value", off)
            .set_attr_int32("depth", cls_num)
        )
2142
        squeeze = core.GEOperatorFactory.create_operator(
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
            "suqeeze" + self._accumulated_op_id(), "Squeeze"
        ).set_input("x", onehot)
        sub = (
            core.GEOperatorFactory.create_operator(
                "sub" + self._accumulated_op_id(), "Sub"
            )
            .set_input("x1", softmax)
            .set_input("x2", squeeze)
        )
        grad = (
            core.GEOperatorFactory.create_operator(
                "mul" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", loss_grad)
            .set_input("x2", sub)
        )
2159 2160 2161 2162 2163 2164

        return [on, off, label, onehot, grad], [[-1]]


class DotMulGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2165
        super().__init__(graph, var2geop)
2166 2167 2168 2169 2170 2171 2172
        self.parser_name = "elementwise_mul_grad"

    def _apply(self):
        out_grad = self._get_ge_input(self.op.input_arg_names[0])
        out_1 = self._get_ge_input(self.op.input_arg_names[1])
        out_2 = self._get_ge_input(self.op.input_arg_names[2])

2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
        x_grad = (
            core.GEOperatorFactory.create_operator(
                self.parser_name + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", out_grad)
            .set_input("x2", out_2)
        )
        y_grad = (
            core.GEOperatorFactory.create_operator(
                self.parser_name + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", out_1)
            .set_input("x2", out_grad)
        )
2187 2188 2189 2190 2191 2192

        return [x_grad, y_grad], [[0], [1]]


class DotAddGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2193
        super().__init__(graph, var2geop)
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
        self.parser_name = "elementwise_add_grad"

    def _apply(self):
        out_grad = self._get_ge_input(self.op.input_arg_names[0])
        out_1 = self._get_ge_input(self.op.input_arg_names[1])
        out_2 = self._get_ge_input(self.op.input_arg_names[2])
        out_grad_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        out_1_shape = self.op.block.var(self.op.input_arg_names[1]).shape
        out_2_shape = self.op.block.var(self.op.input_arg_names[2]).shape

        x_grad = out_grad
        cur_time_x = len(out_grad_shape) - len(out_1_shape)
        for i in range(cur_time_x):
2207 2208 2209 2210 2211 2212 2213 2214
            x_grad = (
                core.GEOperatorFactory.create_operator(
                    self.parser_name + self._accumulated_op_id(), "ReduceSumD"
                )
                .set_input("x", x_grad)
                .set_attr_vec_int32("axes", [0])
                .set_attr_bool("keep_dims", False)
            )
2215 2216
        for axis, size in enumerate(out_1_shape):
            if size == 1:
2217 2218 2219 2220 2221 2222 2223 2224 2225
                x_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "ReduceSumD",
                    )
                    .set_input("x", x_grad)
                    .set_attr_vec_int32("axes", [axis])
                    .set_attr_bool("keep_dims", True)
                )
2226 2227 2228 2229

        y_grad = out_grad
        cur_time_y = len(out_grad_shape) - len(out_2_shape)
        for i in range(cur_time_y):
2230 2231 2232 2233 2234 2235 2236 2237
            y_grad = (
                core.GEOperatorFactory.create_operator(
                    self.parser_name + self._accumulated_op_id(), "ReduceSumD"
                )
                .set_input("x", y_grad)
                .set_attr_vec_int32("axes", [0])
                .set_attr_bool("keep_dims", False)
            )
2238 2239
        for axis, size in enumerate(out_2_shape):
            if size == 1:
2240 2241 2242 2243 2244 2245 2246 2247 2248
                y_grad = (
                    core.GEOperatorFactory.create_operator(
                        self.parser_name + self._accumulated_op_id(),
                        "ReduceSumD",
                    )
                    .set_input("x", y_grad)
                    .set_attr_vec_int32("axes", [axis])
                    .set_attr_bool("keep_dims", True)
                )
2249 2250 2251 2252 2253 2254

        return [x_grad, y_grad], [[0], [1]]


class DotDivGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2255
        super().__init__(graph, var2geop)
2256 2257 2258 2259 2260 2261 2262 2263
        self.parser_name = "elementwise_div_grad"

    def _apply(self):
        out = self._get_ge_input(self.op.input_arg_names[0])
        out_grad = self._get_ge_input(self.op.input_arg_names[1])
        x = self._get_ge_input(self.op.input_arg_names[2])
        y = self._get_ge_input(self.op.input_arg_names[3])

2264 2265 2266 2267 2268 2269 2270
        y_power = (
            core.GEOperatorFactory.create_operator(
                "power" + self._accumulated_op_id(), "Power"
            )
            .set_input("x", y)
            .set_attr_float("power", -1)
        )
2271 2272

        tensor_zeros = core.GEOperatorFactory.create_operator(
2273 2274 2275 2276 2277 2278 2279 2280 2281
            "zeroslike" + self._accumulated_op_id(), "ZerosLike"
        ).set_input("x", x)
        x_zero = (
            core.GEOperatorFactory.create_operator(
                "equal" + self._accumulated_op_id(), "Equal"
            )
            .set_input("x1", x)
            .set_input("x2", tensor_zeros)
        )
2282
        x_nozero = core.GEOperatorFactory.create_operator(
2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
            "logical_not" + self._accumulated_op_id(), "LogicalNot"
        ).set_input("x", x_zero)
        x_nozero_f = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", x_nozero)
            .set_attr_int32("dst_type", 0)
        )
        x_grad_w = (
            core.GEOperatorFactory.create_operator(
                "mul" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", x_nozero_f)
            .set_input("x2", y_power)
        )
        x_grad = (
            core.GEOperatorFactory.create_operator(
                self.parser_name + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", x_grad_w)
            .set_input("x2", out_grad)
        )

        y_grad_w = (
            core.GEOperatorFactory.create_operator(
                "mul" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", out)
            .set_input("x2", y_power)
        )
        y_grad = (
            core.GEOperatorFactory.create_operator(
                "mul" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", y_grad_w)
            .set_input("x2", out_grad)
        )
2321 2322 2323 2324 2325 2326

        return [x_grad, y_grad], [[0], [1]]


class SoftmaxGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2327
        super().__init__(graph, var2geop)
2328 2329 2330 2331 2332 2333
        self.parser_name = "softmax_grad"

    def _apply(self):
        out = self._get_ge_input(self.op.input_arg_names[0])
        out_grad = self._get_ge_input(self.op.input_arg_names[1])

2334 2335 2336 2337 2338 2339 2340
        x_grad = (
            core.GEOperatorFactory.create_operator(
                self.parser_name + self._accumulated_op_id(), "SoftmaxGrad"
            )
            .set_input("softmax", out)
            .set_input("grad_softmax", out_grad)
        )
2341 2342 2343 2344 2345
        return [x_grad], [[0]]


class ReshapeGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2346
        super().__init__(graph, var2geop)
2347 2348 2349 2350 2351 2352 2353 2354 2355
        self.parser_name = "reshape2_grad"

    def _apply(self):
        out_grad = self._get_ge_input(self.op.input_arg_names[0])
        x_shape = self._get_ge_input(self.op.input_arg_names[1])
        x_shape_list = self.op.block.var(self.op.input_arg_names[1]).shape

        if x_shape_list[0] == 0:
            x_shape_delzero = x_shape_list[1:]
2356 2357 2358
        tensor = self._create_ge_tensor(
            [len(x_shape_delzero)], 2, x_shape_delzero
        )
2359
        const_shape = core.GEOperatorFactory.create_operator(
2360 2361 2362 2363 2364 2365 2366 2367 2368
            "shape" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", tensor)
        x_grad = (
            core.GEOperatorFactory.create_operator(
                "reshape" + self._accumulated_op_id(), "Reshape"
            )
            .set_input("x", out_grad)
            .set_input("shape", const_shape)
        )
2369 2370

        return [x_grad], [[0]]
2371

2372 2373 2374

class GatherGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2375
        super().__init__(graph, var2geop)
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
        self.parser_name = "gather_grad"

    def _apply(self):
        index = self._get_ge_input(self.op.input_arg_names[0])
        out_grad = self._get_ge_input(self.op.input_arg_names[1])
        x = self._get_ge_input(self.op.input_arg_names[2])

        index_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        out_grad_shape = self.op.block.var(self.op.input_arg_names[1]).shape
        x_shape = self.op.block.var(self.op.input_arg_names[2]).shape

        if len(index_shape) == 1:
2388 2389 2390 2391 2392 2393 2394
            index = (
                core.GEOperatorFactory.create_operator(
                    "unsqueeze" + self._accumulated_op_id(), "Unsqueeze"
                )
                .set_input("x", index)
                .set_attr_vec_int32("axes", [1])
            )
2395 2396

        tensor_zeros = core.GEOperatorFactory.create_operator(
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
            "zeroslike" + self._accumulated_op_id(), "ZerosLike"
        ).set_input("x", x)
        x_grad = (
            core.GEOperatorFactory.create_operator(
                "scatter" + self._accumulated_op_id(), "TensorScatterUpdate"
            )
            .set_input("x", tensor_zeros)
            .set_input("indices", index)
            .set_input("updates", out_grad)
        )
2407 2408 2409 2410 2411 2412

        return [tensor_zeros, x_grad], [[-1]]


class TransposeGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2413
        super().__init__(graph, var2geop)
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
        self.parser_name = "transpose2_grad"

    def _apply(self):
        out_grad = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])
        perm = self.op.attr("axis")

        x_shape = self.op.block.var(self.op.input_arg_names[1]).shape[1:]
        out_grad_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        assert list(map(lambda x: out_grad_shape[x], perm)) == list(x_shape)

2425 2426 2427 2428 2429 2430 2431
        x_grad = (
            core.GEOperatorFactory.create_operator(
                "transpose" + self._accumulated_op_id(), "TransposeD"
            )
            .set_input("x", out_grad)
            .set_attr_vec_int32("perm", perm)
        )
2432 2433 2434 2435 2436 2437

        return [x_grad], [[0]]


class LayerNormGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2438
        super().__init__(graph, var2geop)
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
        self.parser_name = "layer_norm_grad"

    def _apply(self):
        bias = self._get_ge_input(self.op.input_arg_names[0])
        mean = self._get_ge_input(self.op.input_arg_names[1])
        scale = self._get_ge_input(self.op.input_arg_names[2])
        variance = self._get_ge_input(self.op.input_arg_names[3])
        x = self._get_ge_input(self.op.input_arg_names[4])
        out_grad = self._get_ge_input(self.op.input_arg_names[5])
        x_dtype = self.op.block.var(self.op.input_arg_names[4]).dtype

2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
        x_grad = (
            core.GEOperatorFactory.create_operator(
                self.parser_name + self._accumulated_op_id(), "LayerNormGrad"
            )
            .set_input("dy", out_grad)
            .set_input("x", x)
            .set_input("variance", variance)
            .set_input("mean", mean)
            .set_input("gamma", scale)
        )

        cast_dtype = (
            0
            if self.ascend_helper.dtype2paddle_inv_map[str(x_dtype)] == 0
            else 1
        )
        out_x_grad = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", x_grad, 0)
            .set_attr_int32("dst_type", cast_dtype)
        )
        out_scale_grad = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", x_grad, 1)
            .set_attr_int32("dst_type", cast_dtype)
        )
        out_bias_grad = (
            core.GEOperatorFactory.create_operator(
                "cast" + self._accumulated_op_id(), "Cast"
            )
            .set_input("x", x_grad, 2)
            .set_attr_int32("dst_type", cast_dtype)
        )
2487 2488 2489 2490 2491 2492

        return [out_x_grad, out_scale_grad, out_bias_grad], [[2], [1], [0]]


class TanhGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2493
        super().__init__(graph, var2geop)
2494 2495 2496 2497 2498
        self.parser_name = 'tanh_grad'

    def _apply(self):
        y = self._get_ge_input(self.op.input_arg_names[0])
        out_grad = self._get_ge_input(self.op.input_arg_names[1])
2499 2500 2501 2502 2503 2504 2505
        tanh_grad = (
            core.GEOperatorFactory.create_operator(
                "tanh_grad" + self._accumulated_op_id(), "TanhGrad"
            )
            .set_input("y", y)
            .set_input("dy", out_grad)
        )
2506 2507 2508 2509 2510 2511

        return [tanh_grad], [[0]]


class LogGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2512
        super().__init__(graph, var2geop)
2513 2514 2515 2516 2517
        self.parser_name = 'log_grad'

    def _apply(self):
        grad = self._get_ge_input(self.op.input_arg_names[0])
        input = self._get_ge_input(self.op.input_arg_names[1])
2518 2519 2520 2521 2522 2523 2524
        log_grad = (
            core.GEOperatorFactory.create_operator(
                "log_grad" + self._accumulated_op_id(), "DivNoNan"
            )
            .set_input("x1", grad)
            .set_input("x2", input)
        )
2525 2526 2527 2528 2529
        return [log_grad], [[0]]


class SqrtGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2530
        super().__init__(graph, var2geop)
2531 2532 2533 2534 2535
        self.parser_name = "sqrt_grad"

    def _apply(self):
        y = self._get_ge_input(self.op.input_arg_names[0])
        out_grad = self._get_ge_input(self.op.input_arg_names[1])
2536 2537 2538 2539 2540 2541 2542
        sqrt_grad = (
            core.GEOperatorFactory.create_operator(
                "sqrt_grad" + self._accumulated_op_id(), "SqrtGrad"
            )
            .set_input("y", y)
            .set_input("dy", out_grad)
        )
2543 2544 2545 2546 2547
        return [sqrt_grad]


class PowGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2548
        super().__init__(graph, var2geop)
2549 2550 2551 2552 2553 2554 2555 2556 2557
        self.parser_name = "pow_grad"

    def _apply(self):
        grad = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])
        factor = self.op.attr("factor")

        shape_tensor = self._create_shape_tensor()
        shape_tensor = core.GEOperatorFactory.create_operator(
2558 2559
            "shape" + self._accumulated_op_id(), "Shape"
        ).set_input("x", x)
2560 2561
        factor_scale = self._create_ge_tensor([1], 5, factor)
        factor_scale = core.GEOperatorFactory.create_operator(
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", factor_scale)
        factor_tensor = (
            core.GEOperatorFactory.create_operator(
                "broadcast_to_d" + self._accumulated_op_id(), "BroadcastTo"
            )
            .set_input("x", factor_scale)
            .set_input("shape", shape_tensor)
        )

        x_power = (
            core.GEOperatorFactory.create_operator(
                "x_power" + self._accumulated_op_id(), "Power"
            )
            .set_input("x", x)
            .set_attr_float("power", factor - 1)
        )
        x_power_mul_factor = (
            core.GEOperatorFactory.create_operator(
                "x_power_mul_factor" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", x)
            .set_input("x2", factor_tensor)
        )
        x_power_mul_factor_grad = (
            core.GEOperatorFactory.create_operator(
                "x_power_mul_factor_grad" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", x_power_mul_factor)
            .set_input("x2", grad)
        )
2593 2594 2595 2596 2597 2598

        return [x_power_mul_factor_grad], [[0]]


class GeluGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2599
        super().__init__(graph, var2geop)
2600 2601 2602 2603 2604 2605 2606
        self.parser_name = "gelu_grad"

    def _apply(self):
        grad = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])

        y = core.GEOperatorFactory.create_operator(
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
            "gelu" + self._accumulated_op_id(), "Gelu"
        ).set_input("x", x)
        gelu_grad = (
            core.GEOperatorFactory.create_operator(
                "gelu_grad" + self._accumulated_op_id(), "GeluGrad"
            )
            .set_input("x", x)
            .set_input("dy", grad)
            .set_input("y", y)
        )
2617 2618 2619 2620 2621 2622

        return [gelu_grad], [[0]]


class MeanGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2623
        super().__init__(graph, var2geop)
2624 2625 2626 2627 2628 2629 2630
        self.parser_name = "mean_grad"

    def _apply(self):
        grad = self._get_ge_input(self.op.input_arg_names[0])
        x = self._get_ge_input(self.op.input_arg_names[1])

        ones_tensor = core.GEOperatorFactory.create_operator(
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
            "one_tensor" + self._accumulated_op_id(), "OnesLike"
        ).set_input("x", x)
        sum = (
            core.GEOperatorFactory.create_operator(
                "mean" + self._accumulated_op_id(), "ReduceSumD"
            )
            .set_input("x", ones_tensor)
            .set_attr_bool("keep_dims", False)
            .set_attr_vec_int32("axes", [])
        )
        mean = (
            core.GEOperatorFactory.create_operator(
                "x_power" + self._accumulated_op_id(), "Power"
            )
            .set_input("x", sum)
            .set_attr_float("power", -1)
        )

        mean_grad = (
            core.GEOperatorFactory.create_operator(
                "mean_grad" + self._accumulated_op_id(), "Mul"
            )
            .set_input("x1", mean)
            .set_input("x2", grad)
        )
2656 2657 2658 2659 2660 2661

        return [mean_grad], [[0]]


class SliceGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2662
        super().__init__(graph, var2geop)
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
        self.parser_name = "slice_grad"

    def _apply(self):
        x = self._get_ge_input(self.op.input_arg_names[0])
        grad = self._get_ge_input(self.op.input_arg_names[1])
        axes = self.op.attr("axes")
        starts = self.op.attr("starts")
        ends = self.op.attr("ends")

        x_shape = self.op.block.var(self.op.input_arg_names[0]).shape
        grad_shape = self.op.block.var(self.op.input_arg_names[1]).shape

        len_shape = len(x_shape)
        axes_cor = list(range(len_shape))
        starts_cor, ends_cor = [], []
        cnt = 0
        for i in range(len_shape):
            starts_cor.append(starts[cnt] if i in axes else 0)
            if i in axes and ends[cnt] <= x_shape[i]:
                ends_cor.append(x_shape[i] - ends[cnt])
            else:
                ends_cor.append(0)
            if i in axes:
                cnt += 1

        starts_cor[0] = 0
        ends_cor[0] = 0
        paddings = [[s, e] for (s, e) in zip(starts_cor, ends_cor)]
2691 2692 2693 2694 2695 2696 2697
        slice_value = (
            core.GEOperatorFactory.create_operator(
                "slice_grad" + self._accumulated_op_id(), "PadD"
            )
            .set_input("x", grad)
            .set_attr_vec_vec_int64("paddings", paddings)
        )
2698 2699 2700 2701 2702 2703

        return [slice_value], [[0]]


class LookUpTableGradParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2704
        super().__init__(graph, var2geop)
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
        self.parser_name = "lookup_table_grad"

    def _apply(self):
        ids = self._get_ge_input(self.op.input_arg_names[0])
        grad = self._get_ge_input(self.op.input_arg_names[1])
        embedding = self._get_ge_input(self.op.input_arg_names[2])

        shape_ids = self.op.block.var(self.op.input_arg_names[0]).shape
        shape_grad = self.op.block.var(self.op.input_arg_names[1]).shape
        shape_embedding = self.op.block.var(self.op.input_arg_names[2]).shape

2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
        ids_flatten = (
            core.GEOperatorFactory.create_operator(
                "flatten" + self._accumulated_op_id(), "FlattenV2"
            )
            .set_input("x", ids)
            .set_attr_int32("axis", 0)
            .set_attr_int32("end_axis", 1)
        )
        grad_flatten = (
            core.GEOperatorFactory.create_operator(
                "flatten" + self._accumulated_op_id(), "FlattenV2"
            )
            .set_input("x", grad)
            .set_attr_int32("axis", 0)
            .set_attr_int32("end_axis", 1)
        )
2732 2733

        tensor_zeros = core.GEOperatorFactory.create_operator(
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743
            "zeroslike" + self._accumulated_op_id(), "ZerosLike"
        ).set_input("x", embedding)
        embedding_grad = (
            core.GEOperatorFactory.create_operator(
                "scatteradd" + self._accumulated_op_id(), "TensorScatterAdd"
            )
            .set_input("x", tensor_zeros)
            .set_input("indices", ids_flatten)
            .set_input("updates", grad_flatten)
        )
2744 2745 2746 2747 2748 2749

        return [embedding_grad], [[0]]


class SGDParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2750
        super().__init__(graph, var2geop)
2751 2752 2753 2754 2755 2756
        self.parser_name = "sgd"

    def _apply(self):
        grad = self._get_ge_input(self.op.input_arg_names[0])
        lr = self._get_ge_input(self.op.input_arg_names[1])
        param = self._get_ge_input(self.op.input_arg_names[2])
2757 2758 2759 2760 2761 2762 2763 2764
        sgd = (
            core.GEOperatorFactory.create_operator(
                "momentum" + self._accumulated_op_id(), "ApplyGradientDescent"
            )
            .set_input("var", param)
            .set_input("alpha", lr)
            .set_input("delta", grad)
        )
2765 2766 2767 2768 2769
        return [sgd], [[0]]


class AdamParser(AscendParserBase):
    def __init__(self, graph, var2geop):
2770
        super().__init__(graph, var2geop)
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
        self.parser_name = "adam"

    def _apply(self):
        beta1_power = self._get_ge_input(self.op.input_arg_names[0])
        beta2_power = self._get_ge_input(self.op.input_arg_names[1])
        grad = self._get_ge_input(self.op.input_arg_names[2])
        lr = self._get_ge_input(self.op.input_arg_names[3])
        moment1 = self._get_ge_input(self.op.input_arg_names[4])
        moment2 = self._get_ge_input(self.op.input_arg_names[5])
        param = self._get_ge_input(self.op.input_arg_names[6])
        beta1 = self.op.attr('beta1')
        beta2 = self.op.attr('beta2')
        epsilon = self.op.attr('epsilon')

        beta1 = core.GEOperatorFactory.create_operator(
2786 2787
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", self._create_ge_tensor([1], 5, beta1))
2788
        beta2 = core.GEOperatorFactory.create_operator(
2789 2790
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", self._create_ge_tensor([1], 5, beta2))
2791
        epsilon = core.GEOperatorFactory.create_operator(
2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809
            "const" + self._accumulated_op_id(), "Const"
        ).set_attr_tensor("value", self._create_ge_tensor([1], 5, epsilon))

        adam = (
            core.GEOperatorFactory.create_operator(
                "adam" + self._accumulated_op_id(), "ApplyAdam"
            )
            .set_input("var", param)
            .set_input("m", moment1)
            .set_input("v", moment2)
            .set_input("beta1_power", beta1_power)
            .set_input("beta2_power", beta2_power)
            .set_input("lr", lr)
            .set_input("beta1", beta1)
            .set_input("beta2", beta2)
            .set_input("epsilon", epsilon)
            .set_input("grad", grad)
        )
2810 2811

        return [adam], [[0]]