benchmark.py 11 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.

yanyan's avatar
yanyan committed
15
16
17
18
19
import time
from pathlib import Path

import numpy as np
import torch
yanyan's avatar
yanyan committed
20
from torch import nn
yan.yan's avatar
yan.yan committed
21
from cumm import tensorview as tv 
yanyan's avatar
yanyan committed
22

yan.yan's avatar
yan.yan committed
23
24
import spconv.pytorch as spconv
from spconv.utils import Point2VoxelCPU3d
yanyan's avatar
yanyan committed
25
def waymo_data(batch_size=1):
yan.yan's avatar
yan.yan committed
26
27
28
29
    gen = Point2VoxelCPU3d([0.1, 0.1, 0.1], [-80, -80, -2, 80, 80, 6], 3,
                           150000, 1)
    # gen = VoxelGeneratorV2([0.1, 0.1, 0.1], [-80, -80, -2, 80, 80, 6], 1,
    #                        150000)
yanyan's avatar
yanyan committed
30
    data = np.load(Path(__file__).parent / "data" / "benchmark-pc.npz")
yan.yan's avatar
yan.yan committed
31
32
33
34
35
    pc = np.ascontiguousarray(data["pc"])
    print(pc.shape)
    voxels_tv, indices_tv, _ = gen.point_to_voxel(tv.from_numpy(pc))
    voxels = voxels_tv.numpy().reshape(-1, 3)
    coors = indices_tv.numpy()
yanyan's avatar
yanyan committed
36
37
38
39
    N = coors.shape[0]
    coors = np.concatenate([np.full([N, 1], 0, coors.dtype), coors], axis=1)
    return voxels, coors, gen.grid_size

yanyan's avatar
yanyan committed
40

yanyan's avatar
yanyan committed
41
class Net(nn.Module):
yanyan's avatar
yanyan committed
42
    def __init__(self, shape, algo):
