test_conv.py 23.4 KB
Newer Older
yan.yan's avatar
yan.yan committed
1
# Copyright 2021 Yan Yan
2
#
traveller59's avatar
traveller59 committed
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
#
traveller59's avatar
traveller59 committed
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
traveller59's avatar
traveller59 committed
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.

yan.yan's avatar
yan.yan committed
15
16
17
18
19
20
"""Compare results between sparse and dense layers:
SparseConvXd
SparseConvTransposeXd
SparseMaxPoolXd
"""

21
22
import time
import unittest
traveller59's avatar
traveller59 committed
23
from pathlib import Path
24
25

import numpy as np
traveller59's avatar
traveller59 committed
26
import torch
27
from torch import nn
yan.yan's avatar
v2.1  
yan.yan committed
28
from spconv.core import ConvAlgo
29

yan.yan's avatar
yan.yan committed
30
import spconv.pytorch as spconv
31
from spconv.test_utils import TestCase, generate_sparse_data, params_grid
yan.yan's avatar
yan.yan committed
32
from spconv.constants import ALL_WEIGHT_IS_KRSC, FILTER_HWIO
33

yan.yan's avatar
v2.1  
yan.yan committed
34
35
36
# we must disable tf32 to increase reference precision.
torch.backends.cuda.matmul.allow_tf32 = False
torch.backends.cudnn.allow_tf32 = False
traveller59's avatar
traveller59 committed
37
38

class SparseConv3dTestTorch(nn.Module):
yanyan's avatar
yanyan committed
39
40
41
42
43
44
45
46
47
48
    def __init__(self,
                 num_layers,
                 ndim,
                 shape,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride,
                 padding,
                 dilation,
yan.yan's avatar
v2.1  
yan.yan committed
49
                 algo=spconv.ConvAlgo.MaskSplitImplicitGemm):
traveller59's avatar
traveller59 committed
50
        super().__init__()
yan.yan's avatar
v2.1  
yan.yan committed
51
        self.algo = algo
52
53
54
55
56
57
58
59
        layers = [
            spconv.SparseConv3d(in_channels,
                                out_channels,
                                kernel_size,
                                stride,
                                padding=padding,
                                dilation=dilation,
                                bias=False,
Yan Yan's avatar
Yan Yan committed
60
                                algo=algo)
61
        ]
traveller59's avatar
traveller59 committed
62
        for i in range(1, num_layers):
63
64
65
66
67
68
69
            layers.append(
                spconv.SparseConv3d(out_channels,
                                    out_channels,
                                    kernel_size,
                                    stride,
                                    padding=padding,
                                    dilation=dilation,
70
                                    bias=False,
Yan Yan's avatar
Yan Yan committed
71
                                    algo=algo))
72
        self.net = spconv.SparseSequential(*layers, )
traveller59's avatar
traveller59 committed
73
74
75
76
77
78
        # self.grid = torch.full([3, *shape], -1, dtype=torch.int32).cuda()
        self.grid = None
        self.shape = shape

    def forward(self, features, coors, batch_size):
        coors = coors.int()
79
80
81
82
        x = spconv.SparseConvTensor(features, coors, self.shape, batch_size,
                                    self.grid)
        return self.net(x)  # .dense()

traveller59's avatar
traveller59 committed
83
class Conv3dTestTorch(nn.Module):
84
85
    def __init__(self, num_layers, ndim, shape, in_channels, out_channels,
                 kernel_size, stride, padding, dilation):
traveller59's avatar
traveller59 committed
86
        super().__init__()
87
88
89
90
91
92
93
94
95
        layers = [
            nn.Conv3d(in_channels,
                      out_channels,
                      kernel_size,
                      stride,
                      padding=padding,
                      dilation=dilation,
                      bias=False)
        ]
traveller59's avatar
traveller59 committed
96
        for i in range(1, num_layers):
97
98
99
100
101
102
103
104
105
            layers.append(
                nn.Conv3d(out_channels,
                          out_channels,
                          kernel_size,
                          stride,
                          padding=padding,
                          dilation=dilation,
                          bias=False))
        self.net = nn.Sequential(*layers, )
