test_zero_dim_tensor.py 32.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#!/usr/bin/env python3

# Copyright (c) 2023 CINN 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.

import unittest
18

19
import numpy as np
20 21
from cinn.common import Bool, Float, Int, is_compiled_with_cuda
from cinn.frontend import NetBuilder
22
from op_test import OpTest, OpTestTool
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
import paddle


def cinn_dtype_convert(dtype_str):
    if dtype_str == "float32":
        return Float(32)
    elif dtype_str == "int64":
        return Int(64)
    elif dtype_str == "bool":
        return Bool()
    else:
        print("Datatype %s has not been supported yet", dtype_str)


##################################
39
#     TestElementwiseAddGrad     #
40 41
##################################
# 1) x is 0D, y is 0D
42 43 44
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
class TestElementwiseAddGrad(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype("float32"),
            "y": np.random.randint(-10, 10, []).astype("float32"),
            "dout": np.random.randint(-10, 10, []).astype("float32"),
        }

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        y = paddle.to_tensor(self.inputs["y"], stop_gradient=False)
        out = paddle.add(x, y)

        self.paddle_outputs = [out]
63 64 65
        self.paddle_grads = self.get_paddle_grads(
            [out], [x, y], [self.inputs["dout"]]
        )
66 67 68 69 70 71 72 73 74

    def build_cinn_program(self, target):
        builder = NetBuilder("add")
        x = builder.create_input(Float(32), self.inputs["x"].shape, "x")
        y = builder.create_input(Float(32), self.inputs["y"].shape, "y")
        # Test elementwise_add here, next unittest tests add, actually these two APIs are same.
        out = builder.elementwise_add(x, y)

        dout = builder.create_input(
75 76
            Float(32), self.inputs["dout"].shape, "dout"
        )
77 78 79 80
        x_grad, y_grad = builder.elementwise_add_grad(dout, x, y)

        prog = builder.build()
        res = self.get_cinn_output(
81 82 83
            prog,
            target,
            [x, y, dout],
84
            [self.inputs["x"], self.inputs["y"], self.inputs["dout"]],
85 86
            [out, x_grad, y_grad],
        )
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

        out, x_grad, y_grad = res
        self.cinn_outputs = [out]
        self.cinn_grads = [x_grad, y_grad]
        self.assertEqual(out.shape, self.inputs["dout"].shape)
        self.assertEqual(x_grad.shape, self.inputs["x"].shape)
        self.assertEqual(y_grad.shape, self.inputs["y"].shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


# 2) x is ND, y is 0D
# NOTE: CINN only supports x's rank >= y's rank, hence no need to test next scenario: `3) x is 0D, y is ND`
class TestElementwiseAddGrad1(TestElementwiseAddGrad):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, [3, 5]).astype("float32"),
            "y": np.random.randint(-10, 10, []).astype("float32"),
            "dout": np.random.randint(-10, 10, [3, 5]).astype("float32"),
        }


