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

C
Charles-hit 已提交
15
import os
16 17 18 19 20 21 22
import struct
from collections import defaultdict

import config
import numpy as np

import paddle
23
from paddle.fluid import core
24 25 26 27 28 29
from paddle.fluid.framework import (
    OpProtoHolder,
    _dygraph_tracer,
    canonicalize_attrs,
    in_dygraph_mode,
)
30
from paddle.incubate.autograd import primapi
31 32 33 34 35 36
from paddle.jit.dy2static.utils import parse_arg_and_kwargs


def flatten(nest_list):
    out = []
    for i in nest_list:
C
Charles-hit 已提交
37
        if isinstance(i, (list, tuple)):
38 39 40 41 42 43 44 45 46 47 48
            tmp_list = flatten(i)
            for j in tmp_list:
                out.append(j)
        else:
            out.append(i)
    return out


def _as_list(x):
    if x is None:
        return []
C
Charles-hit 已提交
49
    return list(x) if isinstance(x, (list, tuple)) else [x]
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68


def convert_uint16_to_float(in_list):
    in_list = np.asarray(in_list)
    out = np.vectorize(
        lambda x: struct.unpack(
            '<f', struct.pack('<I', np.uint32(x) << np.uint32(16))
        )[0],
        otypes=[np.float32],
    )(in_list.flat)
    return np.reshape(out, in_list.shape)


# TODO(wanghao107): OpTestUtils will be moved to op_test.py
class OpTestUtils:
    @classmethod
    def _get_kernel_signature(
        cls, op_type, eager_tensor_inputs, eager_tensor_outputs, attrs_outputs
    ):
69 70 71 72 73
        try:
            op_proto = OpProtoHolder.instance().get_op_proto(op_type)
            canonicalized_attrs = canonicalize_attrs(attrs_outputs, op_proto)
        except ValueError:
            canonicalized_attrs = attrs_outputs
74 75 76 77 78
        try:
            kernel_sig = _dygraph_tracer()._get_kernel_signature(
                op_type,
                eager_tensor_inputs,
                eager_tensor_outputs,
79
                canonicalized_attrs,
80 81 82 83 84 85 86 87 88 89 90 91
            )
        except RuntimeError as re:
            """we think the kernel_sig is missing."""
            kernel_sig = None
            print(
                "[Warning: op_test.py] Kernel Signature is not found for %s, fall back to intermediate state."
                % op_type
            )
        return kernel_sig

    @classmethod
    def prepare_python_api_arguments(
92 93 94 95 96
        cls,
        api,
        op_proto_ins,
        op_proto_attrs,
        kernel_sig,
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
    ):
        """map from `op proto inputs and attrs` to `api input list and api attrs dict`

        NOTE: the op_proto_attrs and op_proto_ins is a default dict. default value is []
        """

        class Empty:
            pass

        def is_empty(a):
            return isinstance(a, Empty)

        def get_default(idx, defaults):
            assert not isinstance(defaults[idx], Empty), (
                "%d-th params of python api don't have default value." % idx
            )
            return defaults[idx]

        def to_defaults_list(params, defaults):
            return [defaults[p] for p in params if p in defaults]

118
        def parse_attri_value(name, op_inputs, op_proto_attrs):
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 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 161 162 163 164 165 166 167 168 169 170 171 172
            """parse true value from inputs and attrs, if there is no name passed by OpTest, return Empty
            1. if the name in op_attrs, use the op_attrs[name]
            2. if the name in op_inputs, convert the op_inputs to [type of default value]
            3. if the name not in op_attrs ans op_inputs, return Empty. (this will use the default value from python api)
            """
            if name in op_proto_attrs:
                return op_proto_attrs[name]
            elif name in op_inputs:
                if len(op_inputs[name]) == 1:
                    # why don't use numpy().item() : if the Tensor is float64, we will change it to python.float32, where we loss accuracy: [allclose_op]
                    # why we reconstruct a tensor: because we want the tensor in cpu.
                    if in_dygraph_mode():
                        return paddle.to_tensor(
                            op_inputs[name][0].numpy(), place='cpu'
                        )
                    else:
                        return op_inputs[name][0]
                else:
                    # if this is a list (test_unsqueeze2_op): we just pass it into the python api.
                    return op_inputs[name]
            else:
                return Empty()

        # NOTE(xiongkun): the logic of constructing parameters:
        # for example:
        #    python api: cumprod(x, dim, dtype=None, name=None)
        #    kernel sig: [["x"], ["dim"], ["out"]]"
        #
        # we will construct a lot of list with the same length : len == len(api_params), here is 4
        #    api_params = ["x", "dim", "dtype", "name"]
        #    api_defaults = [Empty, Empty, None, None]; empty means no defaults.
        #    inputs_and_attrs = ["x", "dim"] , the length may shorter or longer than api_params
        #    input_arguments = [RealValue in self.inputs and self.attrs]
        # then ,we will loop for the api_params, construct a result list:
        #    if the name in ['name', 'dtype', 'out', 'output'], we will use the default value
        #    else, we will consume a input_arguments. (because the name is not corresponding, so we only use the order)

        api_params, api_defaults = parse_arg_and_kwargs(api)
        api_defaults = to_defaults_list(api_params, api_defaults)
        api_defaults = [
            Empty() for i in range(len(api_params) - len(api_defaults))
        ] + api_defaults
        assert len(api_defaults) == len(
            api_params
        ), "Error happens. contack xiongkun03 to solve."
        inputs_sig, attrs_sig, outputs_sig = kernel_sig
        inputs_and_attrs = inputs_sig + attrs_sig
        input_arguments = [
            op_proto_ins.get(name, Empty()) for name in inputs_sig
        ] + [
            parse_attri_value(name, op_proto_ins, op_proto_attrs)
            for name in attrs_sig
        ]
        results = []
173 174 175 176
        # hack support variable length parameter(such as paddle.meshgrid(*args,**kwargs)
        if api_params == []:
            results.append(input_arguments)
            return results
177
        api_ignore_param_list = {'name', 'dtype', 'out', 'output'}
