-
Notifications
You must be signed in to change notification settings - Fork 0
/
ai8x.py
935 lines (751 loc) · 27 KB
/
ai8x.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
###################################################################################################
#
# Copyright (C) Maxim Integrated Products, Inc. All Rights Reserved.
#
# Maxim Integrated Products, Inc. Default Copyright Notice:
# https://www.maximintegrated.com/en/aboutus/legal/copyrights.html
#
###################################################################################################
"""
Contains the limits of the AI84/AI85/AI87 implementations and custom PyTorch modules that take
the limits into account.
"""
import torch
import torch.nn as nn
from torch.autograd import Function
import devices
dev = None
class normalize:
"""
Normalize input to either [-0.5, +0.5] or [-128, +127]
"""
def __init__(self, args):
self.args = args
def __call__(self, img):
if self.args.act_mode_8bit:
return img.sub(0.5).mul(256.).round().clamp(min=-128, max=127)
return img.sub(0.5)
class QuantizationFunction(Function):
"""
Custom AI8X autograd function
The forward pass divides by 2**(bits-1) (typically, 128) and rounds the result to the
nearest integer.
The backward pass is straight through.
"""
@staticmethod
def forward(_, x, bits=None): # pylint: disable=arguments-differ
"""Forward prop"""
if bits > 1:
return x.add(.5).div(2**(bits-1)).add(.5).floor()
if bits < 1:
return x.mul(2**(1-bits)).add(.5).floor()
return x.add(.5).floor()
@staticmethod
def backward(_, x): # pylint: disable=arguments-differ
"""Backprop"""
# Straight through - return as many input gradients as there were arguments;
# gradients of non-Tensor arguments to forward must be None.
return x, None
class Quantize(nn.Module):
"""
Post-activation integer quantization module
Apply the custom autograd function
"""
def __init__(self, num_bits=8):
super().__init__()
self.num_bits = num_bits
def forward(self, x): # pylint: disable=arguments-differ
"""Forward prop"""
return QuantizationFunction.apply(x, self.num_bits)
class FloorFunction(Function):
"""
Custom AI8X autograd function
The forward pass returns the integer floor.
The backward pass is straight through.
"""
@staticmethod
def forward(_, x): # pylint: disable=arguments-differ
"""Forward prop"""
return x.floor()
@staticmethod
def backward(_, x): # pylint: disable=arguments-differ
"""Backprop"""
# Straight through - return as many input gradients as there were arguments;
# gradients of non-Tensor arguments to forward must be None.
return x
class Floor(nn.Module):
"""
Post-pooling integer quantization module
Apply the custom autograd function
"""
def forward(self, x): # pylint: disable=arguments-differ,no-self-use
"""Forward prop"""
return FloorFunction.apply(x)
class RoundFunction(Function):
"""
Custom AI8X autograd function
The forward pass returns the integer rounded.
The backward pass is straight through.
"""
@staticmethod
def forward(_, x): # pylint: disable=arguments-differ
"""Forward prop"""
return x.round()
@staticmethod
def backward(_, x): # pylint: disable=arguments-differ
"""Backprop"""
# Straight through - return as many input gradients as there were arguments;
# gradients of non-Tensor arguments to forward must be None.
return x
class Round(nn.Module):
"""
Post-pooling integer quantization module
Apply the custom autograd function
"""
def forward(self, x): # pylint: disable=arguments-differ,no-self-use
"""Forward prop"""
return RoundFunction.apply(x)
class Clamp(nn.Module):
"""
Post-Activation Clamping Module
Clamp the output to the given range (typically, [-128, +127])
"""
def __init__(self, min_val=None, max_val=None):
super().__init__()
self.min_val = min_val
self.max_val = max_val
def forward(self, x): # pylint: disable=arguments-differ
"""Forward prop"""
return x.clamp(min=self.min_val, max=self.max_val)
def quantize_clamp(wide, output_shift):
"""
Return new Quantization and Clamp objects.
"""
if dev.simulate:
if not wide:
quantize = Quantize(num_bits=dev.DATA_BITS + output_shift)
clamp = Clamp(
min_val=-(2**(dev.ACTIVATION_BITS-1)),
max_val=2**(dev.ACTIVATION_BITS-1)-1,
)
else:
quantize = Quantize(num_bits=dev.DATA_BITS + 1)
clamp = Clamp(
min_val=-(2**(dev.FULL_ACC_BITS-1)),
max_val=2**(dev.FULL_ACC_BITS-1)-1,
)
else:
quantize = Empty()
if not wide:
clamp = Clamp( # Do not combine with ReLU
min_val=-1.,
max_val=1.,
)
else:
clamp = Clamp(
min_val=-(2.**((dev.FULL_ACC_BITS-2*(dev.DATA_BITS-1))-1)),
max_val=2.**((dev.FULL_ACC_BITS-2*(dev.DATA_BITS-1))-1),
)
return quantize, clamp
def quantize_clamp_pool(pooling):
"""
Return new Quantization and Clamp objects for pooling.
"""
if dev.simulate:
if pooling == 'Avg':
quantize = Round() if dev.round_avg else Floor()
clamp = Clamp(
min_val=-(2**(dev.DATA_BITS-1)),
max_val=2**(dev.DATA_BITS-1)-1,
)
else: # Max, None
quantize = Empty()
clamp = Empty()
else:
quantize = Empty()
if pooling == 'Avg':
clamp = Clamp(min_val=-1., max_val=1.)
else: # Max, None
clamp = Empty()
return quantize, clamp
class Abs(nn.Module):
"""
Return abs(x)
"""
def forward(self, x): # pylint: disable=arguments-differ,no-self-use
"""Forward prop"""
return torch.abs_(x) # abs_() is the in-place version
class Empty(nn.Module):
"""
Do nothing
"""
def forward(self, x): # pylint: disable=arguments-differ,no-self-use
"""Forward prop"""
return x
def get_activation(activation=None):
"""
Return the selected `activation` class ('ReLU', 'Abs', None)
"""
if activation == 'ReLU':
return nn.ReLU(inplace=True)
if activation == 'Abs':
assert dev.device != 84
return Abs()
return Empty()
class Conv2d(nn.Module):
"""
AI8X - 2D pooling ('Avg', 'Max' or None) optionally followed by
2D convolution/transposed 2D convolution and activation ('ReLU', 'Abs', None)
"""
def __init__(
self,
in_channels,
out_channels,
kernel_size,
op='Conv2d',
pooling=None,
pool_size=2,
pool_stride=2,
stride=1,
padding=0,
bias=True,
activation=None,
output_shift=0,
wide=False,
batchnorm=None,
):
super().__init__()
assert not wide or activation is None
if pooling is not None:
if pool_stride is None:
pool_stride = pool_size
if isinstance(pool_size, int):
assert dev.device != 84 or pool_size & 1 == 0
assert pool_size <= 16 \
and (dev.device != 84 or pool_size <= 4 or pooling == 'Max')
elif isinstance(pool_size, tuple):
assert len(pool_size) == 2
assert dev.device != 84 or pool_size[0] & 1 == 0
assert pool_size[0] <= 16 \
and (dev.device != 84 or pool_size[0] <= 4 or pooling == 'Max')
assert dev.device != 84 or pool_size[1] & 1 == 0
assert pool_size[1] <= 16 \
and (dev.device != 84 or pool_size[1] <= 4 or pooling == 'Max')
else:
raise ValueError('pool_size must be int or tuple')
if isinstance(pool_stride, int):
assert pool_stride > 0
assert pool_stride <= 16 \
and (dev.device != 84 or pool_stride <= 4 or pooling == 'Max')
elif isinstance(pool_stride, tuple):
assert len(pool_stride) == 2
assert dev.device != 84 or pool_stride[0] == pool_stride[1]
assert 0 < pool_stride[0] <= 16 \
and (dev.device != 84 or pool_stride[0] <= 4 or pooling == 'Max')
assert 0 < pool_stride[1] <= 16 \
and (dev.device != 84 or pool_stride[1] <= 4 or pooling == 'Max')
else:
raise ValueError('pool_stride must be int or tuple')
if op == 'ConvTranspose2d':
assert stride == 2
else:
assert stride == 1
else:
if op == 'ConvTranspose2d':
assert stride == 2
else:
assert 0 < stride <= 3
assert 0 <= padding <= 2
if pooling == 'Max':
self.pool = nn.MaxPool2d(kernel_size=pool_size, stride=pool_stride, padding=0)
elif pooling == 'Avg':
self.pool = nn.AvgPool2d(kernel_size=pool_size, stride=pool_stride, padding=0)
else:
self.pool = None
if batchnorm == 'Affine':
self.bn = nn.BatchNorm2d(out_channels, eps=1e-05, momentum=0.05, affine=True)
elif batchnorm == 'NoAffine':
self.bn = nn.BatchNorm2d(out_channels, eps=1e-05, momentum=0.05, affine=False)
else:
self.bn = None
if kernel_size is not None:
if isinstance(kernel_size, tuple):
assert len(kernel_size) == 2 and kernel_size[0] == kernel_size[1]
kernel_size = kernel_size[0]
assert kernel_size == 3 or dev.device != 84 and kernel_size == 1
if op == 'Conv2d':
self.conv2d = nn.Conv2d(in_channels, out_channels,
kernel_size=kernel_size, stride=stride,
padding=padding, bias=bias)
elif op == 'ConvTranspose2d':
assert dev.device != 84
self.conv2d = nn.ConvTranspose2d(in_channels, out_channels,
kernel_size=kernel_size, stride=stride,
output_padding=1,
padding=padding, bias=bias)
else:
raise ValueError('Unsupported operation')
else:
self.conv2d = None
self.quantize_pool, self.clamp_pool = quantize_clamp_pool(pooling)
self.quantize, self.clamp = quantize_clamp(wide, output_shift)
self.activate = get_activation(activation)
def forward(self, x): # pylint: disable=arguments-differ
"""Forward prop"""
if self.pool is not None:
x = self.clamp_pool(self.quantize_pool(self.pool(x)))
if self.conv2d is not None:
x = self.conv2d(x)
if self.bn is not None:
x = self.bn(x)
x = self.clamp(self.quantize(self.activate(x)))
return x
class FusedMaxPoolConv2d(Conv2d):
"""
AI8X - Fused 2D Max Pool, 2D Convolution and Activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, pooling='Max', **kwargs)
class FusedMaxPoolConv2dReLU(FusedMaxPoolConv2d):
"""
AI8X - Fused 2D Max Pool, 2D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedMaxPoolConv2dBNReLU(FusedMaxPoolConv2dReLU):
"""
AI8X - Fused 2D Max Pool, 2D Convolution, BatchNorm and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, batchnorm='NoAffine', **kwargs)
class FusedMaxPoolConv2dAbs(FusedMaxPoolConv2d):
"""
AI8X - Fused 2D Max Pool, 2D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class MaxPool2d(FusedMaxPoolConv2d):
"""
AI8X - 2D Max Pool
"""
def __init__(self, kernel_size, stride=None, **kwargs):
super().__init__(0, 0, None, pool_size=kernel_size, pool_stride=stride,
activation=None, **kwargs)
class FusedAvgPoolConv2d(Conv2d):
"""
AI8X - Fused 2D Avg Pool, 2D Convolution and activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, pooling='Avg', **kwargs)
class FusedAvgPoolConv2dReLU(FusedAvgPoolConv2d):
"""
AI8X - Fused 2D Avg Pool, 2D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedAvgPoolConv2dAbs(FusedAvgPoolConv2d):
"""
AI8X - Fused 2D Avg Pool, 2D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class AvgPool2d(FusedAvgPoolConv2d):
"""
AI8X - 2D Avg Pool
"""
def __init__(self, kernel_size, stride=None, **kwargs):
super().__init__(0, 0, None, pool_size=kernel_size, pool_stride=stride,
activation=None, **kwargs)
class FusedConv2dReLU(Conv2d):
"""
AI8X - Fused 2D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedConv2dBNReLU(FusedConv2dReLU):
"""
AI8X - Fused 2D Convolution and BatchNorm and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, batchnorm='NoAffine', **kwargs)
class FusedConv2dAbs(Conv2d):
"""
AI8X - Fused 2D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class ConvTranspose2d(Conv2d):
"""
AI8X - 2D pooling ('Avg', 'Max' or None) optionally followed by
transposed 2D convolution and activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, op='ConvTranspose2d', **kwargs)
class FusedMaxPoolConvTranspose2d(ConvTranspose2d):
"""
AI8X - Fused 2D Max Pool, Transposed 2D Convolution and Activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, pooling='Max', **kwargs)
class FusedMaxPoolConvTranspose2dReLU(FusedMaxPoolConvTranspose2d):
"""
AI8X - Fused 2D Max Pool, Transposed 2D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedMaxPoolConvTranspose2dAbs(FusedMaxPoolConvTranspose2d):
"""
AI8X - Fused 2D Max Pool, Transposed 2D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class FusedAvgPoolConvTranspose2d(ConvTranspose2d):
"""
AI8X - Fused 2D Avg Pool, Transposed 2D Convolution and activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, pooling='Avg', **kwargs)
class FusedAvgPoolConvTranspose2dReLU(FusedAvgPoolConvTranspose2d):
"""
AI8X - Fused 2D Avg Pool, Transposed 2D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedAvgPoolConvTranspose2dAbs(FusedAvgPoolConvTranspose2d):
"""
AI8X - Fused 2D Avg Pool, Transposed 2D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class FusedConvTranspose2dReLU(ConvTranspose2d):
"""
AI8X - Fused Transposed 2D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedConvTranspose2dAbs(ConvTranspose2d):
"""
AI8X - Fused Transposed 2D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class FusedSoftwareLinearReLU(nn.Module):
"""
AI84 - Fused Linear and ReLU using Software
"""
def __init__(self, in_features, out_features, bias=None, relu=True):
super().__init__()
if dev.device != 84:
print('WARNING: SoftwareLinear should be used on AI84 only')
self.linear = nn.Linear(in_features, out_features, bias)
if dev.simulate:
self.quantize = Quantize(num_bits=dev.DATA_BITS)
bits = dev.FC_ACTIVATION_BITS
self.clamp = Clamp(min_val=-(2**(bits-1)), max_val=2**(bits-1)-1)
else:
self.quantize = Empty()
self.clamp = Clamp(min_val=-1., max_val=1.) # Do not combine with ReLU
if relu:
self.activate = nn.ReLU(inplace=True)
else:
self.activate = Empty()
def forward(self, x): # pylint: disable=arguments-differ
"""Forward prop"""
x = self.linear(x)
x = self.clamp(self.quantize(self.activate(x)))
return x
class SoftwareLinear(FusedSoftwareLinearReLU):
"""
AI84 - Linear using Software
"""
def __init__(self, in_features, out_features, **kwargs):
super().__init__(in_features, out_features, relu=False, **kwargs)
class Linear(nn.Module):
"""
AI85+ - Fused Linear and activation ('ReLU', 'Abs', None)
"""
def __init__(self, in_features, out_features, bias=None,
activation=None, output_shift=0, wide=False):
super().__init__()
assert dev.device != 84
assert in_features <= 1024
assert out_features <= 1024
assert not wide or activation is None
self.linear = nn.Linear(in_features, out_features, bias)
self.quantize, self.clamp = quantize_clamp(wide, output_shift)
self.activate = get_activation(activation)
def forward(self, x): # pylint: disable=arguments-differ
"""Forward prop"""
x = self.linear(x)
x = self.clamp(self.quantize(self.activate(x)))
return x
class FusedLinearReLU(Linear):
"""
AI85+ - Fused Linear and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedLinearAbs(Linear):
"""
AI85+ - Fused Linear and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class Conv1d(nn.Module):
"""
AI8X - Fused 1D Pool ('Avg', 'Max' or None) followed by
1D Convolution and activation ('ReLU', 'Abs', None)
"""
def __init__(
self,
in_channels,
out_channels,
kernel_size,
pooling=None,
pool_size=2,
pool_stride=2,
stride=3,
padding=0,
bias=True,
activation=None,
output_shift=0,
wide=False,
):
super().__init__()
assert not wide or activation is None
if pooling is not None:
if pool_stride is None:
pool_stride = pool_size
assert dev.device != 84 or pool_size & 1 == 0
assert pool_size <= 16 \
and (dev.device != 84 or pool_size <= 4 or pooling == 'Max')
assert 0 < pool_stride <= 16 \
and (dev.device != 84 or pool_stride <= 4 or pooling == 'Max')
assert stride == 1
else:
assert dev.device != 84 or stride == 3
assert dev.device == 84 or stride == 1
if pooling == 'Max':
self.pool = nn.MaxPool1d(kernel_size=pool_size, stride=pool_stride, padding=0)
elif pooling == 'Avg':
self.pool = nn.AvgPool1d(kernel_size=pool_size, stride=pool_stride, padding=0)
else:
self.pool = None
if kernel_size is not None:
assert dev.device != 84 or padding in [0, 3, 6]
assert dev.device == 84 or padding in [0, 1, 2]
assert dev.device != 84 or kernel_size == 9
assert dev.device == 84 or kernel_size in [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.conv1d = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride,
padding=padding, bias=bias)
else:
self.conv1d = None
self.quantize_pool, self.clamp_pool = quantize_clamp_pool(pooling)
self.quantize, self.clamp = quantize_clamp(wide, output_shift)
self.activate = get_activation(activation)
def forward(self, x): # pylint: disable=arguments-differ
"""Forward prop"""
if self.pool is not None:
x = self.clamp_pool(self.quantize_pool(self.pool(x)))
if self.conv1d is not None:
x = self.conv1d(x)
x = self.clamp(self.quantize(self.activate(x)))
return x
class FusedMaxPoolConv1d(Conv1d):
"""
AI8X - Fused 1D Max Pool, 1D Convolution and Activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, pooling='Max', **kwargs)
class FusedMaxPoolConv1dReLU(FusedMaxPoolConv1d):
"""
AI8X - Fused 1D Max Pool, 1D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedMaxPoolConv1dAbs(FusedMaxPoolConv1d):
"""
AI8X - Fused 1D Max Pool, 1D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class MaxPool1d(FusedMaxPoolConv1d):
"""
AI8X - 1D Max Pool
"""
def __init__(self, kernel_size, stride=None, **kwargs):
super().__init__(0, 0, None, pool_size=kernel_size, pool_stride=stride,
activation=None, **kwargs)
class FusedAvgPoolConv1d(Conv1d):
"""
AI8X - Fused 1D Avg Pool, 1D Convolution and activation ('ReLU', 'Abs', None)
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, pooling='Avg', **kwargs)
class FusedAvgPoolConv1dReLU(FusedAvgPoolConv1d):
"""
AI8X - Fused 1D Avg Pool, 1D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedAvgPoolConv1dAbs(FusedAvgPoolConv1d):
"""
AI8X - Fused 1D Avg Pool, 1D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class AvgPool1d(FusedAvgPoolConv1d):
"""
AI8X - 1D Avg Pool
"""
def __init__(self, kernel_size, stride=None, **kwargs):
super().__init__(0, 0, None, pool_size=kernel_size, pool_stride=stride,
activation=None, **kwargs)
class FusedConv1dReLU(Conv1d):
"""
AI8X - Fused 1D Convolution and ReLU
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='ReLU', **kwargs)
class FusedConv1dAbs(Conv1d):
"""
AI8X - Fused 1D Convolution and Abs
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, activation='Abs', **kwargs)
class Eltwise(nn.Module):
"""
AI8X - Base Class for Elementwise Operation
"""
def __init__(self, f):
super().__init__()
self.f = f
if dev.simulate:
bits = dev.ACTIVATION_BITS
self.clamp = Clamp(min_val=-(2**(bits-1)), max_val=2**(bits-1)-1)
else:
self.clamp = Clamp(min_val=-1., max_val=1.)
def forward(self, *x):
"""Forward prop"""
y = x[0]
for i in range(1, len(x)):
y = self.f(y, x[i])
x = self.clamp(y)
return x
class Add(Eltwise):
"""
AI8X - Elementwise Add Operation
"""
def __init__(self):
super().__init__(torch.add)
class Sub(Eltwise):
"""
AI8X - Elementwise Subtract Operation
"""
@staticmethod
def sub(a, b):
"""
Subtract Tensors
"""
return torch.add(a, torch.neg(b))
def __init__(self):
super().__init__(self.sub)
class Xor(Eltwise):
"""
AI8X - Elementwise Bitwise Xor Operation
"""
@staticmethod
def bitwise_xor(a, b):
"""
Bitwise XOR of Tensors via int intermediate
"""
# Convert input from float to byte
a = a.add(.5).mul(256.).round().int()
b = b.add(.5).mul(256.).round().int()
# Bitwise XOR on integers, convert back to float
return torch.bitwise_or(a, b).div(256.).sub(.5)
def __init__(self):
super().__init__(self.bitwise_xor)
class Or(Eltwise):
"""
AI8X - Elementwise Bitwise Or Operation
"""
@staticmethod
def bitwise_or(a, b):
"""
Bitwise OR of Tensors via int intermediate
"""
a = a.add(.5).mul(256.).round().int()
b = b.add(.5).mul(256.).round().int()
# Bitwise OR on integers, convert back to float
return torch.bitwise_xor(a, b).div(256.).sub(.5)
def __init__(self):
super().__init__(self.bitwise_or)
class Device:
"""
Device base class
"""
def __init__(self, device, simulate, round_avg):
self.device = device
self.simulate = simulate
self.round_avg = round_avg
def __str__(self):
return self.__class__.__name__
class DevAI84(Device):
"""
Implementation limits for AI84
"""
def __init__(self, simulate, round_avg):
assert not round_avg
super().__init__(84, simulate, round_avg)
self.WEIGHT_BITS = 8
self.DATA_BITS = 8
self.ACTIVATION_BITS = 8
self.FULL_ACC_BITS = 8
self.FC_ACTIVATION_BITS = 16
self.WEIGHT_INPUTS = 64
self.WEIGHT_DEPTH = 128
self.MAX_AVG_POOL = 4
def __str__(self):
return self.__class__.__name__
class DevAI85(Device):
"""
Implementation limits for AI85
"""
def __init__(self, simulate, round_avg):
super().__init__(85, simulate, round_avg)
self.WEIGHT_BITS = 8
self.DATA_BITS = 8
self.ACTIVATION_BITS = 8
self.FULL_ACC_BITS = 30
self.FC_ACTIVATION_BITS = 16
self.WEIGHT_INPUTS = 256
self.WEIGHT_DEPTH = 768
self.MAX_AVG_POOL = 16
def __str__(self):
return self.__class__.__name__
class DevAI87(DevAI85):
"""
Implementation limits for AI87. For now, the same as AI85.
"""
def __str__(self):
return self.__class__.__name__
def set_device(
device,
simulate,
round_avg,
):
"""
Change implementation configuration to match the `device` input value and
`simulate` bool. `round_avg` (AI85+) controls the average pooling rounding.
"""
global dev # pylint: disable=global-statement
print(f'Configuring device: {devices.partnum(device)}, simulate={simulate}.')
if device == 84:
dev = DevAI84(simulate, round_avg)
elif device == 85:
dev = DevAI85(simulate, round_avg)
elif device == 87:
dev = DevAI87(simulate, round_avg)
else:
raise ValueError(f'Unkown device {device}.')