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

yanyan's avatar
yanyan committed
15
from __future__ import print_function
yan.yan's avatar
yan.yan committed
16

yanyan's avatar
yanyan committed
17
import argparse
yan.yan's avatar
yan.yan committed
18
19
20
21
import contextlib
import copy
from typing import Dict, Optional

yanyan's avatar
yanyan committed
22
import torch
yan.yan's avatar
yan.yan committed
23
24
25
26
import torch.ao.quantization
import torch.ao.quantization.quantize_fx as qfx
import torch.cuda.amp
import torch.fx
yanyan's avatar
yanyan committed
27
28
29
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
yan.yan's avatar
yan.yan committed
30
31
32
33
from torch.ao.quantization import (DeQuantStub, QuantStub,
                                   get_default_qconfig_mapping)
from torch.ao.quantization.fx._lower_to_native_backend import \
    STATIC_LOWER_FUSED_MODULE_MAP, STATIC_LOWER_MODULE_MAP
yanyan's avatar
yanyan committed
34
from torch.optim.lr_scheduler import StepLR
yan.yan's avatar
yan.yan committed
35
36
37
from torchvision import datasets, transforms

import spconv.pytorch as spconv
yan.yan's avatar
yan.yan committed
38
39
import spconv.pytorch.quantization as spconvq
from spconv.pytorch.quantization import get_default_spconv_trt_ptq_qconfig
yan.yan's avatar
yan.yan committed
40
41
42
43
44
45
46
from spconv.pytorch.quantization.backend_cfg import \
    SPCONV_STATIC_LOWER_FUSED_MODULE_MAP, SPCONV_STATIC_LOWER_MODULE_MAP
from spconv.pytorch.quantization.core import quantize_per_tensor
from spconv.pytorch.quantization.fake_q import \
    get_default_spconv_qconfig_mapping
from spconv.pytorch.quantization.intrinsic.modules import SpconvBnAddReLUNd, SpconvAddReLUNd
import spconv.pytorch.quantization.intrinsic.quantized as snniq
yan.yan's avatar
v2.1  
yan.yan committed
47
48
49

@contextlib.contextmanager
def identity_ctx():
50
    yield
yanyan's avatar
yanyan committed
51

yan.yan's avatar
yan.yan committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
class SubMConvBNReLU(spconv.SparseSequential):
    def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
        padding = (kernel_size - 1) // 2
        super(SubMConvBNReLU, self).__init__(
            spconv.SubMConv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),
            nn.BatchNorm1d(out_planes, momentum=0.1),
            # Replace with ReLU
            nn.ReLU(inplace=False)
        )

class SparseConvBNReLU(spconv.SparseSequential):
    def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1):
        padding = (kernel_size - 1) // 2
        super(SparseConvBNReLU, self).__init__(
            spconv.SparseConv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False),
            nn.BatchNorm1d(out_planes, momentum=0.1),
            # Replace with ReLU
            nn.ReLU(inplace=False)
        )
yanyan's avatar
yanyan committed
71

