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_sgd_momentum.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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 itertools
  10. import os
  11. import numpy as np
  12. import megengine
  13. import megengine.autodiff as ad
  14. import megengine.optimizer as optimizer
  15. from megengine import Parameter, tensor
  16. from megengine.jit import trace
  17. from megengine.module import Module
  18. class Simple(Module):
  19. def __init__(self):
  20. super().__init__()
  21. self.a = Parameter([1.23], dtype=np.float32)
  22. def forward(self, x):
  23. x = x * self.a
  24. return x
  25. def test_sgd_momentum():
  26. net = Simple()
  27. optim = optimizer.SGD(net.parameters(), lr=1.0, momentum=0.9)
  28. optim.clear_grad()
  29. gm = ad.GradManager().attach(net.parameters())
  30. data = tensor([2.34])
  31. # do a step of train
  32. with gm:
  33. loss = net(data)
  34. gm.backward(loss)
  35. optim.step()
  36. np.testing.assert_almost_equal(optim._state[net.a]["momentum_buffer"].numpy(), 2.34)
  37. # do a step of infer
  38. loss = net(data)
  39. np.testing.assert_almost_equal(loss.numpy(), 2.34 * (1.23 - 2.34), 5)
  40. np.testing.assert_almost_equal(optim._state[net.a]["momentum_buffer"].numpy(), 2.34)
  41. # do a step of train
  42. optim.clear_grad()
  43. with gm:
  44. loss = net(data)
  45. gm.backward(loss)
  46. optim.step()
  47. np.testing.assert_almost_equal(loss.numpy(), 2.34 * (1.23 - 2.34), 5)
  48. np.testing.assert_almost_equal(
  49. optim._state[net.a]["momentum_buffer"].numpy(), 0.9 * 2.34 + 2.34, 5
  50. )
  51. def test_sgd_momentum_trace():
  52. origin_inplace = os.getenv("MEGENGINE_INPLACE_UPDATE")
  53. symbolic = (True, False)
  54. inplace = (0, 1)
  55. for symbolic, inplace in itertools.product(symbolic, inplace):
  56. os.environ["MEGENGINE_INPLACE_UPDATE"] = str(inplace)
  57. @trace(symbolic=symbolic)
  58. def train_func(data, *, model=None, optim=None, gm=None):
  59. optim.clear_grad()
  60. with gm:
  61. loss = net(data)
  62. gm.backward(loss)
  63. optim.step()
  64. return loss
  65. @trace(symbolic=symbolic)
  66. def eval_func(data, *, model=None, optim=None, gm=None):
  67. loss = net(data)
  68. return loss
  69. net = Simple()
  70. optim = optimizer.SGD(net.parameters(), lr=1.0, momentum=0.9)
  71. gm = ad.GradManager().attach(net.parameters())
  72. data = tensor([2.34])
  73. train_func(data, model=net, optim=optim, gm=gm)
  74. np.testing.assert_almost_equal(
  75. optim._state[net.a]["momentum_buffer"].numpy(), 2.34
  76. )
  77. # do 3 steps of infer
  78. for _ in range(3):
  79. loss = eval_func(data)
  80. np.testing.assert_almost_equal(loss.numpy(), 2.34 * (1.23 - 2.34), 5)
  81. np.testing.assert_almost_equal(
  82. optim._state[net.a]["momentum_buffer"].numpy(), 2.34
  83. )
  84. # do a step of train
  85. train_func(data, model=net, optim=optim, gm=gm)
  86. np.testing.assert_almost_equal(loss.numpy(), 2.34 * (1.23 - 2.34), 5)
  87. np.testing.assert_almost_equal(
  88. optim._state[net.a]["momentum_buffer"].numpy(), 0.9 * 2.34 + 2.34, 5
  89. )
  90. if origin_inplace:
  91. os.environ["MEGENGINE_INPLACE_UPDATE"] = origin_inplace
  92. else:
  93. del os.environ["MEGENGINE_INPLACE_UPDATE"]

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