".github/vscode:/vscode.git/clone" did not exist on "edf48feb1a133e357176808ef8fd3c445b4a799f"
test_conv.py 20.6 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()

traveller59's avatar
traveller59 committed
193
194

class MaxPool3dTestTorch(nn.Module):
195
196
    def __init__(self, num_layers, ndim, shape, kernel_size, stride, padding,
                 dilation):
traveller59's avatar
traveller59 committed
197
        super().__init__()
198
        layers = [nn.MaxPool3d(kernel_size, stride, padding, dilation)]
traveller59's avatar
traveller59 committed
199
        for i in range(1, num_layers):
200
201
            layers.append(nn.MaxPool3d(kernel_size, stride, padding, dilation))
        self.net = nn.Sequential(*layers, )
traveller59's avatar
traveller59 committed
202
203
204
        self.shape = shape

    def forward(self, x):
205
        return self.net(x)  # .dense()
traveller59's avatar
traveller59 committed
206
207
208
209

def gather_nd(params, indices):
    # this function has a limit that MAX_ADVINDEX_CALC_DIMS=5
    ndim = indices.shape[-1]
210
211
    output_shape = list(indices.shape[:-1]) + list(
        params.shape[indices.shape[-1]:])
traveller59's avatar
traveller59 committed
212
213
214
215
216
    flatted_indices = indices.view(-1, ndim)
    slices = [flatted_indices[:, i] for i in range(ndim)]
    slices += [Ellipsis]
    return params[slices].view(*output_shape)

217

traveller59's avatar
traveller59 committed
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
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
233
234
235
236
237
238
239
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
240

yan.yan's avatar
yan.yan committed
241
242
243
244
245
246
247
248
249
250
    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
251
    algos = [ConvAlgo.Native, ConvAlgo.MaskImplicitGemm, ConvAlgo.MaskSplitImplicitGemm]
yan.yan's avatar
yan.yan committed
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

    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
289
            if FILTER_HWIO:
yan.yan's avatar
yan.yan committed
290
291
292
                filters = np.random.uniform(-1, 1,
                                            size=[k, k, k, IC,
                                                    OC]).astype(np.float32)
yan.yan's avatar
bug fix  
yan.yan committed
293
            else:
yan.yan's avatar
yan.yan committed
294
295
296
297
                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
298
            if FILTER_HWIO:
299
                net_ref.net[0].weight.data[:] = filters_t.permute(
yan.yan's avatar
yan.yan committed
300
                    4, 3, 0, 1, 2).contiguous()
yan.yan's avatar
bug fix  
yan.yan committed
301
            else:
302
                net_ref.net[0].weight.data[:] = filters_t.permute(
yan.yan's avatar
yan.yan committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
                    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
334
335
                if FILTER_HWIO:
                    dw = dw.transpose(4, 3, 0, 1, 2)
yan.yan's avatar
yan.yan committed
336
337
338
339
340
341
342
343
                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
344

yan.yan's avatar
yan.yan committed
345
346
def test_spdeconv3d():
    test_case = TestCase()
traveller59's avatar
traveller59 committed
347

yan.yan's avatar
yan.yan committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
    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(
366
            devices, shapes, batchsizes, in_channels, out_channels, ksizes,
yan.yan's avatar
yan.yan committed
367
            strides, paddings, dilations, algos):
traveller59's avatar
traveller59 committed
368
        if all([s > 1, d > 1]):
yan.yan's avatar
yan.yan committed
369
            continue  # don't support this.
traveller59's avatar
traveller59 committed
370
        device = torch.device(dev)
yan.yan's avatar
yan.yan committed
371
372
        num_points = [1000] * bs
        dtype = torch.float32
traveller59's avatar
traveller59 committed
373
374
375

        sparse_dict = generate_sparse_data(shape, num_points, IC)

376
377
378
379
        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
380
        features_dense = sparse_dict["features_dense"].astype(np.float32)
yan.yan's avatar
yan.yan committed
381
382
383
384
        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)
385

yan.yan's avatar
yan.yan committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
        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
417
        out_ref = net_ref(features_dense_t)
yan.yan's avatar
yan.yan committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
        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
447

yan.yan's avatar
yan.yan committed
448
449
def test_spmaxpool3d():
    test_case = TestCase()
traveller59's avatar
traveller59 committed
450

yan.yan's avatar
yan.yan committed
451
    np.random.seed(485)
452
    devices = ["cuda:0"]
yan.yan's avatar
yan.yan committed
453
454
    shapes = [[19, 18, 17]]
    batchsizes = [1, 2]
455

yan.yan's avatar
yan.yan committed
456
    in_channels = [64]
457
    out_channels = [64]
yan.yan's avatar
yan.yan committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
    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(
473
            devices, shapes, batchsizes, in_channels, out_channels, ksizes,
yan.yan's avatar
yan.yan committed
474
            strides, paddings, dilations, algos):
475
        if all([s > 1, d > 1]):
yan.yan's avatar
yan.yan committed
476
            continue  # don't support this.
477
        device = torch.device(dev)
yan.yan's avatar
yan.yan committed
478
        num_points = [1000] * bs
479

yan.yan's avatar
yan.yan committed
480
481
482
483
484
        # 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])
485
486
487
488
489
490

        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
491
492
493
494
495
496
497
        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)
498
499
500

        out_ref = net_ref(features_dense_t)
        out = net(features_t, indices_t, bs)
yan.yan's avatar
yan.yan committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530

        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)



if __name__ == "__main__":
yan.yan's avatar
yan.yan committed
531
    test_spmaxpool3d()