yan.yan's avatar
yan.yan committed
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
class SparseBasicBlock(spconv.SparseModule):
    """residual block that supported by spconv quantization.
    """
    expansion = 1
    def __init__(self,
                 in_planes, out_planes,
                 stride=1,
                 downsample=None):
        spconv.SparseModule.__init__(self)
        conv1 = spconv.SubMConv2d(in_planes, out_planes, 3, stride, 1, bias=False)
        conv2 = spconv.SubMConv2d(out_planes, out_planes, 3, stride, 1, bias=False)

        norm1 = nn.BatchNorm1d(out_planes, momentum=0.1)
        norm2 = nn.BatchNorm1d(out_planes, momentum=0.1)

        self.conv1_bn_relu = spconv.SparseSequential(conv=conv1, bn=norm1, relu=nn.ReLU(inplace=True))
        self.conv2_bn = spconv.SparseSequential(conv=conv2, bn=norm2)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.iden_for_fx_match = nn.Identity()

    def forward(self, x: spconv.SparseConvTensor):
        identity = self.iden_for_fx_match(x.features)
        # if self.training:
        #     assert x.features.dim() == 2, f'x.features.dim()={x.features.dim()}'

        out = self.conv1_bn_relu(x)
        out = self.conv2_bn(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out = out.replace_feature(self.relu(out.features + identity))
        return out

class SparseBasicBlock1(spconv.SparseModule):
    """residual block that supported by spconv quantization.
    """
    expansion = 1
    def __init__(self,
                 in_planes, out_planes,
                 stride=1,
                 downsample=None):
        spconv.SparseModule.__init__(self)
        self.conv1 = spconv.SubMConv2d(in_planes, out_planes, 3, stride, 1, bias=False)
        self.conv2 = spconv.SubMConv2d(out_planes, out_planes, 3, stride, 1, bias=False)

        self.norm1 = nn.BatchNorm1d(out_planes, momentum=0.1)
        self.norm2 = nn.BatchNorm1d(out_planes, momentum=0.1)

        self.relu1 = nn.ReLU(inplace=True)
        self.relu2 = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.iden_for_fx_match = nn.Identity()

    def forward(self, x: spconv.SparseConvTensor):
        identity = self.iden_for_fx_match(x.features)
        # if self.training:
        #     assert x.features.dim() == 2, f'x.features.dim()={x.features.dim()}'
        out = self.conv1(x)
        out = out.replace_feature(self.relu1(self.norm1(out.features)))
        out = self.conv2(out)
        out = out.replace_feature(self.norm2(out.features))

        # if self.downsample is not None:
        #     identity = self.downsample(x)

        out = out.replace_feature(self.relu2(out.features + identity))
        return out

class SparseBasicBlock2(spconv.SparseModule):
    """residual block that supported by spconv quantization.
    """
    expansion = 1
    def __init__(self,
                 in_planes, out_planes,
                 stride=1,
                 downsample=None):
        spconv.SparseModule.__init__(self)
        self.conv1 = spconv.SubMConv2d(in_planes, out_planes, 3, stride, 1, bias=False)
        self.conv2 = spconv.SubMConv2d(out_planes, out_planes, 3, stride, 1, bias=False)

        self.norm1 = spconv.SparseBatchNorm(out_planes, momentum=0.1)
        self.norm2 = spconv.SparseBatchNorm(out_planes, momentum=0.1)

        self.relu1 = spconv.SparseReLU(inplace=True)
        self.relu2 = spconv.SparseReLU(inplace=True)
        self.downsample = downsample
        self.iden_for_fx_match = spconv.SparseIdentity()

    def forward(self, x: spconv.SparseConvTensor):
        identity = self.iden_for_fx_match(x)
        # if self.training:
        #     assert x.features.dim() == 2, f'x.features.dim()={x.features.dim()}'
        out = self.conv1(x)
        out = self.relu1(self.norm1(out))
        out = self.conv2(out)
        out = self.norm2(out)

        if self.downsample is not None:
            identity = self.downsample(x)
        out = self.relu2(out + identity)
        return out

class SparseBasicBlock3(spconv.SparseModule):
    """residual block that supported by spconv quantization.
    """
    expansion = 1
    def __init__(self,
                 in_planes, out_planes,
                 stride=1,
                 downsample=None):
        spconv.SparseModule.__init__(self)
        self.conv1 = spconv.SubMConv2d(in_planes, out_planes, 3, stride, 1, bias=False)
        conv2 = spconv.SubMConv2d(out_planes, out_planes, 3, stride, 1, bias=False)

        self.norm1 = spconv.SparseBatchNorm(out_planes, momentum=0.1)
        norm2 = spconv.SparseBatchNorm(out_planes, momentum=0.1)
        self.residual_conv = SpconvAddReLUNd(conv2, spconv.SparseReLU(inplace=True))
        self.relu1 = spconv.SparseReLU(inplace=True)
        # self.relu2 = spconv.SparseReLU(inplace=True)
        self.downsample = downsample
        self.iden_for_fx_match = spconv.SparseIdentity()

    def forward(self, x: spconv.SparseConvTensor):
        identity = self.iden_for_fx_match(x)
        # if self.training:
        #     assert x.features.dim() == 2, f'x.features.dim()={x.features.dim()}'
        out = self.conv1(x)
        out = self.relu1(self.norm1(out))

        if self.downsample is not None:
            identity = self.downsample(x)
        out = self.residual_conv(out, identity)
        return out

yanyan's avatar
yanyan committed
208
209
210
211
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.net = spconv.SparseSequential(
yan.yan's avatar
yan.yan committed
212
213
214
            SubMConvBNReLU(1, 32, 3),
            SubMConvBNReLU(32, 64, 3),
            SparseConvBNReLU(64, 64, 2, 2),
215
            spconv.ToDense(),
yanyan's avatar
yanyan committed
216
        )
yan.yan's avatar
yan.yan committed
217
        self.fc1 = nn.Linear(14 * 14 * 64, 128)
yanyan's avatar
yanyan committed
218
219
220
        self.fc2 = nn.Linear(128, 10)
        self.dropout1 = nn.Dropout2d(0.25)
        self.dropout2 = nn.Dropout2d(0.5)
yan.yan's avatar
yan.yan committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        self.quant = QuantStub()
        self.dequant = DeQuantStub()
    
    def forward(self, x_sp: spconv.SparseConvTensor):
    # def forward(self, features: torch.Tensor, indices: torch.Tensor, batch_size: int):
        # x: [N, 28, 28, 1], must be NHWC tensor
        # x = self.quant(x)
        # x_sp = spconv.SparseConvTensor.from_dense(x.reshape(-1, 28, 28, 1))
        # x_sp = spconv.SparseConvTensor(features, indices, [28, 28], batch_size)
        # create SparseConvTensor manually: see SparseConvTensor.from_dense
        x = self.net(x_sp)
        x = torch.flatten(x, 1)
        x = self.dropout1(x)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        # x = self.dequant(x)
        output = F.log_softmax(x, dim=1)
        return output
yanyan's avatar
yanyan committed
241

yan.yan's avatar
yan.yan committed
242
243
244
245
246
247
248
249
250
251
252
class NetV2(nn.Module):
    def __init__(self):
        super(NetV2, self).__init__()
        self.net = spconv.SparseSequential(
            SubMConvBNReLU(1, 32, 3),
            SubMConvBNReLU(32, 64, 3),
            SparseConvBNReLU(64, 64, 2, 2),
            spconv.ToDense(),
        )
        self.fc1 = nn.Linear(14 * 14 * 64, 128)
        self.fc2 = nn.Linear(128, 10)
yan.yan's avatar
yan.yan committed
253
254
        # self.dropout1 = nn.Dropout2d(0.25)
        # self.dropout2 = nn.Dropout2d(0.5)
yan.yan's avatar
yan.yan committed
255
256
257
258
        self.quant = QuantStub()
        self.dequant = DeQuantStub()
    
    def forward(self, features: torch.Tensor, indices: torch.Tensor, batch_size: int):
yanyan's avatar
yanyan committed
259
        # x: [N, 28, 28, 1], must be NHWC tensor
yan.yan's avatar
yan.yan committed
260
261
262
        x = self.quant(features)
        # x_sp = spconv.SparseConvTensor.from_dense(x.reshape(-1, 28, 28, 1))
        x_sp = spconv.SparseConvTensor(features, indices, [28, 28], batch_size)
yanyan's avatar
yanyan committed
263
264
265
        # create SparseConvTensor manually: see SparseConvTensor.from_dense
        x = self.net(x_sp)
        x = torch.flatten(x, 1)
yan.yan's avatar
yan.yan committed
266
        # x = self.dropout1(x)
yanyan's avatar
yanyan committed
267
268
        x = self.fc1(x)
        x = F.relu(x)
yan.yan's avatar
yan.yan committed
269
        # x = self.dropout2(x)
yanyan's avatar
yanyan committed
270
        x = self.fc2(x)
yan.yan's avatar
yan.yan committed
271
272
273
274
275
276
        x = self.dequant(x)
        output = F.log_softmax(x, dim=1)
        return output

class NetPTQ(nn.Module):
    """pytorch currently don't support cuda int8 inference, so
yan.yan's avatar
yan.yan committed
277
    we build a pure sparse network here.
yan.yan's avatar
yan.yan committed
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
    """
    def __init__(self):
        super(NetPTQ, self).__init__()
        self.net = spconv.SparseSequential(
            SubMConvBNReLU(1, 32, 3),
            SubMConvBNReLU(32, 64, 3),
            SparseConvBNReLU(64, 64, 2, 2), # 14x14
            SparseConvBNReLU(64, 64, 2, 2), # 7x7
            SparseConvBNReLU(64, 64, 3, 2, 1), # 4x4
            spconv.SparseConv2d(64, 10, 4, 4),
            spconv.ToDense(),
        )
        # self.fc1 = nn.Linear(64 * 1 * 1, 128)
        # self.fc2 = nn.Linear(128, 10)
        # self.dropout1 = nn.Dropout2d(0.25)
        # self.dropout2 = nn.Dropout2d(0.5)

        self.quant = QuantStub()
        self.dequant = DeQuantStub()
    
    def forward(self, features: torch.Tensor, indices: torch.Tensor, batch_size: int):
        # x: [N, 28, 28, 1], must be NHWC tensor
        features = self.quant(features)
        # x_sp = spconv.SparseConvTensor.from_dense(x.reshape(-1, 28, 28, 1))
        x_sp = spconv.SparseConvTensor(features, indices, [28, 28], batch_size)
        # create SparseConvTensor manually: see SparseConvTensor.from_dense
        x_sp = self.net(x_sp)
        # print(x_sp.shape)
        x = x_sp
        x = torch.flatten(x, 1)
        x = self.dequant(x)
yanyan's avatar
yanyan committed
309
310
311
        output = F.log_softmax(x, dim=1)
        return output

yan.yan's avatar
yan.yan committed
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
class ResidualNetPTQ(nn.Module):
    """pytorch currently don't support cuda int8 inference, so
    we build a pure sparse network here.
    """
    def __init__(self):
        super(ResidualNetPTQ, self).__init__()
        self.net = spconv.SparseSequential(
            SubMConvBNReLU(1, 32, 3),
            SparseBasicBlock2(32, 32),
            SubMConvBNReLU(32, 64, 3),
            SparseConvBNReLU(64, 64, 2, 2), # 14x14
            SparseConvBNReLU(64, 64, 2, 2), # 7x7
            SparseConvBNReLU(64, 64, 3, 2, 1), # 4x4
            spconv.SparseConv2d(64, 10, 4, 4),
            spconv.ToDense(),
        )
        # self.fc1 = nn.Linear(64 * 1 * 1, 128)
        # self.fc2 = nn.Linear(128, 10)
        # self.dropout1 = nn.Dropout2d(0.25)
        # self.dropout2 = nn.Dropout2d(0.5)

        self.quant = QuantStub()
        self.dequant = DeQuantStub()
    
    def forward(self, features: torch.Tensor, indices: torch.Tensor, batch_size: int):
        # x: [N, 28, 28, 1], must be NHWC tensor
        features = self.quant(features)
        # x_sp = spconv.SparseConvTensor.from_dense(x.reshape(-1, 28, 28, 1))
        x_sp = spconv.SparseConvTensor(features, indices, [28, 28], batch_size)
        # create SparseConvTensor manually: see SparseConvTensor.from_dense
        x_sp = self.net(x_sp)
        # print(x_sp.shape)
        x = x_sp
        x = torch.flatten(x, 1)
        x = self.dequant(x)
        output = F.log_softmax(x, dim=1)
        return output
yanyan's avatar
yanyan committed
349

yan.yan's avatar
yan.yan committed
350
351
352
353
354
355
356
357
358
class NetDense(nn.Module):
    def __init__(self):
        super(NetDense, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)
yan.yan's avatar
yan.yan committed
359
360
        self.iden = spconv.SparseIdentity()

yan.yan's avatar
yan.yan committed
361
362
363
364
365
366
367
368
369
370
371
        self.quant = QuantStub()
        self.dequant = DeQuantStub()

    def forward(self, x):
        x = self.quant(x)

        x = self.conv1(x)

        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
yan.yan's avatar
yan.yan committed
372
        x = self.iden(x)
yan.yan's avatar
yan.yan committed
373
374
375
376
377
378
379
380
381
382
383
384
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        x = self.dequant(x)

        output = F.log_softmax(x, dim=1)
        return output

yanyan's avatar
yanyan committed
385
386
def train(args, model, device, train_loader, optimizer, epoch):
    model.train()
yan.yan's avatar
v2.1  
yan.yan committed
387
    scaler = torch.cuda.amp.grad_scaler.GradScaler()
yan.yan's avatar
yan.yan committed
388
    amp_ctx = contextlib.nullcontext()
yan.yan's avatar
v2.1  
yan.yan committed
389
390
    if args.fp16:
        amp_ctx = torch.cuda.amp.autocast()
yanyan's avatar
yanyan committed
391
392
393
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
yan.yan's avatar
v2.1  
yan.yan committed
394
        with amp_ctx:
yan.yan's avatar
yan.yan committed
395
396
397
398
399
400
401
            if args.sparse:
                data_sp = spconv.SparseConvTensor.from_dense(data.reshape(-1, 28, 28, 1))
                # output = model(data_sp)
                output = model(data_sp.features, data_sp.indices, data_sp.batch_size)
            else:
                output = model(data)

yan.yan's avatar
v2.1  
yan.yan committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
            loss = F.nll_loss(output, target)
            scale = 1.0
            if args.fp16:
                assert loss.dtype is torch.float32
                scaler.scale(loss).backward()
                # scaler.step() first unscales the gradients of the optimizer's assigned params.
                # If these gradients do not contain infs or NaNs, optimizer.step() is then called,
                # otherwise, optimizer.step() is skipped.
                # scaler.unscale_(optim)

                # Since the gradients of optimizer's assigned params are now unscaled, clips as usual.
                # You may use the same value for max_norm here as you would without gradient scaling.
                # torch.nn.utils.clip_grad_norm_(models[0].net.parameters(), max_norm=0.1)

                scaler.step(optimizer)
                # Updates the scale for next iteration.
                scaler.update()
                scale = scaler.get_scale()
            else:
                loss.backward()
                optimizer.step()

yanyan's avatar
yanyan committed
424
425
426
427
428
429
        if batch_idx % args.log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))


