MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / test_syncbn1d

Function test_syncbn1d

imperative/python/test/unit/module/test_batchnorm.py:122–162  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

120
121
122def test_syncbn1d():
123 nr_chan = 8
124 data_shape = (3, nr_chan, 4)
125 momentum = 0.9
126 bn = SyncBatchNorm(nr_chan, momentum=momentum)
127 running_mean = np.zeros((1, nr_chan, 1), dtype=np.float32)
128 running_var = np.ones((1, nr_chan, 1), dtype=np.float32)
129 for i in range(3):
130 xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
131 mean = np.mean(np.mean(xv, axis=0, keepdims=True), axis=2, keepdims=True)
132 xv_transposed = np.transpose(xv, [0, 2, 1]).reshape(
133 (data_shape[0] * data_shape[2], nr_chan)
134 )
135
136 var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1))
137 sd = np.sqrt(var_biased + bn.eps)
138
139 var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1))
140 running_mean = running_mean * momentum + mean * (1 - momentum)
141 running_var = running_var * momentum + var_unbiased * (1 - momentum)
142
143 yv = bn(Tensor(xv))
144 yv_expect = (xv - mean) / sd
145
146 _assert_allclose(yv.numpy(), yv_expect)
147 _assert_allclose(bn.running_mean.numpy().reshape(-1), running_mean.reshape(-1))
148 _assert_allclose(bn.running_var.numpy().reshape(-1), running_var.reshape(-1))
149
150 # test set 'training' flag to False
151 mean_backup = bn.running_mean.numpy()
152 var_backup = bn.running_var.numpy()
153 bn.training = False
154 xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
155 data = Tensor(xv)
156 yv1 = bn(data)
157 yv2 = bn(data)
158 np.testing.assert_equal(yv1.numpy(), yv2.numpy())
159 np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
160 np.testing.assert_equal(var_backup, bn.running_var.numpy())
161 yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
162 _assert_allclose(yv1.numpy(), yv_expect)
163
164
165def test_batchnorm2d():

Callers

nothing calls this directly

Calls 13

SyncBatchNormClass · 0.90
TensorClass · 0.90
onesMethod · 0.80
normalMethod · 0.80
assert_equalMethod · 0.80
zerosMethod · 0.45
astypeMethod · 0.45
meanMethod · 0.45
reshapeMethod · 0.45
transposeMethod · 0.45
varMethod · 0.45
sqrtMethod · 0.45

Tested by

no test coverage detected