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

Function test_syncbn2d

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

Source from the content-addressed store, hash-verified

207
208
209def test_syncbn2d():
210 nr_chan = 8
211 data_shape = (3, nr_chan, 16, 16)
212 momentum = 0.9
213 bn = SyncBatchNorm(nr_chan, momentum=momentum)
214 running_mean = np.zeros((1, nr_chan, 1, 1), dtype=np.float32)
215 running_var = np.ones((1, nr_chan, 1, 1), dtype=np.float32)
216 for i in range(3):
217 xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
218 xv_transposed = np.transpose(xv, [0, 2, 3, 1]).reshape(
219 (data_shape[0] * data_shape[2] * data_shape[3], nr_chan)
220 )
221
222 mean = np.mean(xv_transposed, axis=0).reshape(1, nr_chan, 1, 1)
223
224 var_biased = np.var(xv_transposed, axis=0).reshape((1, nr_chan, 1, 1))
225 sd = np.sqrt(var_biased + bn.eps)
226
227 var_unbiased = np.var(xv_transposed, axis=0, ddof=1).reshape((1, nr_chan, 1, 1))
228 running_mean = running_mean * momentum + mean * (1 - momentum)
229 running_var = running_var * momentum + var_unbiased * (1 - momentum)
230
231 yv = bn(Tensor(xv))
232 yv_expect = (xv - mean) / sd
233
234 _assert_allclose(yv.numpy(), yv_expect)
235 _assert_allclose(bn.running_mean.numpy(), running_mean)
236 _assert_allclose(bn.running_var.numpy(), running_var)
237
238 # test set 'training' flag to False
239 mean_backup = bn.running_mean.numpy()
240 var_backup = bn.running_var.numpy()
241 bn.training = False
242 xv = np.random.normal(loc=2.3, size=data_shape).astype(np.float32)
243 data = Tensor(xv)
244 yv1 = bn(data)
245 yv2 = bn(data)
246 np.testing.assert_equal(yv1.numpy(), yv2.numpy())
247 np.testing.assert_equal(mean_backup, bn.running_mean.numpy())
248 np.testing.assert_equal(var_backup, bn.running_var.numpy())
249 yv_expect = (xv - running_mean) / np.sqrt(running_var + bn.eps)
250 _assert_allclose(yv1.numpy(), yv_expect)
251
252
253def test_batchnorm_no_stats():

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
reshapeMethod · 0.45
transposeMethod · 0.45
meanMethod · 0.45
varMethod · 0.45
sqrtMethod · 0.45

Tested by

no test coverage detected