yan.yan's avatar
v2.1  
yan.yan committed
430
def test(args, model, device, test_loader):
yanyan's avatar
yanyan committed
431
432
433
    model.eval()
    test_loss = 0
    correct = 0
yan.yan's avatar
yan.yan committed
434
    amp_ctx = contextlib.nullcontext()
yan.yan's avatar
v2.1  
yan.yan committed
435
436
437
    if args.fp16:
        amp_ctx = torch.cuda.amp.autocast()

yanyan's avatar
yanyan committed
438
439
    with torch.no_grad():
        for data, target in test_loader:
yan.yan's avatar
v2.1  
yan.yan committed
440

yanyan's avatar
yanyan committed
441
            data, target = data.to(device), target.to(device)
yan.yan's avatar
v2.1  
yan.yan committed
442
            with amp_ctx:
yan.yan's avatar
yan.yan committed
443
444
445
446
447
448
                if args.sparse:
                    data_sp = spconv.SparseConvTensor.from_dense(data.reshape(-1, 28, 28, 1))
                    # output = model(data_sp)
                    output = model(data_sp.features, data_sp.indices, data_sp.batch_size)
                else:
                    output = model(data)
449
450
451
452
453
            test_loss += F.nll_loss(
                output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(
                dim=1,
                keepdim=True)  # get the index of the max log-probability
yanyan's avatar
yanyan committed
454
455
456
457
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

458
459
460
461
    print(
        '\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
            test_loss, correct, len(test_loader.dataset),
            100. * correct / len(test_loader.dataset)))
