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

from __future__ import print_function
import unittest
import numpy as np
import paddle
19
from paddle import _C_ops, _legacy_C_ops
20 21
from paddle.fluid import core
from paddle.fluid.framework import _test_eager_guard
22
import paddle.sparse as sparse
23 24 25


class TestSparseConv(unittest.TestCase):
26

27 28 29
    def test_conv3d(self):
        with _test_eager_guard():
            kernel = [[[[[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]]]]]
30 31 32
            dense_kernel = paddle.to_tensor(kernel,
                                            dtype='float32',
                                            stop_gradient=False)
33 34 35 36
            dense_kernel = paddle.reshape(dense_kernel, [1, 3, 3, 1, 1])
            paddings = [0, 0, 0]
            strides = [1, 1, 1]
            dilations = [1, 1, 1]
37
            bias = [1]
38 39 40 41 42 43

            indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]]
            values = [1, 2, 3, 4]
            indices = paddle.to_tensor(indices, dtype='int32')
            values = paddle.to_tensor(values, dtype='float32')
            dense_shape = [1, 1, 3, 4, 1]
44
            correct_out_values = [[5], [11]]
45 46
            sparse_input = core.eager.sparse_coo_tensor(indices, values,
                                                        dense_shape, False)
47 48 49 50 51 52 53 54 55
            out = paddle.sparse.nn.functional.conv3d(sparse_input,
                                                     dense_kernel,
                                                     bias=paddle.to_tensor(
                                                         bias, dtype='float32'),
                                                     stride=strides,
                                                     padding=paddings,
                                                     dilation=dilations,
                                                     groups=1,
                                                     data_format="NDHWC")
56
            out.backward(out)
57
            out = paddle.sparse.coalesce(out)
58
            assert np.array_equal(correct_out_values, out.values().numpy())
59

60 61 62 63 64 65 66
    def test_subm_conv3d(self):
        with _test_eager_guard():
            indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]]
            values = [[1], [2], [3], [4]]
            indices = paddle.to_tensor(indices, dtype='int32')
            values = paddle.to_tensor(values, dtype='float32')
            dense_shape = [1, 1, 3, 4, 1]
67 68 69 70
            sparse_x = paddle.sparse.sparse_coo_tensor(indices,
                                                       values,
                                                       dense_shape,
                                                       stop_gradient=True)
71
            weight = paddle.randn((1, 3, 3, 1, 1), dtype='float32')
72 73 74
            y = paddle.sparse.nn.functional.subm_conv3d(sparse_x,
                                                        weight,
                                                        key='subm_conv')
75 76 77 78 79 80 81 82 83 84 85 86 87
            assert np.array_equal(sparse_x.indices().numpy(),
                                  y.indices().numpy())

    def test_Conv3D(self):
        with _test_eager_guard():
            #(4, non_zero_num), 4-D:(N, D, H, W)
            indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]]
            #(non_zero_num, C)
            values = [[1], [2], [3], [4]]
            indices = paddle.to_tensor(indices, dtype='int32')
            values = paddle.to_tensor(values, dtype='float32')
            dense_shape = [1, 1, 3, 4, 1]
            correct_out_values = [[4], [10]]
88
            sparse_input = paddle.sparse.sparse_coo_tensor(
89
                indices, values, dense_shape, False)
90

91 92 93
            sparse_conv3d = paddle.sparse.nn.Conv3D(1,
                                                    1, (1, 3, 3),
                                                    data_format='NDHWC')
94 95 96 97
            sparse_out = sparse_conv3d(sparse_input)
            #test errors
            with self.assertRaises(ValueError):
                #Currently, only support data_format='NDHWC'
98 99 100 101
                conv3d = paddle.sparse.nn.SubmConv3D(1,
                                                     1, (1, 3, 3),
                                                     data_format='NCDHW',
                                                     key='subm_conv')
102 103 104 105 106 107 108 109 110

    def test_SubmConv3D(self):
        with _test_eager_guard():
            indices = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]]
            values = [[1], [2], [3], [4]]
            indices = paddle.to_tensor(indices, dtype='int32')
            values = paddle.to_tensor(values, dtype='float32')
            dense_shape = [1, 1, 3, 4, 1]
            correct_out_values = [[4], [10]]
111
            sparse_input = paddle.sparse.sparse_coo_tensor(
112
                indices, values, dense_shape, False)
113

114 115 116 117
            subm_conv3d = paddle.sparse.nn.SubmConv3D(1,
                                                      1, (1, 3, 3),
                                                      data_format='NDHWC',
                                                      key='subm_conv')
