forked from adelmanm/approx
-
Notifications
You must be signed in to change notification settings - Fork 1
/
approx_conv2d.py
1065 lines (851 loc) · 55.7 KB
/
approx_conv2d.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
import torch
#import approx_conv2d
from ..modules.utils import topk_indices
''' shape - shape of grad_input. expected: (batch, in_channels,h,w)
weight - weight tensor, shape (out_channels, in_channels, h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def conv2d_bwd_topk(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k):
#print("Sanity check - conv2d_bwd_topk is used with sample_ratio = " + str(sample_ratio) + " and minimal_k = " + str(minimal_k))
#print("shape: {}".format(shape))
#print("weight size: {}".format(weight.size()))
#print("grad_output size: {}".format(grad_output.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
out_channels = weight.size()[0]
# calculate the number of input channels to sample
k_candidate = int(float(out_channels)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),out_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d_bwd instead of approximating
if k == out_channels:
return approx_conv2d.backward_input(shape, weight, grad_output, stride, padding, dilation, groups, False, False, True)
# calculate norms of output channels
weight_out_channels_norms = torch.norm(weight.view(out_channels,-1),dim=1, p=2)
grad_output_out_channels_norms = torch.norm(grad_output.view(grad_output.size()[0],out_channels,-1), dim=2, p=2)
grad_output_out_channels_norms = torch.norm(grad_output_out_channels_norms, dim=0, p=2)
grad_output_out_channels_norms = torch.squeeze(grad_output_out_channels_norms)
# multiply both norms element-wise to and pick the indices of the top K channels
norm_mult = torch.mul(weight_out_channels_norms, grad_output_out_channels_norms)
# top_k_indices = torch.topk(norm_mult,k)[1]
top_k_indices = topk_indices(norm_mult,k)
# pick top-k channels to form new smaller tensors
weight_top_k_channels = torch.index_select(weight,dim = 0, index = top_k_indices)
grad_output_top_k_channels = torch.index_select(grad_output,dim = 1, index = top_k_indices)
# compute sampled tensors
grad_input_approx = approx_conv2d.backward_input(shape, weight_top_k_channels, grad_output_top_k_channels, stride, padding, dilation, groups, False, False, True)
return grad_input_approx
''' shape - shape of grad_input. expected: (batch, in_channels,h,w)
weight - weight tensor, shape (out_channels, in_channels, h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def conv2d_bwd_random_sampling(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, with_replacement, optimal_prob, scale):
#print("Sanity check - conv2d_bwd_random_sampling is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("shape: {}".format(shape))
#print("weight size: {}".format(weight.size()))
#print("grad_output size: {}".format(grad_output.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("with_replacement: {}".format(with_replacement))
#print("optimal_prob: {}".format(optimal_prob))
#print("scale: {}".format(scale))
out_channels = weight.size()[0]
device = weight.device
# calculate the number of input channels to sample
k_candidate = int(float(out_channels)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),out_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d_bwd instead of approximating
if k == out_channels:
return approx_conv2d.backward_input(shape, weight, grad_output, stride, padding, dilation, groups, False, False, True)
if optimal_prob == True:
# calculate norms of output channels
weight_out_channels_norms = torch.norm(weight.view(out_channels,-1),dim=1, p=2)
grad_output_out_channels_norms = torch.norm(grad_output.view(grad_output.size()[0],out_channels,-1),p=2, dim=2)
grad_output_out_channels_norms = torch.norm(grad_output_out_channels_norms, dim=0, p=2)
grad_output_out_channels_norms = torch.squeeze(grad_output_out_channels_norms)
# multiply both norms element-wise
norm_mult = torch.mul(weight_out_channels_norms, grad_output_out_channels_norms)
# use epsilon-optimal sampling to allow learning random weights and to bound the scaling factor
epsilon = 0.1
if epsilon > 0:
sum_norm_mult = torch.sum(norm_mult)
norm_mult = torch.div(norm_mult, sum_norm_mult)
uniform = torch.ones_like(norm_mult)/out_channels
norm_mult = (1-epsilon)*norm_mult + epsilon*uniform
# no need to normalize, it is already done by torch.multinomial
# calculate number of nonzero elements in norm_mult. this serves
# two purposes:
# 1. Possibly reduce number of sampled pairs, as zero elements in norm_mult will not contribute to the result
# 2. Prevents scaling of zero values
nnz = (norm_mult!=0).sum()
if nnz == 0:
#print("zero multiply detected! scenario not optimzied (todo)")
return approx_conv2d.backward_input(shape, weight, grad_output, stride, padding, dilation, groups, False, False, True)
k = min(k,nnz)
indices = torch.multinomial(norm_mult,k,replacement=with_replacement)
# pick top-k channels to form new smaller tensors
weight_top_k_channels = torch.index_select(weight,dim = 0, index = indices)
grad_output_top_k_channels = torch.index_select(grad_output,dim = 1, index = indices)
if scale == True:
# when sampling without replacement a more complicated scaling factor is required (see Horvitz and Thompson, 1952)
assert(with_replacement == True)
# scale out_channels by 1/(k*p_i) to get unbiased estimation
sum_norm_mult = torch.sum(norm_mult)
scale_factors = torch.div(sum_norm_mult,torch.mul(norm_mult,k))
weight_top_k_channels = torch.mul(weight_top_k_channels, scale_factors[indices].view(-1,1,1,1))
else:
# uniform sampling
if with_replacement == True:
indices = torch.randint(low=0,high=out_channels,size=(k,),device=device)
else:
uniform_dist = torch.ones(out_channels,device=device)
indices = torch.multinomial(uniform_dist,k,replacement=False)
# pick k channels to form new smaller tensors
weight_top_k_channels = torch.index_select(weight,dim = 0, index = indices)
grad_output_top_k_channels = torch.index_select(grad_output,dim = 1, index = indices)
if scale == True:
# scale column-row pairs by 1/(k*p_i) to get unbiased estimation
# in case of uniform distribution, p_i = 1/in_features when sampling with replacement
# when sampling without replacement a different scaling factor is required (see Horvitz and Thompson, 1952), but
# for uniform sampling it turns to be in_features/k as well
scale_factor = out_channels/k
weight_top_k_channels = torch.mul(weight_top_k_channels, scale_factor)
# compute sampled tensors
grad_input_approx = approx_conv2d.backward_input(shape, weight_top_k_channels, grad_output_top_k_channels, stride, padding, dilation, groups, False, False, True)
return grad_input_approx
''' shape - shape of grad_input. expected: (batch, in_channels,h,w)
weight - weight tensor, shape (out_channels, in_channels, h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def conv2d_bwd_bernoulli_sampling(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, scale):
#print("Sanity check - conv2d_bwd_bernoulli_sampling is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("shape: {}".format(shape))
#print("weight size: {}".format(weight.size()))
#print("grad_output size: {}".format(grad_output.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("scale: {}".format(scale))
out_channels = weight.size()[0]
device = weight.device
# calculate the number of input channels to sample
k_candidate = int(float(out_channels)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),out_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d_bwd instead of approximating
if k == out_channels:
return approx_conv2d.backward_input(shape, weight, grad_output, stride, padding, dilation, groups, False, False, True)
# calculate norms of output channels
weight_out_channels_norms = torch.norm(weight.view(out_channels,-1),dim=1, p=2)
grad_output_out_channels_norms = torch.norm(grad_output.view(grad_output.size()[0],out_channels,-1),p=2, dim=2)
grad_output_out_channels_norms = torch.norm(grad_output_out_channels_norms, dim=0, p=2)
grad_output_out_channels_norms = torch.squeeze(grad_output_out_channels_norms)
# multiply both norms element-wise
norm_mult = torch.mul(weight_out_channels_norms, grad_output_out_channels_norms)
sum_norm_mult = norm_mult.sum()
# calculate number of nonzero elements in norm_mult. this serves
# two purposes:
# 1. Possibly reduce number of sampled pairs, as zero elements in norm_mult will not contribute to the result
# 2. Prevents scaling of zero values
nnz = (norm_mult!=0).sum()
if nnz == 0:
#print("zero multiply detected! scenario not optimzied (todo)")
return approx_conv2d.backward_input(shape, weight, grad_output, stride, padding, dilation, groups, False, False, True)
k = min(k,nnz)
prob_dist = k * torch.div(norm_mult,sum_norm_mult)
prob_dist = prob_dist.clamp(min=0, max=1)
# use epsilon-optimal sampling to allow learning random weights and to bound the scaling factor
epsilon = 0.1
if epsilon > 0:
uniform = torch.ones_like(prob_dist)/out_channels
prob_dist = (1-epsilon)*prob_dist + epsilon*uniform
indices = torch.bernoulli(prob_dist).nonzero(as_tuple=True)[0]
if len(indices) == 0:
print("no elements selected - hmm")
indices = torch.arange(k, device=device)
# pick top-k channels to form new smaller tensors
weight_top_k_channels = torch.index_select(weight,dim = 0, index = indices)
grad_output_top_k_channels = torch.index_select(grad_output,dim = 1, index = indices)
if scale == True:
# scale out_channels by 1/(p_i) to get unbiased estimation
scale_factors = torch.div(1,prob_dist)
weight_top_k_channels = torch.mul(weight_top_k_channels, scale_factors[indices].view(-1,1,1,1))
# compute sampled tensors
grad_input_approx = approx_conv2d.backward_input(shape, weight_top_k_channels, grad_output_top_k_channels, stride, padding, dilation, groups, False, False,True)
return grad_input_approx
''' shape - shape of grad_input. expected: (batch, in_channels,h,w)
weight - weight tensor, shape (out_channels, in_channels, h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def approx_conv2d_func_bwd(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k):
#return approx_conv2d.backward_input(shape, weight, grad_output, stride, padding, dilation, groups, False, False, True)
#return conv2d_bwd_topk(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k)
#return conv2d_bwd_random_sampling(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, with_replacement=True, optimal_prob=True, scale=True)
return conv2d_bwd_bernoulli_sampling(shape, weight, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, scale=True)
''' input - input tensor, shape (batch, in_channels, h, w)
weight_shape - shape of grad_weight. expected: (out_channels, in_channels,h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def conv2d_wu_topk(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k):
#print("Sanity check - conv2d_bwd_wu is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("input: {}".format(input))
#print("weight_shape: {}".format(weight_shape))
#print("input size: {}".format(input.size()))
#print("grad_output size: {}".format(grad_output.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
batch = input.size()[0]
# calculate the number of minibatch examples to sample
k_candidate = int(float(batch)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),batch)
# if because of minimal_k or sample_ratio k equals the minibatch size, perform full conv2d_wu instead of approximating
if k == batch:
return approx_conv2d.backward_weight(input, weight_shape, grad_output, stride, padding, dilation, groups, False, False, True)
# calculate norms of minibatch examples
input_batch_norms = torch.norm(input.view(batch,-1),dim=1, p=2)
grad_output_batch_norms = torch.norm(grad_output.view(batch,-1),dim=1, p=2)
# multiply both norms element-wise to and pick the indices of the top K minibatch examples
norm_mult = torch.mul(input_batch_norms, grad_output_batch_norms)
# top_k_indices = torch.topk(norm_mult,k)[1]
top_k_indices = topk_indices(norm_mult,k)
# pick top-k batch examples to form new smaller tensors
input_top_k_batch = torch.index_select(input,dim = 0, index = top_k_indices)
grad_output_top_k_batch = torch.index_select(grad_output,dim = 0, index = top_k_indices)
# compute sampled tensors
grad_weight_approx = approx_conv2d.backward_weight(input_top_k_batch, weight_shape, grad_output_top_k_batch, stride, padding, dilation, groups, False, False, True)
return grad_weight_approx
''' input - input tensor, shape (batch, in_channels, h, w)
weight_shape - shape of grad_weight. expected: (out_channels, in_channels,h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def conv2d_wu_random_sampling(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, with_replacement, optimal_prob, scale):
#print("Sanity check - conv2d_bwd_wu is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("input: {}".format(input))
#print("weight_shape: {}".format(weight_shape))
#print("input size: {}".format(input.size()))
#print("grad_output size: {}".format(grad_output.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("with_replacement: {}".format(with_replacement))
#print("optimal_prob: {}".format(optimal_prob))
#print("scale: {}".format(scale))
batch = input.size()[0]
device = input.device
# calculate the number of minibatch examples to sample
k_candidate = int(float(batch)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),batch)
# if because of minimal_k or sample_ratio k equals the minibatch size, perform full conv2d_wu instead of approximating
if k == batch:
return approx_conv2d.backward_weight(input, weight_shape, grad_output, stride, padding, dilation, groups, False, False, True)
if optimal_prob == True:
# calculate norms of output channels
input_batch_norms = torch.norm(input.view(batch, -1),dim=1, p=2)
grad_output_batch_norms = torch.norm(grad_output.view(batch, -1) ,dim=1, p=2)
# multiply both norms element-wise
norm_mult = torch.mul(input_batch_norms, grad_output_batch_norms)
# use epsilon-optimal sampling to allow learning random weights and to bound the scaling factor
epsilon = 0.1
if epsilon > 0:
sum_norm_mult = torch.sum(norm_mult)
norm_mult = torch.div(norm_mult, sum_norm_mult)
uniform = torch.ones_like(norm_mult)/batch
norm_mult = (1-epsilon)*norm_mult + epsilon*uniform
# no need to normalize, it is already done by torch.multinomial
# calculate number of nonzero elements in norm_mult. this serves
# two purposes:
# 1. Possibly reduce number of sampled pairs, as zero elements in norm_mult will not contribute to the result
# 2. Prevents scaling of zero values
nnz = (norm_mult!=0).sum()
if nnz == 0:
#print("zero multiply detected! scenario not optimzied (todo)")
return approx_conv2d.backward_weight(input, weight_shape, grad_output, stride, padding, dilation, groups, False, False, True)
k = min(k,nnz)
indices = torch.multinomial(norm_mult,k,replacement=with_replacement)
# pick top-k minibatch examples to form new smaller tensors
input_top_k_batch = torch.index_select(input,dim = 0, index = indices)
grad_output_top_k_batch = torch.index_select(grad_output,dim = 0, index = indices)
if scale == True:
# when sampling without replacement a more complicated scaling factor is required (see Horvitz and Thompson, 1952)
assert(with_replacement == True)
# scale out_channels by 1/(k*p_i) to get unbiased estimation
sum_norm_mult = torch.sum(norm_mult)
scale_factors = torch.div(sum_norm_mult,torch.mul(norm_mult,k))
input_top_k_batch = torch.mul(input_top_k_batch, scale_factors[indices].view(-1,1,1,1))
else:
# uniform sampling
if with_replacement == True:
indices = torch.randint(low=0,high=batch,size=(k,),device=device)
else:
uniform_dist = torch.ones(batch,device=device)
indices = torch.multinomial(uniform_dist,k,replacement=False)
# pick top-k minibatch examples to form new smaller tensors
input_top_k_batch = torch.index_select(input,dim = 0, index = indices)
grad_output_top_k_batch = torch.index_select(grad_output,dim = 0, index = indices)
if scale == True:
# scale sampled batch examples by 1/(k*p_i) to get unbiased estimation
# in case of uniform distribution, p_i = 1/in_features when sampling with replacement
# when sampling without replacement a different scaling factor is required (see Horvitz and Thompson, 1952), but
# for uniform sampling it turns to be in_features/k as well
scale_factor = batch/k
input_top_k_batch = torch.mul(input_top_k_batch, scale_factor)
# compute sampled tensors
grad_weight_approx = approx_conv2d.backward_weight(input_top_k_batch, weight_shape, grad_output_top_k_batch, stride, padding, dilation, groups, False, False, True)
return grad_weight_approx
''' input - input tensor, shape (batch, in_channels, h, w)
weight_shape - shape of grad_weight. expected: (out_channels, in_channels,h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def conv2d_wu_bernoulli_sampling(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, scale):
#print("Sanity check - conv2d_wu_bernoulli is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("input: {}".format(input))
#print("weight_shape: {}".format(weight_shape))
#print("input size: {}".format(input.size()))
#print("grad_output size: {}".format(grad_output.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("scale: {}".format(scale))
batch = input.size()[0]
device = input.device
# calculate the number of minibatch examples to sample
k_candidate = int(float(batch)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),batch)
# if because of minimal_k or sample_ratio k equals the minibatch size, perform full conv2d_wu instead of approximating
if k == batch:
return approx_conv2d.backward_weight(input, weight_shape, grad_output, stride, padding, dilation, groups, False, False, True)
# calculate norms of output channels
input_batch_norms = torch.norm(input.view(batch, -1),dim=1, p=2)
grad_output_batch_norms = torch.norm(grad_output.view(batch, -1) ,dim=1, p=2)
# multiply both norms element-wise
norm_mult = torch.mul(input_batch_norms, grad_output_batch_norms)
sum_norm_mult = norm_mult.sum()
# calculate number of nonzero elements in norm_mult. this serves
# two purposes:
# 1. Possibly reduce number of sampled pairs, as zero elements in norm_mult will not contribute to the result
# 2. Prevents scaling of zero values
nnz = (norm_mult!=0).sum()
if nnz == 0:
#print("zero multiply detected! scenario not optimzied (todo)")
return approx_conv2d.backward_weight(input, weight_shape, grad_output, stride, padding, dilation, groups, False, False, True)
k = min(k,nnz)
prob_dist = k * torch.div(norm_mult,sum_norm_mult)
prob_dist = prob_dist.clamp(min=0, max=1)
# use epsilon-optimal sampling to allow learning random weights and to bound the scaling factor
epsilon = 0.1
if epsilon > 0:
uniform = torch.ones_like(prob_dist)/batch
prob_dist = (1-epsilon)*prob_dist + epsilon*uniform
indices = torch.bernoulli(prob_dist).nonzero(as_tuple=True)[0]
if len(indices) == 0:
print("no elements selected - hmm")
indices = torch.arange(k, device=device)
# pick top-k minibatch examples to form new smaller tensors
input_top_k_batch = torch.index_select(input,dim = 0, index = indices)
grad_output_top_k_batch = torch.index_select(grad_output,dim = 0, index = indices)
if scale == True:
# scale out_channels by 1/(p_i) to get unbiased estimation
scale_factors = torch.div(1,prob_dist)
input_top_k_batch = torch.mul(input_top_k_batch, scale_factors[indices].view(-1,1,1,1))
# compute sampled tensors
grad_weight_approx = approx_conv2d.backward_weight(input_top_k_batch, weight_shape, grad_output_top_k_batch, stride, padding, dilation, groups, False, False, True)
return grad_weight_approx
''' input - input tensor, shape (batch, in_channels, h, w)
weight_shape - shape of grad_weight. expected: (out_channels, in_channels,h,w)
grad_output - grad output tensor, shape (batch, out_channels, h,w)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of out_channels to sample
minimal_k - Minimal number of out_channels to keep in the sampling
'''
def approx_conv2d_func_wu(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k):
#return approx_conv2d.backward_weight(input, weight_shape, grad_output, stride, padding, dilation, groups, False, False, True)
#return conv2d_wu_topk(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k)
#return conv2d_wu_random_sampling(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, with_replacement=True, optimal_prob=True, scale=True)
return conv2d_wu_bernoulli_sampling(input, weight_shape, grad_output, stride, padding, dilation, groups, sample_ratio,minimal_k, scale=True)
def approx_conv2d_func_forward(A,B,bias, stride, padding, dilation, groups, sample_ratio,minimal_k):
#return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
return conv2d_top_k(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k)
# return conv2d_top_k_weights(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k)
#return conv2d_top_k_approx(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k)
#return conv2d_top_k_adaptive(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k)
#return approx_conv2d.forward(A, B, bias, stride, padding, dilation, groups, sample_ratio, minimal_k, False, False, True)
#return conv2d_narrow(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k)
#return conv2d_uniform_sampling(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k)
#return conv2d_random_sampling(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k, with_replacement=True, optimal_prob=True, scale=True)
#return conv2d_random_sampling_adaptive(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k, with_replacement=False, optimal_prob=True, scale=False)
#return conv2d_bernoulli_sampling(A=A.float(),B=B.float(),bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups, sample_ratio=sample_ratio, minimal_k=minimal_k, scale=True)
''' Approximates 2d convolution with channel sampling
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
with_replacement - True means sampling is done with replacement, False means sampling without replacement
optimal_prob - True means sampling probability is proportional to |Ai|*|Bi|. False means uniform distribution.
scale - True means each input channel is scaled by 1/sqrt(K*pi) to ensure bias 0
'''
def conv2d_random_sampling(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k, with_replacement, optimal_prob, scale):
#print("Sanity check - conv2d_random_sampling is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("A size: {}".format(A.size()))
#print("B size: {}".format(B.size()))
#print("bias size: {}".format(bias.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("with_replacement: {}".format(with_replacement))
#print("optimal_prob: {}".format(optimal_prob))
#print("scale: {}".format(scale))
#print("A mean: {}".format(A.mean()))
#print("A std: {}".format(A.std()))
#print("B mean: {}".format(B.mean()))
#print("B std: {}".format(B.std()))
in_channels = A.size()[1]
device = A.device
# calculate the number of input channels to sample
k_candidate = int(float(in_channels)*sample_ratio)
# make k at least minimal_k
k = min(max(k_candidate,minimal_k),in_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d instead of approximating
if k == in_channels:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
if optimal_prob == True:
with torch.no_grad():
# calculate norms of the input channels of A and B
a_channel_norms = torch.norm(A.view(A.size()[0],A.size()[1],-1),p=2, dim=2)
a_channel_norms = torch.norm(a_channel_norms, dim=0, p=2)
a_channel_norms = torch.squeeze(a_channel_norms)
b_channel_norms = torch.norm(B.view(B.size()[0],B.size()[1],-1),p=2, dim=2)
b_channel_norms = torch.norm(b_channel_norms, dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
# multiply both norms element-wise
norm_mult = torch.mul(a_channel_norms,b_channel_norms)
# use epsilon-optimal sampling to allow learning random weights and to bound the scaling factor
epsilon = 0.1
if epsilon > 0:
sum_norm_mult = torch.sum(norm_mult)
norm_mult = torch.div(norm_mult, sum_norm_mult)
uniform = torch.ones_like(norm_mult)/in_channels
norm_mult = (1-epsilon)*norm_mult + epsilon*uniform
# no need to normalize, it is already done by torch.multinomial
# calculate number of nonzero elements in norm_mult. this serves
# two purposes:
# 1. Possibly reduce number of sampled pairs, as zero elements in norm_mult will not contribute to the result
# 2. Prevents scaling of zero values
nnz = (norm_mult!=0).sum()
if nnz == 0:
#print("zero multiply detected! scenario not optimzied (todo)")
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
k = min(k,nnz)
indices = torch.multinomial(norm_mult,k,replacement=with_replacement)
# pick k channels to form new smaller tensors
A_top_k_channels = torch.index_select(A,dim = 1, index = indices)
B_top_k_channels = torch.index_select(B,dim = 1, index = indices)
if scale == True:
# when sampling without replacement a more complicated scaling factor is required (see Horvitz and Thompson, 1952)
assert(with_replacement == True)
# scale column-row pairs by 1/(k*p_i) to get unbiased estimation
with torch.no_grad():
sum_norm_mult = torch.sum(norm_mult)
scale_factors = torch.div(sum_norm_mult,torch.mul(norm_mult,k))
A_top_k_channels = torch.mul(A_top_k_channels, scale_factors[indices].view(1,-1,1,1))
else:
# uniform sampling
if with_replacement == True:
indices = torch.randint(low=0,high=in_channels,size=(k,),device=device)
else:
uniform_dist = torch.ones(in_channels,device=device)
indices = torch.multinomial(uniform_dist,k,replacement=False)
# pick k column-row pairs to form new smaller matrices
A_top_k_channels = torch.index_select(A, dim=1, index=indices)
B_top_k_channels = torch.index_select(B, dim=1, index=indices)
if scale == True:
# scale column-row pairs by 1/(k*p_i) to get unbiased estimation
# in case of uniform distribution, p_i = 1/in_features when sampling with replacement
# when sampling without replacement a different scaling factor is required (see Horvitz and Thompson, 1952), but
# for uniform sampling it turns to be in_features/k as well
scale_factor = in_channels/k
A_top_k_channels = torch.mul(A_top_k_channels, scale_factor)
# convolve smaller tensors
C_approx = torch.nn.functional.conv2d(input=A_top_k_channels, weight=B_top_k_channels, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
return C_approx
''' Approximates 2d convolution with channel sampling
the number of channels sampled will vary according to norm concentration
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
with_replacement - True means sampling is done with replacement, False means sampling without replacement
optimal_prob - True means sampling probability is proportional to |Ai|*|Bi|. False means uniform distribution.
scale - True means each input channel is scaled by 1/sqrt(K*pi) to ensure bias 0
'''
def conv2d_random_sampling_adaptive(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k, with_replacement, optimal_prob, scale):
#print("Sanity check - conv2d_random_sampling adaptive is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("A size: {}".format(A.size()))
#print("B size: {}".format(B.size()))
#print("bias size: {}".format(bias.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("with_replacement: {}".format(with_replacement))
#print("optimal_prob: {}".format(optimal_prob))
#print("scale: {}".format(scale))
#print("A mean: {}".format(A.mean()))
#print("A std: {}".format(A.std()))
#print("B mean: {}".format(B.mean()))
#print("B std: {}".format(B.std()))
in_channels = A.size()[1]
device = A.device
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d instead of approximating
if minimal_k >= in_channels or sample_ratio == 1.0:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
if optimal_prob == True:
with torch.no_grad():
# calculate norms of the input channels of A and B
a_channel_norms = torch.norm(A.view(A.size()[0],A.size()[1],-1),p=2, dim=2)
a_channel_norms = torch.norm(a_channel_norms, dim=0, p=2)
a_channel_norms = torch.squeeze(a_channel_norms)
b_channel_norms = torch.norm(B.view(B.size()[0],B.size()[1],-1),p=2, dim=2)
b_channel_norms = torch.norm(b_channel_norms, dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
# multiply both norms element-wise
norm_mult = torch.mul(a_channel_norms,b_channel_norms)
# use epsilon-optimal sampling to allow learning random weights and to bound the scaling factor
epsilon = 0.1
if epsilon > 0:
sum_norm_mult = torch.sum(norm_mult)
norm_mult = torch.div(norm_mult, sum_norm_mult)
uniform = torch.ones_like(norm_mult)/in_channels
norm_mult = (1-epsilon)*norm_mult + epsilon*uniform
# no need to normalize, it is already done by torch.multinomial
# calculate number of nonzero elements in norm_mult. this serves
# two purposes:
# 1. Possibly reduce number of sampled pairs, as zero elements in norm_mult will not contribute to the result
# 2. Prevents scaling of zero values
nnz = (norm_mult!=0).sum()
if nnz == 0:
#print("zero multiply detected! scenario not optimzied (todo)")
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
sum_norm_mult = torch.sum(norm_mult)
sorted_indices = topk_indices(norm_mult,in_channels)
for k in range(minimal_k, in_channels):
if norm_mult[sorted_indices[:k]].sum() >= sum_norm_mult*sample_ratio:
break
indices = torch.multinomial(norm_mult,k,replacement=with_replacement)
# pick k channels to form new smaller tensors
A_top_k_channels = torch.index_select(A,dim = 1, index = indices)
B_top_k_channels = torch.index_select(B,dim = 1, index = indices)
if scale == True:
# when sampling without replacement a more complicated scaling factor is required (see Horvitz and Thompson, 1952)
assert(with_replacement == True)
# scale column-row pairs by 1/(k*p_i) to get unbiased estimation
with torch.no_grad():
sum_norm_mult = torch.sum(norm_mult)
scale_factors = torch.div(sum_norm_mult,torch.mul(norm_mult,k))
A_top_k_channels = torch.mul(A_top_k_channels, scale_factors[indices].view(1,-1,1,1))
else:
# uniform sampling
print('adaptive sampling not implemented yet for uniform sampling')
exit()
# convolve smaller tensors
C_approx = torch.nn.functional.conv2d(input=A_top_k_channels, weight=B_top_k_channels, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
return C_approx
''' Approximates 2d convolution with channel sampling according to largest norm
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
'''
def conv2d_top_k(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
#print("Sanity check - conv2d_top_k is used with sample_ratio = " + str(sample_ratio) + " and minimal_k = " + str(minimal_k))
in_channels = A.size()[1]
# calculate the number of channels to sample for the forward propagation phase
k_candidate = int(float(in_channels)*sample_ratio)
# make k at least min_clrows (similar to meProp)
k = min(max(k_candidate,minimal_k),in_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d instead of approximating
if k == in_channels:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
# calculate norms of the columns of A and rows of B
with torch.no_grad():
a_channel_norms = torch.norm(A.view(A.size()[0],A.size()[1],-1),p=2, dim=2)
a_channel_norms = torch.norm(a_channel_norms, dim=0, p=2)
a_channel_norms = torch.squeeze(a_channel_norms)
b_channel_norms = torch.norm(B.view(B.size()[0],B.size()[1],-1),p=2, dim=2)
b_channel_norms = torch.norm(b_channel_norms, dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
# multiply both norms element-wise to and pick the indices of the top K column-row pairs
norm_mult = torch.mul(a_channel_norms,b_channel_norms)
#top_k_indices = torch.topk(norm_mult,k)[1]
top_k_indices = topk_indices(norm_mult,k)
# pick top-k column-row pairs to form new smaller matrices
A_top_k_cols = torch.index_select(A,dim = 1, index = top_k_indices)
B_top_k_rows = torch.index_select(B,dim = 1, index = top_k_indices)
# multiply smaller matrices
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx
''' Approximates 2d convolution with channel sampling according to largest norm
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
'''
def conv2d_top_k_weights(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
#print("Sanity check - conv2d_top_k_weights is used with sample_ratio = " + str(sample_ratio) + " and minimal_k = " + str(minimal_k))
in_channels = A.size()[1]
# calculate the number of channels to sample for the forward propagation phase
k_candidate = int(float(in_channels)*sample_ratio)
# make k at least min_clrows (similar to meProp)
k = min(max(k_candidate,minimal_k),in_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d instead of approximating
if k == in_channels:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
# calculate norms of rows of B
with torch.no_grad():
b_channel_norms = torch.norm(B.view(B.size()[0],B.size()[1],-1),p=2, dim=2)
b_channel_norms = torch.norm(b_channel_norms, dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
#top_k_indices = torch.topk(norm_mult,k)[1]
top_k_indices = topk_indices(b_channel_norms,k)
# pick top-k column-row pairs to form new smaller matrices
A_top_k_cols = torch.index_select(A,dim = 1, index = top_k_indices)
B_top_k_rows = torch.index_select(B,dim = 1, index = top_k_indices)
# multiply smaller matrices
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx
''' Approximates 2d convolution with channel sampling according to largest norm
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
returns conv result and selected indices
'''
def conv2d_top_k_weights_dist(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
#print("Sanity check - conv2d_top_k_weights is used with sample_ratio = " + str(sample_ratio) + " and minimal_k = " + str(minimal_k))
in_channels = A.size()[1]
# calculate the number of channels to sample for the forward propagation phase
k_candidate = int(float(in_channels)*sample_ratio)
# make k at least min_clrows (similar to meProp)
k = min(max(k_candidate,minimal_k),in_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d instead of approximating
if k == in_channels:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups), torch.arange(in_channels, device=A.device)
# calculate norms of rows of B
with torch.no_grad():
b_channel_norms = torch.norm(B.view(B.size()[0],B.size()[1],-1),p=2, dim=2)
b_channel_norms = torch.norm(b_channel_norms, dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
# add explicit sorting because of strange indeterministic behavior across multiple GPUs
top_k_indices = torch.topk(b_channel_norms,k)[1].sort()[0]
#top_k_indices = topk_indices(b_channel_norms,k).sort()[0]
# pick top-k column-row pairs to form new smaller matrices
A_top_k_cols = torch.index_select(A,dim = 1, index = top_k_indices)
B_top_k_rows = torch.index_select(B,dim = 1, index = top_k_indices)
# multiply smaller matrices
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx, top_k_indices
''' Approximates 2d convolution with channel sampling according to largest norm
the norm is sampled from a subset of the reduction dimension
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
'''
def conv2d_top_k_approx(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
#print("Sanity check - conv2d_top_k_approx is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
in_channels = A.size()[1]
# calculate the number of channels to sample for the forward propagation phase
k_candidate = int(float(in_channels)*sample_ratio)
# make k at least min_clrows (similar to meProp)
k = min(max(k_candidate,minimal_k),in_channels)
# if because of minimal_k or sample_ratio k equals the number of features, perform full conv2d instead of approximating
if k == in_channels:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
# calculate norms of the columns of A and rows of B
with torch.no_grad():
a_channel_norms = torch.norm(A[:,:,torch.randint(A.size()[2],size=[1],dtype=torch.long), torch.randint(A.size()[3],size=[1],dtype=torch.long)], dim=0, p=2)
a_channel_norms = torch.squeeze(a_channel_norms)
b_channel_norms = torch.norm(B[:,:,torch.randint(B.size()[2],size=[1],dtype=torch.long), torch.randint(B.size()[3],size=[1],dtype=torch.long)], dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
# multiply both norms element-wise to and pick the indices of the top K column-row pairs
norm_mult = torch.mul(a_channel_norms,b_channel_norms)
#top_k_indices = torch.topk(norm_mult,k)[1]
top_k_indices = topk_indices(norm_mult,k)
# pick top-k column-row pairs to form new smaller matrices
A_top_k_cols = torch.index_select(A,dim = 1, index = top_k_indices)
B_top_k_rows = torch.index_select(B,dim = 1, index = top_k_indices)
# multiply smaller matrices
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx
''' Approximates 2d convolution with channel sampling according to largest norm
the number of channels sampled will vary according to norm concentration
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
'''
def conv2d_top_k_adaptive(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
#print("Sanity check - conv2d_top_k_adaptive is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
in_channels = A.size()[1]
# if because of minimal_k k equals the number of features, perform full conv2d instead of approximating
if sample_ratio == 1.0 or minimal_k >= in_channels:
return torch.nn.functional.conv2d(input=A, weight=B, bias=bias, stride=stride, padding=padding, dilation=dilation, groups=groups)
# calculate norms of the columns of A and rows of B
with torch.no_grad():
a_channel_norms = torch.norm(A.view(A.size()[0],A.size()[1],-1),p=2, dim=2)
a_channel_norms = torch.norm(a_channel_norms, dim=0, p=2)
a_channel_norms = torch.squeeze(a_channel_norms)
b_channel_norms = torch.norm(B.view(B.size()[0],B.size()[1],-1),p=2, dim=2)
b_channel_norms = torch.norm(b_channel_norms, dim=0, p=2)
b_channel_norms = torch.squeeze(b_channel_norms)
# multiply both norms element-wise to and pick the indices of the top K column-row pairs
norm_mult = torch.mul(a_channel_norms,b_channel_norms)
sum_norm_mult = torch.sum(norm_mult)
#top_k_indices = torch.topk(norm_mult,k)[1]
sorted_indices = topk_indices(norm_mult,in_channels)
k = minimal_k
for k in range(minimal_k, in_channels):
if norm_mult[sorted_indices[:k]].sum() >= sum_norm_mult*sample_ratio:
top_k_indices = sorted_indices[:k]
break
# pick top-k column-row pairs to form new smaller matrices
A_top_k_cols = torch.index_select(A,dim = 1, index = top_k_indices)
B_top_k_rows = torch.index_select(B,dim = 1, index = top_k_indices)
# multiply smaller matrices
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx
def conv2d_narrow(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
#print("Sanity check - conv2d_narrow is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
# calculate the number of channels to sample for the forward propagation phase
k_candidate = int(float(B.size()[1])*sample_ratio)
# make k at least min_clrows (similar to meProp)
k = min(max(k_candidate,minimal_k),B.size()[1])
A_top_k_cols = torch.narrow(A,dim = 1, start=0, length=k)
B_top_k_rows = torch.narrow(B,dim = 1, start=0, length=k)
# multiply smaller matrices
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx
def conv2d_uniform_sampling(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k):
# print("Sanity check - conv2d_uniform_sampling is used, sample_ratio = " + str(sample_ratio) + " minimal_k = " + str(minimal_k))
# calculate the number of input channels to sample for the forward propagation phase
k_candidate = int(float(B.size()[1])*sample_ratio)
# make k at least min_clrows (similar to meProp)
k = min(max(k_candidate,minimal_k),B.size()[1])
indices = torch.randperm(B.size()[1])[:k].cuda()
# pick top-k column-row pairs to form new smaller matrices
A_top_k_cols = torch.index_select(A, dim=1, index=indices)
B_top_k_rows = torch.index_select(B,dim = 1, index = indices)
# convolve smaller tensors
C_approx = torch.nn.functional.conv2d(input=A_top_k_cols, weight=B_top_k_rows, bias=bias, stride=stride, padding=padding,
dilation=dilation, groups=groups)
return C_approx
''' Approximates 2d convolution with bernoulli channel sampling
A - input tensor, shape (batch, in_channels, h, w)
B - input matrices, shape (out_channels, in_channels, kw, kw)
bias - bias vector, shape (out_channels)
stride, padding, dilation, groups as in regular conv2d
sample_ratio - Ratio of in_channels to sample
minimal_k - Minimal number of in_channels to keep in the sampling
scale - True means each input channel is scaled by 1/sqrt(K*pi) to ensure bias 0
'''
def conv2d_bernoulli_sampling(A,B,bias, stride, padding, dilation, groups, sample_ratio, minimal_k, scale):
#print("Sanity check - conv2d_bernoulli_sampling is used with sample_ratio = " + str(sample_ratio) + "and minimal_k = " + str(minimal_k))
#print("A size: {}".format(A.size()))
#print("B size: {}".format(B.size()))
#print("bias size: {}".format(bias.size()))
#print("sample_ratio: {}".format(sample_ratio))
#print("minimal_k: {}".format(minimal_k))
#print("scale: {}".format(scale))
#print("A mean: {}".format(A.mean()))
#print("A std: {}".format(A.std()))
#print("B mean: {}".format(B.mean()))
#print("B std: {}".format(B.std()))
in_channels = A.size()[1]
device = A.device