yanyan's avatar
yanyan committed
462
463


yan.yan's avatar
yan.yan committed
464
465
466
467
468
469
470
471
472
473
474
475
476
def calibrate(args, model: torch.nn.Module, data_loader, device):
    model.eval()
    
    with torch.no_grad():
        for image, target in data_loader:
            image = image.to(device)
            if args.sparse:
                data_sp = spconv.SparseConvTensor.from_dense(image.reshape(-1, 28, 28, 1))
                output = model(data_sp.features, data_sp.indices, data_sp.batch_size)
                # output = model(data_sp)
            else:
                output = model(image)

yan.yan's avatar
yan.yan committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507


def is_dequantize_node(node):
    return isinstance(node, torch.fx.Node) and node.op == "call_method" and node.target == "dequantize"

def _get_module(node: torch.fx.Node, modules: Dict[str, nn.Module]) -> Optional[nn.Module]:
    """
    Return the `torch.nn.Module` that corresponds to the specified node's target.
    If no such node exists, return None.
    """
    if node.op == "call_module" and str(node.target) in modules:
        return modules[str(node.target)]
    else:
        return None

def remove_conv_add_dq(model: torch.fx.graph_module.GraphModule):
    modules = dict(model.named_modules(remove_duplicate=False))
    for n in model.graph.nodes:
        if (n.op == "call_module" and type(_get_module(n, modules)) == snniq.SparseConvAddReLU):
            # check second input, if it's dequantized, remove that dequantize node
            arg1 = n.args[1]
            if is_dequantize_node(arg1):
                dq_node = arg1
                assert(isinstance(dq_node, torch.fx.Node))
                dn_input = dq_node.args[0]
                n.replace_input_with(dq_node, dn_input)
    model.graph.eliminate_dead_code()
    model.recompile()
    model.graph.lint() # Does some checks to make sure the
                 # Graph is well-formed.
    return model
