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_optimizer.py 7.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2020 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 megengine.functional as F
  11. from megengine import Parameter, optimizer
  12. from megengine.module import Linear, Module
  13. from megengine.tensor import TensorDict, tensor
  14. class MLP(Module):
  15. def __init__(self):
  16. super().__init__()
  17. self.dense0 = Linear(28, 50)
  18. self.dense1 = Linear(50, 20)
  19. def forward(self, x):
  20. x = self.dense0(x)
  21. x = F.relu(x)
  22. x = self.dense1(x)
  23. return x
  24. class Simple(Module):
  25. def __init__(self):
  26. super().__init__()
  27. self.a = Parameter(1.23, dtype=np.float32)
  28. def forward(self, x):
  29. x = x * self.a
  30. return x
  31. def _test_optimizer(opt_str, test_case, check_class, update_lr=False):
  32. iter_num = 3
  33. net = Simple()
  34. opt = getattr(optimizer, opt_str)(net.parameters(), **test_case)
  35. check_func = check_class(net, **test_case)
  36. step = 0
  37. data_shape = (2, 28)
  38. for i in range(iter_num):
  39. if update_lr and i == 1: # change learning rate
  40. for group in opt.param_groups:
  41. group["lr"] += 0.01
  42. check_func.lr += 0.01
  43. data = tensor(np.random.random(data_shape).astype(np.float32))
  44. opt.zero_grad()
  45. with opt.record():
  46. pred = net(data)
  47. loss = pred.sum()
  48. opt.backward(loss)
  49. ori_params = TensorDict()
  50. for param in net.parameters():
  51. ori_params[param] = np.copy(param.numpy())
  52. opt.step()
  53. step += 1
  54. check_func(ori_params, net.parameters(), step)
  55. def test_sgd():
  56. class CheckValue:
  57. def __init__(self, net, **kwarg):
  58. self.slots = TensorDict()
  59. for param in net.parameters():
  60. self.slots[param] = np.zeros(param.shape).astype(np.float32)
  61. for k, v in kwarg.items():
  62. setattr(self, k, v)
  63. def __call__(self, ori_params, new_params, step):
  64. for param in new_params:
  65. grad = param.grad.numpy()
  66. if hasattr(self, "momentum"):
  67. self.slots[param] = grad + self.slots[param] * self.momentum
  68. delta = -self.lr * self.slots[param]
  69. else:
  70. delta = -self.lr * grad
  71. np.testing.assert_almost_equal(param.numpy(), ori_params[param] + delta)
  72. cases = [
  73. {"momentum": 0.9, "lr": 0.01}, # SGD with momentum
  74. {"lr": 0.01}, # simple SGD
  75. {"weight_decay": 0.1, "lr": 0.01}, # with weight_decay
  76. ]
  77. for case in cases:
  78. _test_optimizer("SGD", case, CheckValue)
  79. _test_optimizer("SGD", case, CheckValue, update_lr=True)
  80. def test_adam():
  81. class CheckValue:
  82. def __init__(self, net, **kwarg):
  83. self.m_slots = TensorDict()
  84. self.v_slots = TensorDict()
  85. for param in net.parameters():
  86. self.m_slots[param] = np.zeros(param.shape).astype(np.float32)
  87. self.v_slots[param] = np.zeros(param.shape).astype(np.float32)
  88. for k, v in kwarg.items():
  89. setattr(self, k, v)
  90. def __call__(self, ori_params, new_params, step):
  91. for param in new_params:
  92. grad = param.grad.numpy()
  93. m = self.m_slots[param]
  94. v = self.v_slots[param]
  95. m *= self.betas[0]
  96. m += (1 - self.betas[0]) * grad
  97. v *= self.betas[1]
  98. v += (1 - self.betas[1]) * grad * grad
  99. delta = (m / (1 - self.betas[0] ** step)) / (
  100. np.sqrt(v / (1 - self.betas[1] ** step)) + self.eps
  101. )
  102. np.testing.assert_almost_equal(
  103. param.numpy(), ori_params[param] - self.lr * delta
  104. )
  105. cases = [
  106. {"betas": (0.8, 0.9), "eps": 1e-04, "lr": 0.01},
  107. {
  108. "betas": (0.8, 0.9),
  109. "eps": 1e-04,
  110. "lr": 0.01,
  111. "weight_decay": 0.1,
  112. }, # with weight_decay
  113. ]
  114. for case in cases:
  115. _test_optimizer("Adam", case, CheckValue)
  116. _test_optimizer("Adam", case, CheckValue, update_lr=True)
  117. def test_adagrad():
  118. class CheckValue:
  119. def __init__(self, net, **kwarg):
  120. self.s_slots = TensorDict()
  121. for param in net.parameters():
  122. self.s_slots[param] = np.zeros(param.shape).astype(np.float32)
  123. for k, v in kwarg.items():
  124. setattr(self, k, v)
  125. def __call__(self, ori_params, new_params, step):
  126. for param in new_params:
  127. grad = param.grad.numpy()
  128. self.s_slots[param] += grad ** 2
  129. delta = grad / (self.s_slots[param] + self.eps) ** 0.5
  130. delta *= -(self.lr / (1 + (step - 1) * self.lr_decay))
  131. np.testing.assert_almost_equal(param.numpy(), ori_params[param] + delta)
  132. cases = [
  133. {"lr": 0.01, "eps": 1e-06, "lr_decay": 0.01},
  134. {"lr": 0.01, "eps": 1e-06, "lr_decay": 0.0}, # without lr_decay
  135. {
  136. "lr": 0.01,
  137. "eps": 1e-06,
  138. "lr_decay": 0.01,
  139. "weight_decay": 0.1,
  140. }, # with weight_decay
  141. ]
  142. for case in cases:
  143. _test_optimizer("Adagrad", case, CheckValue)
  144. _test_optimizer("Adagrad", case, CheckValue, update_lr=True)
  145. def test_adadelta():
  146. class CheckValue:
  147. def __init__(self, net, **kwarg):
  148. self.s_slots = TensorDict()
  149. self.a_slots = TensorDict()
  150. for param in net.parameters():
  151. self.s_slots[param] = np.zeros(param.shape).astype(np.float32)
  152. self.a_slots[param] = np.zeros(param.shape).astype(np.float32)
  153. for k, v in kwarg.items():
  154. setattr(self, k, v)
  155. def __call__(self, ori_params, new_params, step):
  156. for param in new_params:
  157. grad = param.grad.numpy()
  158. self.s_slots[param] = self.s_slots[param] * self.rho + grad ** 2 * (
  159. 1 - self.rho
  160. )
  161. delta = (
  162. grad
  163. * ((self.a_slots[param] + self.eps) ** 0.5)
  164. / (self.s_slots[param] + self.eps) ** 0.5
  165. )
  166. self.a_slots[param] = self.a_slots[param] * self.rho + delta ** 2 * (
  167. 1 - self.rho
  168. )
  169. delta *= -self.lr
  170. np.testing.assert_almost_equal(param.numpy(), ori_params[param] + delta)
  171. cases = [
  172. {"lr": 1.0, "eps": 1e-06, "rho": 0.9},
  173. {"lr": 1.0, "eps": 1e-06, "rho": 0.9, "weight_decay": 0.9}, # with weight_decay
  174. ]
  175. for case in cases:
  176. _test_optimizer("Adadelta", case, CheckValue)
  177. _test_optimizer("Adadelta", case, CheckValue, update_lr=True)

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