test_hello_world.py 1.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import subprocess

import numpy as np
import pytest

import megengine
15
import megengine.autodiff as ad
16 17 18 19 20 21 22 23
import megengine.optimizer as optimizer
from megengine import Parameter, tensor
from megengine.module import Module


class Simple(Module):
    def __init__(self):
        super().__init__()
24
        self.a = Parameter([1.23], dtype=np.float32)
25 26 27 28 29 30 31 32 33 34

    def forward(self, x):
        x = x * self.a
        return x


def test_hello_world():
    net = Simple()

    optim = optimizer.SGD(net.parameters(), lr=1.0)
35
    optim.clear_grad()
M
Megvii Engine Team 已提交
36
    gm = ad.GradManager().attach(net.parameters())
37 38

    data = tensor([2.34])
M
Megvii Engine Team 已提交
39
    with gm:
40
        loss = net(data)
41
        gm.backward(loss)
42 43 44 45
    optim.step()
    np.testing.assert_almost_equal(
        net.a.numpy(), np.array([1.23 - 2.34]).astype(np.float32)
    )