yan.yan's avatar
yan.yan committed
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
    
def transform_qdq(m: torch.fx.GraphModule) -> torch.fx.GraphModule:
    """torch.quantize_per_tensor don't support SparseConvTensor, so we
    use a custom one by fx transform.
    """
    for node in m.graph.nodes:
        # Checks if we're calling a function (i.e:
        # torch.add)
        if node.op == 'call_function':
            # The target attribute is the function
            # that call_function calls.
            if node.target == torch.quantize_per_tensor:
                node.target = quantize_per_tensor
    m.graph.lint() # Does some checks to make sure the
                 # Graph is well-formed.
    m.recompile()
    return m
yan.yan's avatar
yan.yan committed
525

yanyan's avatar
yanyan committed
526
527
528
def main():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
529
530
531
532
    parser.add_argument('--batch-size',
                        type=int,
                        default=64,
                        metavar='N',
yanyan's avatar
yanyan committed
533
                        help='input batch size for training (default: 64)')
534
535
536
537
    parser.add_argument('--test-batch-size',
                        type=int,
                        default=1000,
                        metavar='N',
yanyan's avatar
yanyan committed
538
                        help='input batch size for testing (default: 1000)')
539
540
    parser.add_argument('--epochs',
                        type=int,
yan.yan's avatar
yan.yan committed
541
                        default=1,
542
                        metavar='N',
yanyan's avatar
yanyan committed
543
                        help='number of epochs to train (default: 14)')
