This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
test_gluon.py
3161 lines (2688 loc) · 109 KB
/
test_gluon.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import gc
import mxnet as mx
from mxnet import gluon
from mxnet import init
from mxnet.gluon import nn
from mxnet.base import py_str, MXNetError
from mxnet.test_utils import assert_almost_equal, default_device, assert_allclose
from mxnet.util import is_np_array
from mxnet.ndarray.ndarray import _STORAGE_TYPE_STR_TO_ID
from mxnet.test_utils import use_np
from common import assertRaises, assert_raises_cudnn_not_satisfied, \
xfail_when_nonstandard_decimal_separator, environment, with_environment
import numpy as onp
from numpy.testing import assert_array_equal
import pytest
from copy import deepcopy
import warnings
import json
import random
import tempfile
mx.npx.reset_np()
def test_parameter():
p = gluon.Parameter('weight', shape=(10, 10))
p.initialize(init='xavier', device=[mx.cpu(0), mx.cpu(1)])
assert len(p.list_data()) == 2
assert len(p.list_grad()) == 2
assert p.data(mx.cpu(1)).context == mx.cpu(1)
assert p.data(mx.cpu(0)).shape == (10, 10)
assert p.grad(mx.cpu(0)).stype == 'default'
assert p.data(mx.cpu(0)).stype == 'default'
p.reset_device(device=[mx.cpu(1), mx.cpu(2)])
assert p.list_device() == [mx.cpu(1), mx.cpu(2)]
def test_invalid_parameter_stype():
with pytest.raises(AssertionError):
p = gluon.Parameter('weight', shape=(10, 10), stype='invalid')
def test_invalid_parameter_grad_stype():
with pytest.raises(AssertionError):
p = gluon.Parameter('weight', shape=(10, 10), grad_stype='invalid')
def test_sparse_parameter():
p = gluon.Parameter('weight', shape=(10, 10), stype='row_sparse', grad_stype='row_sparse')
p.initialize(init='xavier', device=[mx.cpu(0), mx.cpu(1)])
row_id = mx.np.arange(0, 10, device=mx.cpu(1))
assert len(p.list_grad()) == 2
# getting row_sparse data without trainer throws an exception
assertRaises(RuntimeError, p.list_row_sparse_data, row_id)
trainer = mx.gluon.Trainer([p], 'sgd')
assert len(p.list_row_sparse_data(row_id)) == 2
weight = p.row_sparse_data(row_id)
assert weight.context == mx.cpu(1)
assert weight.shape == (10, 10)
assert weight.stype == 'row_sparse'
assert p.var().attr('__storage_type__') == str(_STORAGE_TYPE_STR_TO_ID['row_sparse'])
assert p.grad(mx.cpu(0)).stype == 'row_sparse'
p.reset_device(device=[mx.cpu(1), mx.cpu(2)])
assert p.list_device() == [mx.cpu(1), mx.cpu(2)]
def test_parameter_invalid_access():
# cannot call data on row_sparse parameters
p0 = gluon.Parameter('weight', shape=(10, 10), stype='row_sparse', grad_stype='row_sparse')
p0.initialize(init='xavier', device=[mx.cpu(0), mx.cpu(1)])
assertRaises(RuntimeError, p0.data)
assertRaises(RuntimeError, p0.list_data)
row_id = mx.np.arange(0, 10)
# cannot call row_sparse_data on dense parameters
p1 = gluon.Parameter('weight', shape=(10, 10))
p1.initialize(init='xavier', device=[mx.cpu(0), mx.cpu(1)])
assertRaises(RuntimeError, p1.row_sparse_data, row_id.copyto(mx.cpu(0)))
assertRaises(RuntimeError, p1.list_row_sparse_data, row_id)
def test_parameter_row_sparse_data():
ctx0 = mx.cpu(1)
ctx1 = mx.cpu(2)
dim0 = 4
x = gluon.Parameter('x', shape=(dim0, 2), stype='row_sparse')
x.initialize(init='xavier', ctx=[ctx0, ctx1])
trainer = gluon.Trainer([x], 'sgd')
x_param = x._data[0].copy()
assert x_param.stype == 'row_sparse'
row_id_0 = mx.nd.array([0,1], ctx=ctx0)
retained_0 = x.row_sparse_data(row_id_0)
retained_target_0 = mx.nd.sparse.retain(x_param, row_id_0.as_in_context(ctx0))
mx.test_utils.assert_almost_equal(retained_0.asnumpy(), retained_target_0.asnumpy())
assert retained_0.context == ctx0
row_id_1 = mx.nd.arange(0, dim0, ctx=ctx1)
retained_1 = x.row_sparse_data(row_id_1)
retained_target_1 = x_param
mx.test_utils.assert_almost_equal(retained_1.asnumpy(), retained_target_1.asnumpy())
assert retained_1.context == ctx1
row_id_2 = mx.nd.array([0,1,2])
retained_2 = x.list_row_sparse_data(row_id_2)
retained_target_2 = mx.nd.sparse.retain(x_param, row_id_2.as_in_context(ctx0))
mx.test_utils.assert_almost_equal(retained_2[0].asnumpy(), retained_target_2.asnumpy())
@use_np
def test_constant():
class Test(gluon.HybridBlock):
def __init__(self, **kwargs):
super(Test, self).__init__(**kwargs)
self.value = onp.asarray([[1,2], [3,4]])
self.const = gluon.Constant(self.value)
def forward(self, x):
return x + self.const.data()
test = Test()
test.initialize()
trainer = gluon.Trainer(test.collect_params(), 'sgd',
{'learning_rate': 1.0, 'momentum': 0.5})
with mx.autograd.record():
x = mx.np.ones((2,2))
x.attach_grad()
y = test(x)
y.backward()
trainer.step(1)
assert (test.const.data().asnumpy() == test.value).all()
assert (x.grad.asnumpy() == 1).all()
@use_np
def test_parameter_sharing():
class Net(gluon.Block):
def __init__(self, in_units=0, **kwargs):
super(Net, self).__init__(**kwargs)
self.dense0 = nn.Dense(5, in_units=in_units)
self.dense1 = nn.Dense(5, in_units=in_units)
def forward(self, x):
return self.dense1(self.dense0(x))
net1 = Net(in_units=5)
net2 = Net().share_parameters(net1.collect_params())
net1.initialize()
net2(mx.np.zeros((3, 5)))
net1.save_parameters('net1.params')
net3 = Net()
net3.load_parameters('net1.params', mx.cpu())
net4 = Net()
net5 = Net(in_units=5).share_parameters(net4.collect_params())
net4.initialize()
net5(mx.np.zeros((3, 5)))
net4.save_parameters('net4.params')
net6 = Net()
net6.load_parameters('net4.params', mx.cpu())
def test_parameter_str():
class Net(gluon.Block):
def __init__(self, **kwargs):
super(Net, self).__init__(**kwargs)
self.dense0 = nn.Dense(10, in_units=5, use_bias=False)
net = Net()
lines = str(net.collect_params()).splitlines()
assert 'dense0.weight' in lines[0]
assert '(10, 5)' in lines[0]
assert 'float32' in lines[0]
def test_collect_parameters():
net = nn.HybridSequential()
net.add(nn.Conv2D(10, 3))
net.add(nn.Dense(10, activation='relu'))
assert set(net.collect_params().keys()) == \
set(['0.weight', '0.bias','1.weight','1.bias'])
assert set(net.collect_params('.*weight').keys()) == \
set(['0.weight', '1.weight'])
assert set(net.collect_params('0.bias|1.bias').keys()) == \
set(['0.bias', '1.bias'])
@use_np
def test_basic():
model = nn.Sequential()
model.add(nn.Dense(128, activation='tanh', in_units=10, flatten=False))
model.add(nn.Dropout(0.5))
model.add(nn.Dense(64, activation='tanh', in_units=256),
nn.Dense(32, in_units=64))
model.add(nn.Activation('relu'))
# ndarray
model.initialize(mx.init.Xavier(magnitude=2.24))
x = model(mx.np.zeros((32, 2, 10)))
assert x.shape == (32, 32)
x.wait_to_read()
model.setattr('grad_req', 'null')
assert list(model.collect_params().values())[0]._grad is None
model.setattr('grad_req', 'write')
assert list(model.collect_params().values())[0]._grad is not None
def test_sparse_symbol_block():
data = mx.sym.var('data')
weight = mx.sym.var('weight', stype='row_sparse')
bias = mx.sym.var('bias')
out = mx.sym.broadcast_add(mx.sym.dot(data, weight), bias)
with pytest.raises(AssertionError):
# an exception is expected when creating a SparseBlock w/ sparse param
net = gluon.SymbolBlock(out, data)
def test_sparse_hybrid_block():
params = {}
params['weight'] = gluon.Parameter('weight', shape=(5,5), stype='row_sparse', dtype='float32')
params['bias'] = gluon.Parameter('bias', shape=(5), dtype='float32')
net = gluon.nn.Dense(5).share_parameters(params)
net.initialize()
x = mx.np.ones((2,5))
with pytest.raises(RuntimeError):
# an exception is expected when forwarding a HybridBlock w/ sparse param
y = net(x)
@use_np
def test_hybrid_block_none_args():
class Foo(gluon.HybridBlock):
def forward(self, a, b):
if a is None and b is not None:
return b
elif b is None and a is not None:
return a
elif a is not None and b is not None:
return a + b
else:
raise NotImplementedError
class FooDefault(gluon.HybridBlock):
def forward(self, a, b=None):
if a is None and b is not None:
return b
elif b is None and a is not None:
return a
elif a is not None and b is not None:
return a + b
else:
raise NotImplementedError
class FooNested(gluon.HybridBlock):
def __init__(self):
super(FooNested, self).__init__()
self.f1 = Foo()
self.f2 = Foo()
self.f3 = Foo()
def forward(self, a, b):
data = self.f1(a, b)
data = self.f2(a, data)
data = self.f3(data, b)
return data
for arg_inputs in [(None, mx.np.ones((10,))),
(mx.np.ones((10,)), mx.np.ones((10,))),
(mx.np.ones((10,)), None)]:
foo1 = FooNested()
foo1.hybridize()
foo2 = FooNested()
for _ in range(2): # Loop for 2 times to trigger forwarding of the cached version
out1 = foo1(*arg_inputs)
out2 = foo2(*arg_inputs)
if isinstance(out1, tuple):
for lhs, rhs in zip(out1, out2):
assert_almost_equal(lhs.asnumpy(), rhs.asnumpy())
else:
assert_almost_equal(out1.asnumpy(), out2.asnumpy())
for do_hybridize in [True, False]:
foo = FooNested()
if do_hybridize:
foo.hybridize()
pytest.raises(ValueError, foo, None, None)
# Make sure the ValueError is correctly raised
foo = FooNested()
foo.hybridize()
foo(None, mx.np.ones((10,))) # Pass for the first time to initialize the cached op
pytest.raises(ValueError, lambda: foo(mx.np.ones((10,)), mx.np.ones((10,))))
foo = FooNested()
pytest.raises(TypeError, lambda: foo(mx.np.ones((10,)), mx.sym.var('a')))
foo = FooNested()
pytest.raises(TypeError, lambda: foo(mx.sym.var('a'), mx.np.ones((10,))))
# Test the case of the default values
foo1 = FooDefault()
foo1.hybridize()
foo2 = FooDefault()
out1 = foo1(mx.np.ones((10,)))
out2 = foo2(mx.np.ones((10,)))
out3 = foo1(mx.np.ones((10,)), None)
out4 = foo2(mx.np.ones((10,)), None)
assert_almost_equal(out1.asnumpy(), out2.asnumpy())
assert_almost_equal(out1.asnumpy(), out3.asnumpy())
assert_almost_equal(out1.asnumpy(), out4.asnumpy())
foo1 = FooDefault()
foo1.hybridize()
out1 = foo1(mx.np.ones((10,)), None)
out2 = foo1(mx.np.ones((10,)))
assert_almost_equal(out1.asnumpy(), out2.asnumpy())
pytest.raises(ValueError, lambda: foo1(mx.np.ones((10,)), mx.np.ones((10,))))
@use_np
def test_hybrid_block_hybrid_no_hybrid():
class FooHybrid(gluon.HybridBlock):
def forward(self, a, b):
if isinstance(a, (list, tuple)):
a = sum(a)
if isinstance(b, (list, tuple)):
b = sum(b)
return a + b
class Foo(gluon.Block):
def forward(self, a, b):
if isinstance(a, (list, tuple)):
a = sum(a)
if isinstance(b, (list, tuple)):
b = sum(b)
return a + b
# When hybridize is not called, HybridBlock acts the same as Block
foo_hybrid = FooHybrid()
foo = Foo()
for a, b in [(mx.np.ones((10,)), 1),
(mx.np.ones((20,)), 2),
([mx.np.ones((10,)), mx.np.ones((10,))],
[mx.np.ones((10)), mx.np.ones((10,)), mx.np.ones((10,))]),
([mx.np.ones((10,)), mx.np.ones((10,))], 3)]:
hybrid_block_out = foo_hybrid(a, b)
block_out = foo(a, b)
assert_almost_equal(hybrid_block_out.asnumpy(), block_out.asnumpy())
# When hybridize is called, we need to make sure that the model raises for the unsupported cases
# 1. Scalar values in the input
# 2. No sym in the input
# 3. No mixing of cpu ndarray and gpu ndarray (Tested in gpu/test_gluon_gpu.py)
# 4. Allow mixing of cpu_pinned and cpu
foo_hybrid = FooHybrid()
foo_hybrid.hybridize()
pytest.raises(ValueError, lambda: foo_hybrid(mx.np.ones((10,)), 1))
foo_hybrid = FooHybrid()
foo_hybrid.hybridize()
pytest.raises(TypeError, lambda: foo_hybrid(mx.np.ones((10,)), mx.sym.var('a')))
foo_hybrid = FooHybrid()
foo_hybrid.hybridize()
pytest.raises(ValueError, lambda: foo_hybrid(mx.np.ones((10,), device=mx.cpu(1)),
mx.np.ones((10,), device=mx.cpu(2))))
def check_layer_forward(layer, dshape):
print("checking layer {}\nshape: {}.".format(layer, dshape))
layer.initialize()
x = mx.np.ones(shape=dshape)
x.attach_grad()
with mx.autograd.record():
out = layer(x)
out.backward()
np_out = out.asnumpy()
np_dx = x.grad.asnumpy()
layer.hybridize()
x = mx.np.ones(shape=dshape)
x.attach_grad()
with mx.autograd.record():
out = layer(x)
out.backward()
mx.test_utils.assert_almost_equal(np_out, out.asnumpy(), rtol=1e-5, atol=1e-6)
mx.test_utils.assert_almost_equal(np_dx, x.grad.asnumpy(), rtol=1e-5, atol=1e-6)
@pytest.mark.parametrize('layer,shape', [
(nn.Conv1D(16, 3, in_channels=4), (1, 4, 10)),
(nn.Conv1D(16, 3, groups=2, in_channels=4), (1, 4, 10)),
(nn.Conv1D(16, 3, strides=3, groups=2, in_channels=4), (1, 4, 10)),
(nn.Conv2D(16, (3, 4), in_channels=4), (1, 4, 20, 20)),
(nn.Conv2D(16, (5, 4), in_channels=4), (1, 4, 20, 20)),
(nn.Conv2D(16, (3, 4), groups=2, in_channels=4), (1, 4, 20, 20)),
(nn.Conv2D(16, (3, 4), strides=4, in_channels=4), (1, 4, 20, 20)),
(nn.Conv2D(16, (3, 4), dilation=4, in_channels=4), (1, 4, 20, 20)),
(nn.Conv2D(16, (3, 4), padding=4, in_channels=4), (1, 4, 20, 20)),
(nn.Conv3D(16, (1, 8, 4), in_channels=4, activation='relu'), (1, 4, 10, 10, 10)),
(nn.Conv3D(16, (5, 4, 3), in_channels=4), (1, 4, 10, 10, 10)),
(nn.Conv3D(16, (3, 3, 3), groups=2, in_channels=4), (1, 4, 10, 10, 10)),
(nn.Conv3D(16, 4, strides=4, in_channels=4), (1, 4, 10, 10, 10)),
(nn.Conv3D(16, (3, 3, 3), padding=4, in_channels=4), (1, 4, 10, 10, 10)),
])
def test_conv(layer, shape):
check_layer_forward(layer, shape)
@pytest.mark.parametrize('layer,shape', [
(nn.Conv2D(16, (3, 3), layout='NHWC', in_channels=4), (1, 10, 10, 4)),
# (nn.Conv3D(16, (3, 3, 3), layout='NDHWC', in_channels=4), (1, 10, 10, 10, 4)),
])
@pytest.mark.skipif(mx.device.current_device().device_type!='gpu' or
not mx.runtime.Features().is_enabled('CUDNN'),
reason='nhwc/ndhwc layout is only supported with CUDNN.')
def test_conv_nhwc(layer, shape):
check_layer_forward(layer, shape)
@pytest.mark.parametrize('layer,shape', [
(nn.Conv1DTranspose(16, 3, in_channels=4), (1, 4, 10)),
(nn.Conv1DTranspose(16, 3, groups=2, in_channels=4), (1, 4, 10)),
(nn.Conv1DTranspose(16, 3, strides=3, groups=2, in_channels=4, output_padding=2), (1, 4, 10)),
(nn.Conv2DTranspose(16, (3, 4), in_channels=4), (1, 4, 20, 20)),
(nn.Conv2DTranspose(16, (5, 4), in_channels=4), (1, 4, 20, 20)),
(nn.Conv2DTranspose(16, (3, 4), groups=2, in_channels=4), (1, 4, 20, 20)),
(nn.Conv2DTranspose(16, (3, 4), strides=4, in_channels=4, output_padding=3), (1, 4, 20, 20)),
(nn.Conv2DTranspose(16, (3, 4), dilation=4, in_channels=4), (1, 4, 20, 20)),
(nn.Conv2DTranspose(16, (3, 4), padding=4, in_channels=4), (1, 4, 20, 20)),
(nn.Conv3DTranspose(16, (1, 8, 4), in_channels=4, activation='relu'), (1, 4, 10, 10, 10)),
(nn.Conv3DTranspose(16, (5, 4, 3), in_channels=4), (1, 4, 10, 10, 10)),
(nn.Conv3DTranspose(16, (3, 3, 3), groups=2, in_channels=4), (1, 4, 10, 10, 10)),
(nn.Conv3DTranspose(16, 4, strides=4, in_channels=4, output_padding=3), (1, 4, 10, 10, 10)),
(nn.Conv3DTranspose(16, (3, 3, 3), padding=4, in_channels=4), (1, 4, 10, 10, 10)),
])
def test_deconv(layer, shape):
if len(shape) == 5 and mx.current_device().device_type == 'gpu':
pytest.skip('Skipping Conv3DTranspose tests for GPU')
check_layer_forward(layer, shape)
@use_np
def test_deconv_dilation():
data = mx.np.array([[[[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]],
[[[0, 0, 0],
[0, 2, 0],
[0, 0, 0]]]])
weight = mx.np.array([[[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]]])
layer = nn.Conv2DTranspose(in_channels=1, channels=1,
kernel_size=(3, 3), padding=(1, 1),
strides=(1, 1), dilation=(2, 2))
layer.initialize()
layer.weight.set_data(weight)
out = layer(data)
expected = mx.np.array(
[[[[1., 0., 2., 0., 3.],
[0., 0., 0., 0., 0.],
[4., 0., 5., 0., 6.],
[0., 0., 0., 0., 0.],
[7., 0., 8., 0., 9.]]],
[[[2., 0., 4., 0., 6.],
[0., 0., 0., 0., 0.],
[8., 0., 10., 0., 12.],
[0., 0., 0., 0., 0.],
[14., 0., 16., 0., 18.]]]
])
assert_almost_equal(out, expected)
def test_pool():
# transpose shape to bring feature dimension 'c' from 2nd position to last
def transpose(shape):
return (shape[0],) + shape[2:] + (shape[1],)
for layout in ['NCW', 'NWC']:
shape1d = (1, 2, 10)
if layout == 'NWC':
shape1d = transpose(shape1d)
layers1d = [
nn.MaxPool1D(layout=layout),
nn.MaxPool1D(3, layout=layout),
nn.MaxPool1D(3, 2, layout=layout),
nn.AvgPool1D(layout=layout),
nn.AvgPool1D(count_include_pad=False, layout=layout),
nn.GlobalAvgPool1D(layout=layout),
]
for layer in layers1d:
check_layer_forward(layer, shape1d)
for layout in ['NCHW', 'NHWC']:
shape2d = (1, 2, 10, 10)
if layout == 'NHWC':
shape2d = transpose(shape2d)
layers2d = [
nn.MaxPool2D(layout=layout),
nn.MaxPool2D((3, 3), layout=layout),
nn.MaxPool2D(3, 2, layout=layout),
nn.AvgPool2D(layout=layout),
nn.AvgPool2D(count_include_pad=False, layout=layout),
nn.GlobalAvgPool2D(layout=layout),
]
for layer in layers2d:
check_layer_forward(layer, shape2d)
for layout in ['NCDHW', 'NDHWC']:
shape3d = (1, 2, 10, 10, 10)
if layout == 'NDHWC':
shape3d = transpose(shape3d)
layers3d = [
nn.MaxPool3D(layout=layout),
nn.MaxPool3D((3, 3, 3), layout=layout),
nn.MaxPool3D(3, 2, layout=layout),
nn.AvgPool3D(layout=layout),
nn.AvgPool3D(count_include_pad=False, layout=layout),
nn.GlobalAvgPool3D(layout=layout),
]
for layer in layers3d:
check_layer_forward(layer, shape3d)
# test ceil_mode
for layout in ['NCHW', 'NHWC']:
xshape = (2, 2, 10, 10)
noceil_out_shape = (2, 2, 3, 3)
ceil_out_shape = (2, 2, 4, 4)
if layout == 'NHWC':
xshape = transpose(xshape)
noceil_out_shape = transpose(noceil_out_shape)
ceil_out_shape = transpose(ceil_out_shape)
x = mx.np.zeros(xshape)
layer = nn.MaxPool2D(3, ceil_mode=False, layout=layout)
layer.initialize()
assert (layer(x).shape==noceil_out_shape)
layer = nn.MaxPool2D(3, ceil_mode=True, layout=layout)
layer.initialize()
assert (layer(x).shape==ceil_out_shape)
@pytest.mark.parametrize('variable', ['running_var', 'running_mean'])
def test_batchnorm_backward_synchronization(variable):
"""
Tests if synchronization of BatchNorm running variables is done correctly.
If not, the test sometimes fails - depending on the timing.
"""
device = mx.test_utils.default_device()
for _ in range(20):
layer = nn.BatchNorm()
layer.initialize(device=device)
for _ in range(3):
data = mx.np.random.normal(loc=10, scale=2, size=(1, 3, 10, 10), device=device)
with mx.autograd.record():
out = layer(data)
out.backward()
# check if each read give the same value
var1 = getattr(layer, variable).data().asnumpy()
for _ in range(10):
var2 = getattr(layer, variable).data().asnumpy()
if (var1 != var2).any():
raise AssertionError("Two consecutive reads of " + variable + " give different results")
def test_batchnorm():
layer = nn.BatchNorm(in_channels=10)
check_layer_forward(layer, (2, 10, 10, 10))
@use_np
@xfail_when_nonstandard_decimal_separator
def test_sync_batchnorm():
def _check_batchnorm_result(input, num_devices=1, cuda=False):
from mxnet.gluon.utils import split_and_load
def _find_bn(module):
if isinstance(module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):
return module
elif isinstance(module.module, (mx.gluon.nn.BatchNorm, mx.gluon.nn.SyncBatchNorm)):
return module.module
raise RuntimeError('BN not found')
def _syncParameters(bn1, bn2, device):
device = input.context
bn2.gamma.set_data(bn1.gamma.data(device))
bn2.beta.set_data(bn1.beta.data(device))
bn2.running_mean.set_data(bn1.running_mean.data(device))
bn2.running_var.set_data(bn1.running_var.data(device))
input1 = input.copy()
input2 = input.copy()
if cuda:
input1 = input.as_in_context(mx.gpu(0))
device_list = [mx.gpu(i) for i in range(num_devices)]
else:
device_list = [mx.cpu(0) for _ in range(num_devices)]
nch = input.shape[1] if input.ndim > 1 else 1
bn1 = mx.gluon.nn.BatchNorm(in_channels=nch)
bn2 = mx.gluon.nn.SyncBatchNorm(
in_channels=nch, num_devices=num_devices)
bn1.initialize(device=device_list[0])
bn2.initialize(device=device_list)
# using the same values for gamma and beta
#_syncParameters(_find_bn(bn1), _find_bn(bn2), device_list[0])
input1.attach_grad()
inputs2 = split_and_load(input2, device_list, batch_axis=0)
for xi in inputs2:
xi.attach_grad()
with mx.autograd.record():
output1 = bn1(input1)
output2 = [bn2(xi) for xi in inputs2]
loss1 = (output1 ** 2).sum()
loss2 = [(output ** 2).sum() for output in output2]
mx.autograd.backward(loss1)
mx.autograd.backward(loss2)
output2 = mx.np.concatenate([output.as_in_context(input.context)
for output in output2], axis=1)
# check bn1
momentum = 0.9
epsilon = 1e-5
axis = 1
data = input1
running_mean = mx.np.zeros(nch, device=data.context)
running_var = mx.np.ones(nch, device=data.context)
axes = list(range(data.ndim))
del axes[axis]
data_mean = data.mean(axis=axes, keepdims=True)
data_var = mx.np.square(data - data_mean).mean(axis=axes, keepdims=True)
target_output = (data - data_mean) / mx.np.sqrt(data_var + epsilon)
# squeeze data_mean and data_var
data_mean_flat = data_mean.squeeze()
data_var_flat = data_var.squeeze()
running_mean = running_mean * momentum + \
data_mean_flat * (1 - momentum)
running_var = running_var * momentum + \
data_var_flat * (1 - momentum)
atol = 1e-2
rtol = 1e-2
assert_almost_equal(output1.asnumpy(), target_output.asnumpy(),
atol=atol, rtol=rtol)
assert_almost_equal(_find_bn(bn1).running_mean.data(device_list[0]).asnumpy(),
running_mean.asnumpy(),
atol=atol, rtol=rtol)
assert_almost_equal(_find_bn(bn1).running_var.data(device_list[0]).asnumpy(),
running_var.asnumpy(),
atol=atol, rtol=rtol)
# assert forwarding
assert_almost_equal(input1.asnumpy(), input2.asnumpy(),
atol=atol, rtol=rtol)
assert_almost_equal(output1.asnumpy(),
output2.asnumpy(), atol=atol, rtol=rtol)
assert_almost_equal(_find_bn(bn1).running_mean.data(device_list[0]).asnumpy(),
_find_bn(bn2).running_mean.data(device_list[0]).asnumpy(),
atol=atol, rtol=rtol)
assert_almost_equal(_find_bn(bn1).running_var.data(device_list[0]).asnumpy(),
_find_bn(bn2).running_var.data(device_list[0]).asnumpy(),
atol=atol, rtol=rtol)
input2grad = mx.np.concatenate(
[output.grad.as_in_context(input.device) for output in inputs2], axis=0)
assert_almost_equal(input1.grad.asnumpy(),
input2grad.asnumpy(), atol=atol, rtol=rtol)
cfgs = [(1, False)]
num_gpus = 0 if default_device().device_type != 'gpu' else mx.device.num_gpus()
batch_size = 24
for i in range(1, num_gpus + 1):
if batch_size % i == 0:
cfgs.append((i, True))
for ndev, cuda in cfgs:
# check with unsync version
for shape in [(batch_size, 2), (batch_size, 3, 4), (batch_size, 4, 4, 4), (batch_size, 5, 6, 4, 4)]:
print(str((ndev, cuda, shape)))
for _ in range(10):
_check_batchnorm_result(mx.np.random.uniform(size=shape,
device=mx.cpu(0)),
num_devices=ndev, cuda=cuda)
def test_instancenorm():
layer = nn.InstanceNorm(in_channels=10)
check_layer_forward(layer, (2, 10, 10, 10))
def test_layernorm():
layer = nn.LayerNorm(in_channels=10)
check_layer_forward(layer, (2, 10, 10, 10))
# Check for the case of error raising
for hybridize in [False, True]:
layer = nn.LayerNorm(in_channels=10)
layer.initialize()
if hybridize:
layer.hybridize()
pytest.raises(AssertionError, lambda: layer(mx.np.ones((2, 11))))
def test_groupnorm():
layer = nn.GroupNorm()
check_layer_forward(layer, (2, 10, 10, 10))
layer = nn.GroupNorm(num_groups=2)
check_layer_forward(layer, (2, 10, 10, 10))
layer = nn.GroupNorm(num_groups=5)
check_layer_forward(layer, (2, 10, 10, 10))
def test_reflectionpad():
layer = nn.ReflectionPad2D(3)
check_layer_forward(layer, (2, 3, 24, 24))
def test_reshape():
x = mx.np.ones((2, 4, 10, 10))
layer = nn.Conv2D(10, 2, in_channels=4)
layer.initialize()
with mx.autograd.record():
x = layer(x)
x = x.reshape((-1,))
x = x + 10
x.backward()
def test_slice():
x = mx.np.ones((5, 4, 10, 10))
layer = nn.Conv2D(10, 2, in_channels=4)
layer.initialize()
with mx.autograd.record():
x = layer(x)
x = x[1:3]
x = x + 10
x.backward()
def test_at():
x = mx.np.ones((5, 4, 10, 10))
layer = nn.Conv2D(10, 2, in_channels=4)
layer.initialize()
with mx.autograd.record():
x = layer(x)
x = x[1]
x = x + 10
x.backward()
def test_deferred_init():
x = mx.np.ones((5, 4, 10, 10))
layer = nn.Conv2D(10, 2)
layer.initialize()
layer(x)
@use_np
def check_split_data(x, num_slice, batch_axis, **kwargs):
res = gluon.utils.split_data(x, num_slice, batch_axis, **kwargs)
assert len(res) == num_slice
mx.test_utils.assert_almost_equal(mx.np.concatenate(res, axis=batch_axis).asnumpy(),
x.asnumpy())
np_res = onp.array_split(x.asnumpy(), num_slice, axis=batch_axis)
res_asnp = [s.asnumpy() for s in res]
for r1, r2 in zip(np_res, res_asnp):
assert all(r1.reshape(-1) == r2.reshape(-1))
@use_np
def test_split_data_np():
x = mx.np.random.uniform(size=(128, 33, 64))
check_split_data(x, 8, 0)
check_split_data(x, 3, 1)
check_split_data(x, 4, 1, even_split=False)
check_split_data(x, 15, 1, even_split=False)
try:
check_split_data(x, 4, 1)
except ValueError:
return
assert False, "Should have failed"
def test_split_data():
x = mx.np.random.uniform(size=(128, 33, 64))
check_split_data(x, 8, 0)
check_split_data(x, 3, 1)
check_split_data(x, 4, 1, even_split=False)
check_split_data(x, 15, 1, even_split=False)
try:
check_split_data(x, 4, 1)
except ValueError:
return
assert False, "Should have failed"
def test_flatten():
flatten = nn.Flatten()
x = mx.np.zeros((3,4,5,6))
assert flatten(x).shape == (3, 4*5*6)
x = mx.np.zeros((3,6))
assert flatten(x).shape == (3, 6)
x = mx.np.zeros((3,))
assert flatten(x).shape == (3, 1)
def test_block_attr_hidden():
b = gluon.Block()
# regular attributes can change types
b.a = None
b.a = 1
def test_block_attr_block():
b = gluon.Block()
with pytest.raises(TypeError):
# regular variables can't change types
b.b = gluon.Block()
b.b = (2,)
def test_block_attr_param():
b = gluon.Block()
with pytest.raises(TypeError):
# regular variables can't change types
b.b = gluon.Parameter()
b.b = (2,)
def test_block_attr_regular():
b = gluon.Block()
# set block attribute also sets a weakref in _children
b.c = gluon.Block()
c2 = gluon.Block()
b.c = c2
assert b.c is c2 and list(b._children.values())[0]() is c2
def test_block_attr_list_of_block():
class Model1(gluon.Block):
def __init__(self, **kwargs):
super(Model1, self).__init__(**kwargs)
self.layers = [nn.Dense(i * 10) for i in range(6)]
class Model2(gluon.Block):
def __init__(self, **kwargs):
super(Model2, self).__init__(**kwargs)
self.layers = dict()
self.layers['a'] = [nn.Dense(10), nn.Dense(10)]
class Model3(gluon.Block):
def __init__(self, **kwargs):
super(Model3, self).__init__(**kwargs)
self.layers = nn.Sequential()
self.layers.add(*[nn.Dense(i * 10) for i in range(6)])
class Model4(gluon.Block):
def __init__(self, **kwargs):
super(Model4, self).__init__(**kwargs)
self.data = {'a': '4', 'b': 123}
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
model = Model1()
model.collect_params()
assert len(w) > 0
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
model = Model2()
model.collect_params()
assert len(w) > 0
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
model = Model3()
model.collect_params()
assert len(w) == 0
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
model = Model4()
model.collect_params()
assert len(w) == 0
def check_sequential(net):
dense1 = gluon.nn.Dense(10)
net.add(dense1)
dense2 = gluon.nn.Dense(10)
net.add(dense2)
dense3 = gluon.nn.Dense(10)
net.add(dense3)
net.initialize()
net(mx.np.zeros((10, 10)))
net.hybridize()
assert net[1] is dense2
assert net[-1] is dense3
slc = net[1:3]
assert len(slc) == 2 and slc[0] is dense2 and slc[1] is dense3
assert isinstance(slc, type(net))
@use_np
def check_sequential_dc(net):
class MyBlock(mx.gluon.HybridBlock):
def __init__(self):
super().__init__()
self.dense = mx.gluon.nn.Dense(units=10, in_units=10)
self.weight = mx.gluon.Parameter('weight', shape=(10, ))
def forward(self, x):
return self.dense(x) + self.weight.data()
dense1 = MyBlock()
net.add(dense1)
dense2 = MyBlock()
net.add(dense2)
dense3 = MyBlock()
net.add(dense3)
net.initialize()
net.hybridize()
net(mx.np.zeros((10, 10)))
assert net[1] is dense2
assert net[-1] is dense3
slc = net[1:3]
assert len(slc) == 2 and slc[0] is dense2 and slc[1] is dense3
assert isinstance(slc, type(net))
@use_np
@pytest.mark.garbage_expected
def test_sequential():
check_sequential(gluon.nn.Sequential())
check_sequential(gluon.nn.HybridSequential())
check_sequential_dc(gluon.nn.HybridSequential())
def test_sequential_warning():
with warnings.catch_warnings(record=True) as w:
# The following line permits the test to pass if run multiple times
warnings.simplefilter('always')
b = gluon.nn.Sequential()
b.add(gluon.nn.Dense(20))
b.hybridize()
assert len(w) == 1
@use_np
def test_global_norm_clip():
def check_global_norm_clip(check_isfinite):
x1 = mx.np.ones((3,3))
x2 = mx.np.ones((4,4))
norm = gluon.utils.clip_global_norm([x1, x2], 1.0, check_isfinite=check_isfinite)
assert norm == 5.0
assert_almost_equal(x1.asnumpy(), onp.ones((3,3))/5)
assert_almost_equal(x2.asnumpy(), onp.ones((4,4))/5)
x3 = mx.np.array([1.0, 2.0, float('nan')])
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
gluon.utils.clip_global_norm([x1, x3], 2.0, check_isfinite=check_isfinite)
assert len(w) == check_isfinite
for check_isfinite in [True, False]:
check_global_norm_clip(check_isfinite)
def test_embedding():
def check_embedding():
layer = gluon.nn.Embedding(10, 100)
layer.initialize()
x = mx.np.array([3,4,2,0,1])
with mx.autograd.record():
y = layer(x)
y.backward()
assert (layer.weight.grad().asnumpy()[:5] == 1).all()