test_primops.py 5.7 KB
Newer Older
L
levi131 已提交
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
#
L
levi131 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
6
#
L
levi131 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
L
levi131 已提交
9 10 11 12 13 14
# 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
15 16
import uuid

L
levi131 已提交
17 18
import numpy as np
import paddle
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
from numpy.random import randint, randn
from paddle.incubate.autograd import primops, primx
from paddle.incubate.autograd import utils as prim_utils

import config
import utils

paddle.enable_static()


@utils.place(config.DEVICES)
@utils.parameterize(
    (utils.TEST_CASE_NAME, 'op', 'args', 'kwargs', 'expected_shape',
     'expected_dtype'),
    (
        ('add', primops.add, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
        ('sub', primops.sub, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
        ('mul', primops.mul, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
        ('div', primops.div, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
        ('sub', primops.sub, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
        ('sqrt', primops.sqrt, randn(2, 3), {}, (2, 3), 'float64'),
        ('tanh', primops.tanh, randn(2, 3), {}, (2, 3), 'float64'),
        ('sin', primops.sin, randn(2, 3), {}, (2, 3), 'float64'),
        ('cos', primops.cos, randn(2, 3), {}, (2, 3), 'float64'),
        ('exp', primops.exp, randn(2, 3), {}, (2, 3), 'float64'),
44
        ('erf', primops.erf, randn(2, 3), {}, (2, 3), 'float64'),
45
        ('log', primops.log, randn(2, 3), {}, (2, 3), 'float64'),
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
        ('reshape', primops.reshape, randn(2, 3), {
            'shape': (3, 2)
        }, (3, 2), 'float64'),
        ('broadcast', primops.broadcast, randn(2), {
            'shape': (3, 2)
        }, (3, 2), 'float64'),
        ('transpose', primops.transpose, randn(2, 3), {
            'axis': (1, 0)
        }, (3, 2), 'float64'),
        ('concat_axis0', primops.concat, ((randn(2, 3), randn(2, 3)), ), {
            'axis': 0
        }, (4, 3), 'float64'),
        ('concat_axis1', primops.concat, ((randn(2, 3), randn(2, 3)), ), {
            'axis': 1
        }, (2, 6), 'float64'),
        ('reduce_axis1', primops.reduce, randn(2, 3), {
            'axis': (1, )
        }, (2, ), 'float64'),
        ('reduce_axis01', primops.reduce, randn(2, 3), {
            'axis': (0, 1)
        }, (1, ), 'float64'),
        ('split', primops.split, randn(2, 3), {
            'num_or_sections': [1, 2],
            'axis': 1
        }, ((2, 1), (2, 2)), ('float64', 'float64')),
        ('matmul', primops.matmul, (randn(2, 3), randn(3, 2)), {},
         (2, 2), 'float64'),
        ('slice_select', primops.slice_select, randn(3, 2), {
            'axis': [0],
            'starts': [0],
            'ends': [2],
            'strides': [1]
        }, (2, 2), 'float64'),
        ('slice_assign', primops.slice_assign, (randn(2, 3), randn(2, 2)), {
            'axis': [1],
            'starts': [1],
            'ends': [3],
            'strides': [1]
        }, (2, 3), 'float64'),
        ('gather', primops.gather, (randn(3, 2), randint(0, 2,
                                                         (5, ), np.int32)), {
                                                             'axis': 0
                                                         }, (5, 2), 'float64'),
        ('scatter_add', primops.scatter_add,
         (randn(3, 2), randn(5, 2), randint(0, 2, (5, ), np.int32)), {
             'axis': 0
         }, (3, 2), 'float64'),
        ('fill_const', primops.fill_const, (), {
            'value': 10,
            'shape': (3, 2),
            'dtype': paddle.float32
        }, (3, 2), 'float32'),
        ('neg', primops.neg, randn(2, 3), {}, (2, 3), 'float64'),
99 100 101 102
        ('select', primops.select,
         (randn(2, 3) > 0, randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
        ('eq', primops.eq, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'bool'),
        ('pow', primops.pow, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
103
        ('max', primops.max, (randn(2, 3), randn(2, 3)), {}, (2, 3), 'float64'),
104 105 106 107 108
    ))
class TestPrimops(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
L
levi131 已提交
109 110
        paddle.enable_static()

111 112 113 114 115 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
    @classmethod
    def tearDownClass(cls):
        paddle.disable_static()

    def test_prim_ops(self):
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            args = self._as_tuple(self.args)
            args = self.arr2var(args)
            results = self.op(*args, **self.kwargs)
            results = self._as_tuple(results)
            expected_shape = self._as_tuple(self.expected_shape)
            expected_dtype = self._as_tuple(self.expected_dtype)

            for r, shape, dtype in zip(results, expected_shape, expected_dtype):
                self.assertEqual(r.shape, shape)
                self.assertEqual(str(r.dtype).split('.')[1], dtype)

    def arr2var(self, arr):
        """convert numpy ndarray to paddle Variable recursively."""
        return [
            paddle.static.data(f'x{uuid.uuid4()}', v.shape, v.dtype)
            if isinstance(v, np.ndarray) else self.arr2var(v) for v in arr
        ]

    def _as_tuple(self, input):
        if isinstance(input, (tuple, list)) and len(input) == 0:
            return input
        if not isinstance(input, (tuple, list)) or all(
                isinstance(i, int) for i in input):
            return (input, )
        return input
L
levi131 已提交
143 144 145 146


if __name__ == '__main__':
    unittest.main()