traveller59's avatar
traveller59 committed
106
107
108
        self.shape = shape

    def forward(self, x):
109
        return self.net(x)  # .dense()
traveller59's avatar
traveller59 committed
110
111

class SparseDeConv3dTestTorch(nn.Module):
112
    def __init__(self, num_layers, ndim, shape, in_channels, out_channels,
yan.yan's avatar
yan.yan committed
113
                 kernel_size, stride, padding, dilation, algo):
traveller59's avatar
traveller59 committed
114
        super().__init__()
yan.yan's avatar
yan.yan committed
115
        self.algo = algo
116
117
118
119
120
121
122
        layers = [
            spconv.SparseConvTranspose3d(in_channels,
                                         out_channels,
                                         kernel_size,
                                         stride,
                                         padding=padding,
                                         dilation=dilation,
yan.yan's avatar
yan.yan committed
123
124
                                         bias=False,
                                         algo=algo)
125
        ]
traveller59's avatar
traveller59 committed
126
        for i in range(1, num_layers):
127
128
129
130
131
132
133
            layers.append(
                spconv.SparseConvTranspose3d(out_channels,
                                             out_channels,
                                             kernel_size,
                                             stride,
                                             padding=padding,
                                             dilation=dilation,
yan.yan's avatar
yan.yan committed
134
135
                                             bias=False,
                                             algo=algo))
136
        self.net = spconv.SparseSequential(*layers, )
traveller59's avatar
traveller59 committed
137
138
139
140
        self.shape = shape

    def forward(self, features, coors, batch_size):
        coors = coors.int()
141
142
143
        x = spconv.SparseConvTensor(features, coors, self.shape, batch_size)
        return self.net(x)  # .dense()

traveller59's avatar
traveller59 committed
144
145

class DeConv3dTestTorch(nn.Module):
146
147
    def __init__(self, num_layers, ndim, shape, in_channels, out_channels,
                 kernel_size, stride, padding, dilation):
traveller59's avatar
traveller59 committed
148
        super().__init__()
149
150
151
152
153
154
155
156
157
        layers = [
            nn.ConvTranspose3d(in_channels,
                               out_channels,
                               kernel_size,
                               stride,
                               padding=padding,
                               dilation=dilation,
                               bias=False)
        ]
traveller59's avatar
traveller59 committed
158
        for i in range(1, num_layers):
159
160
161
162
163
164
165
166
167
            layers.append(
                nn.ConvTranspose3d(out_channels,
                                   out_channels,
                                   kernel_size,
                                   stride,
                                   padding=padding,
                                   dilation=dilation,
                                   bias=False))
        self.net = nn.Sequential(*layers, )
traveller59's avatar
traveller59 committed
168
169
170
        self.shape = shape

    def forward(self, x):
171
        return self.net(x)  # .dense()
traveller59's avatar
traveller59 committed
172
173
174


class SparseMaxPoolTestTorch(nn.Module):
175
    def __init__(self, num_layers, ndim, shape, kernel_size, stride, padding,
yan.yan's avatar
yan.yan committed
176
                 dilation, algo):
traveller59's avatar
traveller59 committed
177
        super().__init__()
yan.yan's avatar
yan.yan committed
178
        self.algo = algo
179
        layers = [
yan.yan's avatar
yan.yan committed
180
            spconv.SparseMaxPool3d(kernel_size, stride, padding, dilation, algo=algo)
181
        ]
traveller59's avatar
traveller59 committed
182
        for i in range(1, num_layers):
183
            layers.append(
yan.yan's avatar
yan.yan committed
184
                spconv.SparseMaxPool3d(kernel_size, stride, padding, dilation, algo=algo))
185
        self.net = spconv.SparseSequential(*layers, )
traveller59's avatar
traveller59 committed
186
187
188
189
        self.shape = shape

    def forward(self, features, coors, batch_size):
        coors = coors.int()
190
191
192
        x = spconv.SparseConvTensor(features, coors, self.shape, batch_size)
        return self.net(x)  # .dense()

