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.0 kB

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

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