178 179 180 181
        idx_of_op_proto_arguments = 0
        for idx, arg_name in enumerate(api_params):
            if arg_name in api_ignore_param_list:
                results.append(get_default(idx, api_defaults))
W
wanghuancoder 已提交
182 183
                if idx_of_op_proto_arguments < len(input_arguments):
                    idx_of_op_proto_arguments += 1
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
            else:
                if idx_of_op_proto_arguments < len(input_arguments):
                    tmp = input_arguments[idx_of_op_proto_arguments]
                    idx_of_op_proto_arguments += 1
                else:
                    tmp = Empty()  # use the default value

                if isinstance(tmp, Empty):
                    results.append(get_default(idx, api_defaults))
                else:
                    results.append(tmp)
        assert len(results) == len(api_params)
        return results

    @classmethod
    def assumption_assert_and_transform(cls, args, inp_num):
        """
        transform inputs by the following rules:
202
            Note: it may not be possible to distinguish list with one Tensor,you should use wrapper to distinguish.
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
            1. [Tensor] -> Tensor
            2. [Tensor, Tensor, ...] -> list of Tensors
            3. None -> None
            4. Others: raise Error

        only support "X" is list of Tensor, currently don't support other structure like dict.
        """
        inp_args = [
            [inp] if inp is None else inp for inp in args[:inp_num]
        ]  # convert None -> [None]
        for inp in inp_args:
            assert isinstance(
                inp, list
            ), "currently only support `X` is [Tensor], don't support other structure."
        args = [inp[0] if len(inp) == 1 else inp for inp in inp_args] + args[
            inp_num:
        ]
        return args

    @classmethod
    def is_bfloat16_type(cls, np_type):
        if np_type == np.dtype('uint16'):
            return True
        return False


def apply_to_static(net, use_cinn):
    build_strategy = paddle.static.BuildStrategy()
    build_strategy.build_cinn_pass = use_cinn
    return paddle.jit.to_static(net, build_strategy=build_strategy)


class PrimNet(paddle.nn.Layer):
236
    def __init__(self, public_python_api):
237
        super().__init__()
238
        self.public_python_api = public_python_api
239 240

    def forward(self, args):
241
        out = self.public_python_api(*args)
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
        return out


class PrimForwardChecker:
    def __init__(self, op_test, place):
        self.checker_name = "PrimForwardChecker"
        self.place = place
        self.op_test = op_test
        self.save_eager_or_static_status()
        self.init()
        self.init_checker()

    def init(self):
        pass

    def save_eager_or_static_status(self):
        self.eager_mode = True if in_dygraph_mode() else False

    def recover_eager_or_static_status(self):
        if self.eager_mode:
            paddle.disable_static()
        else:
            paddle.enable_static()

    def init_checker(self):
        assert hasattr(
            self.op_test, 'prim_op_type'
269
        ), "if you want to test comp op, please set prim_op_type with \'prim\' or \'comp\' in setUp function."
270 271 272 273 274 275 276 277 278
        assert self.op_test.prim_op_type in [
            "comp",
            "prim",
        ], "prim_op_type must be comp or prim in setUp function."
        assert hasattr(
            self.op_test, 'dtype'
        ), "Please set dtype in setUp function."
        self.op_type = self.op_test.op_type
        self.prim_op_type = self.op_test.prim_op_type
279 280 281 282
        assert hasattr(
            self.op_test, 'public_python_api'
        ), "If you want to check prim, please set public_python_api in setUp function."
        self.public_python_api = self.op_test.public_python_api
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
        self.dtype = np.dtype(self.op_test.dtype)
        self.inputs = self.op_test.inputs
        self.attrs = (
            self.op_test.attrs if hasattr(self.op_test, 'attrs') else {}
        )
        self.outputs = self.op_test.outputs
        self.init_checker_threshold()
        self.enable_fw_comp = (
            self.op_test.enable_fw_comp
            if hasattr(self.op_test, 'enable_fw_comp')
            else True
        )
        self.enable_rev_comp = (
            self.op_test.enable_rev_comp
            if hasattr(self.op_test, 'enable_rev_comp')
            else True
        )
        self.enable_cinn = (
            self.op_test.enable_cinn
            if hasattr(self.op_test, 'enable_cinn')
            else True
        )