##################################
111
#    TestElementwiseBinaryOp     #
112
##################################
113 114 115
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
116 117 118 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
class TestElementwiseBinaryOp_0DTo0D(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.init_dtype()
        self.init_input()

    def init_dtype(self):
        self.dtype = "float32"

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
            "y": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def paddle_func(self, x, y):
        return paddle.add(x, y)

    def cinn_func(self, builder, x, y):
        return builder.add(x, y)

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        y = paddle.to_tensor(self.inputs["y"], stop_gradient=False)
        out = self.paddle_func(x, y)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("binary_op")
        x = builder.create_input(
148 149
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
150
        y = builder.create_input(
151 152
            cinn_dtype_convert(self.dtype), self.inputs["y"].shape, "y"
        )
153 154 155
        out = self.cinn_func(builder, x, y)

        prog = builder.build()
156 157 158
        res = self.get_cinn_output(
            prog, target, [x, y], [self.inputs["x"], self.inputs["y"]], [out]
        )
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


class TestElementwiseBinaryOp_NdTo0d(TestElementwiseBinaryOp_0DTo0D):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, [3, 5]).astype(self.dtype),
            "y": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = (3, 5)


176 177 178 179 180 181
def create_unit_test(
    parent, test_name, fn_paddle, fn_cinn, dtype="float32", **kwargs
):
    @OpTestTool.skip_if(
        not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
    )
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    class TestClass(parent):
        def setUp(self):
            super().setUp()
            for k, v in kwargs.items():
                setattr(self, k, v)

        def init_dtype(self):
            self.dtype = dtype

        def paddle_func(self, *args):
            return fn_paddle(*args)

        def cinn_func(self, builder, *args):
            return eval(fn_cinn)(*args)

197
    cls_name = f"{parent.__name__}_{test_name}"
198 199 200 201 202
    TestClass.__name__ = cls_name
    globals()[cls_name] = TestClass


# NOTE: CINN only supports x's rank >= y's rank, hence no need to test scenario: x is 0D, y is ND
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
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "sub", paddle.subtract, "builder.subtract"
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d, "sub", paddle.subtract, "builder.subtract"
)
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "mul1", paddle.multiply, "builder.multiply"
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d, "mul1", paddle.multiply, "builder.multiply"
)
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "mul2",
    paddle.multiply,
    "builder.elementwise_mul",
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "mul2",
    paddle.multiply,
    "builder.elementwise_mul",
)
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "div", paddle.divide, "builder.divide"
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d, "div", paddle.divide, "builder.divide"
)
233
# Paddle'atan2 only supports 0D + 0D -> 0D
234 235 236
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "atan2", paddle.atan2, "builder.atan2"
)
237 238 239 240 241
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "floor_divide",
    paddle.floor_divide,
    "builder.floor_divide",
242 243
    dtype="int64",
)
244 245 246 247 248
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "floor_divide",
    paddle.floor_divide,
    "builder.floor_divide",
249 250
    dtype="int64",
)
251 252 253 254 255
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "mod",
    paddle.mod,
    "builder.mod",
256 257
    dtype="int64",
)
258 259 260 261 262
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "mod",
    paddle.mod,
    "builder.mod",
263 264
    dtype="int64",
)
265 266 267 268 269
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "remainder",
    paddle.remainder,
    "builder.remainder",
270 271
    dtype="int64",
)
272 273 274 275 276
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "remainder",
    paddle.remainder,
    "builder.remainder",
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    dtype="int64",
)
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "max", paddle.maximum, "builder.max"
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d, "max", paddle.maximum, "builder.max"
)
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "min", paddle.minimum, "builder.min"
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d, "min", paddle.minimum, "builder.min"
)
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D, "pow", paddle.pow, "builder.pow"
)
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d, "pow", paddle.pow, "builder.pow"
)
297 298 299 300 301 302

create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "logical_and",
    paddle.logical_and,
    "builder.logical_and",
303 304
    dtype="bool",
)
305 306 307 308 309
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "logical_and",
    paddle.logical_and,
    "builder.logical_and",
310 311
    dtype="bool",
)
312 313 314 315 316
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "logical_or",
    paddle.logical_or,
    "builder.logical_or",
317 318
    dtype="bool",
)
319 320 321 322 323
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "logical_or",
    paddle.logical_or,
    "builder.logical_or",
324 325
    dtype="bool",
)
326 327 328 329 330
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "logical_xor",
    paddle.logical_xor,
    "builder.logical_xor",
331 332
    dtype="bool",
)
333 334 335 336 337
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "logical_xor",
    paddle.logical_xor,
    "builder.logical_xor",
338 339
    dtype="bool",
)
340 341 342 343 344 345

create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "bitwise_and",
    paddle.bitwise_and,
    "builder.bitwise_and",
346 347
    dtype="int64",
)
348 349 350 351 352
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "bitwise_and",
    paddle.bitwise_and,
    "builder.bitwise_and",
353 354
    dtype="int64",
)
355 356 357 358 359
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "bitwise_or",
    paddle.bitwise_or,
    "builder.bitwise_or",
360 361
    dtype="int64",
)
362 363 364 365 366
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "bitwise_or",
    paddle.bitwise_or,
    "builder.bitwise_or",
367 368
    dtype="int64",
)
369 370 371 372 373
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "bitwise_xor",
    paddle.bitwise_xor,
    "builder.bitwise_xor",
