• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15
16import numpy as np
17import pytest
18
19import mindspore.context as context
20import mindspore.nn as nn
21from mindspore import Tensor
22from mindspore.ops import operations as P
23from mindspore.ops import composite as C
24
25def maskedselect():
26    x = np.array([1, 2, 3, 4]).astype(np.int32)
27    mask = np.array([[[0], [1], [0], [1]], [[0], [1], [0], [1]]]).astype(np.bool)
28    net = P.MaskedSelect()
29    return net(Tensor(x), Tensor(mask))
30
31@pytest.mark.level0
32@pytest.mark.platform_x86_cpu
33@pytest.mark.env_onecard
34def test_maskedselect():
35    context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
36    y = maskedselect()
37    expect = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
38    assert (y.asnumpy() == expect).all()
39
40
41class Grad(nn.Cell):
42    def __init__(self, network):
43        super(Grad, self).__init__()
44        self.grad = C.GradOperation(get_all=True, sens_param=True)
45        self.network = network
46
47    def construct(self, x, mask, grad):
48        gout = self.grad(self.network)(x, mask, grad)
49        return gout
50
51class Net(nn.Cell):
52    def __init__(self):
53        super(Net, self).__init__()
54        self.op = P.MaskedSelect()
55
56    def construct(self, x, mask):
57        return self.op(x, mask)
58
59def masked_select_grad():
60    x = np.array([1, 2, 3, 4]).astype(np.int32)
61    mask = np.array([[0], [1], [0], [1]]).astype(np.bool)
62    dy = np.array([i for i in range(8)]).astype(np.int32)
63    grad = Grad(Net())
64    return grad(Tensor(x), Tensor(mask), Tensor(dy))[0]
65
66
67@pytest.mark.level0
68@pytest.mark.platform_x86_cpu
69@pytest.mark.env_onecard
70def test_masked_select_grad():
71    context.set_context(mode=context.GRAPH_MODE, device_target="CPU")
72    dx = masked_select_grad()
73    expect = [4, 6, 8, 10]
74    assert (dx.asnumpy() == expect).all()
75