193
194
195
196
197
198
199
200
201
202
203
204
205
206
class SparseGlobalMaxPoolTestTorch(nn.Module):
    def __init__(self, shape):
        super().__init__()
        layers = [
            spconv.SparseGlobalMaxPool()
        ]
        self.net = spconv.SparseSequential(*layers, )
        self.shape = shape

    def forward(self, features, coors, batch_size):
        coors = coors.int()
        x = spconv.SparseConvTensor(features, coors, self.shape, batch_size)
        return self.net(x)  # .dense()

traveller59's avatar
traveller59 committed
207
208

class MaxPool3dTestTorch(nn.Module):
209
210
    def __init__(self, num_layers, ndim, shape, kernel_size, stride, padding,
                 dilation):
traveller59's avatar
traveller59 committed
211
        super().__init__()
212
        layers = [nn.MaxPool3d(kernel_size, stride, padding, dilation)]
traveller59's avatar
traveller59 committed
213
        for i in range(1, num_layers):
214
215
            layers.append(nn.MaxPool3d(kernel_size, stride, padding, dilation))
        self.net = nn.Sequential(*layers, )
traveller59's avatar
traveller59 committed
216
217
218
        self.shape = shape

    def forward(self, x):
219
        return self.net(x)  # .dense()
traveller59's avatar
traveller59 committed
220
221
222
223

def gather_nd(params, indices):
    # this function has a limit that MAX_ADVINDEX_CALC_DIMS=5
    ndim = indices.shape[-1]
224
225
    output_shape = list(indices.shape[:-1]) + list(
        params.shape[indices.shape[-1]:])
traveller59's avatar
traveller59 committed
226
227
228
229
230
    flatted_indices = indices.view(-1, ndim)
    slices = [flatted_indices[:, i] for i in range(ndim)]
    slices += [Ellipsis]
    return params[slices].view(*output_shape)

231

traveller59's avatar
traveller59 committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def scatter_nd(indices, updates, shape):
    """pytorch edition of tensorflow scatter_nd.
    this function don't contain except handle code. so use this carefully
    when indice repeats, don't support repeat add which is supported
    in tensorflow.
    """
    ret = torch.zeros(*shape, dtype=updates.dtype, device=updates.device)
    ndim = indices.shape[-1]
    output_shape = list(indices.shape[:-1]) + shape[indices.shape[-1]:]
    flatted_indices = indices.view(-1, ndim)
    slices = [flatted_indices[:, i] for i in range(ndim)]
    slices += [Ellipsis]
    ret[slices] = updates.view(*output_shape)
    return ret

yan.yan's avatar
yan.yan committed
247
248
249
250
251
252
253
def test_spconv3d():
    test_case = TestCase()
    np.random.seed(484)
    torch.manual_seed(48848)
    devices = ["cuda:0"]
    shapes = [[19, 18, 17]]
    batchsizes = [1, 2]
traveller59's avatar
traveller59 committed
254

yan.yan's avatar
yan.yan committed
255
256
257
258
259
260
261
262
263
264
    in_channels = [32]
    out_channels = [32, 48, 64]
    ksizes = [2, 3]
    strides = [1, 2, 3]
    paddings = [0, 1, 2]
    dilations = [1, 2, 3]
    algos = [
        ConvAlgo.Native, ConvAlgo.MaskImplicitGemm,
        ConvAlgo.MaskSplitImplicitGemm
    ]
Yan Yan's avatar
Yan Yan committed
265
    algos = [ConvAlgo.Native, ConvAlgo.MaskImplicitGemm, ConvAlgo.MaskSplitImplicitGemm]