374 375
    dtype="int64",
)
376 377 378 379 380
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "bitwise_xor",
    paddle.bitwise_xor,
    "builder.bitwise_xor",
381 382
    dtype="int64",
)
383 384 385 386 387 388

create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "equal",
    paddle.equal,
    "builder.equal",
389 390
    dtype="int64",
)
391 392 393 394 395
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "equal",
    paddle.equal,
    "builder.equal",
396 397
    dtype="int64",
)
398 399 400 401 402
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "not_equal",
    paddle.not_equal,
    "builder.not_equal",
403 404
    dtype="int64",
)
405 406 407 408 409
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "not_equal",
    paddle.not_equal,
    "builder.not_equal",
410 411
    dtype="int64",
)
412 413 414 415 416
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "greater_than",
    paddle.greater_than,
    "builder.greater_than",
417 418
    dtype="int64",
)
419 420 421 422 423
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "greater_than",
    paddle.greater_than,
    "builder.greater_than",
424 425
    dtype="int64",
)
426 427 428 429 430
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "greater_equal",
    paddle.greater_equal,
    "builder.greater_equal",
431 432
    dtype="int64",
)
433 434 435 436 437
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "greater_equal",
    paddle.greater_equal,
    "builder.greater_equal",
438 439
    dtype="int64",
)
440 441 442 443 444
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "less_than",
    paddle.less_than,
    "builder.less_than",
445 446
    dtype="int64",
)
447 448 449 450 451
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "less_than",
    paddle.less_than,
    "builder.less_than",
452 453
    dtype="int64",
)
454 455 456 457 458
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "less_equal",
    paddle.less_equal,
    "builder.less_equal",
459 460
    dtype="int64",
)
461 462 463 464 465
create_unit_test(
    TestElementwiseBinaryOp_NdTo0d,
    "less_equal",
    paddle.less_equal,
    "builder.less_equal",
466 467
    dtype="int64",
)
468 469 470 471 472 473
create_unit_test(
    TestElementwiseBinaryOp_0DTo0D,
    "is_close",
    paddle.isclose,
    "builder.isclose",
)
474 475 476


######################
477
#    TestUnaryOp     #
478
######################
479 480 481
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
class TestUnaryOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.init_dtype()
        self.init_input()

    def init_dtype(self):
        self.dtype = "float32"

    def init_input(self):
        self.inputs = {
            "x": np.random.uniform(0.0, 1.0, []).astype(self.dtype),
        }
        self.target_shape = ()

    def paddle_func(self, x):
        return paddle.sqrt(x)

    def cinn_func(self, builder, x):
        return builder.sqrt(x)

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = self.paddle_func(x)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("unary_op")
        x = builder.create_input(
512 513
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
514 515 516
        out = self.cinn_func(builder, x)

        prog = builder.build()
517
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])
518 519 520 521 522 523 524 525 526

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


