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_hello_world.py 1.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 subprocess
  10. import numpy as np
  11. import pytest
  12. import megengine
  13. import megengine.autodiff as ad
  14. import megengine.optimizer as optimizer
  15. from megengine import Parameter, tensor
  16. from megengine.module import Module
  17. class Simple(Module):
  18. def __init__(self):
  19. super().__init__()
  20. self.a = Parameter([1.23], dtype=np.float32)
  21. def forward(self, x):
  22. x = x * self.a
  23. return x
  24. def test_hello_world():
  25. net = Simple()
  26. optim = optimizer.SGD(net.parameters(), lr=1.0)
  27. optim.clear_grad()
  28. gm = ad.GradManager().attach(net.parameters())
  29. data = tensor([2.34])
  30. with gm:
  31. loss = net(data)
  32. gm.backward(loss)
  33. optim.step()
  34. np.testing.assert_almost_equal(
  35. net.a.numpy(), np.array([1.23 - 2.34]).astype(np.float32)
  36. )