test_multi_impl.py 13 KB
Newer Older
yan.yan's avatar
yan.yan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2021 Yan Yan
# 
# 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.

yan.yan's avatar
yan.yan committed
15
16
"""Compare results between different algos:
CPU: simple gather-mm-scatter
yan.yan's avatar
yan.yan committed
17
Native: Fused gather-mm-scatter
yan.yan's avatar
yan.yan committed
18
ImplicitGemm: implicit gemm
yan.yan's avatar
yan.yan committed
19
20
"""

yan.yan's avatar
yan.yan committed
21
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
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
99
100
101
102
103
104
105
106
107
108
109
110
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
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
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
import time
from pathlib import Path

import numpy as np
import torch
from torch import nn
from cumm import tensorview as tv
from spconv.core import ConvAlgo

import spconv.pytorch as spconv
import pickle
from spconv.test_utils import generate_sparse_data, params_grid


class Net(nn.Module):
    def __init__(self, shape, algo):
        super().__init__()
        pool_algo = algo
        # pool_algo = ConvAlgo.Native
        self.net = spconv.SparseSequential(
            spconv.SubMConv3d(3, 32, 3, bias=False, indice_key="c0",
                              algo=algo),
            spconv.SubMConv3d(32,
                              32,
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
            # # nn.BatchNorm1d(32),
            # # nn.ReLU(),
            spconv.SubMConv3d(32, 64, 3, bias=False, indice_key="c0",
                              algo=algo),
            spconv.SubMConv3d(64,
                              64,
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
            # nn.BatchNorm1d(32),
            # # nn.ReLU(),
            spconv.SparseConv3d(64, 64, 3, 2, 1, bias=False, indice_key="m0", algo=algo),
            # # spconv.SparseMaxPool3d(2, 2, algo=pool_algo),
            spconv.SubMConv3d(64,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            spconv.SubMConv3d(96,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            # nn.BatchNorm1d(64),
            # nn.ReLU(),
            spconv.SparseConv3d(96, 96, 2, 2, bias=False, indice_key="m1", algo=algo),
            # spconv.SparseMaxPool3d(2, 2, algo=pool_algo),
            spconv.SubMConv3d(96,
                              128,
                              3,
                              bias=False,
                              indice_key="c2",
                              algo=algo),
            spconv.SubMConv3d(128,
                              128,
                              3,
                              bias=False,
                              indice_key="c2",
                              algo=algo),
            # nn.BatchNorm1d(128),
            # nn.ReLU(),
            # spconv.SparseConv3d(128, 128, 2, 2, bias=False, indice_key="m2"),
            spconv.SparseMaxPool3d(2, 2, algo=pool_algo),
            spconv.SubMConv3d(128,
                              160,
                              3,
                              bias=False,
                              indice_key="c3",
                              algo=algo),
            spconv.SubMConv3d(160,
                              160,
                              3,
                              bias=False,
                              indice_key="c3",
                              algo=algo),
            # nn.BatchNorm1d(128),
            # nn.ReLU(),
            # spconv.SparseConv3d(160, 160, 2, 2, bias=False, indice_key="m3"),
            spconv.SparseMaxPool3d(2, 2, algo=pool_algo, indice_key="m3"),
            spconv.SubMConv3d(160,
                              192,
                              3,
                              bias=False,
                              indice_key="c4",
                              algo=algo),
            spconv.SubMConv3d(192,
                              192,
                              3,
                              bias=False,
                              indice_key="c4",
                              algo=algo),
            # nn.BatchNorm1d(128),
            # nn.ReLU(),
            spconv.SparseMaxPool3d(2, 2, indice_key="m4", algo=pool_algo),
            # spconv.SparseConv3d(192, 192, 2, 2, bias=False, indice_key="m4"),
            spconv.SubMConv3d(192,
                              224,
                              3,
                              bias=False,
                              indice_key="c5",
                              algo=algo),
            spconv.SubMConv3d(224,
                              224,
                              3,
                              bias=False,
                              indice_key="c5",
                              algo=algo),
            # nn.BatchNorm1d(256),
            # nn.ReLU(),

            spconv.SparseInverseConv3d(224, 128, 2, indice_key="m4", bias=False, algo=algo),
            # # nn.BatchNorm1d(128),
            # nn.ReLU(),

            spconv.SparseInverseConv3d(128, 64, 2, indice_key="m3", bias=False, algo=algo),
        )
        max_batch_size = 1
        # grid (dense map) is used for indice generation. use pre-allocated grid can run faster.
        # self.grid = None
        self.shape = shape

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

class NetLight(nn.Module):
    def __init__(self, shape, algo):
        super().__init__()
        pool_algo = algo
        # pool_algo = ConvAlgo.Native
        self.net = spconv.SparseSequential(
            spconv.SubMConv3d(3, 32, 3, bias=False, indice_key="c0",
                              algo=algo),
            spconv.SubMConv3d(32,
                              32,
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
            # # nn.BatchNorm1d(32),
            # # nn.ReLU(),
            spconv.SubMConv3d(32, 64, 3, bias=False, indice_key="c0",
                              algo=algo),
            spconv.SubMConv3d(64,
                              64,
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
            # nn.BatchNorm1d(32),
            # # nn.ReLU(),
            spconv.SparseConv3d(64, 64, 3, 2, 1, bias=False, indice_key="m0", algo=algo),
            # # spconv.SparseMaxPool3d(2, 2, algo=pool_algo),
            spconv.SubMConv3d(64,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            spconv.SubMConv3d(96,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            # nn.BatchNorm1d(64),
            # nn.ReLU(),
            spconv.SparseConv3d(96, 96, 2, 2, bias=False, indice_key="m1", algo=algo),
            # spconv.SparseMaxPool3d(2, 2, algo=pool_algo),

            spconv.SparseInverseConv3d(96, 64, 2, indice_key="m1", bias=False, algo=algo),
            # # nn.BatchNorm1d(128),
            # nn.ReLU(),

            spconv.SparseInverseConv3d(64, 32, 3, indice_key="m0", bias=False, algo=algo),
        )
        max_batch_size = 1
        # grid (dense map) is used for indice generation. use pre-allocated grid can run faster.
        # self.grid = None
        self.shape = shape

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


def _test_multi_impl(dtype: torch.dtype):
yan.yan's avatar
yan.yan committed
225
    # TODO pytorch 1.12 don't support cpu half mm, f**k pytorch
yan.yan's avatar
yan.yan committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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
    # TODO remove or release this when tf32 op is ready
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False

    np.random.seed(50051)
    if dtype != torch.float16:
        with open(Path(__file__).parent / "data" / "test_spconv.pkl", "rb") as f:
            (voxels, coors, spatial_shape) = pickle.load(f)
    else:
        # CPU fp16 is very slow, so we use a small data here.
        spatial_shape = [19, 18, 17]
        sparse_dict = generate_sparse_data(spatial_shape, [1500] * 1, 3)

        voxels = np.ascontiguousarray(sparse_dict["features"]).astype(
            np.float32)
        coors = np.ascontiguousarray(
            sparse_dict["indices"][:, [3, 0, 1, 2]]).astype(np.int32)
    device = torch.device("cuda:0")
    device_cpu = torch.device("cpu:0")

    voxels_th = torch.from_numpy(voxels).to(device_cpu).to(dtype)
    coors_th = torch.from_numpy(coors).to(device_cpu).int()
    voxels_th_cuda = torch.from_numpy(voxels).to(device).to(dtype)
    coors_th_cuda = torch.from_numpy(coors).to(device).int()
    net_cls = Net
    if dtype == torch.float16:
        # CPU fp16 is very slow, so we use a small network here.
        net_cls = NetLight
    # cpu 
    torch.manual_seed(50051)
    net_native_cpu = net_cls(spatial_shape, ConvAlgo.Native).to(device_cpu).to(dtype)
    # gpu_native 
    torch.manual_seed(50051)
    net_native_gpu = net_cls(spatial_shape, ConvAlgo.Native).to(device).to(dtype)
    
    torch.manual_seed(50051)
    net_imp_gpu = net_cls(spatial_shape, ConvAlgo.MaskImplicitGemm).to(device).to(dtype)
    
    torch.manual_seed(50051)
    net_simp_gpu = net_cls(spatial_shape, ConvAlgo.MaskSplitImplicitGemm).to(device).to(dtype)

    spconv.assign_name_for_sparse_modules(net_native_cpu)
    spconv.assign_name_for_sparse_modules(net_native_gpu)
    spconv.assign_name_for_sparse_modules(net_imp_gpu)
    spconv.assign_name_for_sparse_modules(net_simp_gpu)
    with torch.no_grad():
        out: torch.Tensor = net_native_cpu(voxels_th, coors_th, 1).dense()
    dout = np.random.uniform(-0.2, 0.2, out.shape).astype(np.float32)
    dout_t = torch.from_numpy(dout).to(device_cpu).to(dtype)
    dout_t_cu = torch.from_numpy(dout).to(device).to(dtype)

yan.yan's avatar
yan.yan committed
277
278
    t = time.time()
    print(1, time.time() - t)
yan.yan's avatar
yan.yan committed
279
    out_cpu = net_native_cpu(voxels_th, coors_th, 1).dense()
yan.yan's avatar
yan.yan committed
280
281
    if dtype != torch.float16:
        out_cpu.backward(dout_t)
yan.yan's avatar
yan.yan committed
282
    out = net_native_gpu(voxels_th_cuda, coors_th_cuda, 1).dense()
yan.yan's avatar
yan.yan committed
283
    print(2, time.time() - t)
yan.yan's avatar
yan.yan committed
284
285
286

    out.backward(dout_t_cu)
    out_imp = net_imp_gpu(voxels_th_cuda, coors_th_cuda, 1).dense()
yan.yan's avatar
yan.yan committed
287
    print(3, time.time() - t)
yan.yan's avatar
yan.yan committed
288
289
290

    out_imp.backward(dout_t_cu)
    out_simp = net_simp_gpu(voxels_th_cuda, coors_th_cuda, 1).dense()
yan.yan's avatar
yan.yan committed
291
    print(4, time.time() - t)
yan.yan's avatar
yan.yan committed
292
293
294
295
296
297
298
299
300
301
302

    out_simp.backward(dout_t_cu)
    with torch.no_grad():
        dense_cpu = out_cpu.cuda()
        dense_native = out
        dense_imp = out_imp
        dense_simp = out_simp

        error_native = torch.linalg.norm(dense_cpu - dense_native).cpu().item()
        error_imp = torch.linalg.norm(dense_cpu - dense_imp).cpu().item()
        error_simp = torch.linalg.norm(dense_cpu - dense_simp).cpu().item()
yan.yan's avatar
yan.yan committed
303
    print(5, time.time() - t)
yan.yan's avatar
yan.yan committed
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

    print("error_native", error_native)
    print("error_imp", error_imp)
    print("error_simp", error_simp)
    if dtype == torch.float32:
        assert error_native < 0.01
        assert error_imp < 0.01
        assert error_simp < 0.01
    else:
        assert error_native < 10
        assert error_imp < 10
        assert error_simp < 10


    cpu_params = dict(net_native_cpu.named_parameters())
    native_params = dict(net_native_gpu.named_parameters())
    imp_params = dict(net_imp_gpu.named_parameters())
    simp_params = dict(net_simp_gpu.named_parameters())

    for k, cpu_w in cpu_params.items():
        native_w = native_params[k]
        imp_w = imp_params[k]
        simp_w = simp_params[k]
        native_w_grad = native_w.grad.detach()
        imp_w_grad = imp_w.grad.detach()
        simp_w_grad = simp_w.grad.detach()
yan.yan's avatar
yan.yan committed
330
331
332
        if dtype != torch.float16:
            cpu_w_grad = cpu_w.grad.detach().cuda()
            error_native = torch.linalg.norm(native_w_grad - cpu_w_grad).cpu().item()
yan.yan's avatar
yan.yan committed
333
334
        error_imp = torch.linalg.norm(native_w_grad - imp_w_grad).cpu().item()
        error_simp = torch.linalg.norm(native_w_grad - simp_w_grad).cpu().item()
yan.yan's avatar
yan.yan committed
335
        print(k, error_imp, error_simp)
yan.yan's avatar
yan.yan committed
336
337
338
339
340
341
342
343
344
345
        assert error_imp < 1
        assert error_simp < 1

def test_multi_impl():
    _test_multi_impl(torch.float32)
    _test_multi_impl(torch.float16)


if __name__ == "__main__":
    test_multi_impl()