You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_bn.py 6.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import numpy as np
  10. import pytest
  11. import megengine
  12. import megengine.autodiff as ad
  13. import megengine.distributed as dist
  14. import megengine.functional as F
  15. import megengine.optimizer as optimizer
  16. from megengine import tensor
  17. from megengine.jit import trace
  18. from megengine.module import BatchNorm2d, Conv2d, Module, Sequential, SyncBatchNorm
  19. def run_frozen_bn(BNModule, is_training, use_trace, use_symbolic):
  20. nchannel = 3
  21. m = BNModule(nchannel, freeze=True)
  22. if is_training:
  23. m.train()
  24. else:
  25. m.eval()
  26. var = 4.0
  27. bias = 1.0
  28. shape = (1, nchannel, 1, 1)
  29. m.running_var[...] = var * F.ones(shape)
  30. m.running_mean[...] = bias * F.ones(shape)
  31. saved_var = m.running_var.numpy()
  32. saved_mean = m.running_mean.numpy()
  33. saved_wt = m.weight.numpy()
  34. saved_bias = m.bias.numpy()
  35. gm = ad.GradManager().attach(m.parameters())
  36. optim = optimizer.SGD(m.parameters(), lr=1.0)
  37. optim.clear_grad()
  38. data = np.random.random((6, nchannel, 2, 2)).astype("float32")
  39. def train_fn(d):
  40. for _ in range(3):
  41. with gm:
  42. loss = m(d).mean()
  43. gm.backward(loss)
  44. optim.step()
  45. return loss
  46. if use_trace:
  47. train_fn = trace(train_fn, symbolic=use_symbolic)
  48. for _ in range(3):
  49. loss = train_fn(megengine.tensor(data))
  50. if not is_training:
  51. np.testing.assert_equal(m.running_var.numpy(), saved_var)
  52. np.testing.assert_equal(m.running_mean.numpy(), saved_mean)
  53. np.testing.assert_almost_equal(
  54. loss.numpy(), ((data - bias) / np.sqrt(var)).mean(), 5
  55. )
  56. np.testing.assert_equal(m.weight.numpy(), saved_wt)
  57. np.testing.assert_equal(m.bias.numpy(), saved_bias)
  58. @pytest.mark.parametrize("is_training", [False, True])
  59. @pytest.mark.parametrize("use_trace", [False, True])
  60. @pytest.mark.parametrize("use_symbolic", [False, True])
  61. def test_frozen_bn(is_training, use_trace, use_symbolic):
  62. run_frozen_bn(BatchNorm2d, is_training, use_trace, use_symbolic)
  63. @pytest.mark.require_ngpu(2)
  64. @pytest.mark.isolated_distributed
  65. @pytest.mark.parametrize("is_training", [False, True])
  66. @pytest.mark.parametrize("use_trace", [False, True])
  67. @pytest.mark.parametrize("use_symbolic", [False, True])
  68. def test_frozen_synced_bn(is_training, use_trace, use_symbolic):
  69. @dist.launcher(n_gpus=2)
  70. def worker():
  71. run_frozen_bn(SyncBatchNorm, is_training, use_trace, use_symbolic)
  72. worker()
  73. def test_bn_no_track_stat():
  74. nchannel = 3
  75. m = BatchNorm2d(nchannel, track_running_stats=False)
  76. gm = ad.GradManager().attach(m.parameters())
  77. optim = optimizer.SGD(m.parameters(), lr=1.0)
  78. optim.clear_grad()
  79. data = tensor(np.random.random((6, nchannel, 2, 2)).astype("float32"))
  80. with gm:
  81. loss = m(data).sum()
  82. gm.backward(loss)
  83. optim.step()
  84. def test_bn_no_track_stat2():
  85. nchannel = 3
  86. m = BatchNorm2d(nchannel) # Init with track_running_stat = True
  87. m.track_running_stats = False
  88. # m.running_var and m.running_mean created during init time
  89. saved_var = m.running_var.numpy()
  90. assert saved_var is not None
  91. saved_mean = m.running_mean.numpy()
  92. assert saved_mean is not None
  93. gm = ad.GradManager().attach(m.parameters())
  94. optim = optimizer.SGD(m.parameters(), lr=1.0)
  95. optim.clear_grad()
  96. data = tensor(np.random.random((6, nchannel, 2, 2)).astype("float32"))
  97. with gm:
  98. loss = m(data).sum()
  99. gm.backward(loss)
  100. optim.step()
  101. np.testing.assert_equal(m.running_var.numpy(), saved_var)
  102. np.testing.assert_equal(m.running_mean.numpy(), saved_mean)
  103. def test_bn_no_track_stat3():
  104. nchannel = 3
  105. m = BatchNorm2d(nchannel, track_running_stats=False)
  106. m.track_running_stats = True
  107. data = np.random.random((6, nchannel, 2, 2)).astype("float32")
  108. with pytest.raises(Exception):
  109. m(data)
  110. def test_trace_bn_forward_twice():
  111. class Simple(Module):
  112. def __init__(self):
  113. super().__init__()
  114. self.bn = BatchNorm2d(1)
  115. def forward(self, inp):
  116. x = self.bn(inp)
  117. x = self.bn(x)
  118. return x
  119. @trace(symbolic=True)
  120. def train_bn(inp, net=None):
  121. net.train()
  122. pred = net(inp)
  123. return pred
  124. x = tensor(np.ones((1, 1, 32, 32), dtype=np.float32))
  125. y = train_bn(x, net=Simple())
  126. np.testing.assert_equal(y.numpy(), 0)
  127. def run_syncbn(trace_mode):
  128. x = F.ones([2, 16, 4, 4], dtype="float32")
  129. net = Sequential(
  130. Conv2d(16, 16, 1), SyncBatchNorm(16), Conv2d(16, 16, 1), SyncBatchNorm(16),
  131. )
  132. gm = ad.GradManager().attach(
  133. net.parameters(), callbacks=dist.make_allreduce_cb("MEAN")
  134. )
  135. opt = optimizer.SGD(net.parameters(), 1e-3)
  136. def train_func(x):
  137. with gm:
  138. y = net(x)
  139. loss = y.mean()
  140. gm.backward(loss)
  141. opt.step().clear_grad()
  142. return loss
  143. if trace_mode is not None:
  144. train_func = trace(train_func, symbolic=trace_mode)
  145. for _ in range(3):
  146. loss = train_func(x)
  147. loss.numpy()
  148. @pytest.mark.require_ngpu(2)
  149. @pytest.mark.isolated_distributed
  150. @pytest.mark.parametrize("trace_mode", [None, True, False])
  151. def test_trace_several_syncbn(trace_mode):
  152. @dist.launcher(n_gpus=2)
  153. def worker():
  154. run_syncbn(trace_mode)
  155. worker()
  156. # https://github.com/MegEngine/MegEngine/issues/145
  157. @pytest.mark.parametrize("is_training", [False, True])
  158. def test_frozen_bn_no_affine(is_training):
  159. nchannel = 3
  160. m = BatchNorm2d(nchannel, freeze=True, affine=False)
  161. if is_training:
  162. m.train()
  163. else:
  164. m.eval()
  165. data = megengine.tensor(np.random.random((6, nchannel, 2, 2)).astype("float32"))
  166. m(data).numpy()

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台