yan.yan's avatar
yan.yan committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302

    for dev, shape, bs, IC, OC, k, s, p, d, al in params_grid(
            devices, shapes, batchsizes, in_channels, out_channels, ksizes,
            strides, paddings, dilations, algos):
        if all([s > 1, d > 1]):
            continue  # don't support this.
        # print(dev, shape, bs, IC, OC, k, s, p, d)
        device = torch.device(dev)
        num_points = [1500] * bs
        dtype = torch.float32
        net = SparseConv3dTestTorch(1,
                                    3,
                                    shape,
                                    IC,
                                    OC,
                                    k,
                                    s,
                                    p,
                                    d,
                                    algo=al).to(device).to(dtype)
        net_ref = Conv3dTestTorch(1, 3, shape, IC, OC, k, s, p,
                                    d).to(device).to(dtype)

        sparse_dict = generate_sparse_data(shape, num_points, IC)

        features = np.ascontiguousarray(sparse_dict["features"]).astype(
            np.float32)
        indices = np.ascontiguousarray(
            sparse_dict["indices"][:, [3, 0, 1, 2]]).astype(np.int32)
        features_dense = sparse_dict["features_dense"].astype(np.float32)
        indices_t = torch.from_numpy(indices).int().to(device)
        features_t = torch.from_numpy(features).to(device).to(dtype)
        features_t.requires_grad = True
        features_dense_t = torch.from_numpy(features_dense).to(device).to(
            dtype)
        features_dense_t.requires_grad = True
        if net.algo == ConvAlgo.Native and not ALL_WEIGHT_IS_KRSC:
yan.yan's avatar
bug fix  
yan.yan committed
303
            if FILTER_HWIO:
yan.yan's avatar
yan.yan committed
304
305
306
                filters = np.random.uniform(-1, 1,
                                            size=[k, k, k, IC,
                                                    OC]).astype(np.float32)
yan.yan's avatar
bug fix  
yan.yan committed
307
            else:
yan.yan's avatar
yan.yan committed
308
309
310
311
                filters = np.random.uniform(-1, 1,
                                            size=[k, k, k, OC,
                                                    IC]).astype(np.float32)
            filters_t = torch.from_numpy(filters).to(device).to(dtype)
yan.yan's avatar
bug fix  
yan.yan committed
312
            if FILTER_HWIO:
313
                net_ref.net[0].weight.data[:] = filters_t.permute(
yan.yan's avatar
yan.yan committed
314
                    4, 3, 0, 1, 2).contiguous()
yan.yan's avatar
bug fix  
yan.yan committed
315
            else:
316
                net_ref.net[0].weight.data[:] = filters_t.permute(
yan.yan's avatar
yan.yan committed
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
                    3, 4, 0, 1, 2).contiguous()
        else:
            filters = np.random.uniform(-1, 1,
                                        size=[OC, k, k, k,
                                                IC]).astype(np.float32)
            filters_t = torch.from_numpy(filters).to(device).to(dtype)
            net_ref.net[0].weight.data[:] = filters_t.permute(
                0, 4, 1, 2, 3).contiguous()
        net.net[0].weight.data[:] = filters_t
        out_ref = net_ref(features_dense_t)
        out = net(features_t, indices_t, bs).dense()
        out_np = out.detach().cpu().numpy()
        out_ref_np = out_ref.detach().cpu().numpy()
        test_case.assertAllClose(out_np, out_ref_np, atol=1e-4)

        dout = np.random.uniform(-0.2, 0.2,
                                    out_ref.shape).astype(features.dtype)
        dout_t = torch.from_numpy(dout).to(device)
        out.backward(dout_t)
        out_ref.backward(dout_t)
        din_dense = features_dense_t.grad.detach().permute(0, 2, 3, 4,
                                                            1).contiguous()
        din_sparse = gather_nd(din_dense, indices_t.long())
        din = features_t.grad.detach()

        din_np = din.cpu().numpy()
        din_sparse_np = din_sparse.cpu().numpy()
        for layer, layer_ref in zip(net.net, net_ref.net):
            dw = layer.weight.grad.detach().cpu().numpy()
            dw_ref = layer_ref.weight.grad.detach().cpu().numpy()
            if net.algo == ConvAlgo.Native and not ALL_WEIGHT_IS_KRSC:
yan.yan's avatar
bug fix  
yan.yan committed
348
349
                if FILTER_HWIO:
                    dw = dw.transpose(4, 3, 0, 1, 2)
