/
torch_models.py
1577 lines (1201 loc) · 46.4 KB
/
torch_models.py
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
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
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
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
417
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Torch modules for our pytests."""
# pylint: disable=too-many-lines
from typing import Union
import brevitas.nn as qnn
import numpy
import torch
from brevitas.quant import Int8ActPerTensorFloat, Int8WeightPerTensorFloat, IntBias
from torch import nn
from torch.nn.utils import prune
from concrete.ml.quantization.qat_quantizers import Int8ActPerTensorPoT, Int8WeightPerTensorPoT
# pylint: disable=too-many-lines
class MultiOutputModel(nn.Module):
"""Multi-output model."""
def __init__(
self,
) -> None:
"""Torch Model."""
super().__init__()
self.value = 3.0
def forward(self, x, y):
"""Forward pass.
Args:
x (torch.Tensor): The input of the model.
y (torch.Tensor): The input of the model.
Returns:
Tuple[torch.Tensor. torch.Tensor]: Output of the network.
"""
return x + y + self.value, (x - y) ** 2
class SimpleNet(torch.nn.Module):
"""Fake torch model used to generate some onnx."""
def __init__(self) -> None:
super().__init__()
self.scale = 2.2
self.offset = 1.1
def forward(self, inputs):
"""Forward function.
Arguments:
inputs: the inputs of the model.
Returns:
torch.Tensor: the result of the computation
"""
res = (inputs * self.scale) + self.offset
res = torch.relu(inputs)
return res
class FCSmall(nn.Module):
"""Torch model for the tests."""
def __init__(self, input_output, activation_function):
super().__init__()
self.fc1 = nn.Linear(in_features=input_output, out_features=input_output)
self.act_f = activation_function()
self.fc2 = nn.Linear(in_features=input_output, out_features=input_output)
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
out = self.fc1(x)
out = self.act_f(out)
out = self.fc2(out)
return out
class FC(nn.Module):
"""Torch model for the tests."""
def __init__(self, activation_function, input_output=32 * 32 * 3):
super().__init__()
self.fc1 = nn.Linear(in_features=input_output, out_features=128)
self.act_1 = activation_function()
self.fc2 = nn.Linear(in_features=128, out_features=64)
self.act_2 = activation_function()
self.fc3 = nn.Linear(in_features=64, out_features=64)
self.act_3 = activation_function()
self.fc4 = nn.Linear(in_features=64, out_features=64)
self.act_4 = activation_function()
self.fc5 = nn.Linear(in_features=64, out_features=10)
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
out = self.fc1(x)
out = self.act_1(out)
out = self.fc2(out)
out = self.act_2(out)
out = self.fc3(out)
out = self.act_3(out)
out = self.fc4(out)
out = self.act_4(out)
out = self.fc5(out)
return out
class CNN(nn.Module):
"""Torch CNN model for the tests."""
def __init__(self, input_output, activation_function):
super().__init__()
self.conv1 = nn.Conv2d(input_output, 6, 5)
self.pool = nn.AvgPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.act_f = activation_function()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.pool(torch.relu(self.conv1(x)))
x = self.pool(torch.relu(self.conv2(x)))
x = torch.flatten(x, 1)
x = self.act_f(self.fc1(x))
x = self.act_f(self.fc2(x))
x = self.fc3(x)
return x
class CNNMaxPool(nn.Module):
"""Torch CNN model for the tests with a max pool."""
def __init__(self, input_output, activation_function):
super().__init__()
self.conv1 = nn.Conv2d(input_output, 6, 5)
self.maxpool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.act_f = activation_function()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.maxpool(torch.relu(self.conv1(x)))
x = self.maxpool(torch.relu(self.conv2(x)))
x = torch.flatten(x, 1)
x = self.act_f(self.fc1(x))
x = self.act_f(self.fc2(x))
x = self.fc3(x)
return x
class CNNOther(nn.Module):
"""Torch CNN model for the tests."""
def __init__(self, input_output, activation_function):
super().__init__()
self.activation_function = activation_function()
self.conv1 = nn.Conv2d(input_output, 3, 3, stride=1, padding=1)
self.pool = nn.AvgPool2d(2, 2)
self.conv2 = nn.Conv2d(3, 3, 1)
self.bn1 = nn.BatchNorm2d(3)
self.fc1 = nn.Linear(3 * 3 * 3, 5)
self.fc2 = nn.Linear(5, 3)
self.fc3 = nn.Linear(3, 2)
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.pool(self.activation_function(self.conv1(x)))
x = self.activation_function(self.conv2(x))
x = self.bn1(x)
x = x.flatten(1)
x = self.activation_function(self.fc1(x))
x = self.activation_function(self.fc2(x))
x = self.fc3(x)
return x
class CNNInvalid(nn.Module):
"""Torch CNN model for the tests."""
def __init__(self, activation_function, groups):
super().__init__()
padding = True
self.activation_function = activation_function()
self.flatten_function = lambda x: torch.flatten(x, 1)
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.AvgPool2d(2, 2, padding=1) if padding else nn.AvgPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5, groups=2) if groups else nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * (5 + padding * 1) * (5 + padding * 1), 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.gather_slice = True
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.pool(self.activation_function(self.conv1(x)))
x = self.pool(self.activation_function(self.conv2(x)))
x = self.flatten_function(x)
x = self.activation_function(self.fc1(x))
x = self.activation_function(self.fc2(x))
x = self.fc3(x)
# Produce a Gather and Slice which are not supported
if self.gather_slice:
x = x[0, 0:-1:2]
x = torch.mean(x)
return x
class CNNGrouped(nn.Module):
"""Torch CNN model with grouped convolution for compile torch tests."""
def __init__(self, input_output, activation_function, groups):
super().__init__()
self.activation_function = activation_function()
self.conv1 = nn.Conv2d(input_output, 3, 3, stride=1, padding=1, dilation=1, groups=groups)
self.pool = nn.AvgPool2d(2, 2)
self.conv2 = nn.Conv2d(3, 3, 1, stride=1, padding=0, dilation=1, groups=3)
self.fc1 = nn.Linear(3 * 3 * 3, 5)
self.fc2 = nn.Linear(5, 3)
self.fc3 = nn.Linear(3, 2)
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.pool(self.activation_function(self.conv1(x)))
x = self.activation_function(self.conv2(x))
x = x.flatten(1)
x = self.activation_function(self.fc1(x))
x = self.activation_function(self.fc2(x))
x = self.fc3(x)
return x
class NetWithLoops(torch.nn.Module):
"""Torch model, where we reuse some elements in a loop.
Torch model, where we reuse some elements in a loop in the forward and don't expect the
user to define these elements in a particular order.
"""
def __init__(self, activation_function, input_output, n_fc_layers):
super().__init__()
self.fc1 = nn.Linear(input_output, 3)
self.ifc = nn.Sequential()
for i in range(n_fc_layers):
self.ifc.add_module(f"fc{i+1}", nn.Linear(3, 3))
self.out = nn.Linear(3, 1)
self.act = activation_function()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.act(self.fc1(x))
for m in self.ifc:
x = self.act(m(x))
x = self.act(self.out(x))
return x
class MultiInputNN(nn.Module):
"""Torch model to test multiple inputs forward."""
def __init__(self, input_output, activation_function): # pylint: disable=unused-argument
super().__init__()
self.act = activation_function()
def forward(self, x, y):
"""Forward pass.
Args:
x: the first input of the NN
y: the second input of the NN
Returns:
the output of the NN
"""
return self.act(x + y)
class MultiInputNNConfigurable(nn.Module):
"""Torch model to test multiple inputs forward."""
layer1: nn.Module
layer2: nn.Module
def __init__(self, use_conv, use_qat, input_output, n_bits): # pylint: disable=unused-argument
super().__init__()
if use_conv:
self.layer1 = nn.Conv2d(input_output[0], input_output[0], 1, 1, 0)
self.layer2 = nn.Conv2d(input_output[0], input_output[0], 1, 1, 0)
else:
self.layer1 = nn.Linear(input_output, input_output)
self.layer2 = nn.Linear(input_output, input_output)
def forward(self, x, y):
"""Forward pass.
Args:
x: the first input of the NN
y: the second input of the NN
Returns:
the output of the NN
"""
x = self.layer1(x)
y = self.layer2(y)
return self.layer1(x + y)
class MultiInputNNDifferentSize(nn.Module):
"""Torch model to test multiple inputs with different shape in the forward pass."""
def __init__(
self,
input_output,
activation_function=None,
is_brevitas_qat=False,
n_bits=3,
): # pylint: disable=unused-argument
super().__init__()
# input_output is expected to be a list of two integers representing in and out features
# for both x and y
if is_brevitas_qat:
# n_bits is used for quantizing both the inputs and the weights, therefore we need
# to make sure that it is at least 2 bits
assert n_bits > 1, "Weights cannot be quantized over a single bit"
self.quant1 = qnn.QuantIdentity(bit_width=n_bits)
self.quant2 = qnn.QuantIdentity(bit_width=n_bits)
self.quant3 = qnn.QuantIdentity(bit_width=n_bits)
self.layer1 = qnn.QuantLinear(
input_output[0], input_output[0], bias=False, weight_bit_width=n_bits
)
self.layer2 = qnn.QuantLinear(
input_output[1], input_output[0], bias=False, weight_bit_width=n_bits
)
else:
self.layer1 = nn.Linear(input_output[0], input_output[0])
self.layer2 = nn.Linear(input_output[1], input_output[0])
self.is_brevitas_qat = is_brevitas_qat
def forward(self, x, y):
"""Forward pass.
Args:
x: The first input of the NN.
y: The second input of the NN.
Returns:
The output of the NN.
"""
if self.is_brevitas_qat:
x = self.layer1(self.quant1(x))
y = self.layer2(self.quant2(y))
return self.layer1(self.quant3(x + y))
x = self.layer1(x)
y = self.layer2(y)
return self.layer1(x + y)
class BranchingModule(nn.Module):
"""Torch model with some branching and skip connections."""
# pylint: disable-next=unused-argument
def __init__(self, input_output, activation_function):
super().__init__()
self.act = activation_function()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
return x + self.act(x + 1.0) - self.act(x * 2.0)
class BranchingGemmModule(nn.Module):
"""Torch model with some branching and skip connections."""
def __init__(self, input_output, activation_function):
super().__init__()
self.act = activation_function()
self.fc1 = nn.Linear(input_output, input_output)
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
return x + self.act(x + 1.0) - self.act(self.fc1(x * 2.0))
class UnivariateModule(nn.Module):
"""Torch model that calls univariate and shape functions of torch."""
# pylint: disable-next=unused-argument
def __init__(self, input_output, activation_function):
super().__init__()
self.act = activation_function()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = x.view(-1, 1)
x = torch.reshape(x, (-1, 1))
x = x.flatten(1)
x = self.act(torch.abs(torch.exp(torch.log(1.0 + torch.sigmoid(x)))))
return x
class StepActivationModule(nn.Module):
"""Torch model implements a step function that needs Greater, Cast and Where."""
# pylint: disable-next=unused-argument
def __init__(self, input_output, activation_function):
super().__init__()
self.act = activation_function()
def forward(self, x):
"""Forward pass with a quantizer built into the computation graph.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
def step(x, bias):
"""Forward-step function for quantization.
Args:
x: the input
bias: the bias
Returns:
one step further
"""
y = torch.zeros_like(x)
mask = torch.gt(x - bias, 0.0)
y[mask] = 1.0
return y
x = step(x, 0.5) * 2.0
x = self.act(x)
return x
class NetWithConcatUnsqueeze(torch.nn.Module):
"""Torch model to test the concat and unsqueeze operators."""
def __init__(self, activation_function, input_output, n_fc_layers):
super().__init__()
self.fc1 = nn.Linear(input_output, 3)
self.ifc = nn.Sequential()
for i in range(n_fc_layers):
self.ifc.add_module(f"fc{i+1}", nn.Linear(3, 3))
self.out = nn.Linear(3, 1)
self.act = activation_function()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.act(self.fc1(x))
results = []
for module in self.ifc:
results.append(module(x))
# Use torch.stack which creates Unsqueeze operators for each module
# and a final Concat operator.
return torch.stack(results)
class MultiOpOnSingleInputConvNN(nn.Module):
"""Network that applies two quantized operations on a single input."""
def __init__(self, can_remove_input_tlu: bool):
super().__init__()
self.can_remove_input_tlu = can_remove_input_tlu
self.conv1 = nn.Conv2d(1, 8, 3)
self.conv2 = nn.Conv2d(1, 8, 3)
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
# The quantizer for this network can be moved in the clear if the
# input is fed directly to two conv layers that have the same quantizer.
# To ensure the quantizer is performed in FHE, a univariate op is applied
# before _one_ of the convolutions
y = x if self.can_remove_input_tlu else torch.sigmoid(x)
layer1_out = torch.relu(self.conv1(y))
layer2_out = torch.relu(self.conv2(x))
return layer1_out + layer2_out
class FCSeq(nn.Module):
"""Torch model that should generate MatMul->Add ONNX patterns.
This network generates additions with a constant scalar
"""
def __init__(self, input_output, act):
super().__init__()
self.feat = nn.Sequential()
in_features = input_output
self.n_layers = 2
self.biases = [torch.Tensor(size=(1,)) for _ in range(self.n_layers)]
for b in self.biases:
nn.init.uniform_(b)
for idx in range(self.n_layers):
out_features = in_features if idx == self.n_layers - 1 else in_features
layer_name = f"fc{idx}"
layer = nn.Linear(in_features=in_features, out_features=out_features, bias=False)
self.feat.add_module(layer_name, layer)
in_features = out_features
self.act = act()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
for idx, layer in enumerate(self.feat):
x = self.act(layer(x) + self.biases[idx])
return x
class FCSeqAddBiasVec(nn.Module):
"""Torch model that should generate MatMul->Add ONNX patterns.
This network tests the addition with a constant vector
"""
def __init__(self, input_output, act):
super().__init__()
self.feat = nn.Sequential()
in_features = input_output
self.n_layers = 2
self.biases = [torch.Tensor(size=(input_output,)) for _ in range(self.n_layers)]
for b in self.biases:
nn.init.uniform_(b)
for idx in range(self.n_layers):
out_features = in_features if idx == self.n_layers - 1 else in_features
layer_name = f"fc{idx}"
layer = nn.Linear(in_features=in_features, out_features=out_features, bias=False)
self.feat.add_module(layer_name, layer)
in_features = out_features
self.act = act()
def forward(self, x):
"""Forward pass.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
for idx, layer in enumerate(self.feat):
x = self.act(layer(x) + self.biases[idx])
return x
class TinyCNN(nn.Module):
"""A very small CNN."""
def __init__(self, n_classes, act) -> None:
"""Create the tiny CNN with two conv layers.
Args:
n_classes: number of classes
act: the activation
"""
super().__init__()
self.conv1 = nn.Conv2d(1, 2, 2, stride=1, padding=0)
self.avg_pool1 = nn.AvgPool2d(2, 2)
self.conv2 = nn.Conv2d(2, n_classes, 2, stride=1, padding=0)
self.act = act()
self.n_classes = n_classes
def forward(self, x):
"""Forward the two layers with the chosen activation function.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
x = self.act(self.avg_pool1(self.conv1(x)))
x = self.act(self.conv2(x))
return x
class TinyQATCNN(nn.Module):
"""A very small QAT CNN to classify the sklearn digits data-set.
This class also allows pruning to a maximum of 10 active neurons, which
should help keep the accumulator bit-width low.
"""
def __init__(self, n_classes, n_bits, n_active, signed, narrow, power_of_two_scaling) -> None:
"""Construct the CNN with a configurable number of classes.
Args:
n_classes (int): number of outputs of the neural net
n_bits (int): number of weight and activation bits for quantization
n_active (int): number of active (non-zero weight) neurons to keep
signed (bool): whether quantized integer values are signed
narrow (bool): whether the range of quantized integer values is narrow/symmetric
power_of_two_scaling (bool): whether to use power-of-two scaling quantizers which
allows to test the round PBS optimization when the scales are power-of-two
"""
super().__init__()
a_bits = n_bits
w_bits = n_bits
self.n_active = n_active
q_args = {"signed": signed, "narrow_range": narrow}
if power_of_two_scaling:
act_quant = Int8ActPerTensorPoT
weight_quant = Int8WeightPerTensorPoT
bias_quant = IntBias
else:
act_quant = Int8ActPerTensorFloat
weight_quant = Int8WeightPerTensorFloat
bias_quant = None
self.quant1 = qnn.QuantIdentity(
bit_width=a_bits, return_quant_tensor=True, **q_args, act_quant=act_quant
)
self.conv1 = qnn.QuantConv2d(
1,
2,
3,
stride=1,
padding=0,
weight_bit_width=w_bits,
**q_args,
weight_quant=weight_quant,
bias_quant=bias_quant,
)
self.quant2 = qnn.QuantIdentity(
bit_width=a_bits, return_quant_tensor=True, **q_args, act_quant=act_quant
)
self.conv2 = qnn.QuantConv2d(
2,
3,
3,
stride=2,
padding=0,
weight_bit_width=w_bits,
**q_args,
weight_quant=weight_quant,
bias_quant=bias_quant,
)
self.quant3 = qnn.QuantIdentity(
bit_width=a_bits, return_quant_tensor=True, **q_args, act_quant=act_quant
)
self.conv3 = qnn.QuantConv2d(
3,
16,
2,
stride=1,
padding=0,
weight_bit_width=w_bits,
**q_args,
weight_quant=weight_quant,
bias_quant=bias_quant,
)
self.quant4 = qnn.QuantIdentity(bit_width=a_bits, return_quant_tensor=True, **q_args)
self.fc1 = qnn.QuantLinear(16, n_classes, weight_bit_width=3, bias=True, **q_args)
# Enable pruning, prepared for training
self.toggle_pruning(True)
def toggle_pruning(self, enable):
"""Enable or remove pruning.
Args:
enable: if we enable the pruning or not
"""
# Maximum number of active neurons (i.e., corresponding weight != 0)
# Go through all the convolution layers
for layer in (self.conv1, self.conv2, self.conv3):
s = layer.weight.shape
# Compute fan-in (number of inputs to a neuron)
# and fan-out (number of neurons in the layer)
layer_size = [s[0], numpy.prod(s[1:])]
# The number of input neurons (fan-in) is the product of
# the kernel width x height x inChannels.
if layer_size[1] > self.n_active:
if enable:
# This will create a forward hook to create a mask tensor that is multiplied
# with the weights during forward. The mask will contain 0s or 1s
prune.l1_unstructured(
layer, "weight", (layer_size[1] - self.n_active) * layer_size[0]
)
else:
# When disabling pruning, the mask is multiplied with the weights
# and the result is stored in the weights member
prune.remove(layer, "weight")
def forward(self, x):
"""Run inference on the tiny CNN, apply the decision layer on the reshaped conv output.
Args:
x: the input to the NN
Returns:
the output of the NN
"""
x = self.quant1(x)
x = self.conv1(x)
x = torch.relu(x)
x = self.quant2(x)
x = self.conv2(x)
x = torch.relu(x)
x = self.quant3(x)
x = self.conv3(x)
x = torch.relu(x)
x = self.quant4(x)
x = x.view(-1, 16)
x = self.fc1(x)
return x
class SimpleQAT(nn.Module):
"""Torch model implements a step function that needs Greater, Cast and Where."""
def __init__(self, input_output, activation_function, n_bits=2, disable_bit_check=False):
super().__init__()
self.act = activation_function()
self.fc1 = nn.Linear(input_output, input_output)
# Create pre-quantized weights
# Note the weights in the network are not integers, but uniformly spaced float values
# that are selected from a discrete set
weight_scale = 1.5
n_bits_weights = n_bits
# Generate the pattern 0, 1, ..., 2^N-1, 0, 1, .. 2^N-1, 0, 1..
all_weights = numpy.mod(
numpy.arange(numpy.prod(self.fc1.weight.shape)), 2**n_bits_weights
)
# Shuffle the pattern and reshape to weight shape
numpy.random.shuffle(all_weights)
int_weights = all_weights.reshape(self.fc1.weight.shape)
# A check that is used to ensure this class is used correctly
# but we may want to disable it to check that the QAT import catches the error
if not disable_bit_check:
# Ensure we have the correct max/min that produces the correct scale in Quantized Array
assert numpy.max(int_weights) - numpy.min(int_weights) == (2**n_bits_weights - 1)
# We want signed weights, so offset the generated weights
int_weights = int_weights - 2 ** (n_bits_weights - 1)
# Initialize with scaled float weights
self.fc1.weight.data = torch.from_numpy(int_weights * weight_scale).float()
self.n_bits = n_bits
def forward(self, x):
"""Forward pass with a quantizer built into the computation graph.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
def step(x, bias):
"""Forward-step function for quantization.
Args:
x: the input of the layer
bias: the bias
Returns:
the output of the layer
"""
y = torch.zeros_like(x)
mask = torch.gt(x - bias, 0.0)
y[mask] = 1.0
return y
# A step quantizer with steps at -5, 0, 5, ...
# For example at n_bits == 2
# / 0 if x < -5 \
# f(x) = { 5 if x >= 0 and x < 5 }
# \ 10 if x >= 5 and x < 10 /
# \ 15 if x >= 10 /
x_q = step(x, -5)
for i in range(1, 2**self.n_bits - 1):
x_q += step(x, (i - 1) * 5)
x_q = x_q.mul(5)
result_fc1 = self.fc1(x_q)
return self.act(result_fc1)
class QATTestModule(nn.Module):
"""Torch model that implements a simple non-uniform quantizer."""
def __init__(self, activation_function):
super().__init__()
self.act = activation_function()
def forward(self, x):
"""Forward pass with a quantizer built into the computation graph.
Args:
x: the input of the NN
Returns:
the output of the NN
"""
def step(x, bias):
"""Forward-step function for quantization.
Args:
x: the input of the layer
bias: the bias
Returns:
the output of the layer
"""
y = torch.zeros_like(x)
mask = torch.gt(x - bias, 0.0)
y[mask] = 1.0
return y
x = step(x, 0.5) * 2.0
x = self.act(x)
return x
class SingleMixNet(nn.Module):
"""Torch model that with a single conv layer that produces the output, e.g., a blur filter."""
mixing_layer: Union[nn.Module, nn.Sequential]
def __init__(self, use_conv, use_qat, inp_size, n_bits):
super().__init__()
if use_conv:
# Initialize a blur filter float weights
np_weights = numpy.asarray([[[[1, 1, 1], [1, 4, 1], [1, 1, 1]]]])
if use_qat:
self.mixing_layer = nn.Sequential(
qnn.QuantIdentity(bit_width=n_bits),
qnn.QuantConv2d(1, 1, 3, stride=1, bias=True, weight_bit_width=n_bits),
)
layer_obj = self.mixing_layer[1]
else:
self.mixing_layer = nn.Conv2d(1, 1, 3, stride=1, bias=True)
layer_obj = self.mixing_layer
else:
# Initialize a linear layer with 1s
np_weights = numpy.asarray([[1] * inp_size])
if use_qat:
self.mixing_layer = nn.Sequential(
qnn.QuantIdentity(bit_width=n_bits),