forked from elikosan/cunn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test.lua
6486 lines (5479 loc) · 247 KB
/
test.lua
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
local cunntest = torch.TestSuite()
local ffi = require 'ffi'
local precision_forward = 1e-4
local precision_backward = 1e-2
local nloop = 1
local times = {}
-- load THC
local THC = ffi.os == 'Windows' and ffi.load('THC') or ffi.C
--e.g.: th -lcunn -e "nn.testcuda{'Sigmoid_forward'}"
local typenames = {
'torch.CudaTensor',
'torch.CudaDoubleTensor',
}
local t2cpu = {
['torch.CudaTensor'] = 'torch.FloatTensor',
['torch.CudaDoubleTensor'] = 'torch.DoubleTensor',
}
local function checkHalf()
if cutorch.hasHalf then
table.insert(typenames, 'torch.CudaHalfTensor')
t2cpu['torch.CudaHalfTensor'] = 'torch.FloatTensor'
end
end
local function half_max_error(maxabs)
-- arbitrarily double the precision limit
return 2 * ((maxabs and (2^(math.floor(math.log(maxabs) / math.log(2)))) * (2^(-10))) or 0)
end
-- half has additional error on top of double/float
local function precision_forward_type(precision_f, tensor_type, maxabs)
if (tensor_type == 'torch.CudaHalfTensor') then
return 1e-2 + precision_f + half_max_error(maxabs)
else
return precision_f
end
end
local function precision_backward_type(precision_b, tensor_type, maxabs)
if (tensor_type == 'torch.CudaHalfTensor') then
return 1e-1 + precision_b + half_max_error(maxabs)
else
return precision_b
end
end
local function precision_backward_conv_weightbias(precision_b, tensor_type, maxabs)
if (tensor_type == 'torch.CudaHalfTensor') then
-- cudnn uses 8 here
return 2 + precision_b + half_max_error(maxabs)
else
return precision_b
end
end
local function makeNonContiguous(tensor)
size = tensor:size()
local osize = {}
for i = 1, #size do osize[i] = size[i] end
-- randomly inflate a few dimensions in osize
for i = 1, 3 do
local dim = torch.random(1,#osize)
local add = torch.random(4, 15)
osize[dim] = osize[dim] + add
end
local input = torch[tensor:type():match('torch.(%a+)')]()
input:resize(torch.LongStorage(osize))
-- now extract the input of correct size from 'input'
for i = 1, #size do
if input:size(i) ~= size[i] then
local bounds = torch.random(1, input:size(i) - size[i] + 1)
input = input:narrow(i, bounds, size[i])
end
end
input:copy(tensor)
return input
end
local function pointwise_forward(proto_module, name, max_error)
local size = math.random(1,100)
if name == 'GatedLinearUnit' then size = size*2 end
for k, typename in ipairs(typenames) do
local input = torch.randn(size):type(typename)
local ctype = t2cpu[typename]
local input = makeNonContiguous(input:type(ctype))
if name == 'Sqrt' then input:abs() end
local sconv = proto_module:type(ctype)
local groundtruth = sconv:forward(input)
input = makeNonContiguous(input:type(typename))
local gconv = proto_module:clone():type(typename)
local rescuda = gconv:forward(input)
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(), precision_forward_type(max_error, typename),
string.format('error on state (forward) with %s', typename))
end
end
local function pointwise_backward(proto_module, name, max_error)
local size = math.random(1,100)
if name == 'GatedLinearUnit' then size = size*2 end
for k, typename in ipairs(typenames) do
local input = torch.randn(size):type(typename)
local gradOutput = torch.randn(size):type(typename)
if name == 'GatedLinearUnit' then gradOutput = torch.randn(size/2) end
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
gradOutput = makeNonContiguous(gradOutput:type(ctype))
if name == 'Sqrt' then input:abs() end
local sconv = proto_module:type(ctype)
sconv:forward(input)
local groundgrad = sconv:backward(input, gradOutput)
input = makeNonContiguous(input:type(typename))
gradOutput = makeNonContiguous(gradOutput:type(typename))
local gconv = proto_module:clone():type(typename)
gconv:forward(input)
local rescuda = gconv:backward(input, gradOutput)
local error = rescuda:double() - groundgrad:double()
mytester:assertlt(error:abs():max(),
precision_backward_type(max_error, typename, rescuda:abs():max()),
string.format('error on state (backward) with %s', typename))
end
end
local function pointwise_backward_inplace(proto_module, name)
local size = math.random(1,100)
for k, typename in ipairs(typenames) do
local input = torch.randn(size):type(typename)
local ctype = t2cpu[typename]
input = input:type(ctype)
if name == 'Sqrt' then input:abs() end
local gradOutput = makeNonContiguous(torch.randn(size))
gradOutput = makeNonContiguous(gradOutput:type(ctype))
local sconv = proto_module:type(ctype)
local groundgrad = sconv:backward(input, gradOutput)
mytester:assertTensorEq(groundgrad:double(),
gradOutput:double(),
0.000001,
string.format("inplace not respected for %s", ctype))
input = makeNonContiguous(torch.randn(size))
input = makeNonContiguous(input:type(typename))
if name == 'Sqrt' then input:abs() end
gradOutput = makeNonContiguous(torch.randn(size))
gradOutput = makeNonContiguous(gradOutput:type(typename))
local sconv = proto_module:clone():type(typename)
local groundgrad = sconv:backward(input, gradOutput)
mytester:assertTensorEq(groundgrad:double(),
gradOutput:double(),
0.000001,
string.format("cuda inplace not respected for %s", typename))
end
end
local function pointwise_transposed(proto_module, name, max_error)
max_error = max_error or 1e-7
for k, typename in ipairs(typenames) do
local ctype = t2cpu[typename]
local input = torch.Tensor(11, 19):uniform(-1, 1):type(typename)
input = input:type(ctype)
local proto_module = proto_module:type(ctype)
if name == 'Sqrt' then
input:uniform(0.1, 1)
end
local inputCUDA = input:clone():type(typename)
local cuda_module = proto_module:clone():type(typename)
-- transpose the inputs and DON'T make contiguous
input = input:transpose(1, 2)
inputCUDA = inputCUDA:transpose(1, 2)
local output = proto_module:forward(input)
local outputCUDA = cuda_module:forward(inputCUDA)
local error = outputCUDA:double() - output:double()
mytester:assertlt(error:abs():max(), precision_forward_type(max_error, typename),
string.format('error on state (forward) for %s', typename))
local gradOutput = torch.Tensor(11, 19):uniform(-1, 1):type(ctype)
local gradOutputCUDA = gradOutput:clone():type(typename)
gradOutput = gradOutput:transpose(1, 2)
gradOutputCUDA = gradOutputCUDA:transpose(1, 2)
local gradInput = proto_module:backward(input, gradOutput)
local gradInputCUDA = cuda_module:backward(inputCUDA, gradOutputCUDA)
local error = gradInputCUDA:double() - gradInput:double()
mytester:assertlt(error:abs():max(), precision_backward_type(max_error, typename),
string.format('error on state (backward) for %s', typename))
end
end
function cunntest.Tanh_forward()
pointwise_forward(nn.Tanh(), 'Tanh', precision_forward)
end
function cunntest.Tanh_backward()
pointwise_backward(nn.Tanh(), 'Tanh', precision_backward)
end
function cunntest.Tanh_transposed()
pointwise_transposed(nn.Tanh(), 'Tanh', 1.8e-7)
end
function cunntest.HardTanh_forward()
pointwise_forward(nn.HardTanh(), 'HardTanh', precision_forward)
end
function cunntest.HardTanh_backward()
pointwise_backward(nn.HardTanh(), 'HardTanh', precision_backward)
end
function cunntest.HardTanh_backward_inplace()
pointwise_backward_inplace(nn.HardTanh(nil, nil, true), 'HardTanh')
end
function cunntest.HardTanh_transposed()
pointwise_transposed(nn.HardTanh(), 'HardTanh', 1.5e-7)
end
function cunntest.Abs_forward()
pointwise_forward(nn.Abs(), 'Abs', precision_forward)
end
function cunntest.Abs_backward()
pointwise_backward(nn.Abs(), 'Abs', precision_backward)
end
function cunntest.Abs_transposed()
pointwise_transposed(nn.Abs(), 'Abs')
end
function cunntest.Sigmoid_forward()
pointwise_forward(nn.Sigmoid(), 'Sigmoid', precision_forward)
end
function cunntest.Sigmoid_backward()
pointwise_backward(nn.Sigmoid(), 'Sigmoid', precision_backward)
end
function cunntest.Sigmoid_transposed()
pointwise_transposed(nn.Sigmoid(), 'Sigmoid')
end
function cunntest.LogSigmoid_forward()
pointwise_forward(nn.LogSigmoid(), 'LogSigmoid', precision_forward)
end
function cunntest.LogSigmoid_backward()
pointwise_backward(nn.LogSigmoid(), 'LogSigmoid', precision_backward)
end
function cunntest.LogSigmoid_transposed()
pointwise_transposed(nn.LogSigmoid(), 'LogSigmoid', 1e-6)
end
function cunntest.GatedLinearUnit_forward()
pointwise_forward(nn.GatedLinearUnit(), 'GatedLinearUnit', precision_forward)
end
function cunntest.GatedLinearUnit_backward()
pointwise_backward(nn.GatedLinearUnit(), 'GatedLinearUnit', precision_backward)
end
function cunntest.Threshold_forward()
pointwise_forward(nn.Threshold(), 'Threshold', precision_forward)
pointwise_forward(nn.Threshold(nil, nil, true), 'Threshold_inplace', precision_forward)
end
function cunntest.Threshold_backward()
pointwise_backward(nn.Threshold(), 'Threshold', precision_backward)
pointwise_backward(nn.Threshold(nil, nil, true), 'Threshold_inplace', precision_backward)
end
function cunntest.ReLU6_forward()
for inplace = 0, 1 do
local net = nn.Sequential()
-- pointwise_forward uses randn, so add a big constant to make sure some
-- of the values saturate.
net:add(nn.MulConstant(6))
net:add(nn.ReLU6(inplace == 1))
pointwise_forward(net, 'ReLU6 inplace ' .. inplace, precision_forward)
end
end
function cunntest.ReLU6_backward()
for inplace = 0, 1 do
local net = nn.Sequential()
net:add(nn.MulConstant(6))
net:add(nn.ReLU6(inplace == 1))
pointwise_backward(net, 'ReLU6 inplace ' .. inplace, precision_backward)
end
end
function cunntest.LeakyReLU_forward()
pointwise_forward(nn.LeakyReLU(), 'LeakyReLU', precision_forward)
end
function cunntest.LeakyReLU_backward()
pointwise_backward(nn.LeakyReLU(), 'LeakyReLU', precision_backward)
end
function cunntest.LeakyReLU_transposed()
pointwise_transposed(nn.LeakyReLU(), 'LeakyReLU', 1.5e-7)
end
function cunntest.Sqrt_forward()
pointwise_forward(nn.Sqrt(), 'Sqrt', precision_forward)
end
function cunntest.Sqrt_backward()
pointwise_backward(nn.Sqrt(), 'Sqrt', precision_backward)
end
function cunntest.Sqrt_zero()
local size = math.random(1, 100)
for k, typename in ipairs(typenames) do
-- Test zero inputs; we will avoid a div-by-zero by setting to zero
local module_gpu = nn.Sqrt():type(typename)
local input_gpu = makeNonContiguous(torch.CudaTensor(size, size):zero():type(typename))
module_gpu:forward(input_gpu)
local gradOutput_gpu = makeNonContiguous(torch.CudaTensor(size, size):fill(1):type(typename))
local gradInput_gpu = module_gpu:backward(input_gpu, gradOutput_gpu)
mytester:assertTensorEq(gradInput_gpu:double(),
torch.DoubleTensor(size, size):zero(),
0.000001, "error in sqrt backward singularity")
-- Verify CPU and GPU zero behavior equivalency
local ctype = t2cpu[typename]
local module_cpu = nn.Sqrt():type(ctype)
local input_cpu = makeNonContiguous(input_gpu:type(ctype))
module_cpu:forward(input_cpu)
local gradOutput_cpu = makeNonContiguous(gradOutput_gpu:type(ctype))
local gradInput_cpu = module_cpu:backward(input_cpu, gradOutput_cpu)
mytester:assertTensorEq(gradInput_gpu:double(),
gradInput_cpu:double(),
0.000001, "Sqrt_zero CPU and GPU not equivalent")
end
end
function cunntest.Sqrt_transposed()
pointwise_transposed(nn.Sqrt(), 'Sqrt')
end
function cunntest.Square_forward()
pointwise_forward(nn.Square(), 'Square', precision_forward)
end
function cunntest.Square_backward()
pointwise_backward(nn.Square(), 'Square', precision_backward)
end
function cunntest.Square_transposed()
pointwise_transposed(nn.Square(), 'Square')
end
function cunntest.SoftShrink_forward()
local r = math.random()
pointwise_forward(nn.SoftShrink(r), 'SoftShrink', precision_forward)
end
function cunntest.SoftShrink_backward()
local r = math.random()
pointwise_backward(nn.SoftShrink(r), 'SoftShrink', precision_backward)
end
function cunntest.SoftShrink_transposed()
local r = math.random()
pointwise_transposed(nn.SoftShrink(r), 'SoftShrink', precision_backward)
end
function cunntest.ELU_forward()
pointwise_forward(nn.ELU(), 'ELU', precision_forward)
end
function cunntest.ELU_backward()
pointwise_backward(nn.ELU(), 'ELU', precision_backward)
end
function cunntest.ELU_transposed()
pointwise_transposed(nn.ELU(), 'ELU', 1e-6)
end
function cunntest.SoftMax_forward()
pointwise_forward(nn.SoftMax(), 'SoftMax', precision_forward)
end
function cunntest.SoftMax_backward()
pointwise_backward(nn.SoftMax(), 'SoftMax', precision_backward)
end
function cunntest.LogSoftMax_forward()
pointwise_forward(nn.LogSoftMax(), 'LogSoftMax', precision_forward*10)
end
function cunntest.LogSoftMax_backward()
pointwise_backward(nn.LogSoftMax(), 'LogSoftMax', precision_backward)
end
function cunntest.SpatialSoftMax()
local bs = math.random(32,256)
local dim = torch.random(1, 50)
local h = torch.random(1, 50)
local w = torch.random(1, 50)
local input = makeNonContiguous(torch.randn(bs, dim, h, w))
local sconv = nn.SpatialSoftMax()
local groundtruth = sconv:forward(input)
local gradOutput = makeNonContiguous(groundtruth:clone():fill(0.5))
local gradInput = sconv:backward(input, gradOutput)
input = makeNonContiguous(input:cuda())
gradOutput = makeNonContiguous(gradOutput:cuda())
local gconv = nn.SpatialSoftMax():cuda()
local rescuda = gconv:forward(input)
local gradcuda = gconv:backward(input, gradOutput)
local error = rescuda:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward*10, 'error on state (forward) ')
local error = gradcuda:float() - gradInput
mytester:assertlt(error:abs():max(), precision_backward*10, 'error on state (backward) ')
end
function cunntest.LogSoftMax_forward_batch()
local size = math.random(1,256)
local bs = math.random(32,256)
for k, typename in ipairs(typenames) do
local input = torch.randn(bs, size):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
local sconv = nn.LogSoftMax():type(ctype)
local groundtruth = sconv:forward(input)
input = makeNonContiguous(input:type(typename))
local gconv = nn.LogSoftMax():type(typename)
local rescuda = gconv:forward(input)
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(), precision_forward_type(precision_forward*10, typename),
string.format('error on state (forward) with %s', typename))
end
end
function cunntest.LogSoftMax_backward_batch()
local size = math.random(1,256)
local bs = math.random(32,256)
for k, typename in ipairs(typenames) do
local input = torch.randn(bs, size):type(typename)
local gradOutput = torch.randn(bs, size):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
gradOutput = makeNonContiguous(gradOutput:type(ctype))
local sconv = nn.LogSoftMax():type(ctype)
sconv:forward(input)
local groundgrad = sconv:backward(input, gradOutput)
input = makeNonContiguous(input:type(typename))
gradOutput = makeNonContiguous(gradOutput:type(typename))
local gconv = sconv:clone():type(typename)
gconv:forward(input)
local rescuda = gconv:backward(input, gradOutput)
local error = rescuda:double() - groundgrad:double()
mytester:assertlt(error:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on state (backward) with %s', typename))
end
end
function cunntest.SpatialLogSoftMax_forward()
local size = math.random(1,256)
local ini = math.random(8,32)
local inj = math.random(8,32)
for k, typename in ipairs(typenames) do
local input = torch.randn(size, inj, ini):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
local sconv = nn.SpatialLogSoftMax():type(ctype)
local groundtruth = sconv:forward(input):type(ctype)
input = makeNonContiguous(input:type(typename))
local gconv = nn.SpatialLogSoftMax():type(typename)
local rescuda = gconv:forward(input)
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(),
precision_forward_type(precision_forward*25, typename),
string.format('error on state (forward) with %s', typename))
end
end
function cunntest.SpatialLogSoftMax_backward()
local size = math.random(1,256)
local ini = math.random(8,32)
local inj = math.random(8,32)
for k, typename in ipairs(typenames) do
local input = torch.randn(size, inj, ini):type(typename)
local gradOutput = torch.randn(size, inj, ini):type(typename)
local ctype = t2cpu[typename]
input = input:type(ctype)
gradOutput = makeNonContiguous(gradOutput:type(ctype))
local sconv = nn.SpatialLogSoftMax():type(ctype)
sconv:forward(input)
local groundgrad = sconv:backward(input, gradOutput)
input = makeNonContiguous(input:type(typename))
gradOutput = makeNonContiguous(gradOutput:type(typename))
local gconv = sconv:clone():type(typename)
gconv:forward(input)
local rescuda = gconv:backward(input, gradOutput)
local error = rescuda:double() - groundgrad:double()
mytester:assertlt(error:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on state (backward) with %s', typename))
end
end
function cunntest.SpatialLogSoftMax_forward_batch()
local size = math.random(1,256)
local bs = math.random(8,32)
local ini = math.random(8,32)
local inj = math.random(8,32)
for k, typename in ipairs(typenames) do
local input = torch.randn(bs, size, inj, ini):type(typename)
local ctype = t2cpu[typename]
input = input:type(ctype)
local sconv = nn.SpatialLogSoftMax():type(ctype)
local groundtruth = sconv:forward(input)
input = makeNonContiguous(input:type(typename))
local gconv = nn.SpatialLogSoftMax():type(typename)
local rescuda = gconv:forward(input)
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(),
precision_forward_type(precision_forward*25, typename),
string.format('error on state (forward) with %s', typename))
end
end
function cunntest.SpatialLogSoftMax_backward_batch()
local size = math.random(1,256)
local bs = math.random(8,32)
local ini = math.random(8,32)
local inj = math.random(8,32)
for k, typename in ipairs(typenames) do
local input = torch.randn(bs, size, inj, ini):type(typename)
local gradOutput = torch.randn(bs, size, inj, ini):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
gradOutput = makeNonContiguous(gradOutput:type(ctype))
local sconv = nn.SpatialLogSoftMax():type(ctype)
sconv:forward(input)
local groundgrad = sconv:backward(input, gradOutput)
input = makeNonContiguous(input:type(typename))
gradOutput = makeNonContiguous(gradOutput:type(typename))
local gconv = sconv:clone():type(typename)
gconv:forward(input)
local rescuda = gconv:backward(input, gradOutput)
local error = rescuda:double() - groundgrad:double()
mytester:assertlt(error:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on state (backward) with %s', typename))
end
end
function cunntest.Euclidean_forward_batch()
local bs = math.random(8,32)
local nin = math.random(1,100)
local nout = math.random(1,100)
local tm = {}
local title = string.format('Euclidean forward %d %d -> %d %d', bs, nin, bs, nout)
times[title] = tm
local input = makeNonContiguous(torch.randn(bs, nin))
local sconv = nn.Euclidean(nin, nout)
local groundtruth = sconv:forward(input)
local a = torch.Timer()
for i = 1,nloop do
groundtruth = sconv:forward(input)
end
tm.cpu = a:time().real
input = makeNonContiguous(input:cuda())
local gconv = sconv:clone():cuda()
local rescuda = gconv:forward(input)
a:reset()
for i = 1,nloop do
rescuda = gconv:forward(input)
end
cutorch.synchronize()
tm.gpu = a:time().real
local error = rescuda:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) batch ')
end
function cunntest.Euclidean_backward_batch()
local bs = math.random(8,32)
local nin = math.random(1,100)
local nout = math.random(1,100)
local tm = {}
local title = string.format('Euclidean backward %d %d <- %d %d', bs, nin, bs, nout)
times[title] = tm
local input = makeNonContiguous(torch.randn(bs, nin))
local gradOutput = makeNonContiguous(torch.randn(bs, nout))
local sconv = nn.Euclidean(nin, nout)
sconv:forward(input)
sconv:zeroGradParameters()
local groundgrad = sconv:backward(input, gradOutput)
local a = torch.Timer()
for i = 1,nloop do
sconv:zeroGradParameters()
groundgrad = sconv:backward(input, gradOutput)
end
local groundweight = sconv.gradWeight
tm.cpu = a:time().real
input = makeNonContiguous(input:cuda())
gradOutput = makeNonContiguous(gradOutput:cuda())
local gconv = sconv:clone():cuda()
gconv:forward(input)
gconv:zeroGradParameters()
local rescuda = gconv:backward(input, gradOutput)
a:reset()
for i = 1,nloop do
gconv:zeroGradParameters()
rescuda = gconv:backward(input, gradOutput)
end
cutorch.synchronize()
tm.gpu = a:time().real
local weightcuda = gconv.gradWeight
local error = rescuda:float() - groundgrad
local werror = weightcuda:float() - groundweight
mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ')
mytester:assertlt(werror:abs():max(), precision_backward, 'error on weight (backward) ')
end
function cunntest.WeightedEuclidean_forward_batch()
local bs = math.random(8,32)
local nin = math.random(1,100)
local nout = math.random(1,100)
local tm = {}
local title = string.format('WeightedEuclidean forward %d %d -> %d %d', bs, nin, bs, nout)
times[title] = tm
local input = makeNonContiguous(torch.randn(bs, nin))
local sconv = nn.WeightedEuclidean(nin, nout)
local groundtruth = sconv:forward(input)
local a = torch.Timer()
for i = 1,nloop do
groundtruth = sconv:forward(input)
end
tm.cpu = a:time().real
input = makeNonContiguous(input:cuda())
local gconv = sconv:clone():cuda()
local rescuda = gconv:forward(input)
a:reset()
for i = 1,nloop do
rescuda = gconv:forward(input)
end
cutorch.synchronize()
tm.gpu = a:time().real
local error = rescuda:float() - groundtruth
mytester:assertlt(error:abs():max(), precision_forward, 'error on state (forward) batch ')
end
function cunntest.WeightedEuclidean_backward_batch()
local bs = math.random(8,32)
local nin = math.random(1,100)
local nout = math.random(1,100)
local tm = {}
local title = string.format('WeightedEuclidean backward %d %d <- %d %d', bs, nin, bs, nout)
times[title] = tm
local input = makeNonContiguous(torch.randn(bs, nin))
local gradOutput = makeNonContiguous(torch.randn(bs, nout))
local sconv = nn.WeightedEuclidean(nin, nout)
sconv:forward(input)
sconv:zeroGradParameters()
local groundgrad = sconv:backward(input, gradOutput)
local a = torch.Timer()
for i = 1,nloop do
sconv:zeroGradParameters()
groundgrad = sconv:backward(input, gradOutput)
end
local groundweight = sconv.gradWeight
local grounddiagCov = sconv.gradDiagCov
tm.cpu = a:time().real
input = makeNonContiguous(input:cuda())
gradOutput = makeNonContiguous(gradOutput:cuda())
local gconv = sconv:clone():cuda()
gconv:forward(input)
gconv:zeroGradParameters()
local rescuda = gconv:backward(input, gradOutput)
a:reset()
for i = 1,nloop do
gconv:zeroGradParameters()
rescuda = gconv:backward(input, gradOutput)
end
cutorch.synchronize()
tm.gpu = a:time().real
local weightcuda = gconv.gradWeight
local diagCovcuda = gconv.gradDiagCov
local error = rescuda:float() - groundgrad
local werror = weightcuda:float() - groundweight
local derror = diagCovcuda:float() - grounddiagCov
mytester:assertlt(error:abs():max(), precision_backward, 'error on state (backward) ')
mytester:assertlt(werror:abs():max(), precision_backward, 'error on weight (backward) ')
mytester:assertlt(derror:abs():max(), precision_backward, 'error on diagCov (backward) ')
end
function cunntest.SparseLinear_forward()
local inb = math.random(5,10)
local ini = math.random(50,100)
local inj = math.random(5,10)
for k, typename in ipairs(typenames) do
if typename ~= "torch.CudaHalfTensor" then
local ctype = t2cpu[typename]
local module = nn.SparseLinear(ini,inj):type(ctype)
local sslin = module
local gslin = module:clone():type(typename)
-- Create a random sparse vector
local input = {}
for i=1,inb do
local nnz = math.random(5, 10)
local inds = torch.randperm(ini)[{{1,nnz}}]
input[i] = torch.Tensor(nnz, 2):type(ctype)
input[i]:select(2,1):copy(inds)
input[i]:select(2,2):copy(torch.rand(nnz):type(typename):type(ctype))
end
local groundtruth = sslin:forward(input)
sslin:zeroGradParameters()
for i,v in ipairs(input) do input[i] = input[i]:type(typename) end
local rescuda = gslin:forward(input)
gslin:zeroGradParameters()
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(), precision_forward_type(precision_forward, typename),
string.format('error on state (forward) with %s', typename))
end
end
end
function cunntest.SparseLinear_backward()
local inb = math.random(5,10)
local ini = math.random(50,100)
local inj = math.random(5,10)
for k, typename in ipairs(typenames) do
if typename ~= "torch.CudaHalfTensor" then
local ctype = t2cpu[typename]
local gslin = nn.SparseLinear(ini,inj):type(typename)
local sslin = nn.Linear(ini,inj):type(ctype)
gslin.weight = sslin.weight:clone():type(typename)
gslin.bias = sslin.bias:clone():type(typename)
-- Create a random sparse vector
local input = {}
local nonsparse = torch.zeros(inb, ini):type(ctype)
for i=1,inb do
local nnz = math.random(3, 5)
local inds = torch.randperm(ini)[{{1,nnz}}]
input[i] = torch.Tensor(nnz, 2):type(ctype)
input[i]:select(2,1):copy(inds)
input[i]:select(2,2):copy(torch.rand(nnz):type(typename):type(ctype))
nonsparse[i]:scatter(1, input[i]:select(2,1):long(), input[i]:select(2,2))
end
local gradOutput = makeNonContiguous(torch.randn(inb, inj):type(typename):type(ctype))
sslin:forward(nonsparse)
local groundgrad = sslin:backward(nonsparse, gradOutput)
sslin:zeroGradParameters()
local groundweight = sslin.gradWeight
local groundbias = sslin.gradBias
for i,v in ipairs(input) do input[i] = input[i]:type(typename) end
gradOutput = makeNonContiguous(gradOutput:type(typename))
gslin:forward(input)
local rescuda = gslin:backward(input, gradOutput)
gslin:zeroGradParameters()
local weightcuda = gslin.gradWeight
local biascuda = gslin.gradBias
local werror = weightcuda:double() - groundweight:double()
local berror = biascuda:double() - groundbias:double()
mytester:assertlt(werror:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on weight (backward) with %s', typename))
mytester:assertlt(berror:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on bias (backward) with %s', typename))
gslin:updateParameters(.1)
sslin:updateParameters(.1)
werror = gslin.weight:double() - sslin.weight:double()
berror = gslin.bias:double() - sslin.bias:double()
mytester:assertlt(werror:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on weight (update) with %s', typename))
mytester:assertlt(berror:abs():max(), precision_backward_type(precision_backward, typename),
string.format('error on bias (update) with %s', typename))
gslin:zeroGradParameters()
end
end
end
local function BatchNormalization_forward(moduleName, inputSize)
local planes = inputSize[2]
for k, typename in ipairs(typenames) do
local input = torch.randn(table.unpack(inputSize)):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
local sbnorm = nn[moduleName](planes):type(ctype)
local groundtruth = sbnorm:forward(input)
input = makeNonContiguous(input:type(typename))
local gbnorm = nn[moduleName](planes):type(typename)
gbnorm.weight = sbnorm.weight:type(typename)
gbnorm.bias = sbnorm.bias:type(typename)
local rescuda = gbnorm:forward(input)
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(), precision_forward_type(precision_forward, typename, rescuda:abs():max()),
string.format('error on state (forward) with %s', typename))
mytester:assertlt((gbnorm.running_mean:double() - sbnorm.running_mean:double()):abs():max(),
precision_forward_type(precision_forward, typename, gbnorm.running_mean:abs():max()),
string.format('error on running_mean (forward) with %s', typenanme))
mytester:assertlt((gbnorm.running_var:double() - sbnorm.running_var:double()):abs():max(),
precision_forward_type(precision_forward, typename, gbnorm.running_var:abs():max()),
string.format('error on running_var (forward) with %s', typename))
end
end
local function BatchNormalization_forward_inference(moduleName, inputSize)
local planes = inputSize[2]
for k, typename in ipairs(typenames) do
local input = torch.randn(table.unpack(inputSize)):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
local sbnorm = nn[moduleName](planes):type(ctype)
sbnorm.running_mean:normal(1, 2)
sbnorm.running_var:uniform(1e-3, 2)
sbnorm.running_var = sbnorm.running_var:type(typename):type(ctype)
sbnorm.running_mean = sbnorm.running_mean:type(typename):type(ctype)
sbnorm:evaluate()
local groundtruth = sbnorm:forward(input)
input = makeNonContiguous(input:type(typename))
local gbnorm = nn[moduleName](planes):type(typename)
gbnorm:evaluate()
gbnorm.weight = sbnorm.weight:type(typename)
gbnorm.bias = sbnorm.bias:type(typename)
gbnorm.running_mean = sbnorm.running_mean:type(typename)
gbnorm.running_var = sbnorm.running_var:type(typename)
local rescuda = gbnorm:forward(input)
local error = rescuda:double() - groundtruth:double()
mytester:assertlt(error:abs():max(), precision_forward_type(precision_forward, typename, rescuda:abs():max()),
string.format('error on state (forward evaluate) with %s', typename))
end
end
local function BatchNormalization_backward(moduleName, mode, inputSize, backwardFn)
assert(mode == 'training' or mode == 'evaluation', 'invalid mode')
local planes = inputSize[2]
for k, typename in ipairs(typenames) do
local input = torch.randn(table.unpack(inputSize)):type(typename)
local gradOutput = torch.randn(table.unpack(inputSize)):type(typename)
local ctype = t2cpu[typename]
input = makeNonContiguous(input:type(ctype))
gradOutput = makeNonContiguous(gradOutput:type(ctype))
local sbnorm = nn[moduleName](planes):type(ctype)
if mode == 'training' then
sbnorm:training()
else
sbnorm:evaluate()
end
sbnorm:forward(input)
sbnorm:zeroGradParameters()
local groundgrad = backwardFn(sbnorm, input, gradOutput)
local groundweight = sbnorm.gradWeight
local groundbias = sbnorm.gradBias
input = makeNonContiguous(input:type(typename))
gradOutput = makeNonContiguous(gradOutput:type(typename))
local gbnorm = nn[moduleName](planes):type(typename)
if mode == 'training' then
gbnorm:training()
else
gbnorm:evaluate()
end
gbnorm.weight = sbnorm.weight:type(typename)
gbnorm.bias = sbnorm.bias:type(typename)
gbnorm:forward(input)
gbnorm:zeroGradParameters()
local rescuda = backwardFn(gbnorm, input, gradOutput)
local weightcuda = gbnorm.gradWeight
local biascuda = gbnorm.gradBias
local error = rescuda:double() - groundgrad:double()
local werror = weightcuda:double() - groundweight:double()
local berror = biascuda:double() - groundbias:double()
local backerror = precision_backward_type(precision_backward, typename, rescuda:abs():max())
if typename == 'torch.CudaHalfTensor' and (mode == 'training') then
-- this correction is empirical; mean can be off by roughly 4e-4, multiplied by roughly stdval^2.
backerror = backerror + (sbnorm.save_std:max())^2 * 4e-4
end
mytester:assertlt(error:abs():max(),
backerror,
string.format('error on state (backward) with %s', typename))
mytester:assertlt(werror:abs():max(),
precision_backward_type(precision_backward, typename, weightcuda:abs():max()),
string.format('error on weight (backward) with %s', typename))
mytester:assertlt(berror:abs():max(),
precision_backward_type(precision_backward, typename, biascuda:abs():max()),
string.format('error on bias (backward) with %s', typename))
end
end
local function testBatchNormalization(name, dim, k)
local function inputSize()
local inputSize = { torch.random(2,32), torch.random(1, k) }
for i=1,dim do
table.insert(inputSize, torch.random(1,k))
end
return inputSize
end
local function backward1(m, input, gradOutput)
return m:backward(input, gradOutput)
end
local function backward2(m, input, gradOutput)
local gradInput = m:updateGradInput(input, gradOutput)
m:accGradParameters(input, gradOutput)
return gradInput
end
BatchNormalization_forward(name, inputSize())
BatchNormalization_forward_inference(name, inputSize())
BatchNormalization_backward(name, 'training', inputSize(), backward1)