yan.yan's avatar
yan.yan committed
350
351
352
353
354
355
356
357
                else:
                    dw = dw.transpose(3, 4, 0, 1, 2)
            else:
                # OHWI -> OIHW
                dw = dw.transpose(0, 4, 1, 2, 3)

            test_case.assertAllClose(dw, dw_ref, atol=1e-4)
        test_case.assertAllClose(din_np, din_sparse_np, atol=1e-4)
traveller59's avatar
traveller59 committed
358

yan.yan's avatar
yan.yan committed
359
360
def test_spdeconv3d():
    test_case = TestCase()
traveller59's avatar
traveller59 committed
361

yan.yan's avatar
yan.yan committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    np.random.seed(484)
    devices = ["cuda:0"]
    shapes = [[19, 18, 17]]
    batchsizes = [1, 2]

    in_channels = [64]
    out_channels = [32, 48, 64]
    ksizes = [2, 3]
    strides = [2, 3]
    paddings = [0, 1, 2]
    dilations = [1, 2, 3]

    algos = [
        ConvAlgo.Native, ConvAlgo.MaskImplicitGemm,
        ConvAlgo.MaskSplitImplicitGemm
    ]

    for dev, shape, bs, IC, OC, k, s, p, d, al in params_grid(
380
            devices, shapes, batchsizes, in_channels, out_channels, ksizes,
yan.yan's avatar
yan.yan committed
381
            strides, paddings, dilations, algos):
traveller59's avatar
traveller59 committed
382
        if all([s > 1, d > 1]):
yan.yan's avatar
yan.yan committed
383
            continue  # don't support this.
traveller59's avatar
traveller59 committed
384
        device = torch.device(dev)
yan.yan's avatar
yan.yan committed
385
386
        num_points = [1000] * bs
        dtype = torch.float32
traveller59's avatar
traveller59 committed
387
388
389

        sparse_dict = generate_sparse_data(shape, num_points, IC)

390
391
392
393
        features = np.ascontiguousarray(sparse_dict["features"]).astype(
            np.float32)
        indices = np.ascontiguousarray(
            sparse_dict["indices"][:, [3, 0, 1, 2]]).astype(np.int32)
traveller59's avatar
traveller59 committed
394
        features_dense = sparse_dict["features_dense"].astype(np.float32)
yan.yan's avatar
yan.yan committed
395
396
397
398
        net = SparseDeConv3dTestTorch(1, 3, shape, IC, OC, k, s, p,
                                        d, al).to(device)
        net_ref = DeConv3dTestTorch(1, 3, shape, IC, OC, k, s, p,
                                    d).to(device)
399

yan.yan's avatar
yan.yan committed
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
        if net.algo == ConvAlgo.Native and not ALL_WEIGHT_IS_KRSC:
            if FILTER_HWIO:
                filters = np.random.uniform(-1, 1,
                                            size=[k, k, k, IC,
                                                    OC]).astype(np.float32)
            else:
                filters = np.random.uniform(-1, 1,
                                            size=[k, k, k, OC,
                                                    IC]).astype(np.float32)
            filters_t = torch.from_numpy(filters).to(device).to(dtype)
            if FILTER_HWIO:
                net_ref.net[0].weight.data[:] = filters_t.permute(
                    3, 4, 0, 1, 2).contiguous()
            else:
                net_ref.net[0].weight.data[:] = filters_t.permute(
                    4, 3, 0, 1, 2).contiguous()
        else:
            filters = np.random.uniform(-1, 1,
                                        size=[OC, k, k, k,
                                                IC]).astype(np.float32)
            filters_t = torch.from_numpy(filters).to(device).to(dtype)
            net_ref.net[0].weight.data[:] = filters_t.permute(
                4, 0, 1, 2, 3).contiguous()
        net.net[0].weight.data[:] = filters_t

        indices_t = torch.from_numpy(indices).int().to(device)
        features_t = torch.from_numpy(features).to(device)
        features_t.requires_grad = True
        features_dense_t = torch.from_numpy(features_dense).to(device)
        features_dense_t.requires_grad = True
        filters_t = torch.from_numpy(filters).to(device)
traveller59's avatar
traveller59 committed
431
        out_ref = net_ref(features_dense_t)
