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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 itertools
  10. import os
  11. import numpy as np
  12. import pytest
  13. import megengine
  14. import megengine.autodiff as ad
  15. import megengine.optimizer as optimizer
  16. from megengine import Parameter, tensor
  17. from megengine.jit import trace
  18. from megengine.module import Module
  19. class Simple(Module):
  20. def __init__(self):
  21. super().__init__()
  22. self.a = Parameter([1.23], dtype="float32")
  23. def forward(self, x):
  24. x = x * self.a
  25. return x
  26. @pytest.mark.parametrize("trace_mode", [True, False, None])
  27. @pytest.mark.parametrize("inplace_mode", [True, False])
  28. def test_sgd_momentum(monkeypatch, trace_mode, inplace_mode):
  29. with monkeypatch.context() as mk:
  30. mk.setenv("MEGENGINE_INPLACE_UPDATE", str(int(inplace_mode)))
  31. def train_func(data, *, model=None, optim=None, gm=None):
  32. optim.clear_grad()
  33. with gm:
  34. loss = net(data)
  35. gm.backward(loss)
  36. optim.step()
  37. return loss
  38. if trace_mode is not None:
  39. train_func = trace(symbolic=trace_mode)(train_func)
  40. def eval_func(data, *, model=None, optim=None, gm=None):
  41. loss = net(data)
  42. return loss
  43. if trace_mode is not None:
  44. eval_func = trace(symbolic=trace_mode)(eval_func)
  45. net = Simple()
  46. optim = optimizer.SGD(net.parameters(), lr=1.0, momentum=0.9)
  47. gm = ad.GradManager().attach(net.parameters())
  48. data = tensor([2.34])
  49. train_func(data, model=net, optim=optim, gm=gm)
  50. np.testing.assert_almost_equal(
  51. optim._state[net.a]["momentum_buffer"].numpy(), 2.34
  52. )
  53. # do 3 steps of infer
  54. for _ in range(3):
  55. loss = eval_func(data)
  56. np.testing.assert_almost_equal(loss.numpy(), 2.34 * (1.23 - 2.34), 5)
  57. np.testing.assert_almost_equal(
  58. optim._state[net.a]["momentum_buffer"].numpy(), 2.34
  59. )
  60. # do a step of train
  61. train_func(data, model=net, optim=optim, gm=gm)
  62. np.testing.assert_almost_equal(loss.numpy(), 2.34 * (1.23 - 2.34), 5)
  63. np.testing.assert_almost_equal(
  64. optim._state[net.a]["momentum_buffer"].numpy(), 0.9 * 2.34 + 2.34, 5
  65. )