544
545
546
547
    parser.add_argument('--lr',
                        type=float,
                        default=1.0,
                        metavar='LR',
yanyan's avatar
yanyan committed
548
                        help='learning rate (default: 1.0)')
549
550
551
552
    parser.add_argument('--gamma',
                        type=float,
                        default=0.7,
                        metavar='M',
yanyan's avatar
yanyan committed
553
                        help='Learning rate step gamma (default: 0.7)')
554
555
556
    parser.add_argument('--no-cuda',
                        action='store_true',
                        default=False,
yanyan's avatar
yanyan committed
557
                        help='disables CUDA training')
558
559
560
561
    parser.add_argument('--seed',
                        type=int,
                        default=1,
                        metavar='S',
yanyan's avatar
yanyan committed
562
                        help='random seed (default: 1)')
yan.yan's avatar
yan.yan committed
563
564
    parser.add_argument('--sparse',
                        action='store_true',
yan.yan's avatar
yan.yan committed
565
                        default=False,
yan.yan's avatar
yan.yan committed
566
                        help='use sparse conv network instead of dense')
567
568
569
570
571
572
573
574
575
576
    parser.add_argument(
        '--log-interval',
        type=int,
        default=10,
        metavar='N',
        help='how many batches to wait before logging training status')

    parser.add_argument('--save-model',
                        action='store_true',
                        default=False,
yanyan's avatar
yanyan committed
577
                        help='For Saving the current Model')