yan.yan's avatar
yan.yan committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
        out = net(features_t, indices_t, bs).dense()
        out_np = out.detach().cpu().numpy()
        out_ref_np = out_ref.detach().cpu().numpy()
        test_case.assertAllClose(out_np, out_ref_np, atol=1e-4)

        dout = np.random.uniform(-0.2, 0.2,
                                    out_ref.shape).astype(features.dtype)
        dout_t = torch.from_numpy(dout).to(device)
        out.backward(dout_t)
        out_ref.backward(dout_t)
        din_dense = features_dense_t.grad.detach().permute(0, 2, 3, 4,
                                                            1).contiguous()
        din_sparse = gather_nd(din_dense, indices_t.long())
        din = features_t.grad.detach()
        din_np = din.cpu().numpy()
        din_sparse_np = din_sparse.cpu().numpy()
        test_case.assertAllClose(din_np, din_sparse_np, atol=1e-4)
        for layer, layer_ref in zip(net.net, net_ref.net):
            dw = layer.weight.grad.detach().cpu().numpy()
            dw_ref = layer_ref.weight.grad.detach().cpu().numpy()
            if net.algo == ConvAlgo.Native and not ALL_WEIGHT_IS_KRSC:
                if FILTER_HWIO:
                    dw = dw.transpose(3, 4, 0, 1, 2)
                else:
                    dw = dw.transpose(4, 3, 0, 1, 2)
            else:
                # OHWI -> OIHW
                dw = dw.transpose(4, 0, 1, 2, 3)
            test_case.assertAllClose(dw, dw_ref, atol=1e-4)
traveller59's avatar
traveller59 committed
461

yan.yan's avatar
yan.yan committed
462
463
def test_spmaxpool3d():
    test_case = TestCase()
traveller59's avatar
traveller59 committed
464

yan.yan's avatar
yan.yan committed
465
    np.random.seed(485)
466
    devices = ["cuda:0"]
yan.yan's avatar
yan.yan committed
467
468
    shapes = [[19, 18, 17]]
    batchsizes = [1, 2]
469

yan.yan's avatar
yan.yan committed
470
    in_channels = [64]
471
    out_channels = [64]
yan.yan's avatar
yan.yan committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    ksizes = [2, 3]
    strides = [1, 2, 3]
    paddings = [0, 1]
    dilations = [1, 2, 3]
    # ksizes = [2]
    # strides = [2]
    # paddings = [0]
    # dilations = [1]
    algos = [
        ConvAlgo.Native, ConvAlgo.MaskImplicitGemm,
        ConvAlgo.MaskSplitImplicitGemm
    ]


    for dev, shape, bs, IC, OC, k, s, p, d, al in params_grid(
487
            devices, shapes, batchsizes, in_channels, out_channels, ksizes,
yan.yan's avatar
yan.yan committed
488
            strides, paddings, dilations, algos):
489
        if all([s > 1, d > 1]):
yan.yan's avatar
yan.yan committed
490
            continue  # don't support this.
491
        device = torch.device(dev)
yan.yan's avatar
yan.yan committed
492
        num_points = [1000] * bs
493

yan.yan's avatar
yan.yan committed
494
495
496
497
498
        # when data contains negative, sparse maxpool is not equal to dense maxpool.
        sparse_dict = generate_sparse_data(shape,
                                            num_points,
                                            IC,
                                            data_range=[0.1, 1])
499
500
501
502
503
504

        features = np.ascontiguousarray(sparse_dict["features"]).astype(
            np.float32)
        indices = np.ascontiguousarray(
            sparse_dict["indices"][:, [3, 0, 1, 2]]).astype(np.int32)
        features_dense = sparse_dict["features_dense"].astype(np.float32)
yan.yan's avatar
yan.yan committed
505
506
507
508
509
510
511
        indices_t = torch.from_numpy(indices).int().to(device)
        features_t = torch.from_numpy(features).to(device)
        features_t.requires_grad = True
        features_dense_t = torch.from_numpy(features_dense).to(device)
        features_dense_t.requires_grad = True
        net = SparseMaxPoolTestTorch(1, 3, shape, k, s, p, d, al).to(device)
        net_ref = MaxPool3dTestTorch(1, 3, shape, k, s, p, d).to(device)