yanyan's avatar
yanyan committed
43
44
        super().__init__()
        self.net = spconv.SparseSequential(
yanyan's avatar
yanyan committed
45
46
            spconv.SubMConv3d(3, 64, 3, bias=False, indice_key="c0",
                              algo=algo),
yan.yan's avatar
yan.yan committed
47
48
49
50
51
52
53
54
55
56
57
58
            # spconv.SubMConv3d(32,
            #                   32,
            #                   3,
            #                   bias=False,
            #                   indice_key="c0",
            #                   algo=algo),
            # # nn.BatchNorm1d(32),
            # # nn.ReLU(),
            # # spconv.SparseConv3d(64, 64, 2, 2, bias=False,
            # #                   algo=algo),
            # spconv.SubMConv3d(32, 64, 3, bias=False, indice_key="c0",
            #                   algo=algo),
yanyan's avatar
yanyan committed
59
60
61
62
63
64
            spconv.SubMConv3d(64,
                              64,
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
65
66
67
            # nn.BatchNorm1d(32),
            # nn.ReLU(),
            spconv.SparseConv3d(64, 64, 2, 2, bias=False, indice_key="m0"),
yan.yan's avatar
yan.yan committed
68

69
            # spconv.SparseMaxPool3d(2, 2),
yanyan's avatar
yanyan committed
70
71
72
73
74
75
76
77
78
79
80
81
            spconv.SubMConv3d(64,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            spconv.SubMConv3d(96,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
yanyan's avatar
yanyan committed
82
83
            # nn.BatchNorm1d(64),
            # nn.ReLU(),
84
85
86
            spconv.SparseConv3d(96, 96, 2, 2, bias=False, indice_key="m1"),

            # spconv.SparseMaxPool3d(2, 2),
yanyan's avatar
yanyan committed
87
88
89
90
91
92
93
94
95
96
97
98
            spconv.SubMConv3d(96,
                              128,
                              3,
                              bias=False,
                              indice_key="c2",
                              algo=algo),
            spconv.SubMConv3d(128,
                              128,
                              3,
                              bias=False,
                              indice_key="c2",
                              algo=algo),
yanyan's avatar
yanyan committed
99
100
            # nn.BatchNorm1d(128),
            # nn.ReLU(),
101
102
103
            spconv.SparseConv3d(128, 128, 2, 2, bias=False, indice_key="m2"),

            # spconv.SparseMaxPool3d(2, 2),
yanyan's avatar
yanyan committed
104
105
106
107
108
109
110
111
112
113
114
115
            spconv.SubMConv3d(128,
                              160,
                              3,
                              bias=False,
                              indice_key="c3",
                              algo=algo),
            spconv.SubMConv3d(160,
                              160,
                              3,
                              bias=False,
                              indice_key="c3",
                              algo=algo),
yanyan's avatar
yanyan committed
116
117
            # nn.BatchNorm1d(128),
            # nn.ReLU(),
118
119
120
            spconv.SparseConv3d(160, 160, 2, 2, bias=False, indice_key="m3"),

            # spconv.SparseMaxPool3d(2, 2),
yanyan's avatar
yanyan committed
121
122
123
124
125
126
127
128
129
130
131
132
            spconv.SubMConv3d(160,
                              192,
                              3,
                              bias=False,
                              indice_key="c4",
                              algo=algo),
            spconv.SubMConv3d(192,
                              192,
                              3,
                              bias=False,
                              indice_key="c4",
                              algo=algo),
yanyan's avatar
yanyan committed
133
134
            # nn.BatchNorm1d(128),
            # nn.ReLU(),
135
136
137
            # spconv.SparseMaxPool3d(2, 2, indice_key="m4"),
            spconv.SparseConv3d(192, 192, 2, 2, bias=False, indice_key="m4"),

yanyan's avatar
yanyan committed
138
139
140
141
142
143
144
145
146
147
148
149
            spconv.SubMConv3d(192,
                              224,
                              3,
                              bias=False,
                              indice_key="c5",
                              algo=algo),
            spconv.SubMConv3d(224,
                              224,
                              3,
                              bias=False,
                              indice_key="c5",
                              algo=algo),
150
151
152
153
            nn.BatchNorm1d(224),
            nn.ReLU(),
            spconv.SparseConv3d(224, 224, 2, 2, bias=False, indice_key="m5"),
            # spconv.SparseMaxPool3d(2, 2, indice_key="m5"),
yanyan's avatar
yanyan committed
154
155
156
157
158
159
160
161
162
163
164
165
            spconv.SubMConv3d(224,
                              256,
                              3,
                              bias=False,
                              indice_key="c6",
                              algo=algo),
            spconv.SubMConv3d(256,
                              256,
                              3,
                              bias=False,
                              indice_key="c6",
                              algo=algo),
166
167
168
169
170
171
172
173
174

            nn.BatchNorm1d(256),
            nn.ReLU(),

            spconv.SparseInverseConv3d(256, 128, 2, indice_key="m5", bias=False),
            nn.BatchNorm1d(128),
            nn.ReLU(),

            spconv.SparseInverseConv3d(128, 64, 2, indice_key="m4", bias=False),
yan.yan's avatar
yan.yan committed
175

yanyan's avatar
yanyan committed
176
177
        )
        max_batch_size = 1
yanyan's avatar
yanyan committed
178
        # grid (dense map) is used for indice generation. use pre-allocated grid can run faster.
yanyan's avatar
yanyan committed
179
180
        self.grid = torch.full([max_batch_size, *shape], -1,
                               dtype=torch.int32).cuda()
yanyan's avatar
yanyan committed
181
182
183
184
185
186
187
188
        # self.grid = None
        self.shape = shape

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

yan.yan's avatar
yan.yan committed
189
190
191
192
class Net2(nn.Module):
    def __init__(self, shape, algo):
        super().__init__()
        self.net = spconv.SparseSequential(
193
            spconv.SubMConv3d(3, 128, 3, bias=False, indice_key="c0",
yan.yan's avatar
yan.yan committed
194
195
196
197
198
199
200
201
202
203
204
205
206
                              algo=algo),
            # spconv.SubMConv3d(32,
            #                   32,
            #                   3,
            #                   bias=False,
            #                   indice_key="c0",
            #                   algo=algo),
            # # nn.BatchNorm1d(32),
            # # nn.ReLU(),
            # # spconv.SparseConv3d(64, 64, 2, 2, bias=False,
            # #                   algo=algo),
            # spconv.SubMConv3d(32, 64, 3, bias=False, indice_key="c0",
            #                   algo=algo),
207
208
            spconv.SubMConv3d(128,
                              128,
yan.yan's avatar
yan.yan committed
209
210
211
212
213
214
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
            # nn.BatchNorm1d(32),
            # nn.ReLU(),
215
216
217
218
219
220
221
222
223
224
225
226
227
            # spconv.SparseMaxPool3d(2, 2),
            # spconv.SubMConv3d(256,
            #                   512,
            #                   3,
            #                   bias=False,
            #                   indice_key="c1",
            #                   algo=algo),
            # spconv.SubMConv3d(512,
            #                   512,
            #                   3,
            #                   bias=False,
            #                   indice_key="c1",
            #                   algo=algo),
yan.yan's avatar
yan.yan committed
228
229
230
231
232
233
234
235
236
237
238
239
240
        )
        max_batch_size = 1
        # grid (dense map) is used for indice generation. use pre-allocated grid can run faster.
        self.grid = torch.full([max_batch_size, *shape], -1,
                               dtype=torch.int32).cuda()
        # self.grid = None
        self.shape = shape

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

yanyan's avatar
yanyan committed
241
242

def main():
yan.yan's avatar
yan.yan committed
243
244
245
246
247
248
    import pickle 
    np.random.seed(50051)
    torch.manual_seed(50051)
    # voxels, coors, spatial_shape = waymo_data()
    # with open("/home/yy/test_spconv.pkl", "wb") as f:
    #     pickle.dump((voxels, coors, spatial_shape), f)
yan.yan's avatar
bug fix  
yan.yan committed
249
    with open(Path(__file__).parent / "data" / "test_spconv.pkl", "rb") as f:
yan.yan's avatar
yan.yan committed
250
251
252
253
254
        (voxels, coors, spatial_shape) = pickle.load(f)
    print(spatial_shape)
    print(voxels.shape)
    # voxels = voxels[:100]
    # coors = coors[:100]
yan.yan's avatar
bug fix  
yan.yan committed
255
256
257
    dtype = torch.float32

    voxels_th = torch.from_numpy(voxels).cuda().to(dtype)
yanyan's avatar
yanyan committed
258
    coors_th = torch.from_numpy(coors).cuda().int()
yan.yan's avatar
yan.yan committed
259
    voxels_th.requires_grad = True
yanyan's avatar
yanyan committed
260
    algo = spconv.ConvAlgo.Native
yan.yan's avatar
bug fix  
yan.yan committed
261
    net = Net(spatial_shape, algo).cuda().eval().to(dtype)
yanyan's avatar
yanyan committed
262
263
264
    print(coors_th.shape)
    out = net(voxels_th, coors_th, 1)
    print(out.spatial_shape)
yan.yan's avatar
yan.yan committed
265
266
267
    print(voxels.mean(),  voxels.max(), voxels.min())
    dout = np.random.uniform(-0.2, 0.2,
                                out.features.shape).astype(np.float32)
yan.yan's avatar
bug fix  
yan.yan committed
268
    dout_t = torch.from_numpy(dout).cuda().to(dtype)
yan.yan's avatar
yan.yan committed
269
270

    print(out.spatial_shape, out.features.mean(),  out.features.max(),  out.features.min())
271
272
273
274
275
276
277
278
279
280
    # times = []
    # with torch.no_grad():
    #     for i in range(20):
    #         print("------------")
    #         torch.cuda.synchronize()
    #         t = time.time()
    #         out_nograd = net(voxels_th, coors_th, 1)
    #         torch.cuda.synchronize()
    #         times.append(time.time() - t)
    # print("spconv time", np.mean(times[10:]))
yan.yan's avatar
yan.yan committed
281
282
    times = []

283
    for i in range(1):
yan.yan's avatar
yan.yan committed
284
285
286
287
288
289
290
291
        out = net(voxels_th, coors_th, 1)
        print("------------")
        torch.cuda.synchronize()
        t = time.time()
        out.features.backward(dout_t)
        torch.cuda.synchronize()
        times.append(time.time() - t)

292
293
294
    # # print((net.grid == -1).float().sum(), net.grid.numel())
    # # print("spconv time", time.time() - t)
    # print("spconv bw time", np.mean(times[5:]))
yanyan's avatar
yanyan committed
295

yanyan's avatar
yanyan committed
296

yanyan's avatar
yanyan committed
297
if __name__ == "__main__":
yanyan's avatar
yanyan committed
298
    main()