fuse_bn_act.py 16.6 KB
Newer Older
yan.yan's avatar
yan.yan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
# 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.

"""simple fuse
see https://pytorch.org/tutorials/intermediate/fx_conv_bn_fuser.html
"""

import time
from pathlib import Path
from typing import Any, Dict, Tuple

import numpy as np
import torch
from torch import nn
from cumm import tensorview as tv
from spconv.core import ConvAlgo
import torch.fx
import spconv.pytorch as spconv
import copy 
import pickle
from spconv.pytorch.conv import SparseConvolution
from spconv.pytorch import functional as Fsp


def fuse_bn_weights(conv_w_OKI, conv_b, bn_rm, bn_rv, bn_eps, bn_w, bn_b):
    NDim = conv_w_OKI.ndim - 2
    permute = [0, NDim+1] + [i+1 for i in range(NDim)]
    conv_w_OIK = conv_w_OKI.permute(*permute)
    # OIDHW
    if conv_b is None:
        conv_b = torch.zeros_like(bn_rm)
    if bn_w is None:
        bn_w = torch.ones_like(bn_rm)
    if bn_b is None:
        bn_b = torch.zeros_like(bn_rm)
    bn_var_rsqrt = torch.rsqrt(bn_rv + bn_eps)

    conv_w_OIK = conv_w_OIK * (bn_w * bn_var_rsqrt).reshape([-1] + [1] * (len(conv_w_OIK.shape) - 1))
    conv_b = (conv_b - bn_rm) * bn_var_rsqrt * bn_w + bn_b
    permute = [0,] + [i+2 for i in range(NDim)] + [1,]
    conv_w_OKI = conv_w_OIK.permute(*permute).contiguous()
    return torch.nn.Parameter(conv_w_OKI), torch.nn.Parameter(conv_b)

def fuse_bn(conv, bn):
    """
    Given a conv Module `A` and an batch_norm module `B`, returns a conv
    module `C` such that C(x) == B(A(x)) in inference mode.
    """
    assert(not (conv.training or bn.training)), "Fusion only for eval!"
    fused_conv = copy.deepcopy(conv)

    fused_conv.weight, fused_conv.bias = \
        fuse_bn_weights(fused_conv.weight, fused_conv.bias,
                             bn.running_mean, bn.running_var, bn.eps, bn.weight, bn.bias)

    return fused_conv

def fuse_act_net(conv, act):
    """
    Given a conv Module `A` and an batch_norm module `B`, returns a conv
    module `C` such that C(x) == B(A(x)) in inference mode.
    """
    assert(not (conv.training)), "Fusion only for eval!"
    fused_conv = copy.deepcopy(conv)
    if isinstance(act, torch.nn.ReLU):
        fused_conv.act_type = tv.gemm.Activation.ReLU
yan.yan's avatar
yan.yan committed
78
    elif isinstance(act, torch.nn.Sigmoid):
yan.yan's avatar
yan.yan committed
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
225
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
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
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
        fused_conv.act_type = tv.gemm.Activation.Sigmoid
    elif isinstance(act, torch.nn.LeakyReLU):
        fused_conv.act_type = tv.gemm.Activation.LeakyReLU
        fused_conv.act_alpha = act.negative_slope
    else:
        raise NotImplementedError
    return fused_conv

def _parent_name(target : str) -> Tuple[str, str]:
    """
    Splits a qualname into parent path and last atom.
    For example, `foo.bar.baz` -> (`foo.bar`, `baz`)
    """
    *parent, name = target.rsplit('.', 1)
    return parent[0] if parent else '', name

def replace_node_module(node: torch.fx.Node, modules: Dict[str, Any], new_module: torch.nn.Module):
    assert(isinstance(node.target, str))
    parent_name, name = _parent_name(node.target)
    setattr(modules[parent_name], name, new_module)