create_unit_test(TestUnaryOp, "tanh", paddle.tanh, "builder.tanh")
527
create_unit_test(TestUnaryOp, "relu", paddle.nn.functional.relu, "builder.relu")
528 529 530
create_unit_test(
    TestUnaryOp, "relu6", paddle.nn.functional.relu6, "builder.relu6"
)
531 532 533 534
create_unit_test(TestUnaryOp, "gelu", paddle.nn.functional.gelu, "builder.gelu")
create_unit_test(
    TestUnaryOp, "sigmoid", paddle.nn.functional.sigmoid, "builder.sigmoid"
)
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
create_unit_test(TestUnaryOp, "exp", paddle.exp, "builder.exp")
create_unit_test(TestUnaryOp, "erf", paddle.erf, "builder.erf")
create_unit_test(TestUnaryOp, "rsqrt", paddle.rsqrt, "builder.rsqrt")
create_unit_test(TestUnaryOp, "log", paddle.log, "builder.log")
create_unit_test(TestUnaryOp, "log2", paddle.log2, "builder.log2")
create_unit_test(TestUnaryOp, "log10", paddle.log10, "builder.log10")
create_unit_test(TestUnaryOp, "floor", paddle.floor, "builder.floor")
create_unit_test(TestUnaryOp, "ceil", paddle.ceil, "builder.ceil")
create_unit_test(TestUnaryOp, "round", paddle.round, "builder.round")
create_unit_test(TestUnaryOp, "trunc", paddle.trunc, "builder.trunc")
create_unit_test(TestUnaryOp, "sin", paddle.sin, "builder.sin")
create_unit_test(TestUnaryOp, "cos", paddle.cos, "builder.cos")
create_unit_test(TestUnaryOp, "tan", paddle.tan, "builder.tan")
create_unit_test(TestUnaryOp, "sinh", paddle.sinh, "builder.sinh")
create_unit_test(TestUnaryOp, "cosh", paddle.cosh, "builder.cosh")
create_unit_test(TestUnaryOp, "asin", paddle.asin, "builder.asin")
create_unit_test(TestUnaryOp, "acos", paddle.acos, "builder.acos")
create_unit_test(TestUnaryOp, "atan", paddle.atan, "builder.atan")
create_unit_test(TestUnaryOp, "asinh", paddle.asinh, "builder.asinh")
create_unit_test(TestUnaryOp, "atanh", paddle.atanh, "builder.atanh")
create_unit_test(TestUnaryOp, "isnan", paddle.isnan, "builder.is_nan")
create_unit_test(TestUnaryOp, "isfinite", paddle.isfinite, "builder.is_finite")
create_unit_test(TestUnaryOp, "isinf", paddle.isinf, "builder.is_inf")
create_unit_test(
    TestUnaryOp,
    "logical_not",
    paddle.logical_not,
    "builder.logical_not",
563 564
    dtype="bool",
)
565 566 567 568 569
create_unit_test(
    TestUnaryOp,
    "bitwise_not",
    paddle.bitwise_not,
    "builder.bitwise_not",
570 571
    dtype="int64",
)
572 573 574
create_unit_test(TestUnaryOp, "negative", paddle.neg, "builder.negative")
create_unit_test(TestUnaryOp, "sign", paddle.sign, "builder.sign")
create_unit_test(TestUnaryOp, "abs", paddle.abs, "builder.abs")
575 576 577
create_unit_test(
    TestUnaryOp, "reciprocal", paddle.reciprocal, "builder.reciprocal"
)
578 579 580
create_unit_test(
    TestUnaryOp, "softmax", paddle.nn.functional.softmax, "builder.softmax"
)
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598


# acosh requires input value > 1.0, specific init_input instead of using create_unit_test
class TestUnaryOp_acosh(TestUnaryOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.uniform(1.0, 10.0, []).astype(self.dtype),
        }
        self.target_shape = ()

    def paddle_func(self, x):
        return paddle.acosh(x)

    def cinn_func(self, builder, x):
        return builder.acosh(x)


#######################
599
#    TestSundryOp     #
600
#######################
601 602 603
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
class TestScaleOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.scale(x, scale=2.0, bias=1.0)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
623
        builder = NetBuilder("scale_op")