C
Charles-hit 已提交
305 306
        if os.getenv('FLAGS_enable_cinn'):
            self.enable_cinn = True
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        self.enable_check_eager_comp = (
            self.op_test.enable_check_eager_comp
            if hasattr(self.op_test, 'enable_check_eager_comp')
            else True
        )
        self.enable_check_static_comp = (
            self.op_test.enable_check_static_comp
            if hasattr(self.op_test, 'enable_check_static_comp')
            else True
        )
        self.enable_check_jit_comp = (
            self.op_test.enable_check_jit_comp
            if hasattr(self.op_test, 'enable_check_jit_comp')
            else True
        )
        self.enable_check_jit_comp_with_cinn = (
            self.op_test.enable_check_jit_comp_with_cinn
            if hasattr(self.op_test, 'enable_check_jit_comp_with_cinn')
            else True
        )
        self.kernel_sig = self.get_kernel_sig()

    def init_checker_threshold(self):
        if hasattr(self.op_test, 'jit_comp_rtol'):
            self.jit_comp_rtol = self.op_test.jit_comp_rtol
        else:
            self.jit_comp_rtol = (
                config.TOLERANCE[self.dtype]['jit_comp']['rtol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'jit_comp_atol'):
            self.jit_comp_atol = self.op_test.jit_comp_atol
        else:
            self.jit_comp_atol = (
                config.TOLERANCE[self.dtype]['jit_comp']['atol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'fw_comp_rtol'):
            self.fw_comp_rtol = self.op_test.fw_comp_rtol
        else:
            self.fw_comp_rtol = (
                config.TOLERANCE[self.dtype]['fw_comp']['rtol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'fw_comp_atol'):
            self.fw_comp_atol = self.op_test.fw_comp_atol
        else:
            self.fw_comp_atol = (
                config.TOLERANCE[self.dtype]['fw_comp']['atol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'rev_comp_rtol'):
            self.rev_comp_rtol = self.op_test.rev_comp_rtol
        else:
            self.rev_comp_rtol = (
                config.TOLERANCE[self.dtype]['rev_comp']['rtol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'rev_comp_atol'):
            self.rev_comp_atol = self.op_test.rev_comp_atol
        else:
            self.rev_comp_atol = (
                config.TOLERANCE[self.dtype]['rev_comp']['atol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'cinn_rtol'):
            self.cinn_rtol = self.op_test.cinn_rtol
        else:
            self.cinn_rtol = (
                config.TOLERANCE[self.dtype]['cinn']['rtol']
                if self.dtype in config.TOLERANCE
                else 0
            )

        if hasattr(self.op_test, 'cinn_atol'):
            self.cinn_atol = self.op_test.cinn_atol
        else:
            self.cinn_atol = (
                config.TOLERANCE[self.dtype]['cinn']['atol']
                if self.dtype in config.TOLERANCE
                else 0
            )

    def check(self):
403
        if (
404
            type(self.place) is paddle.fluid.libpaddle.CUDAPlace
405 406 407
            and not paddle.is_compiled_with_cuda()
        ):
            return
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
        self.eager_desire = self.get_eager_desire()
        if self.enable_check_static_comp:
            self.check_static_comp()
        if self.enable_check_jit_comp:
            self.check_jit_comp()
        if self.enable_check_jit_comp_with_cinn:
            self.check_jit_comp_with_cinn()

        self.recover_eager_or_static_status()

    def get_kernel_sig(self):
        paddle.disable_static()
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        (
            eager_tensor_inputs,
            attrs_outputs,
            _,
C
Charles-hit 已提交
428 429
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=True)
        eager_tensor_outputs = self.get_eager_empty_output(stop_gradient=True)
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        kernel_sig = OpTestUtils._get_kernel_signature(
            self.op_type,
            eager_tensor_inputs,
            eager_tensor_outputs,
            attrs_outputs,
        )
        return kernel_sig

    def get_eager_desire(self):
        paddle.disable_static()
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        (
            eager_tensor_inputs,
            attrs_outputs,
            _,
C
Charles-hit 已提交
448
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=True)
449
        args = OpTestUtils.prepare_python_api_arguments(
450
            self.public_python_api,
451 452 453
            eager_tensor_inputs,
            attrs_outputs,
            self.kernel_sig,
454 455 456 457 458
        )
        inputs_sig, _, _ = self.kernel_sig
        args = OpTestUtils.assumption_assert_and_transform(
            args, len(inputs_sig)
        )
459
        ret = flatten(_as_list(self.public_python_api(*args)))
460
        ret = paddle.utils.map_structure(lambda x: x.numpy(), ret)
461
        if OpTestUtils.is_bfloat16_type(self.dtype):
462 463 464
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
465 466
        return ret

C
Charles-hit 已提交
467
    def get_eager_input_attr_and_inputdict(self, stop_gradient):
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        attrs_outputs = {}
        for attrs_name in self.attrs:
            if self.attrs[attrs_name] is not None:
                attrs_outputs[attrs_name] = self.attrs[attrs_name]
        input_dict = {}
        eager_inputs = defaultdict(list)
        for name, item in self.inputs.items():
            if isinstance(item, list):
                for tup in item:
                    dtype = (
                        "bfloat16"
                        if OpTestUtils.is_bfloat16_type(tup[1].dtype)
                        else tup[1].dtype
                    )
                    x = paddle.to_tensor(
                        data=tup[1],
                        place=self.place,
C
Charles-hit 已提交
485
                        stop_gradient=stop_gradient,
486 487 488 489 490 491 492 493 494 495 496 497 498
                        dtype=dtype,
                    )
                    eager_inputs[name].append(x)
                    input_dict.update({str(tup[0]): x})
            else:
                dtype = (
                    "bfloat16"
                    if OpTestUtils.is_bfloat16_type(item.dtype)
                    else item.dtype
                )
                x = paddle.to_tensor(
                    data=item,
                    place=self.place,
C
Charles-hit 已提交
499
                    stop_gradient=stop_gradient,
500 501 502 503 504 505
                    dtype=dtype,
                )
                eager_inputs[name].append(x)
                input_dict.update({name: x})
        return eager_inputs, attrs_outputs, input_dict

C
Charles-hit 已提交
506
    def get_eager_empty_output(self, stop_gradient):
507 508 509 510 511 512 513 514 515 516 517 518
        eager_outputs = defaultdict(list)
        for name, item in self.outputs.items():
            if isinstance(item, list):
                for tup in item:
                    dtype = (
                        "bfloat16"
                        if OpTestUtils.is_bfloat16_type(tup[1].dtype)
                        else tup[1].dtype
                    )
                    x = paddle.to_tensor(
                        data=[],
                        place=self.place,
C
Charles-hit 已提交
519
                        stop_gradient=stop_gradient,
520 521 522 523 524 525 526 527 528 529
                        dtype=dtype,
                    )
                    eager_outputs[name].append(x)
            else:
                dtype = (
                    "bfloat16"
                    if OpTestUtils.is_bfloat16_type(item.dtype)
                    else item.dtype
                )
                x = paddle.to_tensor(
C
Charles-hit 已提交
530 531 532 533
                    data=[],
                    place=self.place,
                    stop_gradient=stop_gradient,
                    dtype=dtype,
534 535 536 537
                )
                eager_outputs[name].append(x)
        return eager_outputs

C
Charles-hit 已提交
538
    def get_static_input_attr_inputdict_and_feed(self, stop_gradient):
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
        attrs_outputs = {}
        for attrs_name in self.attrs:
            if self.attrs[attrs_name] is not None:
                attrs_outputs[attrs_name] = self.attrs[attrs_name]
        input_dict = {}
        static_inputs = defaultdict(list)
        feed = {}
        for name, item in self.inputs.items():
            if isinstance(item, list):
                for tup in item:
                    dtype = (
                        "bfloat16"
                        if OpTestUtils.is_bfloat16_type(tup[1].dtype)
                        else tup[1].dtype
                    )
                    x = paddle.static.data(
                        name=str(tup[0]), shape=tup[1].shape, dtype=dtype
                    )
C
Charles-hit 已提交
557
                    x.stop_gradient = stop_gradient
558 559 560 561 562 563 564 565 566 567
                    static_inputs[name].append(x)
                    feed.update({str(tup[0]): tup[1]})
                    input_dict.update({str(tup[0]): x})
            else:
                dtype = (
                    "bfloat16"
                    if OpTestUtils.is_bfloat16_type(item.dtype)
                    else item.dtype
                )
                x = paddle.static.data(name=name, shape=item.shape, dtype=dtype)
C
Charles-hit 已提交
568
                x.stop_gradient = stop_gradient
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
                static_inputs[name].append(x)
                feed.update({name: item})
                input_dict.update({name: x})
        return static_inputs, attrs_outputs, input_dict, feed

    def check_eager_comp(self):
        pass

    def check_static_comp(self):
        # forward comp only for comp op
        if self.prim_op_type == "prim":
            return
        paddle.enable_static()
        core._set_prim_forward_enabled(self.enable_fw_comp)
        startup_program, main_program = (
            paddle.static.Program(),
            paddle.static.Program(),
        )
        with paddle.static.program_guard(main_program, startup_program):
            (
                static_inputs,
                attrs,
                input_dict,
                feed,
C
Charles-hit 已提交
593 594 595
            ) = self.get_static_input_attr_inputdict_and_feed(
                stop_gradient=True
            )
596
            args = OpTestUtils.prepare_python_api_arguments(
597
                self.public_python_api,
598 599 600
                static_inputs,
                attrs,
                self.kernel_sig,
601 602 603 604 605
            )
            inputs_sig, _, _ = self.kernel_sig
            args = OpTestUtils.assumption_assert_and_transform(
                args, len(inputs_sig)
            )
606
            ret = flatten(_as_list(self.public_python_api(*args)))
607
            primapi.to_prim(main_program.blocks)
C
Charles-hit 已提交
608 609 610 611 612
        # ensure the operator not in program if check_prim is True
        forward_ops = [op.type for op in main_program.blocks[0].ops]
        assert self.op_type not in forward_ops, (
            "%s shouldn't appear in program when check_prim is True"
        ) % (self.op_type)
613 614 615 616
        exe = paddle.static.Executor(self.place)
        exe.run(startup_program)
        ret = exe.run(main_program, feed=feed, fetch_list=ret)
        if OpTestUtils.is_bfloat16_type(self.dtype):
617 618 619
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
620 621 622 623 624 625 626 627 628 629 630 631 632 633
        # check static forward
        if len(ret) != len(self.eager_desire):
            msg = (
                "The static comp forward api out tensor nums is different with eager forward api out tensor nums on %s."
                'when enable_fw_comp is %s, static comp forward api out tensor nums = %s, eager forward api out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_fw_comp,
                    len(ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(ret)):
634
            np.testing.assert_allclose(
635 636 637 638
                ret[i],
                self.eager_desire[i],
                rtol=self.fw_comp_rtol,
                atol=self.fw_comp_atol,
639
                err_msg=(
640 641
                    'Check static comp forward api out failed. Mismatch between static comp '
                    'and eager on %s, when enable_fw_comp is %s,the forward api out tensor\'s index is : %d \n'
642
                    'static comp forward api out tensor:\n%s\n eager forward api out tensor:\n%s\n'
643 644 645 646 647 648 649
                    % (
                        str(self.place),
                        self.enable_fw_comp,
                        i,
                        ret[i],
                        self.eager_desire[i],
                    )
650 651
                ),
            )
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        paddle.disable_static()
        core._set_prim_forward_enabled(False)

    def check_jit_comp(self):
        if self.prim_op_type == "prim":
            return
        paddle.disable_static()
        if type(self.place) == paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) == paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        atol = self.fw_comp_atol if self.enable_fw_comp else self.jit_comp_atol
        rtol = self.fw_comp_rtol if self.enable_fw_comp else self.jit_comp_rtol
        core._set_prim_forward_enabled(self.enable_fw_comp)
        (
            eager_tensor_inputs,
            attrs_outputs,
            _,
C
Charles-hit 已提交
670
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=True)
671
        args = OpTestUtils.prepare_python_api_arguments(
672
            self.public_python_api,
673 674 675
            eager_tensor_inputs,
            attrs_outputs,
            self.kernel_sig,
676 677 678 679 680
        )
        inputs_sig, _, _ = self.kernel_sig
        args = OpTestUtils.assumption_assert_and_transform(
            args, len(inputs_sig)
        )
681
        net = PrimNet(self.public_python_api)
682
        net = apply_to_static(net, False)
C
Charles-hit 已提交
683 684 685 686 687 688 689 690 691 692
        # ensure the operator not in program if check_prim is True
        forward_ops = [
            op.type
            for op in net.forward.get_concrete_program(args)[1]
            .forward_program.block(0)
            .ops
        ]
        assert self.op_type not in forward_ops, (
            "%s shouldn't appear in program when check_prim is True"
        ) % (self.op_type)
693
        ret = flatten(_as_list(net(args)))
694
        ret = paddle.utils.map_structure(lambda x: x.numpy(), ret)
695
        if OpTestUtils.is_bfloat16_type(self.dtype):
696 697 698
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
699 700 701 702 703 704 705 706 707 708 709 710 711 712
        # check jit comp forward
        if len(ret) != len(self.eager_desire):
            msg = (
                "The jit comp forward api out tensor nums is different with eager forward api out tensor nums on %s."
                'when enable_fw_comp is %s, jit comp forward api out tensor nums = %s, eager forward api out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_fw_comp,
                    len(ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(ret)):
713 714 715 716 717 718
            np.testing.assert_allclose(
                ret[i],
                self.eager_desire[i],
                rtol=rtol,
                atol=atol,
                err_msg=(
719 720
                    'Check jit comp forward api out failed. Mismatch between jit comp '
                    'and eager on %s, when enable_fw_comp is %s,the forward api out tensor\'s index is : %d \n'
721
                    'jit comp forward api out tensor:\n%s\n eager forward api out tensor:\n%s\n'
722 723 724 725 726 727 728
                    % (
                        str(self.place),
                        self.enable_fw_comp,
                        i,
                        ret[i],
                        self.eager_desire[i],
                    )
729 730
                ),
            )
731 732 733 734 735 736
        core._set_prim_forward_enabled(False)
        net.forward.program_cache.clear()

    def check_jit_comp_with_cinn(self):
        if self.prim_op_type == "prim":
            return
C
co63oc 已提交
737
        # cinn doesn't support cpu place
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
        if (
            type(self.place) == paddle.fluid.libpaddle.CPUPlace
            and self.enable_cinn
            and core.is_compiled_with_cinn()
        ):
            return
        paddle.disable_static()
        atol = (
            self.cinn_atol
            if self.enable_cinn and core.is_compiled_with_cinn()
            else self.fw_comp_atol
        )
        rtol = (
            self.cinn_rtol
            if self.enable_cinn and core.is_compiled_with_cinn()
            else self.fw_comp_rtol
        )
        core._set_prim_forward_enabled(self.enable_fw_comp)
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        (
            eager_tensor_inputs,
            attrs_outputs,
            _,
C
Charles-hit 已提交
764
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=True)
765
        args = OpTestUtils.prepare_python_api_arguments(
766
            self.public_python_api,
767 768 769
            eager_tensor_inputs,
            attrs_outputs,
            self.kernel_sig,
770 771 772 773 774
        )
        inputs_sig, _, _ = self.kernel_sig
        args = OpTestUtils.assumption_assert_and_transform(
            args, len(inputs_sig)
        )
775
        net = PrimNet(self.public_python_api)
776 777 778
        net = apply_to_static(
            net, core.is_compiled_with_cinn() and self.enable_cinn
        )
C
Charles-hit 已提交
779 780 781 782 783 784 785 786 787 788
        # check the operator not in program if check prim is True
        forward_ops = [
            op.type
            for op in net.forward.get_concrete_program(args)[1]
            .forward_program.block(0)
            .ops
        ]
        assert self.op_type not in forward_ops, (
            "%s shouldn't appear in program when check_prim is True"
        ) % (self.op_type)
789
        ret = flatten(_as_list(net(args)))
790
        ret = paddle.utils.map_structure(lambda x: x.numpy(), ret)
791
        if OpTestUtils.is_bfloat16_type(self.dtype):
792 793 794
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        # check jit comp forward
        if len(ret) != len(self.eager_desire):
            msg = (
                "The jit comp with cinn forward api out tensor nums is different with eager forward api out tensor nums on %s."
                'when enable_fw_comp is %s, enable_cinn is %s, jit comp forward api out tensor nums = %s, eager forward api out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_fw_comp,
                    core.is_compiled_with_cinn() and self.enable_cinn,
                    len(ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(ret)):
810 811 812 813 814 815
            np.testing.assert_allclose(
                ret[i],
                self.eager_desire[i],
                rtol=rtol,
                atol=atol,
                err_msg=(
816 817
                    'Check jit comp with cinn forward api out failed. Mismatch between jit comp and eager on %s, '
                    'when enable_fw_comp is %s, enable_cinn is %s, the forward api out tensor\'s index is : %d \n'
818
                    'jit comp forward api out tensor:\n%s\n eager forward api out tensor:\n%s\n'
819 820 821 822 823 824 825 826
                    % (
                        str(self.place),
                        self.enable_fw_comp,
                        core.is_compiled_with_cinn() and self.enable_cinn,
                        i,
                        ret[i],
                        self.eager_desire[i],
                    )
827 828
                ),
            )
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
        core._set_prim_forward_enabled(False)
        net.forward.program_cache.clear()


class PrimGradChecker(PrimForwardChecker):
    def __init__(
        self,
        op_test,
        place,
        inputs_to_check,
        output_names,
        no_grad_set,
        grad_outputs,
    ):
        PrimForwardChecker.__init__(self, op_test, place)
        self.inputs_to_check = inputs_to_check
        self.output_names = output_names
        self.no_grad_set = no_grad_set
        self.grad_outputs = grad_outputs

    def init(self):
        self.checker_name = "PrimGradChecker"

    def check(self):
853
        if (
854
            type(self.place) is paddle.fluid.libpaddle.CUDAPlace
855 856 857
            and not paddle.is_compiled_with_cuda()
        ):
            return
858 859 860 861 862 863 864 865 866 867 868 869 870
        self.eager_desire = self.get_eager_desire()
        if self.enable_check_eager_comp:
            self.check_eager_comp()
        if self.enable_check_static_comp:
            self.check_static_comp()
        if self.enable_check_jit_comp:
            self.check_jit_comp()
        if self.enable_check_jit_comp_with_cinn:
            self.check_jit_comp_with_cinn()

        self.recover_eager_or_static_status()

    def get_output_dict(self, np_outputs, api_outputs, outputs_sig):
871
        assert len(api_outputs) <= len(outputs_sig), (
C
co63oc 已提交
872
            "forward api outputs length must be the less than or equal to KernelSignature outputs,but receive %s and %s"
873 874
        ) % (len(api_outputs), len(outputs_sig))
        output_dict = {}
875 876
        for i in range(len(api_outputs)):
            output_name = outputs_sig[i]
C
Charles-hit 已提交
877 878 879
            if output_name in np_outputs and isinstance(
                np_outputs[output_name], list
            ):
880 881 882 883 884 885 886 887 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 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
                for j, tup in enumerate(np_outputs[output_name]):
                    output_dict.update({tup[0]: api_outputs[i][j]})
            else:
                output_dict.update({output_name: api_outputs[i]})
        return output_dict

    def gen_eager_grad_outputs(self):
        if self.grad_outputs is None:
            return None
        eager_vs = []
        for np_v in self.grad_outputs:
            eager_vs.append(
                paddle.to_tensor(
                    data=np_v,
                    place=self.place,
                    dtype="bfloat16"
                    if OpTestUtils.is_bfloat16_type(np_v.dtype)
                    else np_v.dtype,
                )
            )
        return eager_vs

    def gen_static_grad_outputs_and_feed(self):
        if self.grad_outputs is None:
            return None, {}
        static_vs = []
        feed = {}
        for i, np_v in enumerate(self.grad_outputs):
            static_vs.append(
                paddle.static.data(
                    name='v_' + str(i),
                    shape=np_v.shape,
                    dtype="bfloat16"
                    if OpTestUtils.is_bfloat16_type(np_v.dtype)
                    else np_v.dtype,
                )
            )
            feed.update({'v_' + str(i): np_v})
        return static_vs, feed

    def gen_no_grad_set(self, var_dict):
        if self.no_grad_set is None:
            return None
        no_grad_set = set()
        for name in self.no_grad_set:
            if name in var_dict:
                no_grad_set.add(var_dict[name])
        return no_grad_set

    def get_eager_desire(self):
        paddle.disable_static()
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        (
            eager_tensor_inputs,
            attrs_outputs,
            inputs_dict,
C
Charles-hit 已提交
939
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=False)
940
        args = OpTestUtils.prepare_python_api_arguments(
941
            self.public_python_api,
942 943 944
            eager_tensor_inputs,
            attrs_outputs,
            self.kernel_sig,
945 946
        )
        inputs_sig, _, outputs_sig = self.kernel_sig
C
Charles-hit 已提交
947 948
        if hasattr(self.op_test, "python_out_sig"):
            outputs_sig = self.op_test.python_out_sig
949 950 951
        args = OpTestUtils.assumption_assert_and_transform(
            args, len(inputs_sig)
        )
952
        ret = _as_list(self.public_python_api(*args))
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
        outputs_dict = self.get_output_dict(self.outputs, ret, outputs_sig)
        ys = []
        if isinstance(self.output_names, list):
            for output_name in self.output_names:
                ys.append(outputs_dict[output_name])
        else:
            ys.append(outputs_dict[self.output_names])
        xs = []
        if isinstance(self.inputs_to_check, list):
            for input_name in self.inputs_to_check:
                xs.append(inputs_dict[input_name])
        else:
            xs.append(inputs_dict[self.inputs_to_check])
        vs = self.gen_eager_grad_outputs()
        no_grad_vars = self.gen_no_grad_set(
            var_dict={**inputs_dict, **outputs_dict}
        )
        ret = paddle.grad(
            ys, xs, vs, allow_unused=True, no_grad_vars=no_grad_vars
        )
973
        ret = paddle.utils.map_structure(lambda x: x.numpy(), ret)
974
        if OpTestUtils.is_bfloat16_type(self.dtype):
975 976 977
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
978 979 980 981 982 983 984 985 986 987 988 989
        return ret

    def check_eager_comp(self):
        if self.prim_op_type == "comp":
            return
        paddle.disable_static()
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        atol = self.rev_comp_atol
        rtol = self.rev_comp_rtol
990
        core.set_prim_eager_enabled(self.enable_rev_comp)
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        actual_ret = self.get_eager_desire()
        # check static forward
        if len(actual_ret) != len(self.eager_desire):
            msg = (
                "The eager comp grad out tensor nums is different with eager grad out tensor nums on %s."
                'when enable_rev_comp is %s, eager comp grad api out tensor nums = %s, eager grad out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_rev_comp,
                    len(actual_ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(actual_ret)):
1006
            np.testing.assert_allclose(
1007 1008 1009 1010
                actual_ret[i],
                self.eager_desire[i],
                rtol=atol,
                atol=rtol,
1011
                err_msg=(
1012 1013
                    'Check eager comp grad out failed. Mismatch between eager comp '
                    'and eager on %s, when enable_rev_comp is %s,the eager comp grad out tensor\'s index is : %d \n'
1014
                    'eager comp grad out tensor:\n%s\n eager grad out tensor:\n%s\n'
1015 1016 1017 1018 1019 1020 1021
                    % (
                        str(self.place),
                        self.enable_rev_comp,
                        i,
                        actual_ret[i],
                        self.eager_desire[i],
                    )
1022 1023
                ),
            )
1024
        core.set_prim_eager_enabled(False)
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

    def check_static_comp(self):
        paddle.enable_static()
        if self.prim_op_type == "prim":
            core._set_prim_backward_enabled(self.enable_rev_comp)
        else:
            core._set_prim_forward_enabled(self.enable_fw_comp)
            core._set_prim_backward_enabled(self.enable_rev_comp)
        atol = self.rev_comp_atol if self.enable_rev_comp else self.fw_comp_atol
        rtol = self.rev_comp_rtol if self.enable_rev_comp else self.fw_comp_rtol
        startup_program, main_program = (
            paddle.static.Program(),
            paddle.static.Program(),
        )
        with paddle.static.program_guard(main_program, startup_program):
            (
                static_inputs,
                attrs,
                inputs_dict,
                feed,
C
Charles-hit 已提交
1045 1046 1047
            ) = self.get_static_input_attr_inputdict_and_feed(
                stop_gradient=False
            )
1048
            args = OpTestUtils.prepare_python_api_arguments(
1049
                self.public_python_api,
1050 1051 1052
                static_inputs,
                attrs,
                self.kernel_sig,
1053 1054
            )
            inputs_sig, _, outputs_sig = self.kernel_sig
C
Charles-hit 已提交
1055 1056
            if hasattr(self.op_test, "python_out_sig"):
                outputs_sig = self.op_test.python_out_sig
1057 1058 1059
            args = OpTestUtils.assumption_assert_and_transform(
                args, len(inputs_sig)
            )
1060
            fw_outs = _as_list(self.public_python_api(*args))
1061 1062 1063
            outputs_dict = self.get_output_dict(
                self.outputs, fw_outs, outputs_sig
            )
1064
            primapi.to_prim(main_program.blocks)
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
            ys = []
            if isinstance(self.output_names, list):
                for output_name in self.output_names:
                    ys.append(outputs_dict[output_name])
            else:
                ys.append(outputs_dict[self.output_names])
            xs = []
            if isinstance(self.inputs_to_check, list):
                for input_name in self.inputs_to_check:
                    xs.append(inputs_dict[input_name])
            else:
                xs.append(inputs_dict[self.inputs_to_check])
            vs, vs_feed = self.gen_static_grad_outputs_and_feed()
            feed.update(vs_feed)
            no_grad_vars = self.gen_no_grad_set(
                var_dict={**inputs_dict, **outputs_dict}
            )
            ret = paddle.static.gradients(ys, xs, vs, no_grad_set=no_grad_vars)
C
Charles-hit 已提交
1083 1084 1085 1086 1087 1088
        # check the backward operator not in program when check_prim is True
        ops = [op.type for op in main_program.blocks[0].ops]
        backward_op_type = self.op_type + "_grad"
        assert backward_op_type not in ops, (
            "%s shouldn't appear in program when check_prim is True"
        ) % (backward_op_type)
1089 1090 1091 1092
        exe = paddle.static.Executor(self.place)
        exe.run(startup_program)
        actual_ret = exe.run(main_program, feed=feed, fetch_list=ret)
        if OpTestUtils.is_bfloat16_type(self.dtype):
1093
            actual_ret = paddle.utils.map_structure(
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                lambda x: convert_uint16_to_float(x), actual_ret
            )
        # check static grad out
        if len(actual_ret) != len(self.eager_desire):
            msg = (
                "The static comp grad out tensor nums is different with eager grad out tensor nums on %s."
                'when enable_fw_comp is %s,enable_rev_comp is %s, static comp grad out tensor nums = %s, eager grad out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_fw_comp,
                    self.enable_rev_comp,
                    len(actual_ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(actual_ret)):
1111 1112 1113 1114 1115 1116
            np.testing.assert_allclose(
                actual_ret[i],
                self.eager_desire[i],
                rtol=rtol,
                atol=atol,
                err_msg=(
1117 1118
                    'Check static comp grad out failed. Mismatch between static comp '
                    'and eager on %s, when enable_fw_comp is %s,enable_rev_comp is %s,the forward api out tensor\'s index is : %d \n'
1119
                    'static comp grad out tensor:\n%s\n eager grad out tensor:\n%s\n'
1120 1121 1122 1123 1124 1125 1126 1127
                    % (
                        str(self.place),
                        self.enable_fw_comp,
                        self.enable_rev_comp,
                        i,
                        actual_ret[i],
                        self.eager_desire[i],
                    )
1128 1129
                ),
            )
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
        core._set_prim_forward_enabled(False)
        core._set_prim_backward_enabled(False)
        paddle.disable_static()

    def check_jit_comp(self):
        paddle.disable_static()
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        if self.prim_op_type == "prim":
            core._set_prim_backward_enabled(self.enable_rev_comp)
        else:
            core._set_prim_forward_enabled(self.enable_fw_comp)
            core._set_prim_backward_enabled(self.enable_rev_comp)
        atol = (
            self.fw_comp_atol
            if self.enable_fw_comp and not self.enable_rev_comp
            else self.jit_comp_atol
        )
        rtol = (
            self.fw_comp_rtol
            if self.enable_fw_comp and not self.enable_rev_comp
            else self.jit_comp_rtol
        )
        atol = self.rev_comp_atol if self.enable_rev_comp else atol
        rtol = self.rev_comp_rtol if self.enable_rev_comp else rtol
        (
            eager_tensor_inputs,
            attrs_outputs,
            inputs_dict,
C
Charles-hit 已提交
1161
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=False)
1162
        args = OpTestUtils.prepare_python_api_arguments(
1163
            self.public_python_api,
1164 1165 1166
            eager_tensor_inputs,
            attrs_outputs,
            self.kernel_sig,
1167 1168 1169 1170 1171
        )
        inputs_sig, _, outputs_sig = self.kernel_sig
        args = OpTestUtils.assumption_assert_and_transform(
            args, len(inputs_sig)
        )
1172
        net = PrimNet(self.public_python_api)
1173
        net = apply_to_static(net, False)
C
Charles-hit 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        # check the backward operator not in program when check_prim is True
        ops = [
            op.type
            for op in net.forward.get_concrete_program(args)[1]
            .backward_program.block(0)
            .ops
        ]
        backward_op_type = self.op_type + "_grad"
        assert backward_op_type not in ops, (
            "%s shouldn't appear in program when check_prim is True"
        ) % (backward_op_type)
1185
        out = _as_list(net(args))
C
Charles-hit 已提交
1186 1187
        if hasattr(self.op_test, "python_out_sig"):
            outputs_sig = self.op_test.python_out_sig
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
        outputs_dict = self.get_output_dict(self.outputs, out, outputs_sig)
        ys = []
        if isinstance(self.output_names, list):
            for output_name in self.output_names:
                ys.append(outputs_dict[output_name])
        else:
            ys.append(outputs_dict[self.output_names])
        xs = []
        if isinstance(self.inputs_to_check, list):
            for input_name in self.inputs_to_check:
                xs.append(inputs_dict[input_name])
        else:
            xs.append(inputs_dict[self.inputs_to_check])
        vs = self.gen_eager_grad_outputs()
        no_grad_vars = self.gen_no_grad_set(
            var_dict={**inputs_dict, **outputs_dict}
        )
        ret = paddle.grad(
            ys, xs, vs, allow_unused=True, no_grad_vars=no_grad_vars
        )
1208
        ret = paddle.utils.map_structure(lambda x: x.numpy(), ret)
1209
        if OpTestUtils.is_bfloat16_type(self.dtype):
1210 1211 1212
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
        # check jit comp grad out
        if len(ret) != len(self.eager_desire):
            msg = (
                "The jit comp grad out tensor nums is different with eager grad out tensor nums on %s."
                'when enable_fw_comp is %s, enable_rev_comp is %s, jit comp grad out tensor nums = %s, eager grad out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_fw_comp,
                    self.enable_rev_comp,
                    len(ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(ret)):
1228 1229 1230 1231 1232 1233
            np.testing.assert_allclose(
                ret[i],
                self.eager_desire[i],
                rtol=rtol,
                atol=atol,
                err_msg=(
1234 1235
                    'Check jit comp grad out failed. Mismatch between jit comp '
                    'and eager on %s, when enable_fw_comp is %s, enable_rev_comp is %s,the grad out tensor\'s index is : %d \n'
1236
                    'jit comp grad out tensor:\n%s\n eager grad out out tensor:\n%s\n'
1237 1238 1239 1240 1241 1242 1243 1244
                    % (
                        str(self.place),
                        self.enable_fw_comp,
                        self.enable_rev_comp,
                        i,
                        ret[i],
                        self.eager_desire[i],
                    )
1245 1246
                ),
            )
1247 1248 1249 1250 1251
        core._set_prim_forward_enabled(False)
        core._set_prim_backward_enabled(False)
        net.forward.program_cache.clear()

    def check_jit_comp_with_cinn(self):
C
co63oc 已提交
1252
        # cinn doesn't support cpu place
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
        if (
            type(self.place) is paddle.fluid.libpaddle.CPUPlace
            and self.enable_cinn
            and core.is_compiled_with_cinn()
        ):
            return
        paddle.disable_static()
        if type(self.place) is paddle.fluid.libpaddle.CPUPlace:
            paddle.device.set_device("cpu")
        if type(self.place) is paddle.fluid.libpaddle.CUDAPlace:
            paddle.device.set_device("gpu:0")
        if self.prim_op_type == "prim":
            core._set_prim_backward_enabled(self.enable_rev_comp)
        else:
            core._set_prim_forward_enabled(self.enable_fw_comp)
            core._set_prim_backward_enabled(self.enable_rev_comp)
        if self.enable_cinn and core.is_compiled_with_cinn():
            atol = self.cinn_atol
            rtol = self.cinn_rtol
        else:
            atol = (
                self.fw_comp_atol
                if self.enable_fw_comp and not self.enable_rev_comp
                else self.jit_comp_atol
            )
            rtol = (
                self.fw_comp_rtol
                if self.enable_fw_comp and not self.enable_rev_comp
                else self.jit_comp_rtol
            )
            atol = self.rev_comp_atol if self.enable_rev_comp else atol
            rtol = self.rev_comp_rtol if self.enable_rev_comp else rtol
        (
            eager_tensor_inputs,
            attrs_outputs,
            inputs_dict,
C
Charles-hit 已提交
1289
        ) = self.get_eager_input_attr_and_inputdict(stop_gradient=False)
1290
        args = OpTestUtils.prepare_python_api_arguments(
1291
            self.public_python_api,
1292 1293 1294
            eager_tensor_inputs,
            attrs_outputs,
            self.kernel_sig,
1295 1296 1297 1298 1299
        )
        inputs_sig, _, outputs_sig = self.kernel_sig
        args = OpTestUtils.assumption_assert_and_transform(
            args, len(inputs_sig)
        )
1300
        net = PrimNet(self.public_python_api)
1301 1302 1303
        net = apply_to_static(
            net, core.is_compiled_with_cinn() and self.enable_cinn
        )
C
Charles-hit 已提交
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        # check the backward operator not in program when check_prim is True
        ops = [
            op.type
            for op in net.forward.get_concrete_program(args)[1]
            .backward_program.block(0)
            .ops
        ]
        backward_op_type = self.op_type + "_grad"
        assert backward_op_type not in ops, (
            "%s shouldn't appear in program when check_prim is True"
        ) % (backward_op_type)

1316
        out = _as_list(net(args))
C
Charles-hit 已提交
1317 1318
        if hasattr(self.op_test, "python_out_sig"):
            outputs_sig = self.op_test.python_out_sig
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        outputs_dict = self.get_output_dict(self.outputs, out, outputs_sig)
        ys = []
        if isinstance(self.output_names, list):
            for output_name in self.output_names:
                ys.append(outputs_dict[output_name])
        else:
            ys.append(outputs_dict[self.output_names])
        xs = []
        if isinstance(self.inputs_to_check, list):
            for input_name in self.inputs_to_check:
                xs.append(inputs_dict[input_name])
        else:
            xs.append(inputs_dict[self.inputs_to_check])
        vs = self.gen_eager_grad_outputs()
        no_grad_vars = self.gen_no_grad_set(
            var_dict={**inputs_dict, **outputs_dict}
        )
        ret = paddle.grad(
            ys, xs, vs, allow_unused=True, no_grad_vars=no_grad_vars
        )
1339
        ret = paddle.utils.map_structure(lambda x: x.numpy(), ret)
1340
        if OpTestUtils.is_bfloat16_type(self.dtype):
1341 1342 1343
            ret = paddle.utils.map_structure(
                lambda x: convert_uint16_to_float(x), ret
            )
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
        # check jit comp grad out
        if len(ret) != len(self.eager_desire):
            msg = (
                "The jit comp with cinn grad out tensor nums is different with eager grad out tensor nums on %s."
                'when enable_fw_comp is %s, enable_rev_comp is %s, enable_cinn is %s, jit comp grad out tensor nums = %s, eager grad out tensor nums = %s. \n'
                % (
                    str(self.place),
                    self.enable_fw_comp,
                    self.enable_rev_comp,
                    self.enable_cinn and core.is_compiled_with_cinn(),
                    len(ret),
                    len(self.eager_desire),
                )
            )
            raise RuntimeError(msg)
        for i in range(len(ret)):
1360 1361 1362 1363 1364 1365
            np.testing.assert_allclose(
                ret[i],
                self.eager_desire[i],
                rtol=rtol,
                atol=atol,
                err_msg=(
1366 1367
                    'Check jit comp with cinn grad out failed. Mismatch between jit comp with cinn '
                    'and eager on %s, when enable_fw_comp is %s, enable_rev_comp is %s, enable_cinn is %s,'
1368
                    'the grad out tensor\'s index is : %d ,jit comp with cinn grad out tensor:\n%s\n eager grad out out tensor:\n%s\n'
1369 1370 1371 1372 1373 1374 1375 1376 1377
                    % (
                        str(self.place),
                        self.enable_fw_comp,
                        self.enable_rev_comp,
                        self.enable_cinn and core.is_compiled_with_cinn(),
                        i,
                        ret[i],
                        self.eager_desire[i],
                    )
1378 1379 1380
                ),
            )

1381 1382 1383
        core._set_prim_forward_enabled(False)
        core._set_prim_backward_enabled(False)
        net.forward.program_cache.clear()