test_advance_indexing.py 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
# -*- 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 numpy as np

import megengine
12
import megengine.autodiff as ad
13 14 15 16 17 18 19 20
import megengine.optimizer as optimizer
from megengine import Parameter, tensor
from megengine.module import Module


class Simple(Module):
    def __init__(self):
        super().__init__()
21
        self.a = Parameter([1.0], dtype=np.float32)
22 23 24 25 26 27 28 29 30

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


class Simple2(Module):
    def __init__(self):
        super().__init__()
31
        self.a = Parameter([1.0], dtype=np.float32)
32 33 34 35 36 37 38 39 40

    def forward(self, x):
        x = x[1, ..., :, 0:4:2, 0:2] * self.a
        return x


def test_advance_indexing():
    net = Simple()

M
Megvii Engine Team 已提交
41
    gm = ad.GradManager().attach(net.parameters())
42
    optim = optimizer.SGD(net.parameters(), lr=1.0)
43
    optim.clear_grad()
44 45 46 47 48 49 50

    dshape = (10, 10)
    raw_data = np.arange(100).reshape(dshape).astype(np.float32)
    raw_mask = (np.random.random_sample(dshape) > 0.5).astype(np.bool_)
    data = tensor(raw_data)
    mask = tensor(raw_mask)
    answer = 1.0 - raw_data[raw_mask].sum()
M
Megvii Engine Team 已提交
51
    with gm:
52
        loss = net(data, mask).sum()
53
        gm.backward(loss)
54 55 56 57 58 59 60
    optim.step()
    np.testing.assert_almost_equal(net.a.numpy(), np.array([answer]).astype(np.float32))


def test_advance_indexing_with_subtensor():
    net = Simple2()

M
Megvii Engine Team 已提交
61
    gm = ad.GradManager().attach(net.parameters())
62
    optim = optimizer.SGD(net.parameters(), lr=1.0)
63
    optim.clear_grad()
64 65 66 67 68

    dshape = (2, 3, 4, 3, 4, 2)
    raw_data = np.arange(576).reshape(dshape).astype(np.float32)
    data = tensor(raw_data)
    answer = 1.0 - raw_data[1, ..., :, 0:4:2, 0:2].sum()
M
Megvii Engine Team 已提交
69
    with gm:
70
        loss = net(data).sum()
71
        gm.backward(loss)
72 73
    optim.step()
    np.testing.assert_almost_equal(net.a.numpy(), np.array([answer]).astype(np.float32))