624
        x = builder.create_input(
625 626
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
627 628 629
        out = builder.scale(x, 2.0, 1.0)

        prog = builder.build()
630
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestCastOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.cast(x, 'int32')

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("cast_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.cast(x, "int32")

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])
669 670 671 672 673 674 675 676

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestTransposeOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.transpose(x, [])

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("transpose_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.transpose(x, [])

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 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 764 765 766 767 768
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestExpandDimsOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.unsqueeze_dim = [0]
        self.target_shape = (1,)

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.unsqueeze(x, self.unsqueeze_dim)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("unsqueeze_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.expand_dims(x, self.unsqueeze_dim)

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestExpandDimsOp2D(TestExpandDimsOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.unsqueeze_dim = [0, 1]
        self.target_shape = (
            1,
            1,
        )


769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestBroadcastToOp1D(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.broadcast_shape = [1]

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.broadcast_to(x, shape=self.broadcast_shape)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("broadcast_to_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.broadcast_to(x, self.broadcast_shape)

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(list(res[0].shape), list(self.broadcast_shape))

    def test_check_results(self):
        self.check_outputs_and_grads()


class TestBroadcastToOp2D(TestBroadcastToOp1D):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.broadcast_shape = [1, 1]


class TestBroadcastToOp3D(TestBroadcastToOp1D):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.broadcast_shape = [3, 3, 3]


823 824 825 826 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 853 854 855 856 857 858 859 860
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestReverseOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.reverse(x, axis=[])

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("reverse_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.reverse(x, [])

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


861 862 863
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
class TestSumOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
            "y": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        y = paddle.to_tensor(self.inputs["y"], stop_gradient=False)
        out = x + y

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
885
        builder = NetBuilder("sum_op")
886
        x = builder.create_input(
887 888
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
889
        y = builder.create_input(
890 891
            cinn_dtype_convert(self.dtype), self.inputs["y"].shape, "y"
        )
892 893 894
        out = builder.sum([x, y])

        prog = builder.build()
895 896 897
        res = self.get_cinn_output(
            prog, target, [x, y], [self.inputs["x"], self.inputs["y"]], [out]
        )
898 899 900 901 902 903 904 905

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


906 907 908
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
class TestDropoutOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.nn.functional.dropout(x, 1.0)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
928
        builder = NetBuilder("dropout_op")
929
        x = builder.create_input(
930 931
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
932 933 934
        out = builder.dropout_infer(x, 1.0)

        prog = builder.build()
935
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])
936 937 938 939 940 941 942 943

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestReshapeOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = [1]

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.reshape(x, self.target_shape)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("reshape_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.reshape(x, self.target_shape)

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(list(res[0].shape), [1] * len(self.target_shape))

    def test_check_results(self):
        self.check_outputs_and_grads()


class TestReshapeOp0DTo2D(TestReshapeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = [1, 1]


class TestReshapeOp0DTo1D_DS(TestReshapeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = [-1]


class TestReshapeOp0DTo2D_DS(TestReshapeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = [-1, 1]


class TestReshapeOp0DTo0D(TestReshapeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = []


class TestReshapeOp1DTo0D(TestReshapeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, [1]).astype(self.dtype),
        }
        self.target_shape = []


1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestSqueezeOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.squeeze_axex = [0]
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.squeeze(x, axis=self.squeeze_axex)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("squeeze_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.squeeze(x, self.squeeze_axex)

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


class TestSqueezeOp1D(TestSqueezeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, [1]).astype(self.dtype),
        }
        self.squeeze_axex = []
        self.target_shape = ()


class TestSqueezeOp2D(TestSqueezeOp):
    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, [1, 1]).astype(self.dtype),
        }
        self.squeeze_axex = [0, 1]
        self.target_shape = ()


1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestMatmulOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, [10]).astype(self.dtype),
            "y": np.random.randint(-10, 10, [10]).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        y = paddle.to_tensor(self.inputs["y"], stop_gradient=False)
        out = paddle.matmul(x, y)

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("matmul_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        y = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["y"].shape, "y"
        )
        out = builder.matmul(x, y)

        prog = builder.build()
        res = self.get_cinn_output(
            prog, target, [x, y], [self.inputs["x"], self.inputs["y"]], [out]
        )

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


1124 1125 1126 1127 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 1161
@OpTestTool.skip_if(
    not is_compiled_with_cuda(), "x86 test will be skipped due to timeout."
)
class TestFlipOp(OpTest):
    def setUp(self):
        np.random.seed(2023)
        self.dtype = "float32"
        self.init_input()

    def init_input(self):
        self.inputs = {
            "x": np.random.randint(-10, 10, []).astype(self.dtype),
        }
        self.target_shape = ()

    def build_paddle_program(self, target):
        x = paddle.to_tensor(self.inputs["x"], stop_gradient=False)
        out = paddle.flip(x, axis=[])

        self.paddle_outputs = [out]

    def build_cinn_program(self, target):
        builder = NetBuilder("flip_op")
        x = builder.create_input(
            cinn_dtype_convert(self.dtype), self.inputs["x"].shape, "x"
        )
        out = builder.flip(x, [])

        prog = builder.build()
        res = self.get_cinn_output(prog, target, [x], [self.inputs["x"]], [out])

        self.cinn_outputs = res
        self.assertEqual(res[0].shape, self.target_shape)

    def test_check_results(self):
        self.check_outputs_and_grads()


1162 1163
if __name__ == "__main__":
    unittest.main()