578
579
580
    parser.add_argument('--fp16',
                        action='store_true',
                        default=False,
yan.yan's avatar
v2.1  
yan.yan committed
581
582
                        help='For mixed precision training')

yanyan's avatar
yanyan committed
583
584
585
586
587
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

yan.yan's avatar
yan.yan committed
588
    device = torch.device("cuda" if use_cuda and args.sparse else "cpu")
yan.yan's avatar
yan.yan committed
589
    qdevice = torch.device("cuda" if use_cuda and args.sparse else "cpu")
yanyan's avatar
yanyan committed
590
    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
yan.yan's avatar
yan.yan committed
591
    if args.sparse:
yan.yan's avatar
yan.yan committed
592
        model = NetV2().to(device)
yan.yan's avatar
yan.yan committed
593
594
595
596
    else:
        model = NetDense().to(device)

    optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
yanyan's avatar
yanyan committed
597
    train_loader = torch.utils.data.DataLoader(
598
599
600
601
602
603
604
605
606
607
608
609
        datasets.MNIST(
            '../data',
            train=True,
            download=True,
            transform=transforms.Compose([
                transforms.ToTensor(),
                # here we remove norm to get sparse tensor with lots of zeros
                # transforms.Normalize((0.1307,), (0.3081,))
            ])),
        batch_size=args.batch_size,
        shuffle=True,
        **kwargs)
yanyan's avatar
yanyan committed
610
    test_loader = torch.utils.data.DataLoader(
611
612
613
614
615
616
617
618
619
620
621
        datasets.MNIST(
            '../data',
            train=False,
            transform=transforms.Compose([
                transforms.ToTensor(),
                # here we remove norm to get sparse tensor with lots of zeros
                # transforms.Normalize((0.1307,), (0.3081,))
            ])),
        batch_size=args.test_batch_size,
        shuffle=True,
        **kwargs)
yanyan's avatar
yanyan committed
622
623
624
625

    scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch)
yan.yan's avatar
v2.1  
yan.yan committed
626
        test(args, model, device, test_loader)
yanyan's avatar
yanyan committed
627
        scheduler.step()
yan.yan's avatar
yan.yan committed
628
629
    if args.save_model:
        torch.save(model.state_dict(), "mnist_cnn.pt")
yan.yan's avatar
yan.yan committed
630
631
632
    model.eval()
    if not args.sparse:
        model = model.cpu()
