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 8.3 kB

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

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