118 119 120 121 122 123
            # test extra_repr
            print(subm_conv3d.extra_repr())

            sparse_out = subm_conv3d(sparse_input)
            # the output shape of subm_conv is same as input shape
            assert np.array_equal(indices, sparse_out.indices().numpy())
124

125 126 127
            #test errors
            with self.assertRaises(ValueError):
                #Currently, only support data_format='NDHWC'
128 129 130 131
                conv3d = paddle.sparse.nn.SubmConv3D(1,
                                                     1, (1, 3, 3),
                                                     data_format='NCDHW',
                                                     key='subm_conv')
Z
zhangkaihuo 已提交
132 133 134 135 136 137 138 139 140

    def test_Conv3D_bias(self):
        with _test_eager_guard():
            paddle.seed(0)
            shape = [1, 4, 4, 4, 3]
            x = paddle.randn(shape)
            sp_x = x.to_sparse_coo(4)
            conv3d = paddle.nn.Conv3D(3, 2, 3, data_format='NDHWC')

141
            sp_conv3d = paddle.sparse.nn.Conv3D(3, 2, 3, data_format='NDHWC')
Z
zhangkaihuo 已提交
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
            sp_conv3d.weight.set_value(
                paddle.to_tensor(conv3d.weight.numpy().transpose(2, 3, 4, 1,
                                                                 0)))
            sp_conv3d.bias.set_value(paddle.to_tensor(conv3d.bias.numpy()))

            x.stop_gradient = False
            out = conv3d(x)
            loss = out.mean()
            loss.backward()

            sp_x.stop_gradient = False
            sp_out = sp_conv3d(sp_x)
            dense_out = sp_out.to_dense()
            sp_loss = dense_out.mean()
            sp_loss.backward()
            assert np.allclose(out.numpy(),
                               dense_out.numpy(),
                               atol=1e-3,
                               rtol=1e-3)
            assert np.allclose(conv3d.weight.grad.numpy().transpose(
                2, 3, 4, 1, 0),
                               sp_conv3d.weight.grad.numpy(),
                               atol=1e-3,
                               rtol=1e-3)
            assert np.allclose(conv3d.bias.grad.numpy(),
                               sp_conv3d.bias.grad.numpy(),
                               atol=1e-5,
                               rtol=1e-5)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 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


class TestStatic(unittest.TestCase):

    def test(self):
        paddle.enable_static()
        indices = paddle.static.data(name='indices',
                                     shape=[4, 4],
                                     dtype='int32')
        values = paddle.static.data(name='values',
                                    shape=[4, 1],
                                    dtype='float32')
        dense_shape = [1, 1, 3, 4, 1]
        sp_x = sparse.sparse_coo_tensor(indices, values, dense_shape)

        weight_shape = [1, 3, 3, 1, 1]
        weight = paddle.static.data(name='weight',
                                    shape=weight_shape,
                                    dtype='float32')
        bias_shape = [1]
        bias = paddle.static.data(name='bias',
                                  shape=bias_shape,
                                  dtype='float32')
        out = sparse.nn.functional.conv3d(sp_x,
                                          weight,
                                          bias,
                                          stride=1,
                                          padding=0,
                                          dilation=1,
                                          groups=1,
                                          data_format="NDHWC")
        sp_out = sparse.nn.functional.relu(out)
        out_indices = sp_out.indices()
        out_values = sp_out.values()
        out = sp_out.to_dense()

        exe = paddle.static.Executor()

        indices_data = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 2], [1, 3, 2, 3]]
        values_data = [[1.0], [2.0], [3.0], [4.0]]
        weight_data = np.array([[[[[1], [1], [1]], [[1], [1], [1]],
                                  [[1], [1], [1]]]]]).astype('float32')
        weight_data = weight_data.reshape(weight_shape)
        bias_data = np.array([1]).astype('float32')

        fetch = exe.run(feed={
            'indices': indices_data,
            'values': values_data,
            'weight': weight_data,
            'bias': bias_data
        },
                        fetch_list=[out, out_indices, out_values],
                        return_numpy=True)
        correct_out = np.array([[[[[5.0], [11.0]]]]]).astype('float64')
        correct_out_values = [[5.0], [11.0]]
        assert np.array_equal(correct_out, fetch[0])
        assert np.array_equal(correct_out_values, fetch[2])
        assert out_indices.dtype == paddle.int32
        paddle.disable_static()


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