def fuse(model: torch.fx.GraphModule) -> torch.fx.GraphModule:
    model = copy.deepcopy(model)
    # The first step of most FX passes is to symbolically trace our model to
    # obtain a `GraphModule`. This is a representation of our original model
    # that is functionally identical to our original model, except that we now
    # also have a graph representation of our forward pass.
    fx_model = model
    modules = dict(fx_model.named_modules())
    # The primary representation for working with FX are the `Graph` and the
    # `Node`. Each `GraphModule` has a `Graph` associated with it - this
    # `Graph` is also what generates `GraphModule.code`.
    # The `Graph` itself is represented as a list of `Node` objects. Thus, to
    # iterate through all of the operations in our graph, we iterate over each
    # `Node` in our `Graph`.
    for node in fx_model.graph.nodes:
        # The FX IR contains several types of nodes, which generally represent
        # call sites to modules, functions, or methods. The type of node is
        # determined by `Node.op`.

        if node.op != 'call_module': # If our current node isn't calling a Module then we can ignore it.
            continue
        # For call sites, `Node.target` represents the module/function/method
        # that's being called. Here, we check `Node.target` to see if it's a
        # batch norm module, and then check `Node.args[0].target` to see if the
        # input `Node` is a convolution.
        # print(node.target, node.args, node.args[0].args)
        if isinstance(modules[node.target], torch.nn.BatchNorm1d):
            if node.args[0].target in modules and isinstance(modules[node.args[0].target], SparseConvolution):
                if len(node.args[0].users) > 1:  # Output of conv is used by other nodes
                    continue
                conv = modules[node.args[0].target]
                bn = modules[node.target]
                fused_conv = fuse_bn(conv, bn)
                assert isinstance(fused_conv, SparseConvolution)
                replace_node_module(node.args[0], modules, fused_conv)
                modules_to_fuse = [node.args[0].target, node.target]
                try:
                    if isinstance(modules[node.next.target], torch.nn.ReLU):
                        modules_to_fuse.append(node.next.target)
                except Exception as e:
                    pass
                # As we've folded the batch nor into the conv, we need to replace all uses
                # of the batch norm with the conv.
                node.replace_all_uses_with(node.args[0])
                # Now that all uses of the batch norm have been replaced, we can
                # safely remove the batch norm.
                fx_model.graph.erase_node(node)
                
    fx_model.graph.lint()
    # After we've modified our graph, we need to recompile our graph in order
    # to keep the generated code in sync.
    fx_model.recompile()
    return fx_model


