test_sparse_unary_op.py 6.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2022 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.

import unittest
import numpy as np
import paddle
18
from paddle.fluid.framework import convert_np_dtype_to_dtype_
19 20 21


class TestSparseUnary(unittest.TestCase):
22

23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
    def to_sparse(self, x, format):
        if format == 'coo':
            return x.detach().to_sparse_coo(sparse_dim=x.ndim)
        elif format == 'csr':
            return x.detach().to_sparse_csr()

    def check_result(self, dense_func, sparse_func, format, *args):
        origin_x = paddle.rand([8, 16, 32], dtype='float32')
        mask = paddle.randint(0, 2, [8, 16, 32]).astype('float32')

        ### check sparse coo with dense ###
        dense_x = origin_x * mask
        sp_x = self.to_sparse(dense_x, format)

        sp_x.stop_gradient = False
        if len(args) == 0:
            sp_out = sparse_func(sp_x)
        elif len(args) == 1:
            sp_out = sparse_func(sp_x, args[0])
        elif len(args) == 2:
            sp_out = sparse_func(sp_x, args[0], args[1])
        sp_out.backward()

        dense_x.stop_gradient = False
        if len(args) == 0:
48
            dense_out = dense_func(dense_x)
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
        elif len(args) == 1:
            dense_out = dense_func(dense_x, args[0])
        elif len(args) == 2:
            if dense_func == paddle.cast:
                dense_out = dense_func(dense_x, args[1])

                int_dtype = convert_np_dtype_to_dtype_(args[0])
                if sp_out.is_sparse_csr():
                    self.assertEqual(sp_out.crows().dtype, int_dtype)
                    self.assertEqual(sp_out.cols().dtype, int_dtype)
                elif sp_out.is_sparse_coo():
                    self.assertEqual(sp_out.indices().dtype, int_dtype)
            else:
                dense_out = dense_func(dense_x, args[0], args[1])
        dense_out.backward()

        # compare forward
66 67 68
        np.testing.assert_allclose(sp_out.to_dense().numpy(),
                                   dense_out.numpy(),
                                   rtol=1e-05)
69 70 71 72 73 74

        # compare backward
        if dense_func == paddle.sqrt:
            expect_grad = np.nan_to_num(dense_x.grad.numpy(), 0., 0., 0.)
        else:
            expect_grad = (dense_x.grad * mask).numpy()
75 76 77
        np.testing.assert_allclose(sp_x.grad.to_dense().numpy(),
                                   expect_grad,
                                   rtol=1e-05)
78 79 80 81 82 83 84 85 86 87 88 89 90

    def compare_with_dense(self, dense_func, sparse_func):
        self.check_result(dense_func, sparse_func, 'coo')
        self.check_result(dense_func, sparse_func, 'csr')

    def compare_with_dense_one_attr(self, dense_func, sparse_func, attr1):
        self.check_result(dense_func, sparse_func, 'coo', attr1)
        self.check_result(dense_func, sparse_func, 'csr', attr1)

    def compare_with_dense_two_attr(self, dense_func, sparse_func, attr1,
                                    attr2):
        self.check_result(dense_func, sparse_func, 'coo', attr1, attr2)
        self.check_result(dense_func, sparse_func, 'csr', attr1, attr2)
91

92
    def test_sparse_sin(self):
93
        self.compare_with_dense(paddle.sin, paddle.sparse.sin)
94

95
    def test_sparse_tan(self):
96
        self.compare_with_dense(paddle.tan, paddle.sparse.tan)
97

98
    def test_sparse_asin(self):
99
        self.compare_with_dense(paddle.asin, paddle.sparse.asin)
100

101
    def test_sparse_atan(self):
102
        self.compare_with_dense(paddle.atan, paddle.sparse.atan)
103

104
    def test_sparse_sinh(self):
105
        self.compare_with_dense(paddle.sinh, paddle.sparse.sinh)
106 107

    def test_sparse_tanh(self):
108
        self.compare_with_dense(paddle.tanh, paddle.sparse.tanh)
109 110

    def test_sparse_asinh(self):
111
        self.compare_with_dense(paddle.asinh, paddle.sparse.asinh)
112 113

    def test_sparse_atanh(self):
114
        self.compare_with_dense(paddle.atanh, paddle.sparse.atanh)
115 116

    def test_sparse_sqrt(self):
117
        self.compare_with_dense(paddle.sqrt, paddle.sparse.sqrt)
118 119

    def test_sparse_square(self):
120
        self.compare_with_dense(paddle.square, paddle.sparse.square)
121 122

    def test_sparse_log1p(self):
123
        self.compare_with_dense(paddle.log1p, paddle.sparse.log1p)
124 125

    def test_sparse_relu(self):
126
        self.compare_with_dense(paddle.nn.ReLU(), paddle.sparse.nn.ReLU())
127

128
    def test_sparse_relu6(self):
129
        self.compare_with_dense(paddle.nn.ReLU6(), paddle.sparse.nn.ReLU6())
130 131 132

    def test_sparse_leaky_relu(self):
        self.compare_with_dense(paddle.nn.LeakyReLU(0.1),
133
                                paddle.sparse.nn.LeakyReLU(0.1))
134

135
    def test_sparse_abs(self):
136
        self.compare_with_dense(paddle.abs, paddle.sparse.abs)
137

138
    def test_sparse_expm1(self):
139
        self.compare_with_dense(paddle.expm1, paddle.sparse.expm1)
140 141

    def test_sparse_deg2rad(self):
142
        self.compare_with_dense(paddle.deg2rad, paddle.sparse.deg2rad)
143 144

    def test_sparse_rad2deg(self):
145
        self.compare_with_dense(paddle.rad2deg, paddle.sparse.rad2deg)
146

147
    def test_sparse_neg(self):
148
        self.compare_with_dense(paddle.neg, paddle.sparse.neg)
149 150

    def test_sparse_pow(self):
151
        self.compare_with_dense_one_attr(paddle.pow, paddle.sparse.pow, 3)
152 153 154

    def test_sparse_mul_scalar(self):
        self.compare_with_dense_one_attr(paddle.Tensor.__mul__,
155
                                         paddle.sparse.multiply, 3)
156 157 158

    def test_sparse_div_scalar(self):
        self.compare_with_dense_one_attr(paddle.Tensor.__div__,
159
                                         paddle.sparse.divide, 2)
160 161

    def test_sparse_cast(self):
162 163 164 165
        self.compare_with_dense_two_attr(paddle.cast, paddle.sparse.cast,
                                         'int32', 'float32')
        self.compare_with_dense_two_attr(paddle.cast, paddle.sparse.cast,
                                         'int32', 'float64')
166 167 168 169


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