512
513
514

        out_ref = net_ref(features_dense_t)
        out = net(features_t, indices_t, bs)
yan.yan's avatar
yan.yan committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542

        outids = out.indices
        outfeatures = out.features
        outids_dev = outids.float()
        out_dense = out.dense(channels_first=False)
        out = out_dense.permute(0, 4, 1, 2, 3).contiguous()
        out_np = out.detach().cpu().numpy()
        out_ref_np = out_ref.detach().cpu().numpy()
        test_case.assertAllClose(out_np, out_ref_np, atol=1e-4)

        dout_sparse = np.random.uniform(
            -0.2, 0.2, outfeatures.shape).astype(features.dtype)
        dout_sparse_t = torch.from_numpy(dout_sparse).to(device)
        dout_t = scatter_nd(outids.long(), dout_sparse_t,
                            list(out_dense.shape))
        dout_t = dout_t.permute(0, 4, 1, 2, 3).contiguous()
        out.backward(dout_t)
        out_ref.backward(dout_t)
        din_dense = features_dense_t.grad.detach().permute(0, 2, 3, 4,
                                                            1).contiguous()
        din_sparse = gather_nd(din_dense, indices_t.long())
        din = features_t.grad.detach()

        din_np = din.cpu().numpy()
        din_sparse_np = din_sparse.cpu().numpy()
        test_case.assertAllClose(din_np, din_sparse_np, atol=1e-4)


543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
def test_spglobalmaxpool3d():
    test_case = TestCase()

    np.random.seed(485)
    devices = ["cpu:0", "cuda:0"]
    shapes = [[19, 18, 17]]
    batchsizes = [1, 2]

    channels = [64]
    # ksizes = [2]
    # strides = [2]
    # paddings = [0]
    # dilations = [1]


    for dev, shape, bs, C in params_grid(
            devices, shapes, batchsizes, channels):
        device = torch.device(dev)
        num_points = [1000] * bs
        # when data contains negative, sparse maxpool is not equal to dense maxpool.
        sparse_dict = generate_sparse_data(shape,
                                            num_points,
                                            C,
                                            data_range=[0.1, 0.4])

        features = np.ascontiguousarray(sparse_dict["features"]).astype(
            np.float32)
        indices = np.ascontiguousarray(
            sparse_dict["indices"][:, [3, 0, 1, 2]]).astype(np.int32)
        features_dense = sparse_dict["features_dense"].astype(np.float32)
        indices_t = torch.from_numpy(indices).int().to(device)
        features_t = torch.from_numpy(features).to(device)
        features_t.requires_grad = True
        features_dense_t = torch.from_numpy(features_dense).to(device)
        features_dense_t.requires_grad = True
        net = SparseGlobalMaxPoolTestTorch(shape).to(device)
        net_ref = MaxPool3dTestTorch(1, 3, shape, shape, shape, 0, 1).to(device)

        out_ref = net_ref(features_dense_t)
        out = net(features_t, indices_t, bs)
        out_dense = out
        out_np = out.detach().cpu().numpy()
        out_ref_np = out_ref.detach().cpu().numpy()
        test_case.assertAllClose(out_np.reshape(-1), out_ref_np.reshape(-1), atol=1e-4)

        dout = np.random.uniform(
            -0.2, 0.2, out_dense.shape).astype(features.dtype)
        dout_t = torch.from_numpy(dout).to(device).view(bs, C, 1, 1, 1)
        out.backward(dout_t.reshape(bs, C))
        out_ref.backward(dout_t)
        din_dense = features_dense_t.grad.detach().permute(0, 2, 3, 4,
                                                            1).contiguous()
        din_sparse = gather_nd(din_dense, indices_t.long())
        din = features_t.grad.detach()
        din_np = din.cpu().numpy()
        din_sparse_np = din_sparse.cpu().numpy()
        test_case.assertAllClose(din_np, din_sparse_np, atol=1e-4)
yan.yan's avatar
yan.yan committed
600
601

if __name__ == "__main__":
602
    test_spglobalmaxpool3d()