def fuse_act(model: torch.fx.GraphModule) -> torch.fx.GraphModule:
    model = copy.deepcopy(model)
    # The first step of most FX passes is to symbolically trace our model to
    # obtain a `GraphModule`. This is a representation of our original model
    # that is functionally identical to our original model, except that we now
    # also have a graph representation of our forward pass.
    fx_model = model
    modules = dict(fx_model.named_modules())
    # The primary representation for working with FX are the `Graph` and the
    # `Node`. Each `GraphModule` has a `Graph` associated with it - this
    # `Graph` is also what generates `GraphModule.code`.
    # The `Graph` itself is represented as a list of `Node` objects. Thus, to
    # iterate through all of the operations in our graph, we iterate over each
    # `Node` in our `Graph`.
    for node in fx_model.graph.nodes:
        # The FX IR contains several types of nodes, which generally represent
        # call sites to modules, functions, or methods. The type of node is
        # determined by `Node.op`.

        if node.op != 'call_module': # If our current node isn't calling a Module then we can ignore it.
            continue
        # For call sites, `Node.target` represents the module/function/method
        # that's being called. Here, we check `Node.target` to see if it's a
        # batch norm module, and then check `Node.args[0].target` to see if the
        # input `Node` is a convolution.
        # print(node.target, node.args, node.args[0].args)
        if isinstance(modules[node.target], (torch.nn.ReLU, torch.nn.LeakyReLU, torch.nn.Sigmoid)):
            if node.args[0].target in modules and isinstance(modules[node.args[0].target], SparseConvolution):
                if len(node.args[0].users) > 1:  # Output of conv is used by other nodes
                    continue
                conv = modules[node.args[0].target]
                act = modules[node.target]
                fused_conv = fuse_act_net(conv, act)
                assert isinstance(fused_conv, SparseConvolution)
                replace_node_module(node.args[0], modules, fused_conv)
                # As we've folded the batch nor into the conv, we need to replace all uses
                # of the batch norm with the conv.
                node.replace_all_uses_with(node.args[0])
                # Now that all uses of the batch norm have been replaced, we can
                # safely remove the batch norm.
                fx_model.graph.erase_node(node)
                
    fx_model.graph.lint()
    # After we've modified our graph, we need to recompile our graph in order
    # to keep the generated code in sync.
    fx_model.recompile()
    return fx_model


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, 64, 3, bias=False, indice_key="c0",
                              algo=algo),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            spconv.SubMConv3d(64,
                              64,
                              3,
                              bias=False,
                              indice_key="c0",
                              algo=algo),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            spconv.SparseConv3d(64, 64, 2, 2, bias=False, indice_key="m0", algo=algo),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            spconv.SubMConv3d(64,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            nn.BatchNorm1d(96),
            nn.ReLU(),

            spconv.SubMConv3d(96,
                              96,
                              3,
                              bias=False,
                              indice_key="c1",
                              algo=algo),
            nn.BatchNorm1d(96),
            nn.ReLU(),
            spconv.SparseConv3d(96, 96, 2, 2, bias=False, indice_key="m1", algo=algo),
            nn.BatchNorm1d(96),
            nn.ReLU(),

            spconv.SubMConv3d(96,
                              128,
                              3,
                              bias=False,
                              indice_key="c2",
                              algo=algo),
            nn.BatchNorm1d(128),
            nn.ReLU(),
            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", algo=algo),
            nn.BatchNorm1d(128),
            nn.ReLU(),

            spconv.SubMConv3d(128,
                              160,
                              3,
                              bias=False,
                              indice_key="c3",
                              algo=algo),
            nn.BatchNorm1d(160),
            nn.ReLU(),
            spconv.SubMConv3d(160,
                              160,
                              3,
                              bias=False,
                              indice_key="c3",
                              algo=algo),
            nn.BatchNorm1d(160),
            nn.ReLU(),
            spconv.SparseConv3d(160, 160, 2, 2, bias=False, indice_key="m3", algo=algo),
            nn.BatchNorm1d(160),
            nn.ReLU(),

            spconv.SubMConv3d(160,
                              192,
                              3,
                              bias=False,
                              indice_key="c4",
                              algo=algo),
            nn.BatchNorm1d(192),
            nn.ReLU(),

            spconv.SubMConv3d(192,
                              192,
                              3,
                              bias=False,
                              indice_key="c4",
                              algo=algo),
            nn.BatchNorm1d(192),
            nn.ReLU(),
            spconv.SparseConv3d(192, 192, 2, 2, bias=False, indice_key="m4", algo=algo),
            nn.BatchNorm1d(192),
            nn.ReLU(),

            spconv.SubMConv3d(192,
                              224,
                              3,
                              bias=False,
                              indice_key="c5",
                              algo=algo),
            nn.BatchNorm1d(224),
            nn.ReLU(),

            spconv.SubMConv3d(224,
                              224,
                              3,
                              bias=False,
                              indice_key="c5",
                              algo=algo),
            nn.BatchNorm1d(224),
            nn.ReLU(),
            spconv.SparseConv3d(224, 224, 2, 2, bias=False, indice_key="m5", algo=algo),
            nn.BatchNorm1d(224),
            nn.ReLU(),

            spconv.SubMConv3d(224,
                              256,
                              3,
                              bias=False,
                              indice_key="c6",
                              algo=algo),
            nn.BatchNorm1d(256),
            nn.ReLU(),

            spconv.SubMConv3d(256,
                              256,
                              3,
                              bias=False,
                              indice_key="c6",
                              algo=algo),
            nn.BatchNorm1d(256),
            nn.ReLU(),

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

        )
        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
        for n in self.net.modules():
            if isinstance(n, nn.BatchNorm1d):
                n.bias.data.uniform_(-0.1, 0.1)

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



class MyTracer(torch.fx.Tracer):
    def is_leaf_module(self, m: torch.nn.Module, module_qualified_name):
        is_custom_leaf_module = isinstance(m, SparseConvolution)
        return super().is_leaf_module(m, module_qualified_name) or is_custom_leaf_module

def main():
    # run this file with SPCONV_FX_TRACE_MODE=1
    torch.manual_seed(50051)
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False
yan.yan's avatar
yan.yan committed
388
    with open(Path(__file__).parent.parent / "test" / "data" / "test_spconv.pkl", "rb") as f:
yan.yan's avatar
yan.yan committed
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
        (voxels, coors, spatial_shape) = pickle.load(f)
    np.random.seed(50051)
    device = torch.device("cuda:0")
    device_cpu = torch.device("cpu:0")
    dtype = torch.float32
    net = Net(spatial_shape, ConvAlgo.MaskImplicitGemm).cuda().eval().to(dtype)
    tracer = MyTracer()
    graph_trace = tracer.trace(net)
    net_fused = torch.fx.GraphModule(tracer.root, graph_trace)
    net_fused = fuse(net_fused)
    net_fused = fuse_act(net_fused)
    print(net_fused)
    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()

    out_ref = net(voxels_th_cuda, coors_th_cuda, 1)
    print("-------------fused------------")
    out_fused = net_fused(voxels_th_cuda, coors_th_cuda, 1)
    res = Fsp.sparse_add_hash_based(out_ref, out_fused.minus())
    print(torch.linalg.norm(res.features))

if __name__ == "__main__":
    main()