yan.yan's avatar
yan.yan committed
633
634
635
636
637
638

    model_qat = copy.deepcopy(model)
    STATIC_LOWER_FUSED_MODULE_MAP.update(SPCONV_STATIC_LOWER_FUSED_MODULE_MAP)
    STATIC_LOWER_MODULE_MAP.update(SPCONV_STATIC_LOWER_MODULE_MAP)

    # tensorrt only support symmetric quantization, per-tensor act and per-channel weight.
yan.yan's avatar
yan.yan committed
639
640
641
    qconfig_mapping = get_default_spconv_qconfig_mapping(False)
    prepare_cfg = spconvq.get_spconv_prepare_custom_config()
    backend_cfg = spconvq.get_spconv_backend_config()
yan.yan's avatar
yan.yan committed
642
    # convert_cfg = spconvq.get_spconv_convert_custom_config()
yan.yan's avatar
yan.yan committed
643
644
645
    # prepare: fuse your model, all patterns such as conv-bn-relu fuse to modules in torch.ao.quantization.intrinsic / spconv.pytorch.quantization.intrinsic
    # then add observers to fused model.
    prepared_model = qfx.prepare_fx(model, qconfig_mapping, (), backend_config=backend_cfg, prepare_custom_config=prepare_cfg)
yan.yan's avatar
yan.yan committed
646
647
648
649
    # print(prepared_model)
    # breakpoint()

    # print(prepared_model)
yan.yan's avatar
yan.yan committed
650
    # calibrate: run model with some inputs
yan.yan's avatar
yan.yan committed
651
    calibrate(args, prepared_model, test_loader, qdevice)
yan.yan's avatar
yan.yan committed
652
    # convert (ptq): replace intrinsic blocks with quantized modules
yan.yan's avatar
yan.yan committed
653
654
655
656
    converted_model = qfx.convert_fx(prepared_model, qconfig_mapping=qconfig_mapping, backend_config=backend_cfg)
    converted_model = transform_qdq(converted_model)
    # test converted ptq model with int8 kernel
    remove_conv_add_dq(converted_model)
yan.yan's avatar
yan.yan committed
657
658

    print(converted_model)
yan.yan's avatar
yan.yan committed
659
    breakpoint()
yanyan's avatar
yanyan committed
660

yan.yan's avatar
yan.yan committed
661
    test(args, converted_model, qdevice, test_loader)
yan.yan's avatar
yan.yan committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
    # do qat
    # qconfig_mapping_qat = get_default_spconv_qconfig_mapping(True)
    # prepared_model_qat = qfx.prepare_qat_fx(model_qat, qconfig_mapping_qat, (), backend_config=backend_cfg, prepare_custom_config=prepare_cfg)
    # # converted_model = qfx.convert_fx(prepared_model_qat, qconfig_mapping=qconfig_mapping_qat, backend_config=backend_cfg)
    # # breakpoint()
    # print(prepared_model_qat)
    # train(args, prepared_model_qat, qdevice, train_loader, optimizer, 1)
    # converted_model = qfx.convert_fx(prepared_model_qat, qconfig_mapping=qconfig_mapping_qat, backend_config=backend_cfg)
    # converted_model = transform_qdq(converted_model)
    # test(args, converted_model, qdevice, test_loader)
    # # [type(m) for m in prepared_model_qat.modules()]
    # # model.qconfig = get_default_spconv_trt_ptq_qconfig()
    # # prepare_custom_config_dict = spconvq.get_prepare_custom_config()
    # # convert_custom_config_dict = spconvq.get_convert_custom_config()
    # # torch.ao.quantization.prepare(model, inplace=True)
    # # print('Post Training Quantization Prepare: Inserting Observers')
    # # print('\n ConvBnReLUBlock:After observer insertion \n\n', model.net[0])
    # # test(args, model, device, test_loader)
    # print(converted_model)
    # you will see some nvrtc compile log here, which means int8 kernel is used.
yan.yan's avatar
yan.yan committed
682
    breakpoint()
yanyan's avatar
yanyan committed
683
684
685

if __name__ == '__main__':
    main()