-
Notifications
You must be signed in to change notification settings - Fork 958
/
Copy pathtest.lua
executable file
·9126 lines (7624 loc) · 349 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
-- you can easily test specific units like this:
-- th -lnn -e "nn.test{'LookupTable'}"
-- th -lnn -e "nn.test{'LookupTable', 'Add'}"
local mytester = torch.Tester()
local jac
local sjac
local precision = 1e-5
local expprecision = 1.1e-4
local nntest = torch.TestSuite()
local function equal(t1, t2, msg)
if (torch.type(t1) == "table") then
for k, v in pairs(t2) do
equal(t1[k], t2[k], msg)
end
else
mytester:eq(t1, t2, 0.00001, msg)
end
end
--[[ Generate tests to exercise the tostring component of modules. ]]
local tostringTestModules = {
nnLinear = nn.Linear(1, 2),
nnReshape = nn.Reshape(10),
nnSpatialZeroPadding = nn.SpatialZeroPadding(1, 1, 1, 1)}
for test_name, component in pairs(tostringTestModules) do
nntest['tostring' .. test_name] =
function ()
mytester:assert(tostring(component):find(
torch.type(component) .. '(', 1, true) ~= nil,
'nn components should have a descriptive tostring' ..
' beginning with the classname')
end
end
function nntest.Add()
local inj_vals = {math.random(3,5), 1} -- Also test the inj = 1 spatial case
local ini = math.random(3,5)
local ink = math.random(3,5)
for ind, inj in pairs(inj_vals) do
local input = torch.Tensor(ini,inj,ink):zero()
local module = nn.Add(ini,inj,ink)
-- 1D
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias)
mytester:assertlt(err,precision, 'error on bias ')
local err = jac.testJacobianUpdateParameters(module, input, module.bias)
mytester:assertlt(err,precision, 'error on bias [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do
mytester:assertlt(err, precision, string.format('error on bias [%s]', t))
end
-- 2D
local nframe = math.random(50,70)
local input = torch.Tensor(nframe, ini,inj,ink):zero()
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.bias, module.gradBias)
mytester:assertlt(err,precision, 'error on bias ')
local err = jac.testJacobianUpdateParameters(module, input, module.bias)
mytester:assertlt(err,precision, 'error on bias [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'bias', 'gradBias')) do
mytester:assertlt(err, precision, string.format('error on bias [%s]', t))
end
-- IO
local ferr,berr = jac.testIO(module,input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
end
function nntest.Bottle()
local ini = 2
local inj = 3
local ink = 4
local out = 5
local input = torch.Tensor(ini,inj,ink):normal()
local linear = nn.Linear(ink, out)
local module1 = nn.Bottle(linear)
local module2 = nn.Sequential()
module2:add(nn.View(ini*inj, ink))
module2:add(linear)
module2:add(nn.View(ini, inj, out))
local output1 = module1:forward(input)
local output2 = module2:forward(input)
mytester:eq(output1, output2, 0.0001, 'Bottle output not the same as Module')
local shape = {4, 5, 6, 7, 8, 1, 3}
local input = torch.Tensor(table.unpack(shape)):normal()
local module = nn.Sequential()
module:add(nn.Squeeze(2))
module:add(nn.Linear(3, 3))
local module1 = nn.Bottle(module, 3, 2)
local outShape = {4, 5, 6, 7, 8, 3}
local module2 = nn.Sequential()
module2:add(nn.View(4*5*6*7*8, 1, 3))
module2:add(module)
module2:add(nn.View(table.unpack(outShape)))
local output1 = module1:forward(input)
local grad = torch.Tensor(output1:size()):normal()
local gradOutput1 = module1:backward(input, grad):clone()
local output2 = module2:forward(input)
local gradOutput2 = module2:backward(input, grad):clone()
mytester:eq(output1, output2, 0.0001, 'Bottle output not the same as Module')
mytester:eq(gradOutput1, gradOutput2, 0.0001, 'Bottle gradOutput not the same as Module')
end
function nntest.WeightNorm()
local input = torch.rand(10, 5)
-- temporal convolution
local model = nn.WeightNorm(nn.TemporalConvolution(5, 20, 2, 1))
local err = nn.Jacobian.testJacobianParameters(model, input,
model.bias, model.gradBias)
mytester:assert(err < precision, 'Temporal Convolution bias')
err = nn.Jacobian.testJacobianParameters(model, input,
model.g, model.gradG)
mytester:assert(err < precision, 'Temporal Convolution g')
err = nn.Jacobian.testJacobianParameters(model, input,
model.v, model.gradV)
mytester:assert(err < precision, 'Temporal Convolution v')
-- linear
model = nn.WeightNorm(nn.Linear(5, 20))
err = nn.Jacobian.testJacobianParameters(model, input,
model.bias, model.gradBias)
mytester:assert(err < precision, 'Linear bias')
err = nn.Jacobian.testJacobianParameters(model, input, model.g, model.gradG)
mytester:assert(err < precision, 'Linear g')
err = nn.Jacobian.testJacobianParameters(model, input,
model.v, model.gradV)
mytester:assert(err < precision, 'Linear v')
-- euclidean with weight but no bias
input = torch.rand(10, 5)
model = nn.WeightNorm(nn.Euclidean(5, 20))
err = nn.Jacobian.testJacobianParameters(model, input, model.g, model.gradG)
mytester:assert(err < precision, 'Euclidean g')
err = nn.Jacobian.testJacobianParameters(model, input,
model.v, model.gradV)
mytester:assert(err < precision, 'Euclidean v')
-- spatial convolution with 4D weights
input = torch.rand(5, 10, 10)
model = nn.WeightNorm(nn.SpatialConvolution(5, 20, 2, 2, 3, 3, 1, 1), 2)
err = nn.Jacobian.testJacobianParameters(model, input,
model.bias, model.gradBias)
mytester:assert(err < precision, 'Spatial Convolution bias')
err = nn.Jacobian.testJacobianParameters(model, input,
model.g, model.gradG)
mytester:assert(err < precision, 'Spatial Convolution g')
err = nn.Jacobian.testJacobianParameters(model, input,
model.v, model.gradV)
mytester:assert(err < precision, 'Spatial Convolution v')
-- linear save/load
model = nn.WeightNorm(nn.Linear(5, 20))
input = torch.rand(10, 5)
local out = model:forward(input)
local modelr = torch.deserialize(torch.serialize(model))
local outr = modelr:forward(input)
mytester:assertTensorEq(out, outr)
end
function nntest.LinearWeightNorm()
local input = torch.rand(10, 5)
local model = nn.LinearWeightNorm(5, 20)
-- check gradient
local err = nn.Jacobian.testJacobianParameters(model, input, model.bias, model.gradBias)
mytester:assert(err < precision, 'bias')
err = nn.Jacobian.testJacobianParameters(model, input, model.g, model.gradG)
mytester:assert(err < precision, 'g')
err = nn.Jacobian.testJacobianParameters(model, input, model.v, model.gradV)
mytester:assert(err < precision, 'v')
-- check conversion functions
local linear = nn.Linear(5,20)
local wnFromLin = nn.LinearWeightNorm.fromLinear(linear)
local linFromWn = wnFromLin:toLinear()
local linOut = linear:forward(input)
local wnOut = wnFromLin:forward(input)
local linFromWnOut = linFromWn:forward(input)
mytester:assertTensorEq(linOut, wnOut, precision, "outputs are not equivalent")
mytester:assertTensorEq(wnOut, linFromWnOut, precision, "outputs are not equivalent")
-- check conversion with nobias
linear = nn.Linear(5,20,false)
wnFromLin = nn.LinearWeightNorm.fromLinear(linear)
linFromWn = wnFromLin:toLinear()
linOut = linear:forward(input)
wnOut = wnFromLin:forward(input)
linFromWnOut = linFromWn:forward(input)
mytester:assertTensorEq(linear.weight, wnFromLin.weight, precision, "weights are not equivalent")
mytester:assert(not wnFromLin.bias)
mytester:assert(not linear.bias)
mytester:assertTensorEq(linOut, wnOut, precision, "outputs are not equivalent")
mytester:assertTensorEq(wnOut, linFromWnOut, precision, "outputs are not equivalent")
-- check gradient with nobias
model = wnFromLin
err = nn.Jacobian.testJacobianParameters(model, input, model.g, model.gradG)
mytester:assert(err < precision, 'g')
err = nn.Jacobian.testJacobianParameters(model, input, model.v, model.gradV)
mytester:assert(err < precision, 'v')
end
function nntest.CAdd()
local function testBackwardPass(module, input, params, dparams)
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, "error computing gradiens w.r.t. inputs")
err = jac.testJacobianParameters(module, input, params, dparams)
mytester:assertlt(err,precision, "error computing gradients w.r.t params")
err = jac.testJacobianUpdateParameters(module, input, module.bias)
mytester:assertlt(err,precision, "error in update using gradients w.r.t parameters")
--Test all of the various update methods
for test, err in pairs(jac.testAllUpdate(module, input, "bias", "gradBias")) do
mytester:assertlt(err, precision, string.format("error on bias [%s]", test))
end
end
local function testModuleIO(module, input)
local fwdErr,bkwdErr = jac.testIO(module,input)
mytester:asserteq(fwdErr, 0, torch.typename(module) .. " - i/o forward err ")
mytester:asserteq(bkwdErr, 0, torch.typename(module) .. " - i/o backward err ")
end
local function testCAddWithNonBatchedInput()
local channels = math.random(3,5)
local width = math.random(3,5)
local height = math.random(3,5)
local input = torch.Tensor(channels, height, width):zero()
--Per channel bias
local module = nn.CAdd(channels, 1, 1)
local params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
local output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[i]:view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per row bias
module = nn.CAdd(1, height, 1)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[{{}, {i}, {}}]:contiguous():view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per column bias
module = nn.CAdd(1, 1, width)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[{{}, {}, {i}}]:contiguous():view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per input component bias
module = nn.CAdd(channels, height, width)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
mytester:assert(module.bias:isSameSizeAs(input))
mytester:assertTensorEq(module.bias, output, precision)
testModuleIO(module, input)
end
local function testCAddWithBatchedInput()
local batchSize = math.random(3,5)
local channels = math.random(3,5)
local width = math.random(3,5)
local height = math.random(3,5)
local input = torch.Tensor(batchSize, channels, height, width):zero()
local module = nn.CAdd(batchSize, channels, height, width)
--Per batch bias
local module = nn.CAdd(batchSize, 1, 1, 1)
local params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
local output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[i]:view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per channel bias
module = nn.CAdd(1, channels, 1, 1)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[{{}, {i}, {}, {}}]:contiguous():view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per row bias
module = nn.CAdd(1, 1, height, 1)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[{{}, {}, {i}, {}}]:contiguous():view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per column bias
module = nn.CAdd(1, 1, 1, width)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
for i = 1, module.bias:view(-1):size(1) do
local bias = module.bias:view(-1)[i]
local result = output[{{}, {}, {}, {i}}]:contiguous():view(-1)
local expectedResult = torch.Tensor({bias}):expandAs(result)
mytester:assertTensorEq(result, expectedResult, precision)
end
--Per input component bias
module = nn.CAdd(batchSize, channels, height, width)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
output = module:forward(input)
mytester:assert(output:isSameSizeAs(input))
mytester:assert(module.bias:isSameSizeAs(input))
mytester:assertTensorEq(module.bias, output, precision)
testModuleIO(module, input)
end
local function testCAddWithLessDimsThanInput()
local input = torch.rand(4,5)
local module = nn.CAdd(5)
local params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
local output = module:forward(input)
local expandedBias = module.bias:view(1,5):expand(4,5):clone()
mytester:assert(output:isSameSizeAs(input))
mytester:assertTensorEq(expandedBias, output, precision)
testModuleIO(module, input)
input = torch.rand(4,5,6)
module = nn.CAdd(5,6)
params, gradParams = module:getParameters()
testBackwardPass(module, input, params, gradParams)
input:zero()
local output = module:forward(input)
expandedBias = module.bias:view(1,5,6):expand(4,5,6):clone()
mytester:assert(output:isSameSizeAs(input))
mytester:assertTensorEq(expandedBias, output, precision)
testModuleIO(module, input)
end
testCAddWithNonBatchedInput()
testCAddWithBatchedInput()
testCAddWithLessDimsThanInput()
end
function nntest.CMul()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local inl = math.random(3,5)
local input = torch.Tensor(ini,inj,ink):zero()
local module = nn.CMul(1, ini, inj, ink, 1)
-- 1D
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight)
mytester:assertlt(err,precision, 'error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight)
mytester:assertlt(err,precision, 'error on weight [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, precision, string.format(
'error on weight [%s]', t))
end
-- 2D
local nframe = math.random(3,14)
local input = torch.randn(nframe, ini,inj,ink)
local output = module:forward(input)
local output2 = torch.cmul(input, module.weight:view(1,ini,inj,ink):expandAs(input))
mytester:assertTensorEq(output2, output, 0.000001, 'CMul forward 2D err')
module:zeroGradParameters()
local gradWeight = module.gradWeight:clone()
local gradInput = module:backward(input, output)
local gradInput2 = gradInput:clone():zero()
local outputView = output:view(input:size(1), -1)
gradInput2:view(input:size(1), -1):addcmul(1, module.weight:view(1,-1):expandAs(outputView), outputView)
mytester:assertTensorEq(gradInput2, gradInput, 0.000001, 'CMul updateGradInput 2D err')
mytester:assert(gradInput:isSameSizeAs(input), 'CMul gradInput 2D size err')
local inputView = input:view(nframe, -1)
local gradWeightView = gradWeight:view(1, -1)
for i=1,nframe do
gradWeightView:addcmul(1, inputView[i], outputView[i])
end
mytester:assertTensorEq(gradWeight, module.gradWeight, 0.000001, 'CMul accGradParameters 2D err')
mytester:assert(module.weight:isSameSizeAs(module.gradWeight), 'CMul gradWeight size err')
-- Expansion
input = torch.randn(nframe, ini,inj,ink,inl)
output = module:forward(input)
output2 = torch.cmul(input, module.weight:expandAs(input))
mytester:assertTensorEq(output2, output, 0.000001, 'CMul forward expand err')
module:zeroGradParameters()
gradWeight:zero()
gradInput = module:backward(input, output)
gradInput2 = gradInput:clone():zero()
gradInput2:addcmul(1, module.weight:expandAs(output), output)
mytester:assertTensorEq(gradInput2, gradInput, 0.000001, 'CMul updateGradInput expansion err')
mytester:assert(gradInput:isSameSizeAs(input), 'CMul gradInput expand size err')
for i=1,nframe do
-- 4 is the [non-batch] singleton dim
gradWeight:add(torch.cmul(input[i], output[i]):sum(4))
end
mytester:assertTensorEq(gradWeight:sum(5), module.gradWeight, 0.000001, 'CMul accGradParameters expand err')
mytester:assert(module.weight:isSameSizeAs(module.gradWeight), 'CMul accGradParameters expand size err')
input:zero()
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight)
mytester:assertlt(err,precision, 'error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight)
mytester:assertlt(err,precision, 'error on weight [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, precision, string.format('error on weight [%s]', t))
end
-- Non-contiguous input or gradOutput
local testModule = nn.CMul(4, 3, 5)
local testInput = torch.rand(10, 3, 5):resize(10, 1, 3, 5):expand(10, 4, 3, 5)
local testOutput = testModule:forward(testInput)
mytester:assert(testOutput:isSameSizeAs(testInput), 'CMul non-contiguous forward err')
local testGradOutput = torch.rand(10, 3, 5):resize(10, 1, 3, 5):expand(10, 4, 3, 5)
testOutput = testModule:forward(testInput)
local testGradInput = testModule:backward(testOutput, testGradOutput)
mytester:assert(testGradInput:isSameSizeAs(testGradOutput), 'CMul non-contiguous backward err')
-- IO
local ferr,berr = jac.testIO(module,input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.Contiguous()
local module = nn.Contiguous()
-- Contiguous input
local input = torch.rand(30,20,10)
local output = module:forward(input)
mytester:assert(output:ne(input):sum() == 0, 'output not equal to input')
-- Make input non-contiguous
local input2 = output:transpose(1,2)
local output2 = module:forward(input2)
mytester:assert(output2:ne(output:contiguous()):sum() == 0, 'output not equal to input')
end
function nntest.Dropout()
local p = 0.2 --prob of droping out a neuron
local input = torch.Tensor(1000):fill((1-p))
local module = nn.Dropout(p)
-- version 2
local output = module:forward(input)
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input, input)
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
-- test inplace version
local module = nn.Dropout(p,nil,true)
local output = module:forward(input:clone())
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input:clone(), input:clone())
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
-- version 1 (old nnx version)
local input = input:fill(1)
local module = nn.Dropout(p,true)
local output = module:forward(input)
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input, input)
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
end
function nntest.SpatialDropout()
local p = 0.2 --prob of dropiing out a neuron
local w = math.random(1,5)
local h = math.random(1,5)
local nfeats = 1000
local input = torch.Tensor(nfeats, w, h):fill(1)
local module = nn.SpatialDropout(p)
module.train = true
local output = module:forward(input)
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input, input)
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
end
function nntest.SpatialDropoutBatch()
local p = 0.2 --prob of dropiing out a neuron
local bsz = math.random(1,5)
local w = math.random(1,5)
local h = math.random(1,5)
local nfeats = 1000
local input = torch.Tensor(bsz, nfeats, w, h):fill(1)
local module = nn.SpatialDropout(p)
module.train = true
local output = module:forward(input)
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input, input)
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
end
function nntest.VolumetricDropout()
local p = 0.2 --prob of dropiing out a neuron
local t = math.random(1,5)
local w = math.random(1,5)
local h = math.random(1,5)
local nfeats = 1000
local input = torch.Tensor(nfeats, t, w, h):fill(1)
local module = nn.VolumetricDropout(p)
module.train = true
local output = module:forward(input)
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input, input)
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
end
function nntest.VolumetricDropoutBatch()
local p = 0.2 --prob of dropiing out a neuron
local bsz = math.random(1,5)
local t = math.random(1,5)
local w = math.random(1,5)
local h = math.random(1,5)
local nfeats = 1000
local input = torch.Tensor(bsz, nfeats, t, w, h):fill(1)
local module = nn.VolumetricDropout(p)
module.train = true
local output = module:forward(input)
mytester:assert(math.abs(output:mean() - (1-p)) < 0.05, 'dropout output')
local gradInput = module:backward(input, input)
mytester:assert(math.abs(gradInput:mean() - (1-p)) < 0.05, 'dropout gradInput')
end
function nntest.ReLU()
local input = torch.randn(3,4)
local gradOutput = torch.randn(3,4)
local module = nn.ReLU()
local output = module:forward(input)
local output2 = input:clone():gt(input, 0):cmul(input)
mytester:assertTensorEq(output, output2, 0.000001, 'ReLU output')
local gradInput = module:backward(input, gradOutput)
local gradInput2 = input:clone():gt(input, 0):cmul(gradOutput)
mytester:assertTensorEq(gradInput, gradInput2, 0.000001, 'ReLU gradInput')
end
function nntest.ReLU6()
for inplace = 0, 1 do
local input = torch.randn(3, 4):mul(6)
local gradOutput = torch.randn(3,4)
local module = nn.ReLU6(inplace == 1)
local output = module:forward(input:clone())
local gt = input:clone():gt(input, 0)
local lt = input:clone():lt(input, 6)
local output2 = gt:clone():cmul(lt):cmul(input)
output2:add(6, input:clone():gt(input, 6))
mytester:assertTensorEq(output, output2, 0.000001, 'ReLU6 output '..(inplace and '(inplace)' or '') )
local gradInput = module:backward(input, gradOutput:clone())
local gradInput2 = gt:clone():cmul(lt):cmul(gradOutput)
mytester:assertTensorEq(gradInput, gradInput2, 0.000001, 'ReLU gradInput '..(inplace and '(inplace)' or '') )
end
end
function nntest.GatedLinearUnit()
local model = nn.GatedLinearUnit()
local t = torch.Tensor({{1, 1}, {2, 2}, {3, 3}})
local thalf = torch.Tensor():resizeAs(t):copy(t):narrow(2, 1, 1)
mytester:assertTensorEq(
thalf:cmul(torch.sigmoid(thalf)),
model:forward(t):resizeAs(thalf),
0.000001,
'Gated Linear output'
)
t = torch.Tensor({{1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}})
thalf = torch.Tensor():resizeAs(t):copy(t):narrow(2, 1, 2)
mytester:assertTensorEq(
thalf:cmul(torch.sigmoid(thalf)),
model:forward(t),
0.000001,
'Gated Linear Unit output'
)
local input = torch.rand(1, 10)
local err = jac.testJacobian(model, input)
mytester:assert(err < precision, 'Gated Linear gradient')
input = torch.rand(5, 10, 6)
model = nn.GatedLinearUnit(2)
err = jac.testJacobian(model, input)
mytester:assert(err < precision, 'Gated Linear gradient, non-default dim')
input = torch.rand(5, 10, 6)
model = nn.GatedLinearUnit(3)
err = jac.testJacobian(model, input)
mytester:assert(err < precision, 'Gated Linear gradient, non-default dim')
input = torch.rand(5, 10)
model = nn.Sequential()
model:add(nn.Linear(10, 10))
model:add(nn.GatedLinearUnit())
model:add(nn.ReLU())
model:add(nn.LogSoftMax())
err = jac.testJacobian(model, input)
mytester:assert(err < precision, 'Gated Linear gradient with other layers')
end
function nntest.CReLU()
local function _verifyCReLU(featureMaps, concatenatedFeatureMaps)
local rectifiedFeatureMaps = nn.ReLU():forward(featureMaps)
local rectifiedNegFeatureMaps = nn.ReLU():forward(-featureMaps)
mytester:asserteq(concatenatedFeatureMaps:size(1), featureMaps:size(1) * 2,
"CReLU should double the number of feature maps")
for i = 1, rectifiedFeatureMaps:size(1) do
local found = false
for j = 1, concatenatedFeatureMaps:size(1) do
found = found or rectifiedFeatureMaps[i]:equal(concatenatedFeatureMaps[j])
end
mytester:assert(found, "Original (rectified) feature maps should be in the output of CReLU")
end
for i = 1, rectifiedNegFeatureMaps:size(1) do
local found = false
for j = 1, concatenatedFeatureMaps:size(1) do
found = found or rectifiedFeatureMaps[i]:equal(concatenatedFeatureMaps[j])
end
mytester:assert(found, "The negative of the original (rectified) feature maps should be in the output of CReLU")
end
end
local model = nn.Sequential()
model:add(nn.SpatialConvolution(1, 3, 3, 3, 1, 1, 1, 1))
for _, inplace in pairs({true, false}) do
--batched
local crelu = nn.CReLU(3, inplace)
local input = torch.Tensor(2, 1, 20, 20):uniform()
local featureMaps = model:forward(input)
local concatenatedFeatureMaps = crelu:forward(featureMaps)
for i = 1, input:size(1) do
_verifyCReLU(featureMaps[i], concatenatedFeatureMaps[i])
end
--non-batched
local input = torch.Tensor(1, 20, 20):uniform()
local featureMaps = model:forward(input)
local concatenatedFeatureMaps = crelu:forward(featureMaps)
_verifyCReLU(featureMaps, concatenatedFeatureMaps)
end
--test gradients w.r.t input
local jac = nn.Jacobian
for _, inplace in pairs({true, false}) do
local crelu = nn.CReLU(3, inplace)
--batched
local input = torch.Tensor(2, 3, 20, 20):uniform()
local err = jac.testJacobian(crelu, input)
mytester:assertlt(err, precision, "error computing gradients w.r.t. inputs")
--I/O
local fwdErr,bkwdErr = jac.testIO(crelu,input)
mytester:asserteq(fwdErr, 0, torch.typename(crelu) .. " - i/o forward err ")
mytester:asserteq(bkwdErr, 0, torch.typename(crelu) .. " - i/o backward err ")
--non-batched
input = torch.Tensor(3, 20, 20):uniform()
err = jac.testJacobian(crelu,input)
mytester:assertlt(err, precision, "error computing gradients w.r.t. inputs")
--I/O
local fwdErr,bkwdErr = jac.testIO(crelu,input)
mytester:asserteq(fwdErr, 0, torch.typename(crelu) .. " - i/o forward err ")
mytester:asserteq(bkwdErr, 0, torch.typename(crelu) .. " - i/o backward err ")
end
end
function nntest.Exp()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local input = torch.Tensor(ini,inj,ink):zero()
local module = nn.Exp()
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local ferr,berr = jac.testIO(module,input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.Log()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local input = torch.Tensor(ini,inj,ink):zero()
local module = nn.Log()
local err = jac.testJacobian(module,input, 0.1, 10)
mytester:assertlt(err,precision, 'error on state ')
local ferr,berr = jac.testIO(module,input, 0.1, 10)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.HardTanh()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local input = torch.Tensor(ink, inj, ini):zero()
local module = nn.HardTanh()
local err = jac.testJacobian(module, input)
mytester:assertlt(err, precision , 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
-- test inclusive bounds -- HardTahn(1,inf) should behave like Threshold(1)
local input = torch.Tensor({1})
local gradOutput = torch.Tensor({1})
local gradOutputClone = gradOutput:clone()
local module = nn.HardTanh(1, math.huge, true)
local tanhGradInput = module:backward(input, gradOutput)
local input = input:clone()
local gradOutput = gradOutputClone
local module = nn.Threshold(1, 0, true)
local threshGradInput = module:backward(input, gradOutput)
mytester:assertTensorEq(tanhGradInput, threshGradInput, 0.000001, 'HardTanh gradInput')
end
function nntest.Clamp()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local max_value = math.abs(math.random())
local min_value = -math.abs(math.random())
local input = torch.Tensor(ink, inj, ini):zero()
local module = nn.Clamp(min_value, max_value)
local err = jac.testJacobian(module, input)
mytester:assertlt(err, precision , 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.Abs()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local input = torch.Tensor(ink, inj, ini):zero()
local module = nn.Abs()
local err = jac.testJacobian(module, input)
mytester:assertlt(err, precision , 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.Threshold()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local input = torch.Tensor(ink, inj, ini):zero()
local module = nn.Threshold(torch.uniform(-2,2),torch.uniform(-2,2))
local err = nn.Jacobian.testJacobian(module, input)
mytester:assertlt(err, precision, 'error on state ')
local ferr, berr = nn.Jacobian.testIO(module, input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.ELU()
local ini = math.random(3,5)
local inj = math.random(3,5)
local ink = math.random(3,5)
local input = torch.Tensor(ink, inj, ini):zero()
local module = nn.ELU(0.3)
local err = jac.testJacobian(module, input)
mytester:assertlt(err, precision , 'error on state ')
local ferr, berr = jac.testIO(module, input)
mytester:eq(ferr, 0, torch.typename(module) .. ' - i/o forward err ', precision)
mytester:eq(berr, 0, torch.typename(module) .. ' - i/o backward err ', precision)
end
function nntest.ELUIP()
local input = torch.randn(3,4)
local input2 = input:clone()
local gradOutput = torch.randn(3,4)
local gradOutput2 = gradOutput:clone()
-- Compare in-place to not in-place
local module = nn.ELU(0.3, true)
local module2 = nn.ELU(0.3, false)
local output = module:forward(input)
local output2 = module2:forward(input2)
mytester:assertTensorEq(output, output2, 0.000001, 'ELU output')
local gradInput = module:backward(input, gradOutput)
local gradInput2 = module2:backward(input2, gradOutput2)
mytester:assertTensorEq(gradInput, gradInput2, 0.000001, 'ELU gradInput')
end
function nntest.PReLU()
local ini = math.random(3,5)
local input = torch.Tensor(ini):zero()
local module = nn.PReLU(ini)
-- 1D
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight)
mytester:assertlt(err,precision, 'error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight)
mytester:assertlt(err,precision, 'error on weight [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, precision, string.format(
'error on weight [%s]', t))
end
-- 2D
local nframe = math.random(1,7)
local input = torch.Tensor(nframe, ini):zero()
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight)
mytester:assertlt(err,precision, 'error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight)
mytester:assertlt(err,precision, 'error on weight [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, precision, string.format(
'error on weight [%s]', t))
end
-- 4D
local nframe = math.random(1,7)
local kW, kH = math.random(1,8), math.random(1,8)
local input = torch.Tensor(nframe, ini, kW, kH):zero()
local err = jac.testJacobian(module,input)
mytester:assertlt(err,precision, 'error on state ')
local err = jac.testJacobianParameters(module, input, module.weight, module.gradWeight)
mytester:assertlt(err,precision, 'error on weight ')
local err = jac.testJacobianUpdateParameters(module, input, module.weight)
mytester:assertlt(err,precision, 'error on weight [direct update] ')
for t,err in pairs(jac.testAllUpdate(module, input, 'weight', 'gradWeight')) do
mytester:assertlt(err, precision, string.format(
'error on weight [%s]', t))
end